@mdbase-dev/sdk 0.1.0-beta.186 → 0.1.0-beta.188

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 (167) hide show
  1. package/README.md +189 -925
  2. package/dist/app-grant/client.js +7 -3
  3. package/dist/app-grant/client.js.map +1 -1
  4. package/dist/app-grant/setup.js +2 -2
  5. package/dist/app-grant/setup.js.map +1 -1
  6. package/dist/app-host/cloud-copy-host.js +1 -1
  7. package/dist/app-host/cloud-copy-host.js.map +1 -1
  8. package/dist/app-host/collection-readiness.js +10 -12
  9. package/dist/app-host/collection-readiness.js.map +1 -1
  10. package/dist/app-host/handover.js +1 -1
  11. package/dist/app-host/handover.js.map +1 -1
  12. package/dist/app-host/initial-sync.js +4 -4
  13. package/dist/app-host/initial-sync.js.map +1 -1
  14. package/dist/app-host/installation-sign-in.d.ts +3 -0
  15. package/dist/app-host/installation-sign-in.js +11 -2
  16. package/dist/app-host/installation-sign-in.js.map +1 -1
  17. package/dist/app-host/web-sign-in-session.d.ts +2 -0
  18. package/dist/app-host/web-sign-in-session.js +25 -3
  19. package/dist/app-host/web-sign-in-session.js.map +1 -1
  20. package/dist/application/asset-pins.json +4 -4
  21. package/dist/application/browser-capabilities.d.ts +1 -1
  22. package/dist/application/browser-capabilities.js +3 -2
  23. package/dist/application/browser-capabilities.js.map +1 -1
  24. package/dist/application/configuration.js +12 -12
  25. package/dist/application/configuration.js.map +1 -1
  26. package/dist/application/entry.d.ts +69 -108
  27. package/dist/application/entry.js +164 -91
  28. package/dist/application/entry.js.map +1 -1
  29. package/dist/application/front-door.d.ts +30 -12
  30. package/dist/application/front-door.js +2 -89
  31. package/dist/application/front-door.js.map +1 -1
  32. package/dist/application/packaged-assets.d.ts +5 -2
  33. package/dist/application/packaged-assets.js +9 -6
  34. package/dist/application/packaged-assets.js.map +1 -1
  35. package/dist/application/phase.d.ts +4 -1
  36. package/dist/application/phase.js +5 -4
  37. package/dist/application/phase.js.map +1 -1
  38. package/dist/application/private-collections.js +2 -1
  39. package/dist/application/private-collections.js.map +1 -1
  40. package/dist/application/registration-refusal.d.ts +1 -1
  41. package/dist/application/registration-refusal.js +1 -3
  42. package/dist/application/registration-refusal.js.map +1 -1
  43. package/dist/application/registration.js +1 -4
  44. package/dist/application/registration.js.map +1 -1
  45. package/dist/application/setup.d.ts +6 -9
  46. package/dist/application/setup.js +16 -0
  47. package/dist/application/setup.js.map +1 -1
  48. package/dist/application/tabs.d.ts +15 -2
  49. package/dist/application/tabs.js +35 -13
  50. package/dist/application/tabs.js.map +1 -1
  51. package/dist/application/unsynced-transfer.d.ts +1 -1
  52. package/dist/application/unsynced-transfer.js +3 -3
  53. package/dist/application/unsynced-transfer.js.map +1 -1
  54. package/dist/application/worker.js +969 -465
  55. package/dist/application/worker.js.map +1 -1
  56. package/dist/browser/mdbase-sdk.js +21319 -20764
  57. package/dist/browser/mdbase-sdk.min.js +65 -65
  58. package/dist/browser.d.ts +1 -0
  59. package/dist/browser.js +1 -0
  60. package/dist/browser.js.map +1 -1
  61. package/dist/client.d.ts +169 -81
  62. package/dist/client.js +236 -178
  63. package/dist/client.js.map +1 -1
  64. package/dist/codec.d.ts +15 -0
  65. package/dist/codec.js +44 -2
  66. package/dist/codec.js.map +1 -1
  67. package/dist/collection-api.d.ts +44 -0
  68. package/dist/collection-api.js +24 -0
  69. package/dist/collection-api.js.map +1 -0
  70. package/dist/collection-availability.js +1 -1
  71. package/dist/collection-availability.js.map +1 -1
  72. package/dist/contract-query.d.ts +22 -3
  73. package/dist/contract-query.js.map +1 -1
  74. package/dist/contract-records.d.ts +2 -1
  75. package/dist/contract-records.js.map +1 -1
  76. package/dist/describe-error.d.ts +1 -1
  77. package/dist/describe-error.js +7 -6
  78. package/dist/describe-error.js.map +1 -1
  79. package/dist/errors.d.ts +3 -5
  80. package/dist/errors.js +3 -8
  81. package/dist/errors.js.map +1 -1
  82. package/dist/files.d.ts +7 -5
  83. package/dist/files.js +16 -17
  84. package/dist/files.js.map +1 -1
  85. package/dist/holds.d.ts +2 -1
  86. package/dist/holds.js.map +1 -1
  87. package/dist/index.d.ts +7 -11
  88. package/dist/index.js +5 -7
  89. package/dist/index.js.map +1 -1
  90. package/dist/live.d.ts +2 -1
  91. package/dist/live.js.map +1 -1
  92. package/dist/manifest.d.ts +1 -1
  93. package/dist/manifest.js +1 -1
  94. package/dist/native/provenance.json +5 -5
  95. package/dist/native/runtime.wasm +0 -0
  96. package/dist/people.js +3 -7
  97. package/dist/people.js.map +1 -1
  98. package/dist/plain.d.ts +102 -0
  99. package/dist/plain.js +62 -0
  100. package/dist/plain.js.map +1 -0
  101. package/dist/presence.d.ts +2 -1
  102. package/dist/presence.js +3 -3
  103. package/dist/presence.js.map +1 -1
  104. package/dist/read-helpers.d.ts +8 -6
  105. package/dist/read-helpers.js +20 -13
  106. package/dist/read-helpers.js.map +1 -1
  107. package/dist/record-set.d.ts +98 -0
  108. package/dist/record-set.js +347 -0
  109. package/dist/record-set.js.map +1 -0
  110. package/dist/records/session.d.ts +2 -1
  111. package/dist/records/session.js +22 -20
  112. package/dist/records/session.js.map +1 -1
  113. package/dist/records/types.d.ts +5 -3
  114. package/dist/records/witness.d.ts +7 -4
  115. package/dist/records/witness.js +13 -8
  116. package/dist/records/witness.js.map +1 -1
  117. package/dist/records.js +5 -2
  118. package/dist/records.js.map +1 -1
  119. package/dist/saved-views.d.ts +12 -4
  120. package/dist/saved-views.js +51 -43
  121. package/dist/saved-views.js.map +1 -1
  122. package/dist/settle.d.ts +62 -0
  123. package/dist/settle.js +119 -0
  124. package/dist/settle.js.map +1 -0
  125. package/dist/status.d.ts +84 -28
  126. package/dist/status.js +54 -48
  127. package/dist/status.js.map +1 -1
  128. package/dist/testing/application.d.ts +16 -9
  129. package/dist/testing/application.js +48 -45
  130. package/dist/testing/application.js.map +1 -1
  131. package/dist/testing/index.d.ts +2 -2
  132. package/dist/testing/memory-contracts.d.ts +5 -0
  133. package/dist/testing/memory-contracts.js.map +1 -1
  134. package/dist/testing/memory-replica.d.ts +58 -5
  135. package/dist/testing/memory-replica.js +126 -19
  136. package/dist/testing/memory-replica.js.map +1 -1
  137. package/dist/testing/test-app.d.ts +9 -10
  138. package/dist/testing/test-app.js +8 -17
  139. package/dist/testing/test-app.js.map +1 -1
  140. package/dist/thin-client.d.ts +15 -38
  141. package/dist/thin-client.js +11 -20
  142. package/dist/thin-client.js.map +1 -1
  143. package/dist/transport/control-route.js +1 -1
  144. package/dist/transport/control-route.js.map +1 -1
  145. package/dist/transport/relay-close.d.ts +0 -1
  146. package/dist/transport/relay-close.js +4 -2
  147. package/dist/transport/relay-close.js.map +1 -1
  148. package/dist/transport/relay-pipe.js +2 -2
  149. package/dist/transport/relay-pipe.js.map +1 -1
  150. package/dist/type-packs.js +4 -4
  151. package/dist/type-packs.js.map +1 -1
  152. package/dist/validation.d.ts +1 -1
  153. package/dist/validation.js +2 -2
  154. package/dist/validation.js.map +1 -1
  155. package/dist/values.d.ts +4 -20
  156. package/dist/values.js +3 -49
  157. package/dist/values.js.map +1 -1
  158. package/dist/view-sources.d.ts +2 -1
  159. package/dist/view-sources.js +1 -1
  160. package/dist/view-sources.js.map +1 -1
  161. package/dist/wire.d.ts +7 -3
  162. package/dist/wire.js +4 -4
  163. package/dist/wire.js.map +1 -1
  164. package/dist/write-ledger.d.ts +2 -1
  165. package/dist/write-ledger.js +3 -6
  166. package/dist/write-ledger.js.map +1 -1
  167. package/package.json +1 -1
