@qntx/wallet-engine 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/controller-DpNVHVsj.d.mts +2295 -0
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -362
  30. package/dist/gateway-contract.mjs +1531 -81
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -515
  37. package/dist/index.mjs +22314 -4901
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +94 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/errors-DpkJneDe.d.mts +0 -1696
  77. package/dist/registry-Deo5WQe1.d.mts +0 -25
  78. package/dist/registry-wYrcuFNc.mjs +0 -99
  79. package/dist/registry-wYrcuFNc.mjs.map +0 -1
  80. package/dist/webln-DzsI7jVb.mjs +0 -3629
  81. package/dist/webln-DzsI7jVb.mjs.map +0 -1
@@ -0,0 +1,136 @@
1
+ import { An as Controller, In as SetTimer, Rn as EngineLogger, Sn as EngineStore, _ as RequestController } from "./controller-DpNVHVsj.mjs";
2
+ import { oa as AppAvailability, sa as EligibilityResponse } from "./index-vBgfOFIh.mjs";
3
+ import { C as AppSocket, S as AppsState, _ as AppRequests, a as AppDetail, b as AppStorage, c as AppGroup, d as AppGroupState, f as AppGroups, g as AppProvider, h as AppNetworks, i as AppDefinition, l as AppGroupBase, m as AppInstance, n as AppAuthority, o as AppError, p as AppId, r as AppContext, s as AppFlow, t as AppApis, u as AppGroupPatch, v as AppStates, x as AppsEligibility, y as AppStatus } from "./types-BpvioFGo.mjs";
4
+ import { VerifyFactor, Wallet } from "@qntx/wallet";
5
+ import { ChainsApi } from "@qntx/wallet/chains";
6
+ /** One row of `AppsController.authorities`: an app's authority, or its own read failure. */
7
+ type AppAuthorityRow = {
8
+ readonly app: AppId;
9
+ } & ({
10
+ readonly authority: AppAuthority;
11
+ } | {
12
+ readonly error: AppError;
13
+ });
14
+ type CreateAppsOptions = {
15
+ readonly wallet: Wallet;
16
+ /**
17
+ * The account derivation seam every app shares — the engine's `signers.apis.account` (or the
18
+ * `chains` account api for a host composing apps without the engine).
19
+ */
20
+ readonly account: ChainsApi["account"];
21
+ readonly requests: Pick<RequestController, "prepare" | "outcome" | "reject">;
22
+ /** The chain clients an app's deposit path reads allowance/burn limits through. */
23
+ readonly networks: AppNetworks;
24
+ readonly fetch: typeof globalThis.fetch;
25
+ readonly now: () => number;
26
+ readonly setTimer: SetTimer;
27
+ readonly random: (length: number) => Uint8Array;
28
+ readonly logger: EngineLogger;
29
+ readonly openStore: () => Promise<EngineStore>;
30
+ /**
31
+ * The WebSocket factory live views stream over — `(url) => new WebSocket(url)` on any runtime
32
+ * (browser, RN, Node ≥ 22). One socket serves every subscription.
33
+ */
34
+ readonly socket: (url: string) => AppSocket;
35
+ /** The gateway base URL — eligibility is fetched through the engine's gateway client. */
36
+ readonly gateway: {
37
+ readonly url: string;
38
+ };
39
+ };
40
+ /** One registered app — the provider plus the availability set `enable`/`renew` start under. */
41
+ type AppRegistration = {
42
+ readonly provider: AppProvider;
43
+ readonly enableWhen: ReadonlyArray<Exclude<AppAvailability, "blocked">>;
44
+ };
45
+ type AppsControllerDeps = {
46
+ /** The registered apps — the controller names none of them; the map key is the id. */
47
+ readonly registrations: ReadonlyMap<AppId, AppRegistration>;
48
+ readonly wallet: Wallet;
49
+ readonly requests: Pick<RequestController, "reject">;
50
+ readonly openStore: () => Promise<EngineStore>;
51
+ /** `GET /v1/eligibility` through the gateway client — throws on transport/malformed answers. */
52
+ readonly fetchEligibility: () => Promise<EligibilityResponse>;
53
+ /**
54
+ * The constructor hands out the private flow runner once — `createApps` closes over it so each
55
+ * definition's `AppContext.flow` binds its own id through the same guards.
56
+ */
57
+ readonly bindFlow: (runner: (group: AppGroup, app: AppId, run: (flow: AppFlow) => Promise<void>) => Promise<void>) => void;
58
+ readonly now: () => number;
59
+ readonly logger: EngineLogger;
60
+ };
61
+ /**
62
+ * Per-group, per-app state machine owner. `init`/`lock` follow the engine's unlock lifecycle; host
63
+ * calls run provider flows under a per-group+app generation so a superseding call or a lock drops
64
+ * stale writes, and one flow per group+app runs at a time (`busy` otherwise).
65
+ */
66
+ declare class AppsController<G extends AppGroups = AppGroups> extends Controller<AppsState<G>> {
67
+ private readonly deps;
68
+ private engineStore;
69
+ private generation;
70
+ private readonly flowGen;
71
+ /** Group+app pairs with a flow in flight — a second enable/renew/disable is `busy`. */
72
+ private readonly busy;
73
+ /** Request ids the flows opened and have not resolved — rejected on lock/cancel. */
74
+ private readonly pendingRequests;
75
+ constructor(deps: AppsControllerDeps);
76
+ init(): Promise<void>;
77
+ destroy(): Promise<void>;
78
+ lock(): Promise<void>;
79
+ private registrationFor;
80
+ private providerFor;
81
+ private requireUnlocked;
82
+ /** The app's availability under the last ready eligibility answer — undefined otherwise. */
83
+ private availability;
84
+ /**
85
+ * `enable`/`renew` gate: unless eligibility is `ready` and the answer is one the app's
86
+ * `enableWhen` declares, the flow must not start — `unknown`/`error`, an app absent from a ready
87
+ * answer and any undeclared availability all refuse (a jurisdiction gate fails closed). This is a
88
+ * UI boundary only: `disable`/`cancel`/trading are not gated, and the platform enforces its own
89
+ * restrictions. The thrown error is the app's own type.
90
+ */
91
+ private requireAvailable;
92
+ /**
93
+ * Refetch `/v1/eligibility` and apply the overlay: `disabled` groups in a blocked jurisdiction
94
+ * read `unavailable`; groups that were only overlaid revert when the app is no longer blocked.
95
+ * Called on every unlock; hosts should call it on foreground too.
96
+ */
97
+ refreshEligibility(): Promise<void>;
98
+ private view;
99
+ private groupOf;
100
+ /** Bump the group+app's flow generation — a running flow's writes go stale — then hand out a view. */
101
+ private start;
102
+ /** Persisted terms acknowledgement — survives lock/unlock; never supersedes a running flow. */
103
+ acknowledgeTerms(group: AppGroup, app: Extract<keyof G, string>): Promise<void>;
104
+ private flow;
105
+ enable(group: AppGroup, app: Extract<keyof G, string>, input?: unknown): Promise<void>;
106
+ renew(group: AppGroup, app: Extract<keyof G, string>, input?: unknown): Promise<void>;
107
+ disable(group: AppGroup, app: Extract<keyof G, string>, options: {
108
+ readonly revoke: boolean;
109
+ readonly verify?: VerifyFactor;
110
+ }): Promise<void>;
111
+ /** Abort the running flow: supersede it (its writes die), then reject and clean up. */
112
+ cancel(group: AppGroup, app: Extract<keyof G, string>): Promise<void>;
113
+ /** Re-derive the group's state from the kernel and the apps' own reads — never a flow. */
114
+ reconcile(group: AppGroup): Promise<void>;
115
+ /**
116
+ * The venue-held authorities every app reports for `group` — display-only, unlocked like the
117
+ * other reads. An app without `authorities` contributes nothing and one's failure lands as its
118
+ * own `{ app, error }` row instead of hiding the rest.
119
+ */
120
+ authorities(group: AppGroup): Promise<ReadonlyArray<AppAuthorityRow>>;
121
+ }
122
+ /**
123
+ * The apps composition: runs each listed definition's `create` over one shared `AppContext`,
124
+ * registers its provider under its id (a duplicate id throws), and drives the controller's
125
+ * lifecycle off the wallet's lock state — the same `transition`/`schedule` chain engine.ts
126
+ * serializes on `wallet.subscribe`. The returned surface mirrors the listed definitions: only their
127
+ * apis appear next to `controller`/`destroy`, and the controller's group state is typed by them.
128
+ */
129
+ export declare function createApps<const A extends ReadonlyArray<AppDefinition<AppId, unknown>>>(options: CreateAppsOptions & {
130
+ readonly apps: A;
131
+ }): {
132
+ readonly controller: AppsController<AppStates<A>>;
133
+ readonly destroy: () => Promise<void>;
134
+ } & AppApis<A>;
135
+ export type { AppApis, AppAuthority, AppAuthorityRow, AppContext, AppDefinition, AppDetail, AppError, AppFlow, AppGroup, AppGroupBase, AppGroupPatch, AppGroupState, AppGroups, AppId, AppInstance, AppNetworks, AppProvider, AppRequests, AppSocket, AppStates, AppStatus, AppStorage, AppsController, AppsEligibility, AppsState, CreateAppsOptions };
136
+ //# sourceMappingURL=apps.d.mts.map
package/dist/apps.mjs ADDED
@@ -0,0 +1,535 @@
1
+ import { t as Controller } from "./controller-rMnaxKAH.mjs";
2
+ import { t as EngineStoreError } from "./errors-horUy5k1.mjs";
3
+ import { t as readJson } from "./json-BDwV38cj.mjs";
4
+ import { c as parseWith, r as eligibility, t as APP_ID } from "./eligibility-BfM9ybYZ.mjs";
5
+ import { t as CLIENT_ID_HEADER } from "./primitives-DbSHLZKq.mjs";
6
+ import { t as gatewaySession } from "./session-CNJFLarP.mjs";
7
+ // src/apps/storage.ts
8
+ /**
9
+ * The `AppStorage` factory: per-app records in the session EngineStore, collection `apps.<id>`,
10
+ * keys `${walletId}/${groupIndex}/${name}` (design.md 不变量 4′/12 — records are group-scoped and
11
+ * their `walletId` prefix is what the wallet-deletion prune matches). Available only while the
12
+ * controller's session store is open — every method throws `EngineStoreError("closed")` after a
13
+ * lock.
14
+ */
15
+ /**
16
+ * `store` resolves the currently open session store — `createApps` tracks the facade it hands the
17
+ * controller; tests bind a memory store directly.
18
+ */
19
+ const key = (group, name) => `${group.walletId}/${group.groupIndex}/${name}`;
20
+ function createAppStorage(id, store) {
21
+ const collection = () => {
22
+ const session = store();
23
+ if (session === void 0) throw new EngineStoreError("closed", "the vault is locked");
24
+ return session.collection(`apps.${id}`);
25
+ };
26
+ return {
27
+ get: async (group, name) => collection().get(key(group, name)),
28
+ put: async (group, name, bytes) => collection().put(key(group, name), bytes),
29
+ delete: async (group, name) => collection().delete(key(group, name)),
30
+ list: async (group) => {
31
+ const prefix = `${group.walletId}/${group.groupIndex}/`;
32
+ const names = [];
33
+ for (const stored of await collection().list()) if (stored.startsWith(prefix)) names.push(stored.slice(prefix.length));
34
+ return names;
35
+ },
36
+ groups: async () => {
37
+ const seen = /* @__PURE__ */ new Map();
38
+ for (const stored of await collection().list()) {
39
+ const first = stored.indexOf("/");
40
+ const second = stored.indexOf("/", first + 1);
41
+ const groupIndex = Number(stored.slice(first + 1, second));
42
+ if (first < 1 || second < first + 2 || !Number.isInteger(groupIndex) || groupIndex < 0) continue;
43
+ const walletId = stored.slice(0, first);
44
+ seen.set(`${walletId}/${groupIndex}`, {
45
+ walletId,
46
+ groupIndex
47
+ });
48
+ }
49
+ return [...seen.values()];
50
+ }
51
+ };
52
+ }
53
+ // src/apps/controller.ts
54
+ const COLLECTION = "apps";
55
+ const authorityError = (error) => error instanceof Error && "category" in error && typeof error.category === "string" ? {
56
+ category: error.category,
57
+ message: error.message
58
+ } : {
59
+ category: "unavailable",
60
+ message: error instanceof Error ? error.message : String(error)
61
+ };
62
+ const DEFAULT_GROUP = {
63
+ status: "disabled",
64
+ termsAcknowledged: false
65
+ };
66
+ const recordKey = (group, app) => `${group.walletId}/${group.groupIndex}/${app}`;
67
+ const groupKey = (group) => `${group.walletId}/${group.groupIndex}`;
68
+ /** Exact keys only — a record with anything else reads as absent (logged by the caller). */
69
+ const parseRecord = (raw) => {
70
+ const value = readJson(raw);
71
+ if (typeof value !== "object" || value === null) return;
72
+ if (Object.keys(value).some((k) => k !== "termsAcknowledged")) return;
73
+ if (!("termsAcknowledged" in value) || value.termsAcknowledged !== true) return;
74
+ return { termsAcknowledged: true };
75
+ };
76
+ const isGroupState = (value) => typeof value === "object" && value !== null && "status" in value && (value.status === "disabled" || value.status === "enabling" || value.status === "enabled" || value.status === "needs-reauthorization" || value.status === "needs-migration" || value.status === "unavailable");
77
+ /**
78
+ * Merge `next` under `app` into the group's row — the `Partial<G>` map is built dynamically from
79
+ * base `AppGroupState` values under registered ids, exactly the shape `G`'s key space declares.
80
+ */
81
+ const mergeGroup = (apps, app, next) => {
82
+ return {
83
+ ...apps,
84
+ [app]: next
85
+ };
86
+ };
87
+ /**
88
+ * Per-group, per-app state machine owner. `init`/`lock` follow the engine's unlock lifecycle; host
89
+ * calls run provider flows under a per-group+app generation so a superseding call or a lock drops
90
+ * stale writes, and one flow per group+app runs at a time (`busy` otherwise).
91
+ */
92
+ var AppsController = class extends Controller {
93
+ deps;
94
+ engineStore;
95
+ generation = 0;
96
+ flowGen = /* @__PURE__ */ new Map();
97
+ /** Group+app pairs with a flow in flight — a second enable/renew/disable is `busy`. */
98
+ busy = /* @__PURE__ */ new Set();
99
+ /** Request ids the flows opened and have not resolved — rejected on lock/cancel. */
100
+ pendingRequests = /* @__PURE__ */ new Set();
101
+ constructor(deps) {
102
+ super({
103
+ name: "apps",
104
+ defaultState: () => ({
105
+ locked: true,
106
+ groups: {},
107
+ eligibility: { status: "unknown" }
108
+ })
109
+ });
110
+ this.deps = deps;
111
+ deps.bindFlow(async (group, app, run) => {
112
+ await this.flow(group, app, async (_provider, view) => run(view));
113
+ });
114
+ }
115
+ async init() {
116
+ this.engineStore = await this.deps.openStore();
117
+ const collection = this.engineStore.collection(COLLECTION);
118
+ const keys = await collection.list();
119
+ const groups = {};
120
+ for (const key of keys) {
121
+ const raw = await collection.get(key);
122
+ const stored = raw === void 0 ? void 0 : parseRecord(raw);
123
+ const slash = key.lastIndexOf("/");
124
+ const group = key.slice(0, slash);
125
+ const suffix = key.slice(slash + 1);
126
+ const app = this.deps.registrations.has(suffix) ? suffix : void 0;
127
+ if (stored === void 0 || app === void 0) this.deps.logger.warn(`apps record ${key} skipped: malformed`);
128
+ else groups[group] = mergeGroup(groups[group], app, {
129
+ ...DEFAULT_GROUP,
130
+ termsAcknowledged: stored.termsAcknowledged
131
+ });
132
+ }
133
+ this.update((state) => ({
134
+ ...state,
135
+ locked: false,
136
+ groups
137
+ }));
138
+ const union = /* @__PURE__ */ new Map();
139
+ for (const key of Object.keys(groups)) {
140
+ const slash = key.lastIndexOf("/");
141
+ union.set(key, {
142
+ walletId: key.slice(0, slash),
143
+ groupIndex: Number(key.slice(slash + 1))
144
+ });
145
+ }
146
+ for (const [id, { provider }] of this.deps.registrations) {
147
+ const discovered = await provider.groups().catch((error) => {
148
+ this.deps.logger.warn(`apps groups ${id} failed`, error);
149
+ return [];
150
+ });
151
+ for (const group of discovered) union.set(groupKey(group), group);
152
+ }
153
+ await this.refreshEligibility();
154
+ for (const group of union.values()) await this.reconcile(group);
155
+ }
156
+ async destroy() {
157
+ await this.lock();
158
+ }
159
+ async lock() {
160
+ this.generation += 1;
161
+ this.flowGen.clear();
162
+ this.busy.clear();
163
+ for (const id of this.pendingRequests) this.deps.requests.reject(id);
164
+ this.pendingRequests.clear();
165
+ const store = this.engineStore;
166
+ this.engineStore = void 0;
167
+ this.update((state) => ({
168
+ ...state,
169
+ locked: true,
170
+ groups: {}
171
+ }));
172
+ await store?.close();
173
+ }
174
+ registrationFor(app) {
175
+ const registration = this.deps.registrations.get(app);
176
+ if (registration === void 0) throw new Error(`app ${app} is not implemented`);
177
+ return registration;
178
+ }
179
+ providerFor(app) {
180
+ return this.registrationFor(app).provider;
181
+ }
182
+ requireUnlocked(app) {
183
+ if (this.getState().locked) throw this.providerFor(app).error("unlock-required", "the vault is locked");
184
+ }
185
+ /** The app's availability under the last ready eligibility answer — undefined otherwise. */
186
+ availability(app) {
187
+ const { eligibility } = this.getState();
188
+ return eligibility.status === "ready" ? eligibility.apps?.[app] : void 0;
189
+ }
190
+ /**
191
+ * `enable`/`renew` gate: unless eligibility is `ready` and the answer is one the app's
192
+ * `enableWhen` declares, the flow must not start — `unknown`/`error`, an app absent from a ready
193
+ * answer and any undeclared availability all refuse (a jurisdiction gate fails closed). This is a
194
+ * UI boundary only: `disable`/`cancel`/trading are not gated, and the platform enforces its own
195
+ * restrictions. The thrown error is the app's own type.
196
+ */
197
+ requireAvailable(app) {
198
+ const availability = this.availability(app);
199
+ if (!(availability !== void 0 && this.registrationFor(app).enableWhen.some((allowed) => allowed === availability))) {
200
+ const { country, region } = this.getState().eligibility;
201
+ const where = country === void 0 || country === null ? "an unverified" : `your (${[country, region].filter(Boolean).join("-")})`;
202
+ throw this.providerFor(app).error("unavailable", `this app is not available in ${where} jurisdiction`);
203
+ }
204
+ }
205
+ /**
206
+ * Refetch `/v1/eligibility` and apply the overlay: `disabled` groups in a blocked jurisdiction
207
+ * read `unavailable`; groups that were only overlaid revert when the app is no longer blocked.
208
+ * Called on every unlock; hosts should call it on foreground too.
209
+ */
210
+ async refreshEligibility() {
211
+ if (this.getState().locked) return;
212
+ try {
213
+ const answer = await this.deps.fetchEligibility();
214
+ this.update((state) => ({
215
+ ...state,
216
+ eligibility: {
217
+ status: "ready",
218
+ apps: answer.apps,
219
+ country: answer.country,
220
+ region: answer.region,
221
+ checkedAt: this.deps.now()
222
+ }
223
+ }));
224
+ } catch (error) {
225
+ this.deps.logger.warn("apps eligibility fetch failed", error);
226
+ this.update((state) => ({
227
+ ...state,
228
+ eligibility: {
229
+ status: "error",
230
+ checkedAt: this.deps.now()
231
+ }
232
+ }));
233
+ }
234
+ const { groups, eligibility } = this.getState();
235
+ const patched = { ...groups };
236
+ let changed = false;
237
+ for (const [gkey, apps] of Object.entries(groups)) for (const [app, group] of Object.entries(apps)) {
238
+ const blocked = this.deps.registrations.has(app) && eligibility.status === "ready" && eligibility.apps?.[app] === "blocked";
239
+ if (group?.status === "disabled" && blocked) {
240
+ patched[gkey] = mergeGroup(patched[gkey], app, {
241
+ ...group,
242
+ status: "unavailable"
243
+ });
244
+ changed = true;
245
+ } else if (group?.status === "unavailable" && eligibility.status === "ready" && !blocked) {
246
+ patched[gkey] = mergeGroup(patched[gkey], app, {
247
+ ...group,
248
+ status: "disabled"
249
+ });
250
+ changed = true;
251
+ }
252
+ }
253
+ if (changed) this.update((state) => ({
254
+ ...state,
255
+ groups: patched
256
+ }));
257
+ }
258
+ view(group, app) {
259
+ const key = recordKey(group, app);
260
+ const gkey = groupKey(group);
261
+ const { generation } = this;
262
+ const myGen = this.flowGen.get(key) ?? 0;
263
+ const current = () => {
264
+ return this.getState().groups[gkey]?.[app] ?? DEFAULT_GROUP;
265
+ };
266
+ const stale = () => generation !== this.generation || (this.flowGen.get(key) ?? 0) !== myGen || this.getState().locked;
267
+ return {
268
+ current,
269
+ stale,
270
+ write: (patch) => {
271
+ if (stale()) return;
272
+ const merged = {};
273
+ for (const [field, value] of Object.entries({
274
+ ...current(),
275
+ ...patch
276
+ })) if (value !== void 0) merged[field] = value;
277
+ if (!isGroupState(merged)) return;
278
+ const next = merged.status === "disabled" && this.availability(app) === "blocked" ? {
279
+ ...merged,
280
+ status: "unavailable"
281
+ } : merged;
282
+ if (patch.requestId !== void 0) this.pendingRequests.add(patch.requestId);
283
+ if (current().requestId !== void 0 && patch.requestId !== current().requestId) this.pendingRequests.delete(current().requestId ?? "");
284
+ this.update((state) => ({
285
+ ...state,
286
+ groups: {
287
+ ...state.groups,
288
+ [gkey]: mergeGroup(state.groups[gkey], app, next)
289
+ }
290
+ }));
291
+ }
292
+ };
293
+ }
294
+ groupOf(group) {
295
+ return {
296
+ walletId: group.walletId,
297
+ groupIndex: group.groupIndex
298
+ };
299
+ }
300
+ /** Bump the group+app's flow generation — a running flow's writes go stale — then hand out a view. */
301
+ start(group, app) {
302
+ const key = recordKey(group, app);
303
+ this.flowGen.set(key, (this.flowGen.get(key) ?? 0) + 1);
304
+ return this.view(group, app);
305
+ }
306
+ /** Persisted terms acknowledgement — survives lock/unlock; never supersedes a running flow. */
307
+ async acknowledgeTerms(group, app) {
308
+ this.requireUnlocked(app);
309
+ const key = recordKey(this.groupOf(group), app);
310
+ this.view(this.groupOf(group), app).write({ termsAcknowledged: true });
311
+ const { engineStore } = this;
312
+ try {
313
+ await engineStore?.collection(COLLECTION).put(key, new TextEncoder().encode(JSON.stringify({ termsAcknowledged: true })));
314
+ } catch (error) {
315
+ this.deps.logger.warn(`apps record ${key} write failed`, error);
316
+ }
317
+ }
318
+ async flow(group, app, run) {
319
+ this.requireUnlocked(app);
320
+ const key = recordKey(group, app);
321
+ const provider = this.providerFor(app);
322
+ if (this.busy.has(key)) throw provider.error("busy", "an enablement flow is already running");
323
+ const view = this.start(this.groupOf(group), app);
324
+ this.busy.add(key);
325
+ try {
326
+ await run(provider, view);
327
+ } finally {
328
+ this.busy.delete(key);
329
+ }
330
+ }
331
+ async enable(group, app, input) {
332
+ this.requireAvailable(app);
333
+ await this.flow(group, app, async (provider, view) => provider.enable(group, view, input));
334
+ }
335
+ async renew(group, app, input) {
336
+ this.requireAvailable(app);
337
+ await this.flow(group, app, async (provider, view) => provider.renew(group, view, input));
338
+ }
339
+ async disable(group, app, options) {
340
+ await this.flow(group, app, async (provider, view) => provider.disable(group, options, view));
341
+ }
342
+ /** Abort the running flow: supersede it (its writes die), then reject and clean up. */
343
+ async cancel(group, app) {
344
+ this.requireUnlocked(app);
345
+ const provider = this.providerFor(app);
346
+ const view = this.start(this.groupOf(group), app);
347
+ await provider.cancel(this.groupOf(group), view);
348
+ }
349
+ /** Re-derive the group's state from the kernel and the apps' own reads — never a flow. */
350
+ async reconcile(group) {
351
+ if (this.getState().locked) return;
352
+ for (const [app, { provider }] of this.deps.registrations) await provider.reconcile(this.groupOf(group), this.view(this.groupOf(group), app)).catch((error) => {
353
+ this.deps.logger.warn(`apps reconcile ${app} failed`, error);
354
+ });
355
+ }
356
+ /**
357
+ * The venue-held authorities every app reports for `group` — display-only, unlocked like the
358
+ * other reads. An app without `authorities` contributes nothing and one's failure lands as its
359
+ * own `{ app, error }` row instead of hiding the rest.
360
+ */
361
+ async authorities(group) {
362
+ const rows = [];
363
+ for (const [app, { provider }] of this.deps.registrations) {
364
+ this.requireUnlocked(app);
365
+ if (provider.authorities === void 0) continue;
366
+ try {
367
+ for (const authority of await provider.authorities(this.groupOf(group))) rows.push({
368
+ app,
369
+ authority
370
+ });
371
+ } catch (error) {
372
+ rows.push({
373
+ app,
374
+ error: authorityError(error)
375
+ });
376
+ }
377
+ }
378
+ return rows;
379
+ }
380
+ };
381
+ /**
382
+ * The apps composition: runs each listed definition's `create` over one shared `AppContext`,
383
+ * registers its provider under its id (a duplicate id throws), and drives the controller's
384
+ * lifecycle off the wallet's lock state — the same `transition`/`schedule` chain engine.ts
385
+ * serializes on `wallet.subscribe`. The returned surface mirrors the listed definitions: only their
386
+ * apis appear next to `controller`/`destroy`, and the controller's group state is typed by them.
387
+ */
388
+ function createApps(options) {
389
+ const controllerRef = { current: void 0 };
390
+ let runFlow;
391
+ let sessionStore;
392
+ const unlocked = () => options.wallet.getSnapshot().vault === "unlocked";
393
+ const openStore = async () => {
394
+ const store = await options.openStore();
395
+ sessionStore = store;
396
+ return {
397
+ collection: (name) => store.collection(name),
398
+ close: async () => {
399
+ if (sessionStore === store) sessionStore = void 0;
400
+ return store.close();
401
+ }
402
+ };
403
+ };
404
+ const context = (id) => ({
405
+ wallet: options.wallet,
406
+ account: options.account,
407
+ requests: {
408
+ prepare: async (input) => options.requests.prepare(input, {
409
+ kind: "app",
410
+ id
411
+ }),
412
+ outcome: async (id) => options.requests.outcome(id),
413
+ reject: (id) => options.requests.reject(id)
414
+ },
415
+ networks: options.networks,
416
+ fetch: options.fetch,
417
+ now: options.now,
418
+ setTimer: options.setTimer,
419
+ random: options.random,
420
+ logger: options.logger,
421
+ socket: options.socket,
422
+ availability: () => {
423
+ const eligibility = controllerRef.current?.getState().eligibility;
424
+ return eligibility?.status === "ready" ? eligibility.apps?.[id] : void 0;
425
+ },
426
+ groupState: (group) => {
427
+ const state = controllerRef.current?.getState();
428
+ return state !== void 0 && !state.locked ? state.groups[groupKey(group)]?.[id] : void 0;
429
+ },
430
+ flow: async (group, run) => {
431
+ if (runFlow === void 0) throw new Error("apps flow is not bound");
432
+ await runFlow(group, id, run);
433
+ },
434
+ storage: createAppStorage(id, () => unlocked() ? sessionStore : void 0)
435
+ });
436
+ const registrations = /* @__PURE__ */ new Map();
437
+ const instances = [];
438
+ const apis = {};
439
+ const registered = [];
440
+ for (const definition of options.apps) {
441
+ const { id } = definition;
442
+ if (!APP_ID.test(id)) throw new Error(`app ${id} must match ^[a-z][a-z0-9-]{1,31}$`);
443
+ if (registrations.has(id)) throw new Error(`app ${id} is defined twice`);
444
+ if (definition.enableWhen.length === 0 || definition.enableWhen.some((allowed) => allowed !== "available" && allowed !== "close-only")) throw new Error(`app ${id} enableWhen must list "available" and/or "close-only"`);
445
+ const instance = definition.create(context(id));
446
+ registrations.set(id, {
447
+ provider: instance.provider,
448
+ enableWhen: definition.enableWhen
449
+ });
450
+ instances.push(instance);
451
+ apis[id] = instance.api;
452
+ registered.push(id);
453
+ }
454
+ const prune = async () => {
455
+ const store = sessionStore;
456
+ if (store === void 0) return;
457
+ const live = new Set(options.wallet.getSnapshot().wallets.map((entry) => entry.walletId));
458
+ for (const id of registered) {
459
+ const collection = store.collection(`apps.${id}`);
460
+ for (const key of await collection.list()) {
461
+ const slash = key.indexOf("/");
462
+ if (!live.has(slash === -1 ? key : key.slice(0, slash))) await collection.delete(key);
463
+ }
464
+ }
465
+ };
466
+ const clientId = gatewaySession(options.gateway.url, options.random).clientIds.service;
467
+ const eligibilityFetch = async (input) => options.fetch(input, { headers: { [CLIENT_ID_HEADER]: clientId } });
468
+ const controller = new AppsController({
469
+ registrations,
470
+ wallet: options.wallet,
471
+ bindFlow: (runner) => {
472
+ runFlow = runner;
473
+ },
474
+ fetchEligibility: async () => {
475
+ const url = new URL(eligibility.path, options.gateway.url);
476
+ const response = await eligibilityFetch(url);
477
+ if (!response.ok) throw new Error(`eligibility answered ${response.status}`);
478
+ const parsed = parseWith(eligibility.response, await response.json());
479
+ if (parsed === void 0) throw new Error("malformed eligibility response");
480
+ return parsed;
481
+ },
482
+ now: options.now,
483
+ requests: options.requests,
484
+ openStore,
485
+ logger: options.logger
486
+ });
487
+ controllerRef.current = controller;
488
+ let started = false;
489
+ let chain = Promise.resolve();
490
+ const transition = async () => {
491
+ if (unlocked() && !started) {
492
+ started = true;
493
+ try {
494
+ for (const instance of instances) await instance.unlock?.();
495
+ await controller.init();
496
+ } catch (error) {
497
+ started = false;
498
+ options.logger.warn("apps init failed", error);
499
+ }
500
+ }
501
+ if (!unlocked() && started) {
502
+ started = false;
503
+ for (const instance of instances) instance.lock?.();
504
+ await controller.lock();
505
+ }
506
+ if (unlocked() && started) await prune();
507
+ };
508
+ const schedule = () => {
509
+ const previous = chain;
510
+ chain = (async () => {
511
+ try {
512
+ await previous;
513
+ await transition();
514
+ } catch (error) {
515
+ options.logger.warn("apps lock transition failed", error);
516
+ }
517
+ })();
518
+ };
519
+ const unsubscribe = options.wallet.subscribe(schedule);
520
+ schedule();
521
+ const destroy = async () => {
522
+ unsubscribe();
523
+ for (const instance of instances) instance.close?.();
524
+ await controller.lock();
525
+ await chain;
526
+ };
527
+ return {
528
+ controller,
529
+ ...apis,
530
+ destroy
531
+ };
532
+ }
533
+ export { createApps };
534
+
535
+ //# sourceMappingURL=apps.mjs.map