@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.
- package/README.md +189 -925
- package/dist/app-grant/client.js +7 -3
- package/dist/app-grant/client.js.map +1 -1
- package/dist/app-grant/setup.js +2 -2
- package/dist/app-grant/setup.js.map +1 -1
- package/dist/app-host/cloud-copy-host.js +1 -1
- package/dist/app-host/cloud-copy-host.js.map +1 -1
- package/dist/app-host/collection-readiness.js +10 -12
- package/dist/app-host/collection-readiness.js.map +1 -1
- package/dist/app-host/handover.js +1 -1
- package/dist/app-host/handover.js.map +1 -1
- package/dist/app-host/initial-sync.js +4 -4
- package/dist/app-host/initial-sync.js.map +1 -1
- package/dist/app-host/installation-sign-in.d.ts +3 -0
- package/dist/app-host/installation-sign-in.js +11 -2
- package/dist/app-host/installation-sign-in.js.map +1 -1
- package/dist/app-host/web-sign-in-session.d.ts +2 -0
- package/dist/app-host/web-sign-in-session.js +25 -3
- package/dist/app-host/web-sign-in-session.js.map +1 -1
- package/dist/application/asset-pins.json +4 -4
- package/dist/application/browser-capabilities.d.ts +1 -1
- package/dist/application/browser-capabilities.js +3 -2
- package/dist/application/browser-capabilities.js.map +1 -1
- package/dist/application/configuration.js +12 -12
- package/dist/application/configuration.js.map +1 -1
- package/dist/application/entry.d.ts +69 -108
- package/dist/application/entry.js +164 -91
- package/dist/application/entry.js.map +1 -1
- package/dist/application/front-door.d.ts +30 -12
- package/dist/application/front-door.js +2 -89
- package/dist/application/front-door.js.map +1 -1
- package/dist/application/packaged-assets.d.ts +5 -2
- package/dist/application/packaged-assets.js +9 -6
- package/dist/application/packaged-assets.js.map +1 -1
- package/dist/application/phase.d.ts +4 -1
- package/dist/application/phase.js +5 -4
- package/dist/application/phase.js.map +1 -1
- package/dist/application/private-collections.js +2 -1
- package/dist/application/private-collections.js.map +1 -1
- package/dist/application/registration-refusal.d.ts +1 -1
- package/dist/application/registration-refusal.js +1 -3
- package/dist/application/registration-refusal.js.map +1 -1
- package/dist/application/registration.js +1 -4
- package/dist/application/registration.js.map +1 -1
- package/dist/application/setup.d.ts +6 -9
- package/dist/application/setup.js +16 -0
- package/dist/application/setup.js.map +1 -1
- package/dist/application/tabs.d.ts +15 -2
- package/dist/application/tabs.js +35 -13
- package/dist/application/tabs.js.map +1 -1
- package/dist/application/unsynced-transfer.d.ts +1 -1
- package/dist/application/unsynced-transfer.js +3 -3
- package/dist/application/unsynced-transfer.js.map +1 -1
- package/dist/application/worker.js +969 -465
- package/dist/application/worker.js.map +1 -1
- package/dist/browser/mdbase-sdk.js +21319 -20764
- package/dist/browser/mdbase-sdk.min.js +65 -65
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +1 -0
- package/dist/browser.js.map +1 -1
- package/dist/client.d.ts +169 -81
- package/dist/client.js +236 -178
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts +15 -0
- package/dist/codec.js +44 -2
- package/dist/codec.js.map +1 -1
- package/dist/collection-api.d.ts +44 -0
- package/dist/collection-api.js +24 -0
- package/dist/collection-api.js.map +1 -0
- package/dist/collection-availability.js +1 -1
- package/dist/collection-availability.js.map +1 -1
- package/dist/contract-query.d.ts +22 -3
- package/dist/contract-query.js.map +1 -1
- package/dist/contract-records.d.ts +2 -1
- package/dist/contract-records.js.map +1 -1
- package/dist/describe-error.d.ts +1 -1
- package/dist/describe-error.js +7 -6
- package/dist/describe-error.js.map +1 -1
- package/dist/errors.d.ts +3 -5
- package/dist/errors.js +3 -8
- package/dist/errors.js.map +1 -1
- package/dist/files.d.ts +7 -5
- package/dist/files.js +16 -17
- package/dist/files.js.map +1 -1
- package/dist/holds.d.ts +2 -1
- package/dist/holds.js.map +1 -1
- package/dist/index.d.ts +7 -11
- package/dist/index.js +5 -7
- package/dist/index.js.map +1 -1
- package/dist/live.d.ts +2 -1
- package/dist/live.js.map +1 -1
- package/dist/manifest.d.ts +1 -1
- package/dist/manifest.js +1 -1
- package/dist/native/provenance.json +5 -5
- package/dist/native/runtime.wasm +0 -0
- package/dist/people.js +3 -7
- package/dist/people.js.map +1 -1
- package/dist/plain.d.ts +102 -0
- package/dist/plain.js +62 -0
- package/dist/plain.js.map +1 -0
- package/dist/presence.d.ts +2 -1
- package/dist/presence.js +3 -3
- package/dist/presence.js.map +1 -1
- package/dist/read-helpers.d.ts +8 -6
- package/dist/read-helpers.js +20 -13
- package/dist/read-helpers.js.map +1 -1
- package/dist/record-set.d.ts +98 -0
- package/dist/record-set.js +347 -0
- package/dist/record-set.js.map +1 -0
- package/dist/records/session.d.ts +2 -1
- package/dist/records/session.js +22 -20
- package/dist/records/session.js.map +1 -1
- package/dist/records/types.d.ts +5 -3
- package/dist/records/witness.d.ts +7 -4
- package/dist/records/witness.js +13 -8
- package/dist/records/witness.js.map +1 -1
- package/dist/records.js +5 -2
- package/dist/records.js.map +1 -1
- package/dist/saved-views.d.ts +12 -4
- package/dist/saved-views.js +51 -43
- package/dist/saved-views.js.map +1 -1
- package/dist/settle.d.ts +62 -0
- package/dist/settle.js +119 -0
- package/dist/settle.js.map +1 -0
- package/dist/status.d.ts +84 -28
- package/dist/status.js +54 -48
- package/dist/status.js.map +1 -1
- package/dist/testing/application.d.ts +16 -9
- package/dist/testing/application.js +48 -45
- package/dist/testing/application.js.map +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/memory-contracts.d.ts +5 -0
- package/dist/testing/memory-contracts.js.map +1 -1
- package/dist/testing/memory-replica.d.ts +58 -5
- package/dist/testing/memory-replica.js +126 -19
- package/dist/testing/memory-replica.js.map +1 -1
- package/dist/testing/test-app.d.ts +9 -10
- package/dist/testing/test-app.js +8 -17
- package/dist/testing/test-app.js.map +1 -1
- package/dist/thin-client.d.ts +15 -38
- package/dist/thin-client.js +11 -20
- package/dist/thin-client.js.map +1 -1
- package/dist/transport/control-route.js +1 -1
- package/dist/transport/control-route.js.map +1 -1
- package/dist/transport/relay-close.d.ts +0 -1
- package/dist/transport/relay-close.js +4 -2
- package/dist/transport/relay-close.js.map +1 -1
- package/dist/transport/relay-pipe.js +2 -2
- package/dist/transport/relay-pipe.js.map +1 -1
- package/dist/type-packs.js +4 -4
- package/dist/type-packs.js.map +1 -1
- package/dist/validation.d.ts +1 -1
- package/dist/validation.js +2 -2
- package/dist/validation.js.map +1 -1
- package/dist/values.d.ts +4 -20
- package/dist/values.js +3 -49
- package/dist/values.js.map +1 -1
- package/dist/view-sources.d.ts +2 -1
- package/dist/view-sources.js +1 -1
- package/dist/view-sources.js.map +1 -1
- package/dist/wire.d.ts +7 -3
- package/dist/wire.js +4 -4
- package/dist/wire.js.map +1 -1
- package/dist/write-ledger.d.ts +2 -1
- package/dist/write-ledger.js +3 -6
- package/dist/write-ledger.js.map +1 -1
- 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 {
|
|
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("
|
|
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,
|
|
82
|
-
assess: refuse, configure: refuse, setup: Object.freeze({ plan: refuse, apply: 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
|
|
138
|
-
*
|
|
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
|
|
143
|
-
*
|
|
144
|
-
|
|
145
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
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
|
|
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
|
|
381
|
-
const
|
|
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
|
-
/**
|
|
389
|
-
|
|
390
|
-
|
|
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 || !
|
|
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
|
-
|
|
398
|
-
return; pending.timer = null; this.revision++; this.notify(false); }
|
|
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
|
|
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
|
|
425
|
-
trackSync(phase,
|
|
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
|
-
|
|
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(
|
|
516
|
+
phase.connection.records.setTransportDeferred(deferred);
|
|
468
517
|
}
|
|
469
518
|
catch { /* observer only */ }
|
|
470
|
-
return this.syncing.status
|
|
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:
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
876
|
-
|
|
877
|
-
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
|
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");
|