@@ -37,9 +37,9 @@ function whenVisible(signal) {
37
37
  signal.addEventListener("abort", stop, { once: true });
38
38
  });
39
39
  }
40
- import { unresolvedSetup } from "./setup.js";
40
+ import { setupResult, unresolvedSetup } from "./setup.js";
41
41
  import { applicationPhase, SLOW_OPENING_MS } from "./phase.js";
42
- import { summarizeStatus } from "../status.js";
42
+ import { BRIEF_PENDING_MS, LONG_PENDING_MS, summarizeSync } from "../status.js";
43
43
  import { applicationForgotten } from "./forgotten.js";
44
44
  import { applicationSessionHint } from "./session-hint.js";
45
45
  import { ApplicationPrivateCollections, withPrivateCollections } from "./private-collections.js";
@@ -59,7 +59,7 @@ function withoutUnsynced(raw) {
59
59
  }
60
60
  export class MdbaseApplicationUnavailableError extends Error {
61
61
  code = "application_not_yet_available";
62
- constructor() { super("MdbaseConnect application runtime is not yet available"); this.name = "MdbaseApplicationUnavailableError"; }
62
+ constructor() { super("mdbase cannot run in this context"); this.name = "MdbaseApplicationUnavailableError"; }
63
63
  }
64
64
  const problem = Object.freeze({ code: "application_not_yet_available" });
65
65
  const facet = Object.freeze({ checking: false, assessment: null, problem });
