@phibac/sdk 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,209 @@
1
+ // The SDK's public entry point (the package's only export): connect()
2
+ // signs in and returns a Backend with typed collections, a local cache in
3
+ // IndexedDB, an offline write queue, live updates and files.
4
+ import { Auth, POPUP_FEATURES, POPUP_NAME, popupBlocked } from "./auth.js";
5
+ import { DEFAULT_BASE_URL } from "./brand.js";
6
+ import { Cache } from "./cache.js";
7
+ import { Bus, CollectionImpl, signedOut } from "./collection.js";
8
+ import { PbError } from "./errors.js";
9
+ import { Files } from "./files.js";
10
+ import { Http } from "./http.js";
11
+ import { Live } from "./live.js";
12
+ import { Flusher, Net, asPbError } from "./queue.js";
13
+ export { PbError };
14
+ /**
15
+ * connect signs the user in if needed and returns their backend for the
16
+ * app. Call it from a click or key handler: when no sign-in is stored it
17
+ * opens the sign-in popup, which browsers allow only inside a user gesture.
18
+ *
19
+ * Whether a sign-in is stored is known only after an IndexedDB read, so a
20
+ * blank popup is opened first, synchronously, and then either sent to the
21
+ * sign-in page or closed again. Outside a gesture (navigator.userActivation
22
+ * says so) no popup is opened: a stored sign-in still works, and a missing
23
+ * one rejects with popup_blocked. No network request is needed when a
24
+ * sign-in is stored, so connect() works offline.
25
+ */
26
+ export function connect(opts) {
27
+ let popup = null;
28
+ try {
29
+ const activation = navigator.userActivation;
30
+ if (!activation || activation.isActive)
31
+ popup = window.open("", POPUP_NAME, POPUP_FEATURES);
32
+ }
33
+ catch {
34
+ popup = null;
35
+ }
36
+ return start(opts, popup);
37
+ }
38
+ async function start(opts, opened) {
39
+ let popup = opened;
40
+ try {
41
+ const base = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
42
+ const auth = new Auth({ app: opts.app, baseUrl: base });
43
+ await auth.ready;
44
+ if (!auth.signedIn) {
45
+ if (!popup || popup.closed)
46
+ throw popupBlocked();
47
+ const p = popup;
48
+ popup = null; // signIn owns it now and closes it on failure
49
+ await auth.signIn(p);
50
+ }
51
+ const origin = new URL(base).origin;
52
+ const userId = auth.userId;
53
+ const part = `${origin} ${opts.app} ${userId}`;
54
+ const cache = await Cache.open(part);
55
+ return new BackendImpl(auth, cache, base, origin, userId, part, opts.schemaMajors ?? {});
56
+ }
57
+ catch (e) {
58
+ throw asPbError(e);
59
+ }
60
+ finally {
61
+ // Every path that did not hand the popup to signIn closes it here, so
62
+ // no blank window is left open (already signed in, or a failure).
63
+ if (popup && !popup.closed)
64
+ popup.close();
65
+ }
66
+ }
67
+ /** The longest signOut() waits for work in flight before clearing the cache. */
68
+ const SIGN_OUT_WAIT_MS = 2000;
69
+ class BackendImpl {
70
+ auth;
71
+ cache;
72
+ files;
73
+ ctx;
74
+ conflicts = new Set();
75
+ /** The union of the majors every handle of a collection reads. */
76
+ versions = new Map();
77
+ channel;
78
+ onOnline = () => {
79
+ this.ctx.net.online = true;
80
+ this.ctx.flusher.kick(true);
81
+ this.ctx.live.refresh();
82
+ };
83
+ onOffline = () => {
84
+ this.ctx.net.online = false;
85
+ };
86
+ closed = false;
87
+ constructor(auth, cache, base, origin, userId, part, schemaMajors) {
88
+ this.auth = auth;
89
+ this.cache = cache;
90
+ const net = new Net(new Http(auth, base));
91
+ const bus = new Bus();
92
+ // Other tabs of this app and user share the cache: tell them what changed.
93
+ this.channel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel(`pb-cache ${part}`);
94
+ this.channel?.unref?.();
95
+ const flusher = new Flusher({
96
+ cache,
97
+ net,
98
+ lockName: `pb-queue ${part}`,
99
+ conflict: (e) => {
100
+ for (const cb of [...this.conflicts])
101
+ cb(e);
102
+ },
103
+ });
104
+ const live = new Live({ net, cache, base, versionsOf: (c) => { const v = this.versions.get(c); return v ? [...v] : undefined; } });
105
+ cache.onChange = (cols) => {
106
+ bus.emit(cols);
107
+ if (!this.closed)
108
+ this.channel?.postMessage({ collections: [...cols] });
109
+ };
110
+ if (this.channel) {
111
+ this.channel.onmessage = (ev) => {
112
+ const cols = ev.data?.collections;
113
+ if (Array.isArray(cols))
114
+ bus.emit(cols.filter((c) => typeof c === "string"));
115
+ void flusher.count().catch(() => undefined);
116
+ };
117
+ }
118
+ this.ctx = {
119
+ userId,
120
+ origin,
121
+ cache,
122
+ net,
123
+ flusher,
124
+ live,
125
+ bus,
126
+ schemaMajors,
127
+ consent: { current: null },
128
+ check: () => {
129
+ if (this.closed)
130
+ throw signedOut();
131
+ },
132
+ };
133
+ this.files = new Files(net);
134
+ window.addEventListener("online", this.onOnline);
135
+ window.addEventListener("offline", this.onOffline);
136
+ void flusher.count().then(() => {
137
+ if (flusher.pending > 0)
138
+ flusher.kick();
139
+ }, () => undefined);
140
+ }
141
+ collection(name, opts = {}) {
142
+ this.ctx.check();
143
+ if (opts.versions) {
144
+ // The changes feed and live updates keep the union of every handle's
145
+ // majors; each handle shows only its own (CollectionImpl.visible).
146
+ let set = this.versions.get(name);
147
+ const widened = set !== undefined && opts.versions.some((v) => !set.has(v));
148
+ if (!set)
149
+ this.versions.set(name, (set = new Set()));
150
+ for (const v of opts.versions)
151
+ set.add(v);
152
+ // Records of the new majors were dropped before: fetch them again.
153
+ if (widened)
154
+ this.ctx.live.granted(name);
155
+ }
156
+ return new CollectionImpl(this.ctx, name, opts);
157
+ }
158
+ onConflict(cb) {
159
+ this.conflicts.add(cb);
160
+ return () => {
161
+ this.conflicts.delete(cb);
162
+ };
163
+ }
164
+ status() {
165
+ const out = { online: this.ctx.net.online, pending: this.ctx.flusher.pending };
166
+ const problem = this.ctx.net.problem();
167
+ if (problem)
168
+ out.problem = problem;
169
+ return out;
170
+ }
171
+ /**
172
+ * signOut stops the queue and the live connection, deletes this user's
173
+ * cached records and queued writes for this app, and forgets the
174
+ * sign-in. The backend cannot be used afterwards.
175
+ */
176
+ async signOut() {
177
+ if (this.closed)
178
+ return;
179
+ this.closed = true;
180
+ this.ctx.flusher.stop();
181
+ this.ctx.live.stop();
182
+ // Cancel this tab's requests in flight, then give the work in flight a
183
+ // short while to settle. Once stopped, nothing writes to the cache
184
+ // (every writer checks before opening its transaction), so the wait is
185
+ // only politeness and never needed for correctness; it is bounded
186
+ // because a flush may be waiting on another tab's lock.
187
+ this.ctx.net.abort();
188
+ let timer;
189
+ await Promise.race([
190
+ Promise.all([this.ctx.flusher.idle(), this.ctx.live.idle()]),
191
+ new Promise((r) => (timer = setTimeout(r, SIGN_OUT_WAIT_MS))),
192
+ ]);
193
+ clearTimeout(timer);
194
+ window.removeEventListener("online", this.onOnline);
195
+ window.removeEventListener("offline", this.onOffline);
196
+ try {
197
+ await this.cache.clear();
198
+ this.cache.close();
199
+ await this.auth.signOut();
200
+ }
201
+ catch (e) {
202
+ throw asPbError(e);
203
+ }
204
+ finally {
205
+ this.channel?.close();
206
+ }
207
+ }
208
+ }
209
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,0EAA0E;AAC1E,6DAA6D;AAC7D,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,GAAG,EAAE,cAAc,EAAE,SAAS,EAAY,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAsB,MAAM,YAAY,CAAC;AAEzE,OAAO,E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AAC;YACnB,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,SAAS,CAAC,CAAC,CAAC,CAAC;QACrB,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC;QACxB,CAAC;IACH,CAAC;CACF"}
package/dist/live.d.ts ADDED
@@ -0,0 +1,116 @@
1
+ import type { Cache } from "./cache.js";
2
+ import { type Net } from "./queue.js";
3
+ export interface LiveDeps {
4
+ net: Net;
5
+ cache: Cache;
6
+ /** The server's base URL (http/https); the WebSocket uses ws/wss. */
7
+ base: string;
8
+ /** The majors the app reads of a collection, when it declared them. */
9
+ versionsOf: (collection: string) => number[] | undefined;
10
+ }
11
+ /**
12
+ * Live holds at most one WebSocket for the collections that have
13
+ * subscribers. On every open it first catches up from /v1/changes, then
14
+ * applies live changes; it reconnects with backoff (1 s doubling to 60 s)
15
+ * after lagging, revoked or a dropped connection, and stops for good on
16
+ * app_suspended or account_closed (reported through Net.problem).
17
+ */
18
+ export declare class Live {
19
+ private readonly d;
20
+ private readonly watched;
21
+ /** The collections the current (or opening) connection is for. */
22
+ private target;
23
+ private ws;
24
+ private caughtUp;
25
+ private gen;
26
+ private attempt;
27
+ private timer;
28
+ private syncQueued;
29
+ private stopped;
30
+ private halted;
31
+ /** Waiting for something to change (a permanent ticket error). */
32
+ private parked;
33
+ /** Serialises catch-ups and change application. */
34
+ private tail;
35
+ /**
36
+ * Collections the server has shown this app can read (a ticket or query
37
+ * for them succeeded). Only for these, or for a collection the changes
38
+ * feed returned a change of, is a catch-up position stored: for an
39
+ * unreadable collection the feed answers "nothing, up to the latest rev",
40
+ * and storing that would skip the history once access is granted.
41
+ */
42
+ private readonly proven;
43
+ /**
44
+ * Watched collections left out of the live connection because the server
45
+ * refused them (no consent, or unknown), so the others still get live
46
+ * updates. Cleared when access is granted or the device comes online.
47
+ */
48
+ private readonly blocked;
49
+ /** Collections whose background catch-up has started in this session. */
50
+ private readonly started;
51
+ /** Background catch-up retries, by collection. */
52
+ private readonly retries;
53
+ constructor(d: LiveDeps);
54
+ /** watch keeps collection live until the returned function is called. */
55
+ watch(collection: string): () => void;
56
+ /** Whether collection is covered by an open, caught-up connection. */
57
+ isLive(collection: string): boolean;
58
+ /**
59
+ * ensure starts collection's background catch-up the first time it is
60
+ * used in this session (reads never wait for it). A failure is retried
61
+ * with backoff and, if it fails again, shown in status().problem.
62
+ */
63
+ ensure(collection: string): void;
64
+ private background;
65
+ /** readable records that the server just served collection to this app. */
66
+ readable(collection: string): void;
67
+ /**
68
+ * unreadable forgets the catch-up positions of collections the server
69
+ * refused (consent_required, revoked): when access comes back, their
70
+ * history is fetched again from the start.
71
+ */
72
+ unreadable(collections: string[]): void;
73
+ /**
74
+ * granted is called when the user granted read access to collection (or
75
+ * the majors read of it widened): its history is fetched from the start,
76
+ * and the live connection is renewed.
77
+ */
78
+ granted(collection: string): void;
79
+ /** idle resolves once no catch-up or change is being applied. */
80
+ idle(): Promise<void>;
81
+ /**
82
+ * fresh brings collection's cache up to date from /v1/changes now, unless
83
+ * the live connection already does (used before refusing a write to a
84
+ * record the cache does not know). Offline, or when the server cannot be
85
+ * reached, the cache is used as it is.
86
+ */
87
+ fresh(collection: string): Promise<void>;
88
+ /**
89
+ * refresh reconnects now and re-runs the background catch-ups (the device
90
+ * came online, or access was granted).
91
+ */
92
+ refresh(): void;
93
+ stop(): void;
94
+ private schedule;
95
+ private sync;
96
+ private opening;
97
+ private close;
98
+ private retryLater;
99
+ private halt;
100
+ private open;
101
+ /**
102
+ * refused returns which of collections the server refused a ticket for:
103
+ * the one the error message names (the server quotes it), else each
104
+ * other app's collection (declared with versions) that a one-record read
105
+ * refuses. The app's own collections are never singled out.
106
+ */
107
+ private refused;
108
+ private serial;
109
+ /**
110
+ * catchUp applies every change since the collections' last caught-up
111
+ * revision, calling /v1/changes until the returned since stops moving,
112
+ * then stores that revision for each collection.
113
+ */
114
+ private catchUp;
115
+ private apply;
116
+ }