Repository navigation
Expand file tree
/
Copy pathTrUAPIHost.swift
More file actions
1748 lines (1516 loc) · 72 KB
/
Copy pathTrUAPIHost.swift
File metadata and controls
1748 lines (1516 loc) · 72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TrUAPIHost - iOS host adapter.
//
// The Rust core (compiled to `libtruapi`, surfaced through UniFFI in the
// sibling `truapi.swift` file) owns wire decoding, request
// routing, subscription lifecycle, and platform trait dispatch.
//
// This file exposes the process-owned `TrUAPIHostRuntime`, its independently
// scoped `TrUAPIProductExecution` connections, and the
// `LocalhostBridgeBootstrap` helper used to publish an execution's WS endpoint.
//
// Products running inside a `WKWebView` connect to the Rust core via the
// localhost WebSocket bridge. The bootstrap publishes its endpoint in
// `window.__truapi_localhost` for the shared container to consume.
import Foundation
import UIKit
/// Package metadata.
public enum TrUAPIHost {
public static let version = "0.1.0"
}
/// Bootstrap helper for the native localhost WebSocket bridge that a product
/// execution starts.
public enum LocalhostBridgeBootstrap {
/// Publishes the WebSocket endpoint for the product's SDK.
/// Inject at document start, before the container and product scripts.
public static func script(port: UInt16, token: String) -> String {
localhostBridgeBootstrapScript(port: port, token: token)
}
}
/// Product-scoped key-value storage provided by the embedding host.
public protocol HostStorageBackend: AnyObject, Sendable {
func read(key: String) throws -> Data?
func write(key: String, value: Data) throws
func clear(key: String) throws
}
/// Core-owned host-private storage backend. Keys are SCALE-encoded
/// `truapi::platform::CoreStorageKey` values, so embedders can persist them
/// opaquely or decode them to choose a secure backing store per slot.
public protocol HostCoreStorageBackend: AnyObject, Sendable {
func read(key: Data) throws -> Data?
func write(key: Data, value: Data) throws
func clear(key: Data) throws
}
/// Host-side callback bundle that the Rust core invokes for capabilities the
/// native shell owns. The permission split mirrors the Rust `Permissions`
/// trait:
///
/// * ``devicePermission(product:request:)`` handles OS-scoped grants
/// (camera, mic, location).
/// * ``remotePermission(product:request:)`` handles per-product capability
/// bundles.
///
/// The Rust core invokes callbacks on its shared background bridge executor.
/// Async callbacks must suspend while waiting for a decision; blocking their
/// thread stalls other TrUAPI traffic. Synchronous callbacks must return promptly.
/// Run UI work on the main actor, for example with `await MainActor.run { ... }`.
public protocol HostBridge: AnyObject, Sendable {
/// Lifecycle logger. Marker is a stable slug, detail is free-form.
func onCoreLog(marker: String, detail: String)
/// Structured lifecycle fact. Marker is the same stable slug
/// ``onCoreLog(marker:detail:)`` carries, and each attribute is a key the
/// core names with a label, a count or a condition under it. Hand these to
/// the reporter as attributes, so a marker can be grouped and filtered by
/// what it carries. Every marker here is listed in the table
/// `coreMarkers()` returns, and its class decides what the host may do
/// with it, exactly as for a log line.
func onCoreEvent(marker: String, attributes: [CoreAttribute])
/// Open a URL in the system browser, suspending for any approval on the main actor.
func navigateTo(url: String) async throws
/// Uncover (`true`) or cover (`false`) the face under this execution's page. Answers
/// `.notPresented` when the product is not under its card and `.userMoving` while the user
/// moves the card. Defaults to `.unsupported`, so an app without cards says so.
func setExpandedCardFaceShown(shown: Bool) async throws -> ExpandedCardFaceOutcome
/// Turn this execution's expanded card so its back (`true`) or its front
/// (`false`) is up. Answers `.noBack` when the card has no back to show,
/// and the face call's outcomes otherwise, without waiting for the
/// animation. Defaults to `.unsupported`, so an app that cannot turn cards
/// says so.
func setExpandedCardBackShown(shown: Bool) async throws -> ExpandedCardTurnOutcome
/// Deliver a push notification (`HostPushNotificationRequest`)
/// and return the host-assigned notification id. Run any UI work on the main actor.
func pushNotification(request: HostPushNotificationRequest) async throws -> UInt32
/// Cancel a previously scheduled notification id.
func cancelNotification(id: UInt32) throws
/// Prompt for a device-level permission `product` requested on the main
/// actor, suspending until the user decides. Preserve the approval lifetime.
func devicePermission(
product: ProductExecutionConfig,
request: HostDevicePermissionRequest
) async throws -> PermissionDecision
/// Report the OS status of a device capability without prompting. Answer
/// from the platform's authorization APIs, for example
/// `AVCaptureDevice.authorizationStatus(for:)` or
/// `UNUserNotificationCenter.getNotificationSettings`.
///
/// The core calls this before every device-permission request and status
/// read, so it must not show UI. A capability your app has no OS gate for
/// answers `.notApplicable`, which leaves the stored product decision
/// governing. Defaults to `.notApplicable`, so an app that does not
/// implement it keeps today's behaviour.
func devicePermissionStatus(request: HostDevicePermissionRequest) async throws
-> DevicePermissionStatus
/// Prompt for a remote permission bundle `product` requested on the main
/// actor, suspending until the user decides.
func remotePermission(
product: ProductExecutionConfig,
request: RemotePermission
) async throws -> PermissionDecision
/// Observe an auth state change, in transition order: render `.pairing` as
/// the pairing QR UI, `.connected`/`.disconnected` as the account badge,
/// and `.loginFailed` as a retryable error, unless its `kind` is
/// `.noFreeAllowanceSlots`, which is unlikely to succeed before the period
/// rolls over, so retry should not be the primary action. A pairing host's
/// session activation reports its outcome even
/// when it is the default `.disconnected`, so a host that awaits activation
/// before routing never has to read silence as "signed out"; every other
/// emission, and every emission on a host role that has no session
/// activation, happens only when the state actually changes.
/// Invoked on the dispatcher thread; hand the state to the main thread and
/// return promptly.
func authStateChanged(state: AuthState)
/// Open a JSON-RPC chain connection and return a host-assigned id, or nil if unsupported.
func chainConnect(genesisHash: Data) throws -> UInt32?
/// Send one JSON-RPC request on a native chain connection.
func chainSend(connectionId: UInt32, request: String) throws
/// Close a native chain connection.
func chainClose(connectionId: UInt32) throws
/// Confirm one user-reviewed core action before it continues.
func confirmUserAction(review: UserConfirmationReview) async throws -> Bool
/// Preserve the selected lifetime for identity and account access consent.
func confirmPermission(review: UserConfirmationReview) async throws -> PermissionDecision
/// Return the current preimage value for `key`, or nil for a miss.
func lookupPreimage(key: Data) async throws -> Data?
/// Return the current host theme. Hosts with no named themes report
/// `ThemeName.default`.
func currentTheme() throws -> HostThemeSubscribeItem
/// Return the language this host presents its interface in, as a BCP 47
/// tag. Hosts with no in-app language picker report the system language.
func currentLocale() throws -> HostLocaleSubscribeItem
/// Answer a feature-support query. Invoked on the dispatcher thread; must
/// return promptly.
func featureSupported(request: HostFeatureSupportedRequest) async throws -> Bool
/// The chains this host builds as V5 general transactions, each with its
/// transaction extension pipeline; every other chain is built as V4. The
/// core builds its own extrinsics the same way. Defaults to none.
func transactionExtensionVersions() async throws -> ExtensionVersionMap
/// Request a product worker transition. `.start` means run the worker now;
/// `.stop` means it is no longer needed and may stop. Every
/// transition arrives here in ledger order, the ones the app asks for by
/// taking a reference of its own included.
///
/// Demand is runtime-wide, so the core invokes this only on the bridge
/// ``TrUAPIHostRuntime/init(bridge:runtimeConfig:)`` was given, never on
/// the per-execution bridge passed to
/// ``TrUAPIHostRuntime/openProductExecution(bridge:configuration:chat:game:)``.
/// Can arrive on any thread, including synchronously on the calling
/// thread during `acquireWorker`/`releaseWorker`, often the main thread
/// and re-entrantly: hand the transition off rather than blocking on
/// another thread from inside it. Defaults to a no-op for a host that
/// runs no workers.
func requestWorkerTransition(productId: ProductId, transition: WorkerTransition)
/// The product's worker crashed `crashes` times in a row while it was
/// needed: tell the user that product is not working. The core keeps
/// starting it again, waiting longer each time, so this needs no answer.
/// Can arrive on any thread. Defaults to a no-op.
func workerCrashing(productId: ProductId, crashes: UInt32)
/// Begin a pending operation, whose id keeps the product's worker alive
/// until it ends. `label` is a log/UI hint, empty when the product gave none.
func beginOperation(productId: ProductId, label: String) async throws -> UInt32
/// End a pending operation. Idempotent: an unknown or already-ended id
/// succeeds, so a retry after an ambiguous failure is safe.
func endOperation(productId: ProductId, id: UInt32) async throws
/// A device finished pairing with this signing host.
///
/// The core has no chat of its own, so announcing the new device to the
/// user's existing contacts is the host's to do. At least once per
/// pairing, and the host keeps its own record of which devices it has
/// already seen: a resumed pairing reports nothing and the core has no
/// list to replay. Arrives on the thread answering the handshake, while
/// the pairing call is still running: hand the device off rather than
/// announcing it inline. Defaults to a no-op for a host that answers no
/// pairing.
func devicePaired(device: PairedSsoPeer)
/// Whether the core has durable transactions still awaiting a verdict.
/// While `pending` is true, keep a background task running that awaits
/// ``TrUAPIHostRuntime/runDurableRecovery()``; false means nothing needs
/// it. Reported on change, starting with the state the runtime finds at
/// launch. Runtime-wide, like `requestWorkerTransition`, and arrives on a
/// core thread: hand it off rather than blocking. Defaults to a no-op
/// for a host that runs no durable work.
func durableWorkChanged(pending: Bool)
/// The 32-byte id of the current app installation, created on first use.
/// NFT purse item keys are derived under it, so it must be the id the
/// host registers for recovery. Runtime-wide, like `durableWorkChanged`.
/// Defaults to a rejection for a host that keeps no installation id.
func currentInstallation() async throws -> Data
/// A value the host keeps encrypted at rest, such as in the Keychain with
/// a `ThisDeviceOnly` accessibility. Return `nil` when nothing is stored
/// under `key`, and throw when the store cannot be read or the value no
/// longer decrypts. The core keeps secrets here that its database must
/// not hold. Runtime-wide, like `durableWorkChanged`. Defaults to a
/// rejection for a host with no such store, which turns off the features
/// that need it.
func encryptedStorageRead(key: Data) async throws -> Data?
/// Stores `value` under `key`, encrypted at rest and excluded from
/// backups, replacing any earlier value. Runtime-wide, like
/// `durableWorkChanged`. Defaults to a rejection.
func encryptedStorageWrite(key: Data, value: Data) async throws
/// Deletes the value stored under `key`. Deleting nothing succeeds.
/// Runtime-wide, like `durableWorkChanged`. Defaults to a rejection.
func encryptedStorageDelete(key: Data) async throws
/// Remove every value `productId` keeps in product storage. Idempotent.
/// Runtime-wide, like `durableWorkChanged`: the core calls it from
/// `TrUAPIHostRuntime.clearProductState`, when the product may have no
/// execution and so no bridge of its own. Every key the product owns
/// starts with
/// `truapi:product-storage:v1:<UTF-8 byte length of the id>:<id>:`, so a
/// shared store removes keys with that prefix and a store kept per
/// product drops that product's store. Defaults to a rejection, so
/// clearing the product's state fails on a host that has not implemented
/// it.
func clearProductStorage(productId: ProductId) throws
/// Scoped key-value storage for the Rust core.
var storage: HostStorageBackend { get }
/// Core-owned host-private storage for auth session, pairing identity,
/// and persisted permission decisions.
var coreStorage: HostCoreStorageBackend { get }
}
/// Native Chat storage and UI surface. Implement and pass to
/// ``TrUAPIHostRuntime/openProductExecution(bridge:configuration:chat:game:)``
/// when the host supports the Chat modality; hosts without it pass nothing.
/// Native Chat storage and UI surface, called from the process-wide dispatch
/// pool shared by every product execution: implementations must be safe to
/// enter concurrently.
///
/// Throw ``HostRejection`` (or an error conforming to `LocalizedError`) to
/// decline a call. A plain `Error` reaches the product as its type name alone,
/// because a value's stored properties would otherwise cross to it.
public protocol ChatHostBridge: AnyObject, Sendable {
/// Create or resolve a native product Chat room. The core has bounded and
/// normalized these arguments and screened the icon scheme; escaping them
/// for the surface that renders them is still the host's job.
func createRoom(roomId: String, name: String, icon: String) async throws
-> ChatRoomRegistrationStatus
/// Register or resolve a native product Chat bot. The core has bounded and
/// normalized these arguments and screened the icon scheme; escaping them
/// for the surface that renders them is still the host's job.
func registerBot(botId: String, name: String, icon: String) async throws
-> ChatBotRegistrationStatus
/// Persist a product-authored message in native Chat storage. Throw for a
/// content variant this host cannot render.
///
/// The core has bounded and screened every field, but a body passes
/// through byte-for-byte and `ChatFile.sizeBytes` is an unverified product
/// assertion, so escaping and sizing remain the host's job.
///
/// The returned id is what `ActionTrigger.messageId` carries back, so it
/// must name this message for as long as the host stores it. An id
/// arriving in a `reaction` or `reactionRemoved` is product-chosen and
/// untrusted: it may name a message in another room, or none at all.
///
/// `alt` is the product's one-line description of the message, already
/// trimmed and screened, for places that list it without drawing it.
func postMessage(roomId: String, content: ChatMessageContent, alt: String?) async throws -> String
/// Set what a product's native Chat room shows below its messages, and
/// keep it until the product sets another.
func setRoomFooter(roomId: String, footer: ChatRoomFooter) async throws
/// Return the current product-scoped native Chat rooms.
func listRooms() async throws -> [ChatRoom]
}
/// Native game-reminder surface. Implement and pass to
/// ``TrUAPIHostRuntime/openProductExecution(bridge:configuration:chat:game:)``
/// when the host can hold reminders; hosts without one pass nothing. Both
/// calls are async, so an implementation may hop to the main actor to answer;
/// implementations must be safe to enter concurrently.
///
/// The host holds one reminder per product: a schedule replaces the reminder
/// the same product already holds. The core asks for no per-product consent;
/// the host asks the OS for what it needs, rings an alarm where the OS allows
/// one and delivers a notification otherwise, may add the game to the
/// calendar, keeps the reminder across app kill and reboot, and drops it once
/// the game starts.
///
/// Both calls throw ``HostRejection`` (or an error conforming to
/// `LocalizedError`) to decline. A failed schedule reaches the product as a
/// host failure carrying its reason, a failed cancel as its generic error.
public protocol GameHostBridge: AnyObject, Sendable {
/// Hold `startsAt` (Unix milliseconds, UTC) as this product's reminder,
/// replacing any it holds. Throw when the OS allows neither alarms nor
/// notifications.
func scheduleReminder(startsAt: UInt64) async throws
/// Drop this product's reminder. Dropping none succeeds.
func cancelReminder() async throws
}
/// Host-implemented contacts surface: a lookup from handles to contacts, and
/// the picker drawn over them.
///
/// Installed once on the runtime with
/// ``TrUAPIHostRuntime/setContacts(_:)``, because the list belongs to the host
/// and not to any one product. A runtime without one answers `contacts.pick`
/// with `Unsupported`.
///
/// No account reaches a product, and the accounts on the list never reach the
/// core: it asks only about the handles a transaction names, and the picker
/// returns the one person the user chose. Usernames reach the core only through
/// ``contactUsernames(productId:)``, for the game product. Omit the
/// contacts the user has blocked, from all three.
public protocol ContactsHostBridge: AnyObject, Sendable {
/// Resolve `lookup.handles` to contacts: one entry per handle, in order,
/// `nil` where none matches. A contact's handle is BLAKE2b-256 keyed with
/// `lookup.handleKey` over its 32-byte account. Called inline, so answer
/// from what is already in hand.
func contacts(lookup: HostContactLookup) throws -> HostContactMatches
/// Present the picker on behalf of `productId` and report what the user
/// did. With no contacts, answer `.noContacts` instead of drawing an empty
/// overlay.
func pickContact(productId: ProductId) async throws -> HostContactPick
/// List the dotNS usernames of the unblocked contacts the picker would
/// offer, each the bare label with no top-level domain. The core asks only
/// for the game product, so `productId` is not a filter. Called inline,
/// so answer from what is already in hand. Defaults to `.unsupported`.
func contactUsernames(productId: ProductId) throws -> HostContactUsernames
}
public extension ContactsHostBridge {
func contactUsernames(productId _: ProductId) throws -> HostContactUsernames {
.unsupported
}
}
/// Host-implemented top-up engine: claims a source's funds into the user's
/// balance.
///
/// Installed once on the runtime with ``TrUAPIHostRuntime/setTopUp(_:)``.
/// The core has already checked the session and the source keys; a
/// `productAccount` source arrives as its derivation index for the host to
/// derive. The host owns claiming, retries, partial claims, persistence and
/// scoping ids to the product. A runtime without one answers `topUp` and
/// `topUpStatusSubscribe` with `Unsupported`.
public protocol TopUpHostBridge: AnyObject, Sendable {
/// Start `request` for `productId`, returning once the host has accepted
/// it. Throw a `HostPaymentTopUpError` to answer with its code; anything
/// else reaches the product as `Unknown`.
func topUp(productId: ProductId, request: HostPaymentTopUpRequest) async throws
/// Follow `productId`'s top-up `id` on the engine, pushing each status
/// it reports with
/// ``TrUAPIHostRuntime/notifyTopUpStatus(productId:id:status:)``, and
/// return when the engine's stream ends. Throw `TopUpNotFound` when the
/// engine holds no such top-up. The core cancels the call once it has a
/// final status.
func followTopUp(productId: ProductId, id: Data) async throws
}
/// Host-implemented payment engine: pays from the user's balance to an
/// account once the user approves.
///
/// Installed once on the runtime with ``TrUAPIHostRuntime/setPayments(_:)``.
/// Answer `InsufficientBalance` whenever the balance is short: the core turns
/// it into `Rejected` for a product without balance access. A runtime without
/// one answers `request` and `statusSubscribe` with `Unsupported`.
public protocol PaymentHostBridge: AnyObject, Sendable {
/// Ask the user to approve `request` for `productId`, returning once the
/// user authorized it and the host took it on. Throw a `HostPaymentError`
/// to answer with its code; anything else reaches the product as
/// `Unknown`.
func requestPayment(productId: ProductId, request: HostPaymentRequest) async throws
/// Follow `productId`'s payment `id` on the engine, pushing each status
/// it reports with
/// ``TrUAPIHostRuntime/notifyPaymentStatus(productId:id:status:)``, and
/// return when the engine's stream ends. Throw `PaymentNotFound` when the
/// engine holds no such payment. The core cancels the call once it has a
/// final status.
func followPayment(productId: ProductId, id: Data) async throws
}
/// Host-implemented balance view: what a payment request can spend right now.
///
/// Installed once on the runtime with ``TrUAPIHostRuntime/setBalance(_:)``.
/// The core checks the product's balance access itself, so never prompt for
/// it here. A runtime without one answers `balanceSubscribe` with
/// `Unsupported`.
public protocol BalanceHostBridge: AnyObject, Sendable {
/// Follow the user's spendable balance, pushing the current one and each
/// change with ``TrUAPIHostRuntime/notifyBalance(available:)``, and
/// return when the stream ends. The core cancels the call once no product
/// follows the balance, and calls again when one does.
func followBalance() async throws
}
/// Draws the viewfinder for `scanner.scan`, following the rules on the core's
/// `ScannerPlatform`. Closes it when the task is cancelled.
public protocol ScannerHostBridge: AnyObject, Sendable {
func scanCode(
productId: ProductId,
executionKind: ExecutableKind,
request: HostScannerScanRequest
) async throws -> HostScan
}
public extension HostBridge {
/// Default no-op logger. Override to plumb into your logging framework.
func onCoreLog(marker: String, detail: String) {}
func onCoreEvent(marker: String, attributes: [CoreAttribute]) {}
func pushNotification(request: HostPushNotificationRequest) async throws -> UInt32 { 0 }
func cancelNotification(id: UInt32) throws {}
func authStateChanged(state: AuthState) {}
func chainConnect(genesisHash: Data) throws -> UInt32? { nil }
func chainSend(connectionId: UInt32, request: String) throws {}
func chainClose(connectionId: UInt32) throws {}
func confirmUserAction(review: UserConfirmationReview) async throws -> Bool { false }
func confirmPermission(review: UserConfirmationReview) async throws -> PermissionDecision {
try await confirmUserAction(review: review) ? .allowAlways : .deny
}
func lookupPreimage(key: Data) async throws -> Data? { nil }
func currentTheme() throws -> HostThemeSubscribeItem {
HostThemeSubscribeItem(name: .default, variant: .dark)
}
func currentLocale() throws -> HostLocaleSubscribeItem {
HostLocaleSubscribeItem(
languageTag: Locale.current.language.languageCode?.identifier ?? "en"
)
}
func transactionExtensionVersions() async throws -> ExtensionVersionMap {
ExtensionVersionMap(chains: [])
}
func requestWorkerTransition(productId: ProductId, transition: WorkerTransition) {}
func workerCrashing(productId: ProductId, crashes: UInt32) {}
func devicePaired(device: PairedSsoPeer) {}
func durableWorkChanged(pending: Bool) {}
func clearProductStorage(productId _: ProductId) throws {
throw HostLocalStorageReadError.Unknown(reason: "this host does not clear product storage")
}
func currentInstallation() async throws -> Data {
throw HostRejection.Rejected(reason: "this host keeps no installation id")
}
func encryptedStorageRead(key: Data) async throws -> Data? {
throw HostRejection.Rejected(reason: "this host keeps no encrypted storage")
}
func encryptedStorageWrite(key: Data, value: Data) async throws {
throw HostRejection.Rejected(reason: "this host keeps no encrypted storage")
}
func encryptedStorageDelete(key: Data) async throws {
throw HostRejection.Rejected(reason: "this host keeps no encrypted storage")
}
func devicePermissionStatus(request: HostDevicePermissionRequest) async throws
-> DevicePermissionStatus { .notApplicable }
func setExpandedCardFaceShown(shown: Bool) async throws -> ExpandedCardFaceOutcome {
.unsupported
}
func setExpandedCardBackShown(shown: Bool) async throws -> ExpandedCardTurnOutcome {
.unsupported
}
/// Defaults opt out of worker keep-alive; override to run background work
/// past the product's surface. The id is still distinct per call, because
/// an `OperationId` names one operation: a host overriding only
/// `endOperation`, and the core's own demand accounting, both end the
/// wrong ones when every operation shares an id.
func beginOperation(productId: ProductId, label: String) async throws -> UInt32 {
defaultOperationIds.take()
}
func endOperation(productId: ProductId, id: UInt32) async throws {}
}
/// Ids handed out by the default `beginOperation`, distinct for the life of
/// the process.
private final class DefaultOperationIds: @unchecked Sendable {
private let lock = NSLock()
private var nextId: UInt32 = 1
func take() -> UInt32 {
lock.lock()
defer { lock.unlock() }
let id = nextId
// Never zero, and never traps: an id is only ever compared, so wrapping
// back to one costs nothing.
nextId = nextId == UInt32.max ? 1 : nextId + 1
return id
}
}
private let defaultOperationIds = DefaultOperationIds()
/// Adapter that bridges the public `ChatHostBridge` to the generated UniFFI
/// `NativeChatCallbacks` protocol.
private final class ChatCallbackAdapter: NativeChatCallbacks, @unchecked Sendable {
private let bridge: ChatHostBridge
init(bridge: ChatHostBridge) {
self.bridge = bridge
}
func createRoom(
roomId: String,
name: String,
icon: String
) async throws -> ChatRoomRegistrationStatus {
try await withHostRejection {
try await bridge.createRoom(roomId: roomId, name: name, icon: icon)
}
}
func registerBot(
botId: String,
name: String,
icon: String
) async throws -> ChatBotRegistrationStatus {
try await withHostRejection {
try await bridge.registerBot(botId: botId, name: name, icon: icon)
}
}
func postMessage(roomId: String, content: ChatMessageContent, alt: String?) async throws -> String {
try await withHostRejection {
try await bridge.postMessage(roomId: roomId, content: content, alt: alt)
}
}
func setRoomFooter(roomId: String, footer: ChatRoomFooter) async throws {
try await withHostRejection {
try await bridge.setRoomFooter(roomId: roomId, footer: footer)
}
}
func listRooms() async throws -> [ChatRoom] {
try await withHostRejection { try await bridge.listRooms() }
}
}
/// Adapter that bridges the public `GameHostBridge` to the generated UniFFI
/// `NativeGameCallbacks` protocol.
private final class GameCallbackAdapter: NativeGameCallbacks, @unchecked Sendable {
private let bridge: GameHostBridge
init(bridge: GameHostBridge) {
self.bridge = bridge
}
func scheduleReminder(startsAt: UInt64) async throws {
try await withHostRejection { try await bridge.scheduleReminder(startsAt: startsAt) }
}
func cancelReminder() async throws {
try await withHostRejection { try await bridge.cancelReminder() }
}
}
/// Adapter that bridges the public `ContactsHostBridge` to the generated
/// UniFFI `NativeContactsCallbacks` protocol.
private final class ContactsCallbackAdapter: NativeContactsCallbacks, @unchecked Sendable {
private let bridge: ContactsHostBridge
init(bridge: ContactsHostBridge) {
self.bridge = bridge
}
func contacts(lookup: HostContactLookup) throws -> HostContactMatches {
try withHostRejection { try bridge.contacts(lookup: lookup) }
}
func pickContact(productId: ProductId) async throws -> HostContactPick {
try await withHostRejection { try await bridge.pickContact(productId: productId) }
}
func contactUsernames(productId: ProductId) throws -> HostContactUsernames {
try withHostRejection { try bridge.contactUsernames(productId: productId) }
}
}
/// Adapter that bridges the public `ScannerHostBridge` to the generated UniFFI
/// `NativeScannerCallbacks` protocol.
private final class ScannerCallbackAdapter: NativeScannerCallbacks, @unchecked Sendable {
private let bridge: ScannerHostBridge
init(bridge: ScannerHostBridge) {
self.bridge = bridge
}
func scanCode(
productId: ProductId,
executionKind: ExecutableKind,
request: HostScannerScanRequest
) async throws -> HostScan {
try await withHostRejection {
try await bridge.scanCode(productId: productId, executionKind: executionKind, request: request)
}
}
}
/// Adapter that bridges the public `TopUpHostBridge` to the generated UniFFI
/// `NativeTopUpCallbacks` protocol.
private final class TopUpCallbackAdapter: NativeTopUpCallbacks, @unchecked Sendable {
private let bridge: TopUpHostBridge
init(bridge: TopUpHostBridge) {
self.bridge = bridge
}
func topUp(productId: ProductId, request: HostPaymentTopUpRequest) async throws {
do {
try await bridge.topUp(productId: productId, request: request)
} catch let error as HostPaymentTopUpError {
throw error
} catch {
throw HostPaymentTopUpError.Unknown(reason: hostRejectionReason(error))
}
}
func followTopUp(productId: ProductId, id: Bytes32) async throws {
do {
try await bridge.followTopUp(productId: productId, id: id)
} catch let error as HostPaymentTopUpStatusSubscribeError {
throw error
} catch {
throw HostPaymentTopUpStatusSubscribeError.Unknown(reason: hostRejectionReason(error))
}
}
}
/// Adapter that bridges the public `PaymentHostBridge` to the generated UniFFI
/// `NativePaymentCallbacks` protocol.
private final class PaymentCallbackAdapter: NativePaymentCallbacks, @unchecked Sendable {
private let bridge: PaymentHostBridge
init(bridge: PaymentHostBridge) {
self.bridge = bridge
}
func requestPayment(productId: ProductId, request: HostPaymentRequest) async throws {
do {
try await bridge.requestPayment(productId: productId, request: request)
} catch let error as HostPaymentError {
throw error
} catch {
throw HostPaymentError.Unknown(reason: hostRejectionReason(error))
}
}
func followPayment(productId: ProductId, id: Bytes32) async throws {
do {
try await bridge.followPayment(productId: productId, id: id)
} catch let error as HostPaymentStatusSubscribeError {
throw error
} catch {
throw HostPaymentStatusSubscribeError.Unknown(reason: hostRejectionReason(error))
}
}
}
/// Adapter that bridges the public `BalanceHostBridge` to the generated UniFFI
/// `NativeBalanceCallbacks` protocol.
private final class BalanceCallbackAdapter: NativeBalanceCallbacks, @unchecked Sendable {
private let bridge: BalanceHostBridge
init(bridge: BalanceHostBridge) {
self.bridge = bridge
}
func followBalance() async throws {
do {
try await bridge.followBalance()
} catch let error as HostRejection {
throw error
} catch {
throw HostRejection.Rejected(reason: hostRejectionReason(error))
}
}
}
/// Adapter that bridges the public `HostBridge` to the generated UniFFI
/// `HostCallbacks` protocol. Kept private so the generated names never
/// leak into consumers.
private final class HostCallbackAdapter: HostCallbacks, @unchecked Sendable {
private let bridge: HostBridge
init(bridge: HostBridge) {
self.bridge = bridge
}
func onCoreLog(marker: String, detail: String) {
bridge.onCoreLog(marker: marker, detail: detail)
}
func onCoreEvent(marker: String, attributes: [CoreAttribute]) {
bridge.onCoreEvent(marker: marker, attributes: attributes)
}
func requestWorkerTransition(productId: ProductId, transition: WorkerTransition) {
bridge.requestWorkerTransition(productId: productId, transition: transition)
}
func workerCrashing(productId: ProductId, crashes: UInt32) {
bridge.workerCrashing(productId: productId, crashes: crashes)
}
func devicePaired(device: PairedSsoPeer) {
bridge.devicePaired(device: device)
}
func durableWorkChanged(pending: Bool) {
bridge.durableWorkChanged(pending: pending)
}
func currentInstallation() async throws -> Data {
try await withHostRejection {
try await bridge.currentInstallation()
}
}
func encryptedStorageRead(key: Data) async throws -> Data? {
try await withHostRejection {
try await bridge.encryptedStorageRead(key: key)
}
}
func encryptedStorageWrite(key: Data, value: Data) async throws {
try await withHostRejection {
try await bridge.encryptedStorageWrite(key: key, value: value)
}
}
func encryptedStorageDelete(key: Data) async throws {
try await withHostRejection {
try await bridge.encryptedStorageDelete(key: key)
}
}
func navigateTo(url: String) async throws {
try await withNavigationRejection {
try await bridge.navigateTo(url: url)
}
}
func pushNotification(request: HostPushNotificationRequest) async throws -> UInt32 {
try await withHostRejection {
try await bridge.pushNotification(request: request)
}
}
func cancelNotification(id: UInt32) throws {
try withHostRejection {
try bridge.cancelNotification(id: id)
}
}
func devicePermission(
product: ProductExecutionConfig,
request: HostDevicePermissionRequest
) async throws -> PermissionDecision {
try await withHostRejection {
try await bridge.devicePermission(
product: product,
request: request
)
}
}
func devicePermissionStatus(request: HostDevicePermissionRequest) async throws
-> DevicePermissionStatus
{
try await withHostRejection {
try await bridge.devicePermissionStatus(request: request)
}
}
func setExpandedCardFaceShown(shown: Bool) async throws -> ExpandedCardFaceOutcome {
try await withHostRejection {
try await bridge.setExpandedCardFaceShown(shown: shown)
}
}
func setExpandedCardBackShown(shown: Bool) async throws -> ExpandedCardTurnOutcome {
try await withHostRejection {
try await bridge.setExpandedCardBackShown(shown: shown)
}
}
func remotePermission(
product: ProductExecutionConfig,
request: RemotePermission
) async throws -> PermissionDecision {
try await withHostRejection {
try await bridge.remotePermission(
product: product,
request: request
)
}
}
func authStateChanged(state: AuthState) {
bridge.authStateChanged(state: state)
}
func coreStorageRead(key: Data) throws -> Data? {
try withHostRejection {
try bridge.coreStorage.read(key: key)
}
}
func coreStorageWrite(key: Data, value: Data) throws {
try withHostRejection {
try bridge.coreStorage.write(key: key, value: value)
}
}
func coreStorageClear(key: Data) throws {
try withHostRejection {
try bridge.coreStorage.clear(key: key)
}
}
func chainConnect(genesisHash: Data) throws -> UInt32? {
try withHostRejection {
try bridge.chainConnect(genesisHash: genesisHash)
}
}
func chainSend(connectionId: UInt32, request: String) throws {
try withHostRejection {
try bridge.chainSend(connectionId: connectionId, request: request)
}
}
func chainClose(connectionId: UInt32) throws {
try withHostRejection {
try bridge.chainClose(connectionId: connectionId)
}
}
func confirmUserAction(review: UserConfirmationReview) async throws -> Bool {
try await withHostRejection {
try await bridge.confirmUserAction(review: review)
}
}
func confirmPermission(review: UserConfirmationReview) async throws -> PermissionDecision {
try await withHostRejection {
try await bridge.confirmPermission(review: review)
}
}
func lookupPreimage(key: Data) async throws -> Data? {
try await withHostRejection {
try await bridge.lookupPreimage(key: key)
}
}
func currentTheme() throws -> HostThemeSubscribeItem {
try withHostRejection {
try bridge.currentTheme()
}
}
func currentLocale() throws -> HostLocaleSubscribeItem {
try withHostRejection {
try bridge.currentLocale()
}
}
func featureSupported(request: HostFeatureSupportedRequest) async throws -> Bool {
try await withHostRejection {
try await bridge.featureSupported(request: request)
}
}
func transactionExtensionVersions() async throws -> ExtensionVersionMap {
try await withHostRejection {
try await bridge.transactionExtensionVersions()
}
}
func localStorageRead(key: String) throws -> Data? {
try withStorageError {
try bridge.storage.read(key: key)
}
}
func localStorageWrite(key: String, value: Data) throws {
try withStorageError {
try bridge.storage.write(key: key, value: value)
}
}
func localStorageClear(key: String) throws {
try withStorageError {
try bridge.storage.clear(key: key)
}
}
func clearProductStorage(productId: ProductId) throws {
try withStorageError {
try bridge.clearProductStorage(productId: productId)
}
}
func beginOperation(productId: ProductId, label: String) async throws -> UInt32 {
try await withHostRejection {
try await bridge.beginOperation(productId: productId, label: label)
}
}
func endOperation(productId: ProductId, id: UInt32) async throws {
try await withHostRejection {
try await bridge.endOperation(productId: productId, id: id)
}
}
private func withNavigationRejection<T>(_ operation: () throws -> T) throws -> T {
do {
return try operation()
} catch let error as HostNavigateToError {
throw error
} catch {
throw HostNavigateToError.Unknown(reason: hostRejectionReason(error))
}
}
private func withNavigationRejection<T>(_ operation: () async throws -> T) async throws -> T {
do {
return try await operation()
} catch let error as HostNavigateToError {
throw error
} catch {
throw HostNavigateToError.Unknown(reason: hostRejectionReason(error))
}
}
private func withStorageError<T>(_ operation: () throws -> T) throws -> T {
do {
return try operation()
} catch let error as HostLocalStorageReadError {
throw error
} catch {
throw HostLocalStorageReadError.Unknown(reason: hostRejectionReason(error))
}
}
}
/// Process-owned Rust host runtime. Product executables open independent
/// connections from this object and share its authentication and core services.
public final class TrUAPIHostRuntime: @unchecked Sendable {
private let inner: NativeTrUApiHostRuntime
private let callbackRetainer: HostCallbacks
private let notificationCenter: NotificationCenter
private let foregroundObserver: NSObjectProtocol
private var contactsRetainer: NativeContactsCallbacks?
private var topUpRetainer: NativeTopUpCallbacks?
private var paymentsRetainer: NativePaymentCallbacks?