@@ -74,14 +74,28 @@ const noSelection = Object.freeze({ state: "none", problem: null, usable: null,
74
74
  /** Honest shell where the SDK cannot host its own module Worker (SSR, Node,
75
75
  * non-browser tests, non-web origins). Performs no registration, key, Worker,
76
76
  * storage, network or popup IO and never returns a fake client/READY state. */
77
- function unavailableApplication() {
77
+ function unavailableApplication(messages) {
78
78
  const base = { status: "blocked", signIn: null, collections: Object.freeze([]), selectedCollectionId: null, problem: problem.code, timing: null, readiness, selection: noSelection };
79
- const snapshot = Object.freeze({ ...base, phase: applicationPhase(base), sync: null, writes: null, links: null });
79
+ const snapshot = Object.freeze({ ...base, phase: applicationPhase(base, messages ? { messages } : {}), sync: null, writes: null, links: null });
80
80
  const refuse = () => Promise.reject(unavailable());
81
- return Object.freeze({ getSnapshot: () => snapshot, subscribe: () => () => { }, start: refuse, authorize: refuse, select: refuse, approve: refuse, reauthorize: refuse, refreshCollectionList: refuse, requestAccess: refuse, chooseAnother: refuse,
82
- assess: refuse, configure: refuse, setup: Object.freeze({ plan: refuse, apply: refuse }), clearSelection: refuse, forget: refuse, deleteCollection: refuse, unlock: refuse, setForeground() { throw unavailable(); }, close: refuse, signOut: refuse });
81
+ return Object.freeze({ getSnapshot: () => snapshot, subscribe: () => () => { }, start: refuse, signIn: refuse, addCollection: refuse, select: refuse, approve: refuse, reauthorize: refuse, refreshCollectionList: refuse, requestAccess: refuse, chooseAnother: refuse,
82
+ assess: refuse, configure: refuse, setup: Object.freeze({ plan: refuse, apply: refuse }), forget: refuse, deleteCollection: refuse, unlock: refuse, connection: () => null, setForeground() { throw unavailable(); }, close: refuse, signOut: refuse,
83
+ unsynced: Object.freeze({ open: refuse, planTransfer: refuse, transfer: refuse, discard: refuse }) });
84
+ }
85
+ /** A host factory's Worker may come from another realm (a parent document's
86
+ * `Worker`), so it is checked by shape rather than `instanceof`. */
87
+ const isWorker = (value) => typeof value === "object" && value !== null &&
88
+ ["postMessage", "terminate", "addEventListener", "removeEventListener"].every(name => typeof value[name] === "function");
89
+ const browserHost = (origin, runsWorker) => (!runsWorker || typeof Worker === "function") && typeof MessageChannel === "function" && currentAppOrigin() !== null && isAppOrigin(origin);
90
+ function sessionOption(value) {
91
+ if (value === undefined)
92
+ return { build: null, host: true };
93
+ if (!value || typeof value !== "object" || typeof value.build !== "string" || !value.build || value.build.length > 128 || /[\u0000-\u001f\u007f]/.test(value.build))
94
+ throw new TypeError("session.build must be a short non-empty string");
95
+ if (value.host !== undefined && typeof value.host !== "boolean")
96
+ throw new TypeError("session.host must be a boolean");
97
+ return { build: value.build, host: value.host !== false };
83
98
  }
84
- const browserHost = (origin) => typeof Worker === "function" && typeof MessageChannel === "function" && currentAppOrigin() !== null && isAppOrigin(origin);
85
99
  function signInOpener(value, declaration) {
86
100
  if (value === undefined)
87
101
  return null;
@@ -134,15 +148,15 @@ function selectionMemory(namespace) {
134
148
  }
135
149
  catch { /* hint storage is optional */ } } });
136
150
  }
