TeraRuntimeModels.swift (25590B)
1 import Foundation 2 3 enum TeraProtectedDataState: Sendable, Equatable { 4 case available 5 case unavailable 6 } 7 8 enum TeraRuntimeNetworkProfile: Sendable, Equatable { 9 case publicNetwork 10 case simulator 11 case device 12 } 13 14 enum TeraBlossomHostKind: String, Codable, Sendable, Equatable { 15 case native 16 case simulator 17 case physicalDevice = "physical_device" 18 } 19 20 enum TeraBlossomEndpointAuthority: String, Codable, Sendable, Equatable { 21 case publicWebPKI = "public_web_pki" 22 case loopbackDevelopment = "loopback_development" 23 case privateNetworkDevelopment = "private_network_development" 24 25 init?(runtimeValue: String) { 26 switch runtimeValue { 27 case "public_webpki": self = .publicWebPKI 28 case "loopback_development": self = .loopbackDevelopment 29 case "private_network_development": self = .privateNetworkDevelopment 30 default: return nil 31 } 32 } 33 } 34 35 struct TeraBlossomEndpointConfiguration: Codable, Sendable, Equatable { 36 let hostKind: TeraBlossomHostKind 37 let endpointAuthority: TeraBlossomEndpointAuthority 38 let primaryOrigin: String 39 let fallbackOrigins: [String] 40 } 41 42 struct TeraBlossomConfigurationStatus: Sendable, Equatable { 43 let schemaVersion: UInt16 44 let hostKind: String 45 let endpointAuthority: String 46 let primaryOrigin: String 47 let fallbackOrigins: [String] 48 let configFingerprint: String 49 } 50 51 struct TeraBlossomEvidence: Sendable, Equatable { 52 let schemaVersion: UInt16 53 let origin: String 54 let configFingerprint: String 55 let state: String 56 let lastSuccessfulState: String 57 let transportSecurity: String 58 let observedAtUnixMilliseconds: UInt64? 59 let httpStatus: UInt16? 60 let errorCode: String? 61 let serverErrorCode: String? 62 let errorPhase: String? 63 let retryable: Bool 64 let possibleOrphan: Bool 65 let attempts: UInt8 66 } 67 68 struct TeraRuntimeAppMetadata: Sendable, Equatable { 69 let bundleIdentifier: String 70 let version: String 71 let buildNumber: String 72 let buildSHA: String? 73 } 74 75 enum TeraRuntimeSignerAvailability: Sendable, Equatable { 76 case ready 77 case busy 78 case locked 79 case unavailable 80 } 81 82 enum TeraRuntimeSigningPurpose: Sendable, Equatable { 83 case nostrEvent 84 case blossomUpload 85 } 86 87 struct TeraRuntimeSigningRequest: Sendable, Equatable { 88 let operationID: String 89 let signerRequestID: String 90 let publicKeyHex: String 91 let purpose: TeraRuntimeSigningPurpose 92 let deadlineUnixMilliseconds: UInt64 93 let digest: Data 94 } 95 96 enum TeraRuntimeSigningOutcome: Sendable, Equatable { 97 case signed(signatureHex: String) 98 case locked 99 case cancelled 100 case rejected 101 case timedOut 102 case unavailable 103 case invalidated 104 case failed 105 } 106 107 protocol TeraRuntimeSigner: Sendable { 108 func availability() async -> TeraRuntimeSignerAvailability 109 func sign(_ request: TeraRuntimeSigningRequest) async -> TeraRuntimeSigningOutcome 110 } 111 112 struct TeraRuntimeLaunchConfiguration: Sendable { 113 let applicationSupportDirectory: String 114 let publicKeyHex: String 115 let sourceGenerationHex: String 116 let sourceGenerationCreatedAtUnixMilliseconds: UInt64 117 let protectedData: TeraProtectedDataState 118 let networkProfile: TeraRuntimeNetworkProfile 119 let writableRelays: [String] 120 let blossom: TeraBlossomEndpointConfiguration? 121 let app: TeraRuntimeAppMetadata 122 let signerGeneration: String 123 let signer: any TeraRuntimeSigner 124 let adoptBootstrapSettings: Bool 125 } 126 127 extension TeraRuntimeLaunchConfiguration: Equatable { 128 static func == (lhs: Self, rhs: Self) -> Bool { 129 lhs.applicationSupportDirectory == rhs.applicationSupportDirectory 130 && lhs.publicKeyHex == rhs.publicKeyHex 131 && lhs.sourceGenerationHex == rhs.sourceGenerationHex 132 && lhs.sourceGenerationCreatedAtUnixMilliseconds 133 == rhs.sourceGenerationCreatedAtUnixMilliseconds 134 && lhs.protectedData == rhs.protectedData 135 && lhs.networkProfile == rhs.networkProfile 136 && lhs.writableRelays == rhs.writableRelays 137 && lhs.blossom == rhs.blossom 138 && lhs.app == rhs.app 139 && lhs.signerGeneration == rhs.signerGeneration 140 && lhs.adoptBootstrapSettings == rhs.adoptBootstrapSettings 141 } 142 } 143 144 struct TeraRuntimeIdentity: Sendable, Equatable { 145 let publicKeyHex: String 146 let hostSignerConfigured: Bool 147 } 148 149 enum TeraRelayAccess: Sendable, Equatable { 150 case readOnly 151 case readWrite 152 153 var label: String { 154 self == .readWrite ? "read write" : "read only" 155 } 156 } 157 158 struct TeraRelayEndpointStatus: Sendable, Equatable { 159 let url: String 160 let access: TeraRelayAccess 161 let readState: String 162 let writeState: String 163 let readLastAttemptUnixMilliseconds: UInt64? 164 let writeLastAttemptUnixMilliseconds: UInt64? 165 let readNextAttemptUnixMilliseconds: UInt64? 166 let writeNextAttemptUnixMilliseconds: UInt64? 167 } 168 169 struct TeraRelayStatus: Sendable, Equatable { 170 let profile: String 171 let state: String 172 let readAvailability: String 173 let writeAvailability: String 174 let relays: [TeraRelayEndpointStatus] 175 } 176 177 enum TeraSettingsIdentityLockState: Sendable, Equatable { 178 case locked 179 case unlocked 180 } 181 182 struct TeraSettingsIdentity: Sendable, Equatable, Identifiable { 183 let id: String 184 let publicKeyHex: String 185 } 186 187 struct TeraSettingsIdentityState: Sendable, Equatable { 188 let identities: [TeraSettingsIdentity] 189 let activeIdentityID: String? 190 let lockState: TeraSettingsIdentityLockState 191 let pendingImportOperationID: String? 192 } 193 194 enum TeraSettingsNetworkEnvironment: String, Sendable, Equatable, CaseIterable, Identifiable { 195 case publicNetwork 196 case simulator 197 case physicalDevice 198 199 var id: String { 200 rawValue 201 } 202 } 203 204 enum TeraRelayAccessPreference: String, Sendable, Equatable, CaseIterable, Identifiable { 205 case readOnly 206 case readWrite 207 208 var id: String { 209 rawValue 210 } 211 212 var label: String { 213 self == .readWrite ? "Read and write" : "Read only" 214 } 215 } 216 217 struct TeraRelayPreference: Sendable, Equatable, Identifiable { 218 let id: UUID 219 var url: String 220 var access: TeraRelayAccessPreference 221 222 init(id: UUID = UUID(), url: String, access: TeraRelayAccessPreference) { 223 self.id = id 224 self.url = url 225 self.access = access 226 } 227 } 228 229 enum TeraBlossomAuthorityPreference: String, Sendable, Equatable, CaseIterable, Identifiable { 230 case publicWebPKI 231 case loopbackDevelopment 232 case privateNetworkDevelopment 233 234 var id: String { 235 rawValue 236 } 237 } 238 239 struct TeraMobileSettings: Sendable, Equatable { 240 let revision: UInt64 241 let identity: TeraSettingsIdentityState 242 var networkEnvironment: TeraSettingsNetworkEnvironment 243 var relays: [TeraRelayPreference] 244 var blossomAuthority: TeraBlossomAuthorityPreference 245 var blossomPrimaryOrigin: String 246 var blossomFallbackOrigins: [String] 247 var allowCellularDownloads: Bool 248 var allowCellularUploads: Bool 249 var allowBackgroundTransfers: Bool 250 var mediaCacheBytes: UInt64 251 var mediaCacheArtifacts: UInt32 252 } 253 254 struct TeraReplaceSettings: Sendable, Equatable { 255 let expectedRevision: UInt64 256 let networkEnvironment: TeraSettingsNetworkEnvironment 257 let relays: [TeraRelayPreference] 258 let blossomAuthority: TeraBlossomAuthorityPreference 259 let blossomPrimaryOrigin: String 260 let blossomFallbackOrigins: [String] 261 let allowCellularDownloads: Bool 262 let allowCellularUploads: Bool 263 let allowBackgroundTransfers: Bool 264 let mediaCacheBytes: UInt64 265 let mediaCacheArtifacts: UInt32 266 } 267 268 struct TeraSettingsTransition: Sendable, Equatable { 269 let settings: TeraMobileSettings 270 let runtimeRestartRequired: Bool 271 let outboxRequeueRequired: Bool 272 let mediaCacheInvalidationRequired: Bool 273 } 274 275 enum TeraIdentityCommandKind: Sendable, Equatable { 276 case beginImport 277 case completeImport 278 case cancelImport 279 case select 280 case lock 281 case unlock 282 case recover 283 } 284 285 struct TeraIdentityCommand: Sendable, Equatable { 286 let kind: TeraIdentityCommandKind 287 let operationID: String? 288 let identityID: String? 289 let publicKeyHex: String? 290 } 291 292 struct TeraProfileMetadataInput: Sendable, Equatable { 293 var name: String 294 var displayName: String? 295 var about: String? 296 var picture: TeraPreparedMediaHandle? 297 var banner: TeraPreparedMediaHandle? 298 var nip05: String? 299 var bot: Bool? 300 } 301 302 struct TeraProfileStatus: Sendable, Equatable, Identifiable { 303 let id: String 304 let revision: UInt64 305 let authorPublicKey: String 306 let state: TeraOutboxState 307 let deliveryID: String? 308 let createdAtUnixMilliseconds: UInt64 309 let updatedAtUnixMilliseconds: UInt64 310 let settlement: TeraOperationSettlement? 311 312 var honestSummary: String { 313 state.summary(settlement: settlement) 314 } 315 } 316 317 struct TeraRuntimeSnapshot: Sendable, Equatable { 318 let identity: TeraRuntimeIdentity 319 let relay: TeraRelayStatus? 320 let blossomConfiguration: TeraBlossomConfigurationStatus? 321 let blossomEvidence: TeraBlossomEvidence? 322 let crateName: String 323 let crateVersion: String 324 let isClosed: Bool 325 } 326 327 struct TeraRuntimeShutdownReceipt: Sendable, Equatable { 328 let state: String 329 let alreadyClosed: Bool 330 331 static let alreadyStopped = Self(state: "closed", alreadyClosed: true) 332 } 333 334 enum TeraRuntimeOperationKind: String, Sendable, Equatable, Hashable { 335 case startup 336 case operation 337 case reconfiguration 338 case subscription 339 case shutdown 340 } 341 342 struct TeraRuntimeDeadlinePolicy: Sendable, Equatable { 343 let startupNanoseconds: UInt64 344 let operationNanoseconds: UInt64 345 let subscriptionNanoseconds: UInt64 346 let shutdownNanoseconds: UInt64 347 348 init( 349 startupNanoseconds: UInt64 = 30_000_000_000, 350 operationNanoseconds: UInt64 = 30_000_000_000, 351 subscriptionNanoseconds: UInt64 = 10_000_000_000, 352 shutdownNanoseconds: UInt64 = 10_000_000_000 353 ) { 354 precondition(startupNanoseconds > 0 && startupNanoseconds <= 120_000_000_000) 355 precondition(operationNanoseconds > 0 && operationNanoseconds <= 120_000_000_000) 356 precondition(subscriptionNanoseconds > 0 && subscriptionNanoseconds <= 60_000_000_000) 357 precondition(shutdownNanoseconds > 0 && shutdownNanoseconds <= 60_000_000_000) 358 self.startupNanoseconds = startupNanoseconds 359 self.operationNanoseconds = operationNanoseconds 360 self.subscriptionNanoseconds = subscriptionNanoseconds 361 self.shutdownNanoseconds = shutdownNanoseconds 362 } 363 364 static let production = Self() 365 } 366 367 enum TeraRuntimeObservationState: Sendable, Equatable { 368 case inactive 369 case subscribing(attempt: UInt32) 370 case active 371 case retrying(attempt: UInt32, message: String) 372 case stopped 373 } 374 375 enum TeraRuntimeObservationBackoff { 376 static func sleep(attempt: UInt32) async throws { 377 let exponent = min(attempt.saturatingSubtractingOne, 7) 378 let delay = min(UInt64(250_000_000) << exponent, 30_000_000_000) 379 try await Task.sleep(nanoseconds: delay) 380 } 381 } 382 383 extension UInt32 { 384 fileprivate var saturatingSubtractingOne: UInt32 { 385 self == 0 ? 0 : self - 1 386 } 387 } 388 389 struct TeraRuntimeFailure: Error, Sendable, Equatable { 390 let schemaVersion: UInt16 391 let code: String 392 let category: String 393 let retryable: Bool 394 let recoveryActions: [String] 395 let operationID: String? 396 let capabilityID: String? 397 let safeMessage: String 398 399 static func local(operation: String, code: String, safeMessage: String) -> Self { 400 Self( 401 schemaVersion: 1, 402 code: code, 403 category: "runtime", 404 retryable: false, 405 recoveryActions: [], 406 operationID: operation, 407 capabilityID: nil, 408 safeMessage: safeMessage 409 ) 410 } 411 } 412 413 extension TeraRuntimeFailure: LocalizedError { 414 var errorDescription: String? { 415 TeraUserMessages.text(.runtimeOperationFailed) 416 } 417 } 418 419 enum TeraRuntimeClientError: Error, Sendable, Equatable { 420 case invalidBufferCapacity 421 case notRunning 422 case superseded 423 case startup(TeraRuntimeFailure) 424 case subscription(TeraRuntimeFailure) 425 case status(TeraRuntimeFailure) 426 case today(TeraRuntimeFailure) 427 case add(TeraRuntimeFailure) 428 case support(TeraRuntimeFailure) 429 case shutdown(TeraRuntimeFailure) 430 } 431 432 extension TeraRuntimeClientError: LocalizedError { 433 var errorDescription: String? { 434 TeraUserMessages.text(for: self, fallback: .runtimeOperationFailed) 435 } 436 } 437 438 struct TeraLocalNetwork: Sendable, Equatable, Hashable, Identifiable { 439 let schemaVersion: UInt16 440 let id: String 441 let label: String 442 let relayURLs: [String] 443 let locality: String? 444 let followedAuthors: [String] 445 let generation: UInt64 446 447 static func defaultContext(snapshot: TeraRuntimeSnapshot) -> Self { 448 Self( 449 schemaVersion: 1, 450 id: "default", 451 label: "Local network", 452 relayURLs: snapshot.relay?.relays.map(\.url) ?? [], 453 locality: nil, 454 followedAuthors: [], 455 generation: 1 456 ) 457 } 458 } 459 460 enum TeraTodayCardType: String, CaseIterable, Sendable, Equatable, Hashable { 461 case update 462 case photoUpdate 463 case ask 464 case event 465 case foodAvailability 466 467 var label: String { 468 switch self { 469 case .update: "Update" 470 case .photoUpdate: "Photo update" 471 case .ask: "Ask" 472 case .event: "Event" 473 case .foodAvailability: "Food availability" 474 } 475 } 476 477 var addCommandType: TeraAddCommandType { 478 switch self { 479 case .update: .createUpdate 480 case .photoUpdate: .createPhotoUpdate 481 case .ask: .createAsk 482 case .event: .createEvent 483 case .foodAvailability: .createFoodAvailability 484 } 485 } 486 } 487 488 enum TeraMediaVerificationState: String, Sendable, Equatable, Hashable { 489 case pending 490 case verified 491 case failed 492 case unavailable 493 } 494 495 struct TeraMediaReference: Sendable, Equatable, Hashable, Identifiable { 496 let referenceFingerprint: String 497 let url: String 498 let sha256: String? 499 let mediaType: String? 500 let width: UInt32? 501 let height: UInt32? 502 let byteSize: UInt64? 503 let alt: String? 504 let verification: TeraMediaVerificationState 505 506 var id: String { 507 referenceFingerprint 508 } 509 510 var verifiedArtifactID: String? { 511 guard verification == .verified, 512 let sha256, 513 sha256.count == 64, 514 sha256.allSatisfy({ $0.isHexDigit && !$0.isUppercase }) 515 else { return nil } 516 return sha256 517 } 518 } 519 520 struct TeraVerifiedMediaArtifact: Sendable, Equatable { 521 let artifactID: String 522 let bytes: Data 523 let byteSize: UInt64 524 let mediaType: String 525 let width: UInt32 526 let height: UInt32 527 528 init?( 529 artifactID: String, 530 bytes: Data, 531 byteSize: UInt64, 532 mediaType: String, 533 width: UInt32, 534 height: UInt32 535 ) { 536 guard artifactID.count == 64, 537 artifactID.allSatisfy({ $0.isHexDigit && !$0.isUppercase }), 538 !bytes.isEmpty, 539 UInt64(bytes.count) == byteSize, 540 ["image/gif", "image/jpeg", "image/png", "image/webp"].contains(mediaType), 541 width > 0, 542 height > 0 543 else { return nil } 544 self.artifactID = artifactID 545 self.bytes = bytes 546 self.byteSize = byteSize 547 self.mediaType = mediaType 548 self.width = width 549 self.height = height 550 } 551 } 552 553 struct TeraProfileSummary: Sendable, Equatable, Hashable { 554 let authorPublicKey: String 555 let name: String? 556 let displayName: String? 557 let about: String? 558 let picture: TeraMediaReference? 559 let banner: TeraMediaReference? 560 let nip05: String? 561 let website: String? 562 let lightningAddress: String? 563 564 var preferredName: String { 565 for candidate in [displayName, name] { 566 if let candidate, !candidate.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { 567 return candidate 568 } 569 } 570 guard authorPublicKey.count > 16 else { return authorPublicKey } 571 return "\(authorPublicKey.prefix(8))…\(authorPublicKey.suffix(8))" 572 } 573 } 574 575 enum TeraThreadEntryType: String, Sendable, Equatable, Hashable { 576 case profile 577 case reply 578 case comment 579 case deletion 580 } 581 582 struct TeraThreadEntry: Sendable, Equatable, Hashable, Identifiable { 583 let id: String 584 let authorPublicKey: String 585 let content: String 586 let authoredAtUnixSeconds: UInt64 587 let type: TeraThreadEntryType 588 let root: String 589 let parentEventID: String 590 let authorProfile: TeraProfileSummary? 591 } 592 593 enum TeraCardLifecycleState: String, Sendable, Equatable, Hashable { 594 case active 595 case sold 596 case past 597 } 598 599 enum TeraTodayProjectionUpdate: Sendable, Equatable { 600 case incremental 601 case rebuild 602 } 603 604 enum TeraSearchResultType: Sendable, Equatable, Hashable { 605 case card 606 case profile 607 } 608 609 struct TeraSearchResult: Sendable, Equatable, Hashable, Identifiable { 610 let type: TeraSearchResultType 611 let id: String 612 let card: TeraTodayCard? 613 let profile: TeraProfileSummary? 614 } 615 616 struct TeraMeSnapshot: Sendable, Equatable { 617 let publicKey: String 618 let profile: TeraProfileSummary? 619 let cards: [TeraTodayCard] 620 } 621 622 enum TeraAddCommandType: String, CaseIterable, Sendable, Equatable, Hashable, Identifiable { 623 case createUpdate 624 case createPhotoUpdate 625 case createAsk 626 case createEvent 627 case createFoodAvailability 628 629 var id: String { 630 rawValue 631 } 632 633 var label: String { 634 switch self { 635 case .createUpdate: "Update" 636 case .createPhotoUpdate: "Photo update" 637 case .createAsk: "Ask" 638 case .createEvent: "Event" 639 case .createFoodAvailability: "Food availability" 640 } 641 } 642 643 var todayCardType: TeraTodayCardType { 644 switch self { 645 case .createUpdate: .update 646 case .createPhotoUpdate: .photoUpdate 647 case .createAsk: .ask 648 case .createEvent: .event 649 case .createFoodAvailability: .foodAvailability 650 } 651 } 652 } 653 654 enum TeraAddFieldKind: Sendable, Equatable, Hashable { 655 case text 656 case multilineText 657 case date 658 case dateTime 659 case decimal 660 case choice 661 case location 662 case media 663 } 664 665 struct TeraAddField: Sendable, Equatable, Hashable, Identifiable { 666 let schemaVersion: UInt16 667 let id: String 668 let label: String 669 let kind: TeraAddFieldKind 670 let required: Bool 671 let choices: [String] 672 let maxBytes: UInt64? 673 let maxItems: UInt16? 674 } 675 676 struct TeraAddSchema: Sendable, Equatable, Hashable, Identifiable { 677 let schemaVersion: UInt16 678 let commandType: TeraAddCommandType 679 let label: String 680 let fields: [TeraAddField] 681 682 var id: TeraAddCommandType { 683 commandType 684 } 685 } 686 687 enum TeraProductSurfaceContractError: LocalizedError, Sendable, Equatable { 688 case invalidAddSchemaInventory 689 690 var errorDescription: String? { 691 "The Add product contract does not match this app." 692 } 693 } 694 695 enum TeraProductSurfaceContract { 696 private struct MediaProfile: Equatable { 697 let required: Bool 698 let maximum: UInt16 699 } 700 701 static let supportingSurfaceIDs = ["context_picker", "search", "me", "settings"] 702 703 static var snapshot: String { 704 let cards = TeraTodayCardType.allCases.map(\.rawValue).joined(separator: ",") 705 let commands = TeraAddCommandType.allCases.map(\.rawValue).joined(separator: ",") 706 let supporting = supportingSurfaceIDs.joined(separator: ",") 707 return "today=\(cards)|add=\(commands)|support=\(supporting)" 708 } 709 710 static func validate(schemas: [TeraAddSchema]) throws -> [TeraAddSchema] { 711 let expectedCommands = TeraAddCommandType.allCases 712 guard schemas.map(\.commandType) == expectedCommands, 713 schemas.allSatisfy({ $0.schemaVersion == 1 && $0.label == $0.commandType.label }), 714 schemas.allSatisfy({ schema in 715 schema.fields.allSatisfy { $0.schemaVersion == 1 } 716 && Set(schema.fields.map(\.id)).count == schema.fields.count 717 }), 718 schemas.allSatisfy({ $0.fields.map(\.id) == expectedFieldIDs(for: $0.commandType) }), 719 schemas.allSatisfy({ $0.fields.map(\.kind) == expectedFieldKinds(for: $0.commandType) }), 720 schemas.allSatisfy({ 721 requiredFieldIDs(in: $0) == expectedRequiredFieldIDs(for: $0.commandType) 722 }), 723 schemas.allSatisfy({ mediaProfile(in: $0) == expectedMediaProfile(for: $0.commandType) }), 724 schemas.first(where: { $0.commandType == .createFoodAvailability })? 725 .fields.first(where: { $0.id == "unit" })?.choices 726 == ["g", "kg", "lb", "oz", "each", "dozen", "bunch", "punnet", "bag", "basket"] 727 else { 728 throw TeraProductSurfaceContractError.invalidAddSchemaInventory 729 } 730 return schemas 731 } 732 733 private static func expectedFieldIDs(for command: TeraAddCommandType) -> [String] { 734 switch command { 735 case .createUpdate: 736 ["content"] 737 case .createPhotoUpdate, .createAsk: 738 ["content", "media"] 739 case .createEvent: 740 ["identifier", "title", "content", "event_start", "event_end", "location", "media"] 741 case .createFoodAvailability: 742 [ 743 "identifier", "title", "summary", "content", "location", "price_amount", "currency", 744 "unit", "quantity", "media", 745 ] 746 } 747 } 748 749 private static func expectedRequiredFieldIDs(for command: TeraAddCommandType) -> Set<String> { 750 switch command { 751 case .createUpdate: 752 ["content"] 753 case .createPhotoUpdate: 754 ["content", "media"] 755 case .createAsk: 756 ["content"] 757 case .createEvent: 758 ["identifier", "title", "event_start"] 759 case .createFoodAvailability: 760 ["identifier", "title", "summary", "content", "location", "price_amount", "currency", "unit"] 761 } 762 } 763 764 private static func expectedFieldKinds( 765 for command: TeraAddCommandType 766 ) -> [TeraAddFieldKind] { 767 switch command { 768 case .createUpdate: 769 [.multilineText] 770 case .createPhotoUpdate, .createAsk: 771 [.multilineText, .media] 772 case .createEvent: 773 [.text, .text, .multilineText, .dateTime, .dateTime, .location, .media] 774 case .createFoodAvailability: 775 [ 776 .text, .text, .text, .multilineText, .location, .decimal, .choice, .choice, .decimal, 777 .media, 778 ] 779 } 780 } 781 782 private static func requiredFieldIDs(in schema: TeraAddSchema) -> Set<String> { 783 Set(schema.fields.lazy.filter(\.required).map(\.id)) 784 } 785 786 private static func expectedMediaProfile( 787 for command: TeraAddCommandType 788 ) -> MediaProfile? { 789 switch command { 790 case .createUpdate: 791 nil 792 case .createPhotoUpdate: 793 MediaProfile(required: true, maximum: 20) 794 case .createAsk: 795 MediaProfile(required: false, maximum: 20) 796 case .createEvent: 797 MediaProfile(required: false, maximum: 1) 798 case .createFoodAvailability: 799 MediaProfile(required: false, maximum: 20) 800 } 801 } 802 803 private static func mediaProfile( 804 in schema: TeraAddSchema 805 ) -> MediaProfile? { 806 let fields = schema.fields.filter { $0.kind == .media } 807 guard fields.count == 1, let field = fields.first, let maximum = field.maxItems else { 808 return nil 809 } 810 return MediaProfile(required: field.required, maximum: maximum) 811 } 812 } 813 814 enum TeraEventTiming: String, Sendable, Equatable, Hashable, CaseIterable, Identifiable { 815 case allDay 816 case timed 817 818 var id: String { 819 rawValue 820 } 821 822 var label: String { 823 self == .allDay ? "All day" : "Specific time" 824 } 825 } 826 827 struct TeraPreparedMedia: Sendable, Equatable, Hashable, Identifiable { 828 let opaqueReference: String 829 let remoteURL: String? 830 let sha256: String 831 let mediaType: String 832 let byteSize: UInt64 833 let width: UInt32 834 let height: UInt32 835 var alt: String 836 let preparedAtUnixSeconds: UInt64 837 838 var id: String { 839 opaqueReference 840 } 841 } 842 843 struct TeraAddForm: Sendable, Equatable, Hashable { 844 var commandType: TeraAddCommandType 845 var content: String = "" 846 var identifier: String? 847 var title: String? 848 var summary: String? 849 var location: String? 850 var eventTiming: TeraEventTiming? 851 var eventStartDate: String? 852 var eventEndDate: String? 853 var eventStartUnixSeconds: UInt64? 854 var eventEndUnixSeconds: UInt64? 855 var eventTimezone: String? 856 var priceAmount: String? 857 var currency: String? 858 var unit: String? 859 var quantity: String? 860 var foodPublishedAtUnixSeconds: UInt64? 861 var foodStatus: String? 862 var media: [TeraPreparedMedia] = [] 863 864 static func empty(_ type: TeraAddCommandType = .createUpdate) -> Self { 865 var form = Self(commandType: type) 866 if type == .createEvent { 867 form.eventTiming = .timed 868 form.eventTimezone = TimeZone.current.identifier 869 } 870 return form 871 } 872 } 873 874 struct TeraAddRuntimeInput: Sendable, Equatable { 875 let form: TeraAddForm 876 let media: [TeraPreparedMediaHandle] 877 } 878 879 enum TeraDraftKind: String, Sendable, Equatable, Hashable { 880 case add 881 case retraction 882 } 883 884 enum TeraDraftMediaStage: String, Sendable, Equatable, Hashable { 885 case pending 886 case preparing 887 case uploading 888 case verified 889 case failed 890 case orphaned 891 } 892 893 struct TeraDraftMediaStatus: Sendable, Equatable, Hashable { 894 let url: String 895 let stage: TeraDraftMediaStage 896 let uploadAttempts: UInt8 897 let verifiedAtUnixMilliseconds: UInt64? 898 let possibleOrphan: Bool 899 let orphanReasonCode: String? 900 let orphanRecordedAtUnixMilliseconds: UInt64? 901 var uploadURL: String? 902 } 903 904 struct TeraOperationSettlement: Sendable, Equatable, Hashable { 905 let artifacts: UInt16 906 let signed: UInt16 907 let admitted: UInt16 908 let pending: UInt16 909 let retryable: UInt16 910 let indeterminate: UInt16 911 let failedTerminal: UInt16 912 let cancelled: UInt16 913 let deliveryPlans: UInt16 914 let deliverySatisfied: UInt16 915 let deliveryPending: UInt16 916 let deliveryRetryable: UInt16 917 let deliveryExhausted: UInt16 918 let deliveryFailedTerminal: UInt16 919 let deliveryCancelled: UInt16 920 } 921 922 struct TeraRetractionDraftInput: Sendable, Equatable, Hashable { 923 let commandType: TeraAddCommandType 924 let targetCardID: String 925 let targetEventID: String 926 let targetKind: UInt32 927 let targetAddress: String? 928 let reason: String 929 } 930 931 struct TeraBlossomUploadIntent: Sendable, Equatable { 932 let draftID: String 933 let expectedRevision: UInt64 934 let media: TeraPreparedMediaHandle 935 } 936 937 struct TeraNativeUploadCompletion: Sendable, Equatable { 938 let draftID: String 939 let expectedRevision: UInt64 940 let media: TeraPreparedMediaHandle 941 let statusCode: UInt16 942 let responseMediaType: String? 943 let responseContentEncoding: String? 944 let responseBody: Data 945 } 946 947 enum TeraRuntimeLifecycle: Sendable, Equatable { 948 case stopped 949 case starting(generation: TeraSessionGeneration) 950 case running(generation: TeraSessionGeneration) 951 case stopping(generation: TeraSessionGeneration) 952 case failed(generation: TeraSessionGeneration, failure: TeraRuntimeFailure) 953 }