137
- /** The application entry. New code: `createMdbase(declaration)`, the same
138
- * entry with a strict snapshot; `MdbaseConnect` keeps its name for one cut.
139
- * Declaration-only public entry. Construction is IO-free; SDK registration,
151
+ /** The entry behind `createMdbase(declaration)`: internal, apps hold its
152
+ * `mdbase`. Declaration-only. Construction is IO-free; SDK registration,
140
153
  * same-artifact Worker and original profile/SQL start lazily on the first
141
154
  * action. The URL names the requested collection; sign-in approval decides what
142
- * opens. No app factories, private authority hooks, replacement actors or
143
- * transport-only READY. */
144
- export class MdbaseConnect {
145
- app;
155
+ * opens. No private authority hooks, replacement actors or transport-only
156
+ * READY: a host's `worker` factory only constructs the SDK's own Worker, which
157
+ * checks its bootstrap and assets as always. */
158
+ export class MdbaseEntry {
159
+ mdbase;
146
160
  declaration;
147
161
  compiled;
148
162
  lifetime = new AbortController();
@@ -175,6 +189,7 @@ export class MdbaseConnect {
175
189
  revision = 0;
176
190
  links = null;
177
191
  cpOrigin = null;
192
+ messages;
178
193
  opening = null;
179
194
  syncing = null;
180
195
  /** On-device storage policy for this origin; null where it cannot be read. */
@@ -182,6 +197,9 @@ export class MdbaseConnect {
182
197
  pendingSave = null;
183
198
  signIn;
184
199
  typeIssues;
200
+ createWorker;
201
+ /** The `session` option: the app's own build name, and whether this context may run the Worker. */
202
+ session;
185
203
  /** SDK-10: this tab's Private collections (page-side thin clients, never the Worker). */
186
204
  privates = null;
187
205
  /** Open the unsynced collection when started signed out; tried once per start. */
@@ -199,9 +217,18 @@ export class MdbaseConnect {
199
217
  throw new TypeError('readiness.typeIssues must be "block" or "degrade"');
200
218
  this.typeIssues = typeIssues;
201
219
  this.unsyncedFirst = options.unsynced === true;
220
+ if (options.urlSelection !== undefined && typeof options.urlSelection !== "boolean")
221
+ throw new TypeError("urlSelection must be a boolean");
222
+ if (options.worker !== undefined && typeof options.worker !== "function")
223
+ throw new TypeError("worker must be a function");
224
+ this.createWorker = options.worker ?? null;
225
+ this.messages = options.messages;
226
+ this.session = sessionOption(options.session);
227
+ if (!this.session.host && this.createWorker)
228
+ throw new TypeError("worker has no effect with session.host: false");
202
229
  this.signIn = signInOpener(options.signIn, this.declaration);
203
- if (!browserHost(this.declaration.origin)) {
204
- this.app = unavailableApplication();
230
+ if (!browserHost(this.declaration.origin, this.session.host)) {
231
+ this.mdbase = unavailableApplication(options.messages);
205
232
  return;
206
233
  }
207
234
  try {
@@ -217,14 +244,15 @@ export class MdbaseConnect {
217
244
  this.followPageLifecycle();
218
245
  this.followFocus();
219
246
  this.followStoragePolicy();
247
+ this.followNetwork();
220
248
  this.memory = selectionMemory(this.declaration.storage.applicationNamespace);
221
249
  if (options.privateCollections !== false)
222
250
  this.privates = new ApplicationPrivateCollections({ declaration: this.declaration, onChange: () => { this.revision++; this.notify(); } });
223
- this.selection = new ApplicationCollectionSelection({ browser: new ApplicationBrowserSelection(this.declaration.origin, {}, browserApplicationSelectionPort()),
251
+ this.selection = new ApplicationCollectionSelection({ browser: new ApplicationBrowserSelection(this.declaration.origin, {}, options.urlSelection === false ? null : browserApplicationSelectionPort()),
224
252
  session: this.selectionSession(), memory: this.memory });
225
253
  this.selection.subscribe(() => { this.unforgetApproved(); this.notify(false); });
226
254
  const view = () => this.getSnapshot();
227
- this.app = Object.freeze({ getSnapshot: view, subscribe: (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; },
255
+ this.mdbase = Object.freeze({ getSnapshot: view, subscribe: (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; },
228
256
  start: (options) => this.track(() => {
229
257
  // Until this start settles, signed out is a step towards work before
230
258
  // connecting, so the sign-in screen is not shown and then replaced.
@@ -264,20 +292,19 @@ export class MdbaseConnect {
264
292
  this.notify(false);
265
293
  } });
266
294
  }),
267
- authorize: (options) => this.track(() => this.approve(undefined, options)),
295
+ signIn: (options) => this.track(() => this.approve(undefined, options)),
268
296
  approve: (id, options) => this.track(() => this.approve(id, options)),
269
297
  reauthorize: (options) => this.track(() => {
270
298
  const selection = this.choose(), snapshot = selection.getSnapshot();
271
299
  const id = this.privates?.state()?.collectionId ?? snapshot.usable?.collectionId ?? snapshot.requested.collectionId;
272
300
  return id ? this.approve(id, options) : selection.reauthorize(options);
273
301
  }),
274
- addPrivateCollection: (options) => this.track(() => this.approve(null, options)),
302
+ addCollection: (options) => this.track(() => this.approve(null, options)),
275
303
  refreshCollectionList: (options) => this.track(() => Promise.all([this.call(runtime => runtime.queue(() => runtime.refreshCollections(options))), this.privates?.refresh(this.account()).catch(() => { })])),
276
304
  requestAccess: (request, options) => this.requestAccess(request, options),
277
305
  // The person switching collections: a pushed history entry, so Back
278
306
  // returns to the previous one. SDK corrections replace the entry.
279
307
  select: (id, options) => this.track(() => this.choose().select(id, { ...options, history: "push" })),
280
- clearSelection: (options) => this.track(() => this.choose().select(null, options)),
281
308
  chooseAnother: (options) => this.track(() => this.choose().chooseAnother(options)),
282
309
  forget: (id, options) => this.track(async () => {
283
310
  // SDK-3: hidden on this device for this account, across reloads; a later
@@ -316,34 +343,37 @@ export class MdbaseConnect {
316
343
  setup: Object.freeze({
317
344
  plan: (options) => (this.privates?.isOpen() ? this.privates.plan(options) : this.call(runtime => runtime.queue(() => runtime.planSetup(options))))
318
345
  .then(plan => unresolvedSetup(plan, this.getSnapshot().readiness)),
319
- apply: (plan, options) => this.track(() => this.privates?.isOpen() ? this.privates.apply(plan, options) : this.call(runtime => runtime.queue(() => runtime.applySetup(plan, options)))),
346
+ apply: (plan, options) => setupResult(this.track(() => this.privates?.isOpen() ? this.privates.apply(plan, options) : this.call(runtime => runtime.queue(() => runtime.applySetup(plan, options)))), view),
320
347
  }),
348
+ connection: (id) => this.connection(id),
321
349
  setForeground: (active) => this.setForeground(active), close: () => this.close(),
322
350
  signOut: (options) => this.signOut(options),
323
- planUnsyncedTransfer: (options = {}) => this.call(runtime => {
324
- const destination = this.transferDestination(null);
325
- return runtime.withUnsyncedSource((source, signal) => planUnsyncedTransfer(source.records, destination.records, { ...(options.map ? { map: options.map } : {}), ...(options.addTypes ? { addTypes: true } : {}), ledger: this.transferLedger(), signal }), options);
326
- }),
327
- transferUnsynced: (plan, options = {}) => this.call(async (runtime) => {
328
- const destination = this.transferDestination(plan?.destination ?? null);
329
- const result = await runUnsyncedTransfer(plan, destination.records, { ...(options.signal ? { signal: options.signal } : {}), ...(options.onProgress ? { onProgress: options.onProgress } : {}) });
330
- // A type that could not be added stays only in the unsynced collection's definitions.
331
- if (result.failed.length || result.failedTypes.length)
332
- return result;
333
- // Retire only when planning again finds nothing left: work saved after
334
- // the plan (here or in another tab) is not left behind.
335
- const request = options.signal ? { signal: options.signal } : {};
336
- if (!await runtime.withUnsyncedSource((source, signal) => unsyncedTransferComplete(plan, source.records, destination.records, signal), request))
337
- return result;
338
- return Object.freeze({ ...result, retired: await runtime.retireUnsynced(plan.source, plan.destination, request) });
339
- }),
340
- discardUnsynced: (options) => this.track(async () => { await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.discardUnsynced(options)); }); }),
341
- openUnsynced: (options) => this.track(async () => {
342
- const selection = this.choose();
343
- this.privates?.close();
344
- if (selection.getSnapshot().requested.collectionId !== null)
345
- await selection.select(null, { ...options, history: "replace" });
346
- await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.openUnsynced(options)); });
351
+ unsynced: Object.freeze({
352
+ planTransfer: (options = {}) => this.call(runtime => {
353
+ const destination = this.transferDestination(null);
354
+ return runtime.withUnsyncedSource((source, signal) => planUnsyncedTransfer(source.records, destination.records, { ...(options.map ? { map: options.map } : {}), ...(options.addTypes ? { addTypes: true } : {}), ledger: this.transferLedger(), signal }), options);
355
+ }),
356
+ transfer: (plan, options = {}) => this.call(async (runtime) => {
357
+ const destination = this.transferDestination(plan?.destination ?? null);
358
+ const result = await runUnsyncedTransfer(plan, destination.records, { ...(options.signal ? { signal: options.signal } : {}), ...(options.onProgress ? { onProgress: options.onProgress } : {}) });
359
+ // A type that could not be added stays only in the unsynced collection's definitions.
360
+ if (result.failed.length || result.failedTypes.length)
361
+ return result;
362
+ // Retire only when planning again finds nothing left: work saved after
363
+ // the plan (here or in another tab) is not left behind.
364
+ const request = options.signal ? { signal: options.signal } : {};
365
+ if (!await runtime.withUnsyncedSource((source, signal) => unsyncedTransferComplete(plan, source.records, destination.records, signal), request))
366
+ return result;
367
+ return Object.freeze({ ...result, retired: await runtime.retireUnsynced(plan.source, plan.destination, request) });
368
+ }),
369
+ discard: (options) => this.track(async () => { await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.discardUnsynced(options)); }); }),
370
+ open: (options) => this.track(async () => {
371
+ const selection = this.choose();
372
+ this.privates?.close();
373
+ if (selection.getSnapshot().requested.collectionId !== null)
374
+ await selection.select(null, { ...options, history: "replace" });
375
+ await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.openUnsynced(options)); });
376
+ })
347
377
  }) });
348
378
  }
349
379
  /** SDK-10: the session's snapshot with this tab's Private collections listed
@@ -372,33 +402,42 @@ export class MdbaseConnect {
372
402
  ? Object.freeze({ ...shown, collections: Object.freeze(shown.collections.filter(c => !hidden.has(c.collectionId) || c.collectionId === shown.selectedCollectionId)) }) : shown;
373
403
  const id = base.selectedCollectionId, connection = id && !this.closed ? this.privates?.connection(id) ?? this.runtime?.connection(id) ?? null : null;
374
404
  const openingUnsynced = this.unsyncedOpening > 0 && !base.unsynced && !base.signOutResult && selection.requested.collectionId === null;
375
- let phase = applicationPhase({ ...base, selection }, { connection, previous: last?.value.phase ?? null, openingUnsynced, startPending: this.selection?.startPending() ?? false, ...(this.cpOrigin ? { cpOrigin: this.cpOrigin } : {}) });
405
+ let phase = applicationPhase({ ...base, selection }, { connection, previous: last?.value.phase ?? null, openingUnsynced, startPending: this.selection?.startPending() ?? false, ...(this.cpOrigin ? { cpOrigin: this.cpOrigin } : {}), ...(this.messages ? { messages: this.messages } : {}) });
376
406
  phase = this.trackOpening(phase);
377
407
  this.timing.observe(phase);
378
- const sync = this.trackSync(phase, base.problem, base.transport ?? null, base.live ?? null);
408
+ const transport = base.transport ?? null, online = globalThis.navigator?.onLine;
409
+ const status = this.trackSync(phase, transport !== null || online === false);
379
410
  const writes = this.syncing?.writes() ?? null;
380
- const saveWarning = this.trackSaveWarning();
381
- const value = Object.freeze({ ...base, selection, phase, sync, writes, storage: this.storagePolicy, saveWarning, links: this.linksFor(id) });
411
+ const pendingForMs = this.trackPending(Math.max(status?.pending ?? 0, writes?.pending.length ?? 0));
412
+ const saveWarning = status && pendingForMs !== null
413
+ ? appSaveState(status.pending, this.storagePolicy ?? { persistent: false, installed: false }, { pendingForMs, connection: status.connection }).warning : null;
414
+ const link = this.syncing?.link();
415
+ const sync = status ? Object.freeze(summarizeSync({ status, writes, problem: base.problem, transport, live: base.live ?? null, storageWarning: saveWarning !== null,
416
+ ...(link === undefined ? {} : { link }), ...(typeof online === "boolean" ? { online } : {}), ...(pendingForMs === null ? {} : { pendingForMs }) })) : null;
417
+ const value = Object.freeze({ ...base, selection, phase, sync, storage: this.storagePolicy, saveWarning, links: this.linksFor(id) });
382
418
  this.composed = { base: raw, selection, revision: this.revision, hint, value };
383
419
  return value;
384
420
  }
385
421
  linksFor(id) {
386
422
  return this.links && id ? Object.freeze({ ...this.links, manageAccess: `${this.cpOrigin}/access?collection=${encodeURIComponent(id)}` }) : this.links;
387
423
  }
388
- /** One grace window per continuously pending replica, not per edit or request. */
389
- trackSaveWarning() {
390
- const syncing = this.syncing, status = syncing?.status, count = status?.pending ?? 0;
424
+ /** How long changes have been pending without a break, or null with none:
425
+ * one clock per continuously pending replica, not per edit or request. It
426
+ * wakes the snapshot when a save stops being brief and when it becomes long. */
427
+ trackPending(count) {
428
+ const syncing = this.syncing;
391
429
  if (this.pendingSave && (this.closed || this.hidden || !count || this.pendingSave.id !== syncing?.id))
392
430
  this.clearPendingSave();
393
- if (this.closed || this.hidden || !syncing || !status || !count)
431
+ if (this.closed || this.hidden || !syncing || !count)
394
432
  return null;
395
433
  if (!this.pendingSave) {
396
434
  const pending = { id: syncing.id, since: performance.now(), timer: null };
397
- pending.timer = setTimeout(() => { if (this.pendingSave !== pending)
398
- return; pending.timer = null; this.revision++; this.notify(false); }, 30_000);
435
+ const wake = (next) => () => { if (this.pendingSave !== pending)
436
+ return; pending.timer = next === null ? null : setTimeout(wake(null), next); this.revision++; this.notify(false); };
437
+ pending.timer = setTimeout(wake(LONG_PENDING_MS - BRIEF_PENDING_MS), BRIEF_PENDING_MS);
399
438
  this.pendingSave = pending;
400
439
  }
401
- return appSaveState(count, this.storagePolicy ?? { persistent: false, installed: false }, { pendingForMs: performance.now() - this.pendingSave.since, connection: status.connection }).warning;
440
+ return performance.now() - this.pendingSave.since;
402
441
  }
403
442
  clearPendingSave() {
404
443
  if (this.pendingSave?.timer !== null && this.pendingSave?.timer !== undefined)
@@ -421,8 +460,8 @@ export class MdbaseConnect {
421
460
  }
422
461
  return phase.kind === "opening" && this.opening.slow ? { ...phase, slow: true } : phase;
423
462
  }
424
- /** Follow the open collection's sync status while it is ready. */
425
- trackSync(phase, problem, transport, live) {
463
+ /** Follow the open collection's status, write ledger and link while it is ready. */
464
+ trackSync(phase, deferred) {
426
465
  const id = phase.kind === "ready" ? phase.collectionId : null;
427
466
  if (this.syncing && this.syncing.id !== id) {
428
467
  try {
@@ -440,10 +479,10 @@ export class MdbaseConnect {
440
479
  status = records.status;
441
480
  }
442
481
  catch { /* not yet known */ }
443
- const syncing = { id: phase.collectionId, stop: () => { }, status, writes: () => null };
482
+ const syncing = { id: phase.collectionId, stop: () => { }, status, writes: () => null, link: () => undefined };
444
483
  const changed = () => { if (this.syncing !== syncing)
445
484
  return; this.revision++; this.getSnapshot(); this.notify(false); };
446
- let offStatus = () => { }, offWrites = () => { };
485
+ let offStatus = () => { }, offWrites = () => { }, offLink = () => { };
447
486
  try {
448
487
  offStatus = records.onStatus(next => { syncing.status = next; changed(); });
449
488
  }
@@ -459,15 +498,25 @@ export class MdbaseConnect {
459
498
  } };
460
499
  }
461
500
  catch { /* no ledger */ }
462
- syncing.stop = () => { offStatus(); offWrites(); };
501
+ try {
502
+ offLink = records.onLink(changed);
503
+ syncing.link = () => { try {
504
+ return records.link;
505
+ }
506
+ catch {
507
+ return undefined;
508
+ } };
509
+ }
510
+ catch { /* link not observable */ }
511
+ syncing.stop = () => { offStatus(); offWrites(); offLink(); };
463
512
  this.syncing = syncing;
464
513
  }
465
514
  // A transport that cannot deliver writes makes pending ones "saved on this device".
466
515
  try {
467
- phase.connection.records.setTransportDeferred(transport !== null);
516
+ phase.connection.records.setTransportDeferred(deferred);
468
517
  }
469
518
  catch { /* observer only */ }
470
- return this.syncing.status ? summarizeStatus(this.syncing.status, problem, transport, live) : null;
519
+ return this.syncing.status;
471
520
  }
472
521
  nativeAuthorization(call, portal, signal) {
473
522
  if (!this.privates || this.closed || this.hidden)
@@ -612,10 +661,10 @@ export class MdbaseConnect {
612
661
  const environment = this.environment(), packaged = packagedApplicationAssets(this.declaration.environment, this.declaration.origin);
613
662
  // A browser below the SDK's feature floor fails here, once, with a typed
614
663
  // problem — before any registration, Worker, key or storage allocation.
615
- const capabilities = await this.timing.time("capabilities", () => probeBrowserCapabilities());
664
+ const capabilities = await this.timing.time("capabilities", () => probeBrowserCapabilities(undefined, this.session.host));
616
665
  this.check();
617
666
  if (!capabilities.ok)
618
- throw mdbaseError("unavailable", "This browser can't run mdbase", { reason: capabilities.problem, details: new Map([["missing", capabilities.missing.join(",")]]) });
667
+ throw mdbaseError("unavailable", "This browser can't run mdbase", { reason: capabilities.problem, details: { missing: capabilities.missing.join(",") } });
619
668
  // Registration resolves BEFORE any Worker, key, profile or DB allocation.
620
669
  // A first visit registers over the network. Work before connecting opens
621
670
  // right after, so the Worker's verified public assets are fetched during
@@ -662,12 +711,12 @@ export class MdbaseConnect {
662
711
  const tabs = this.tabsFor(signInScope), election = new AbortController();
663
712
  this.election?.abort();
664
713
  this.election = election;
665
- const role = tabs ? await this.timing.time("election", () => tabs.elect(AbortSignal.any([this.lifetime.signal, election.signal]))) : { kind: "leader" };
714
+ const role = await this.timing.time("election", () => tabs.elect(AbortSignal.any([this.lifetime.signal, election.signal])));
666
715
  if (this.closed || this.hidden || incarnation !== this.incarnation || election.signal.aborted) {
667
716
  if (role.kind === "follower")
668
717
  role.leave();
669
718
  else
670
- tabs?.resign();
719
+ tabs.resign();
671
720
  throw mdbaseError("cancelled", "Application entry fenced", "application_entry_fenced");
672
721
  }
673
722
  if (role.kind === "follower")
@@ -675,32 +724,41 @@ export class MdbaseConnect {
675
724
  const channel = new MessageChannel(), binding = crypto.randomUUID();
676
725
  let worker;
677
726
  // Literal module-relative form so app bundlers emit the SDK Worker chunk.
727
+ // A host-constructed Worker stands for the script beside this module, and
728
+ // is told that URL to load the native assets beside it.
729
+ const create = this.createWorker, hosted = create ? new URL("./worker.js", moduleUrl).href : null;
678
730
  try {
679
- worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
731
+ if (!create)
732
+ worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
733
+ else {
734
+ worker = create(hosted);
735
+ if (!isWorker(worker))
736
+ throw new TypeError("not a Worker");
737
+ }
680
738
  }
681
739
  catch {
682
- tabs?.resign();
740
+ tabs.resign();
683
741
  channel.port1.close();
684
742
  channel.port2.close();
685
743
  throw mdbaseError("unavailable", "Application Worker construction unavailable", "application_worker_unavailable");
686
744
  }
687
- const failed = (event) => { event.preventDefault(); channel.port1.dispatchEvent(new MessageEvent("messageerror")); tabs?.fault(); };
745
+ const failed = (event) => { event.preventDefault(); channel.port1.dispatchEvent(new MessageEvent("messageerror")); tabs.fault(); };
688
746
  worker.addEventListener("error", failed);
689
- const runtime = new ApplicationRuntime({ declaration, compiledManifest: this.compiled, typeIssues: this.typeIssues, cpOrigin: environment.cpOrigin, port: channel.port1, binding, releaseWorker: () => { worker.removeEventListener("error", failed); worker.terminate(); tabs?.resign(); }, nativeAuthorization: (call, portal, signal) => this.nativeAuthorization(call, portal, signal) });
747
+ const runtime = new ApplicationRuntime({ declaration, compiledManifest: this.compiled, typeIssues: this.typeIssues, cpOrigin: environment.cpOrigin, port: channel.port1, binding, releaseWorker: () => { worker.removeEventListener("error", failed); worker.terminate(); tabs.resign(); }, nativeAuthorization: (call, portal, signal) => this.nativeAuthorization(call, portal, signal) });
690
748
  try {
691
- worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, declaration, ...(storageNamespace === null ? [] : [storageNamespace])], [channel.port2]);
749
+ worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, declaration, ...(hosted !== null ? [storageNamespace, hosted] : storageNamespace === null ? [] : [storageNamespace])], [channel.port2]);
692
750
  }
693
751
  catch {
694
752
  // No startup request was accepted; the original bootstrap transfer failed.
695
753
  worker.removeEventListener("error", failed);
696
754
  worker.terminate();
697
- tabs?.resign();
755
+ tabs.resign();
698
756
  channel.port1.close();
699
757
  channel.port2.close();
700
758
  throw mdbaseError("unavailable", "Application bootstrap unavailable", "application_worker_binding");
701
759
  }
702
760
  // Other tabs of this app attach to this Worker through this page.
703
- tabs?.lead({ attach: (port, id) => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "attach", id], [port]), detach: id => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "detach", id]) });
761
+ tabs.lead({ attach: (port, id) => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "attach", id], [port]), detach: id => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "detach", id]) });
704
762
  return install(runtime);
705
763
  }).catch(error => {
706
764
  // Nothing native was allocated (no runtime installed), so a later explicit
@@ -871,15 +929,12 @@ export class MdbaseConnect {
871
929
  return;
872
930
  void this.signedOut(runtime, result);
873
931
  }
932
+ /** This context's tab group. The capability probe has already required Web
933
+ * Locks and BroadcastChannel. */
874
934
  tabsFor(scope) {
875
- if (this.tabs)
876
- return this.tabs;
877
- const locks = globalThis.navigator?.locks, Channel = globalThis.BroadcastChannel;
878
- if (!locks || typeof locks.request !== "function" || typeof Channel !== "function")
879
- return null;
880
- // The SDK module URL is per build: tabs on different builds never share a Worker.
881
- this.tabs = new ApplicationTabs({ ...scope, build: import.meta.url }, { locks, BroadcastChannel: Channel }, this.leaderLost, this.signedInElsewhere);
882
- return this.tabs;
935
+ // The SDK module URL is per build: tabs on different builds never share a
936
+ // Worker. Contexts built separately share one under the app's own build name.
937
+ return this.tabs ??= new ApplicationTabs({ ...scope, build: this.session.build === null ? import.meta.url : `app-build/${this.session.build}` }, { locks: globalThis.navigator.locks, BroadcastChannel: globalThis.BroadcastChannel }, this.leaderLost, this.signedInElsewhere, { lead: this.session.host, wanted: this.hostWanted });
883
938
  }
884
939
  /** The leader tab went away: start again, as the new leader or a follower of it.
885
940
  * If it went because the session signed out, this tab is signed out too: it
@@ -909,7 +964,15 @@ export class MdbaseConnect {
909
964
  this.snapshot = Object.freeze({ ...previous, status: "starting", problem: null, selectedCollectionId: null, readiness: emptyReadiness });
910
965
  this.notify();
911
966
  this.selection?.resync();
912
- void this.app.start().catch(() => { });
967
+ void this.mdbase.start().catch(() => { });
968
+ };
969
+ /** A context that cannot run the Worker is waiting, and none runs it: start
970
+ * as this context would on load, unless it is already starting or running. */
971
+ hostWanted = () => {
972
+ if (this.closed || this.hidden || this.signingOut || this.runtime !== null || this.initialization !== null)
973
+ return;
974
+ this.selection?.resync();
975
+ void this.mdbase.start().catch(() => { });
913
976
  };
914
977
  /** Every tab signed out, then another tab signed in again: follow that
915
978
  * session as this tab would on load (no second sign-in or approval). */
@@ -917,14 +980,14 @@ export class MdbaseConnect {
917
980
  if (this.closed || this.hidden || this.signingOut || this.runtime !== null || this.initialization !== null || this.snapshot.status !== "signed_out")
918
981
  return;
919
982
  this.selection?.resync();
920
- void this.app.start().catch(() => { });
983
+ void this.mdbase.start().catch(() => { });
921
984
  };
922
985
  setForeground(active) { this.foreground = active; this.runtime?.setForeground(active); }
923
986
  followVisibility() {
924
987
  const doc = globalThis.document;
925
988
  if (!doc || typeof doc.addEventListener !== "function")
926
989
  return;
927
- // Not through this.app: this runs from the constructor, before it exists.
990
+ // Not through this.mdbase: this runs from the constructor, before it exists.
928
991
  const sync = () => { if (!this.closed)
929
992
  this.setForeground(doc.visibilityState !== "hidden"); };
930
993
  const wake = () => { if (doc.visibilityState !== "hidden")
@@ -937,6 +1000,17 @@ export class MdbaseConnect {
937
1000
  }
938
1001
  sync();
939
1002
  }
1003
+ /** `sync.connection` says offline as soon as the browser does, not at the next failed request. */
1004
+ followNetwork() {
1005
+ // `window` in a page; a service worker hears the same events on its own global scope.
1006
+ const scope = typeof window === "undefined" ? globalThis : window;
1007
+ if (typeof scope.addEventListener !== "function")
1008
+ return;
1009
+ const changed = () => { if (this.closed)
1010
+ return; this.revision++; this.notify(false); };
1011
+ scope.addEventListener("online", changed, { signal: this.lifetime.signal });
1012
+ scope.addEventListener("offline", changed, { signal: this.lifetime.signal });
1013
+ }
940
1014
  /** Back/forward cache: a page parked there is frozen with its Worker, which
941
1015
  * would keep holding the collection lease and block the next document of
942
1016
  * this app ("busy"). On pagehide, stop the Worker synchronously (a frozen
@@ -987,7 +1061,7 @@ export class MdbaseConnect {
987
1061
  // Same path as the app's first start: fresh registration check, Worker and
988
1062
  // session; selection then reopens the requested collection.
989
1063
  this.selection?.resync();
990
- void this.app.start().catch(() => { });
1064
+ void this.mdbase.start().catch(() => { });
991
1065
  };
992
1066
  /** Fallback when tabs cannot share one Worker: another tab of this app on a
993
1067
  * different build (or one still letting go during a leader handover) holds the
@@ -1008,7 +1082,7 @@ export class MdbaseConnect {
1008
1082
  if (!current())
1009
1083
  return;
1010
1084
  this.selection?.resync();
1011
- void this.app.start().catch(() => { });
1085
+ void this.mdbase.start().catch(() => { });
1012
1086
  }, () => { this.awaitingOtherTab = false; });
1013
1087
  }
1014
1088
  close() {
@@ -1048,7 +1122,6 @@ export class MdbaseConnect {
1048
1122
  });
1049
1123
  return this.closing;
1050
1124
  }
1051
- application() { return this.app; }
1052
1125
  /** Which revisions of the unsynced collection's records are already in a
1053
1126
  * destination, shared by this browser's tabs. */
1054
1127
  transferLedger() {
@@ -1059,7 +1132,7 @@ export class MdbaseConnect {
1059
1132
  /** The tab's open, ready collection: where an unsynced transfer goes. */
1060
1133
  transferDestination(expected) {
1061
1134
  const phase = this.getSnapshot().phase;
1062
- if (phase?.kind !== "ready")
1135
+ if (phase.kind !== "ready")
1063
1136
  throw mdbaseError("invalid_request", "Open the collection to bring this work into first.", "unsynced_transfer_needs_collection");
1064
1137
  if (expected !== null && phase.collectionId !== expected)
1065
1138
  throw mdbaseError("invalid_request", "This plan is for another collection. Plan the transfer again.", "unsynced_transfer_plan_stale");