@n-dream/builders-sdk 1.0.0-next.0 → 1.4.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/db.js ADDED
@@ -0,0 +1,581 @@
1
+ import { BuildersError, codeOfStatus } from "./errors.js";
2
+ import { isLocalHost, local } from "./local.js";
3
+ import { DATA_LIMITS, MESSAGES, NOT_SUPPORTED, NO_USER, USER_HEADER, compareSort, slotOf } from "./rules.js";
4
+ import { believed, claimedUser } from "./session.js";
5
+ const CODES = ["sign-in-required", "not-allowed", "not-declared", "not-supported", "too-large", "quota", "rate-limit", "conflict", "offline", "app-stopped", "preparing", "invalid", "user-changed"];
6
+ // The user guard (8.3): another user than the page believes. auth reads the
7
+ // user again (its listeners hear the change); the caller gets the error.
8
+ export function userChanged() {
9
+ void believed.refresh?.().catch(() => { });
10
+ return new BuildersError(MESSAGES.userChanged(), 409, "user-changed");
11
+ }
12
+ export function errorOf(status, body) {
13
+ const b = (typeof body === "object" && body !== null ? body : {});
14
+ const code = typeof b.error === "string" && CODES.includes(b.error) ? b.error : codeOfStatus(status);
15
+ const message = typeof b.message === "string" && b.message ? b.message : `Builders did not do it (status ${status}). Try again.`;
16
+ return new BuildersError(message, status, code);
17
+ }
18
+ // The platform: same-origin requests (docs/login-and-data.md 4.7).
19
+ // claim: the user that the page believes is signed in (the user guard);
20
+ // undefined: none named.
21
+ export function httpTransport(env, onUser, claim = claimedUser) {
22
+ async function call(method, path, body, signal, file) {
23
+ const write = method !== "GET";
24
+ // The user guard (8.3): the user that the page believes is signed in.
25
+ const claimed = await claim();
26
+ // A request never goes out without its user (the service refuses it).
27
+ if (claimed === undefined)
28
+ throw new BuildersError("Could not reach Builders to read the signed-in user. Check the connection and try again.", 0, "offline");
29
+ const who = { "x-builders": "1", [USER_HEADER]: claimed ?? NO_USER };
30
+ let res;
31
+ try {
32
+ res = await env().fetch(path, {
33
+ method,
34
+ credentials: "same-origin",
35
+ cache: "no-store",
36
+ // 4.7: a file upload is application/octet-stream, every other write JSON.
37
+ headers: write ? { accept: "application/json", "content-type": file ? "application/octet-stream" : "application/json", ...who } : { accept: "application/json", ...who },
38
+ ...(write ? { body: file ?? JSON.stringify(body ?? {}) } : {}),
39
+ ...(signal ? { signal } : {}),
40
+ });
41
+ }
42
+ catch (e) {
43
+ if (signal?.aborted)
44
+ throw e;
45
+ throw new BuildersError("Could not reach Builders. Check the connection and try again.", 0, "offline");
46
+ }
47
+ const json = await res.json().catch(() => undefined);
48
+ // An answer for another user (the session changed): not used.
49
+ const answered = res.headers.get(USER_HEADER);
50
+ if (answered !== null && answered !== (claimed ?? NO_USER))
51
+ throw userChanged();
52
+ if (!res.ok) {
53
+ const err = errorOf(res.status, json);
54
+ const retry = Number(res.headers.get("retry-after"));
55
+ if (Number.isFinite(retry) && retry > 0)
56
+ err.retryAfter = retry;
57
+ throw err;
58
+ }
59
+ if (json === undefined)
60
+ throw new BuildersError("The answer of Builders is not valid.", res.status, "invalid");
61
+ return json;
62
+ }
63
+ const base = (c, id) => `/_api/data/${encodeURIComponent(c)}${id === undefined ? "" : `/${encodeURIComponent(id)}`}`;
64
+ const query = (q) => `q=${encodeURIComponent(JSON.stringify(q ?? {}))}`;
65
+ return {
66
+ get: (c, id) => call("GET", base(c, id)),
67
+ list: (c, q) => call("GET", `${base(c)}?${query(q)}`),
68
+ count: (c, q) => call("GET", `${base(c)}?count=1&${query(q)}`),
69
+ add: (c, data) => call("POST", base(c), { data }),
70
+ set: (c, id, data, ifRev) => call("PUT", base(c, id), { data, ...(ifRev === undefined ? {} : { ifRev }) }),
71
+ update: (c, id, patch, ifRev) => call("PATCH", base(c, id), { patch, ...(ifRev === undefined ? {} : { ifRev }) }),
72
+ remove: async (c, id) => void (await call("DELETE", base(c, id))),
73
+ // With the slash: the load balancer sends /_api/data/* to the data
74
+ // service, and "/_api/data" alone to the host.
75
+ usage: () => call("GET", "/_api/data/"),
76
+ upload: (set, file, name) => {
77
+ const q = new URLSearchParams();
78
+ if (name !== undefined)
79
+ q.set("name", name);
80
+ if (file.type)
81
+ q.set("type", file.type);
82
+ const qs = q.toString();
83
+ return call("PUT", `/_api/files/${encodeURIComponent(set)}${qs ? `?${qs}` : ""}`, undefined, undefined, file);
84
+ },
85
+ listFiles: (set, q) => call("GET", `/_api/files/${encodeURIComponent(set)}?${query(q)}`),
86
+ removeFile: async (set, id) => void (await call("DELETE", `/_api/files/${encodeURIComponent(set)}/${encodeURIComponent(id)}`)),
87
+ watch: (lists, signal) => call("GET", `/_api/watch?w=${lists.map((l) => `${encodeURIComponent(l.c)}~${l.cursor}`).join(",")}`, undefined, signal),
88
+ onUser,
89
+ };
90
+ }
91
+ // An error that can go away (no connection, the platform is busy or
92
+ // paused): the watch tries again. Other errors end it.
93
+ function shortError(e) {
94
+ // user-changed: auth reads the user again; the next try names the new one.
95
+ return e.status === 0 || e.status >= 500 || e.code === "rate-limit" || e.code === "preparing" || e.code === "user-changed";
96
+ }
97
+ function matches(item, q) {
98
+ if (q.mine && !item.mine)
99
+ return false;
100
+ const data = (item.data ?? {});
101
+ for (const [f, v] of Object.entries(q.where ?? {})) {
102
+ if (slotOf(f, Object.prototype.hasOwnProperty.call(data, f) ? data[f] : undefined) !== slotOf(f, v))
103
+ return false;
104
+ }
105
+ if (q.orderBy && q.orderBy !== "createdAt" && q.orderBy !== "updatedAt") {
106
+ const s = data[q.orderBy];
107
+ if (!(typeof s === "number" && Number.isFinite(s)) && typeof s !== "string")
108
+ return false;
109
+ }
110
+ return true;
111
+ }
112
+ function sortItems(items, q) {
113
+ const dir = q.direction === "asc" ? 1 : -1;
114
+ const key = (i) => (q.orderBy === "updatedAt" ? i.updatedAt : !q.orderBy || q.orderBy === "createdAt" ? i.createdAt : i.data[q.orderBy]);
115
+ return items.sort((a, b) => dir * (compareSort(key(a), key(b)) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
116
+ }
117
+ const sleep = (ms, signal) => new Promise((resolve) => {
118
+ const t = setTimeout(resolve, ms);
119
+ signal?.addEventListener("abort", () => (clearTimeout(t), resolve()), { once: true });
120
+ });
121
+ function visible() {
122
+ const doc = globalThis.document;
123
+ if (!doc || doc.visibilityState !== "hidden")
124
+ return Promise.resolve();
125
+ return new Promise((resolve) => {
126
+ const on = () => {
127
+ if (doc.visibilityState === "hidden")
128
+ return;
129
+ doc.removeEventListener("visibilitychange", on);
130
+ resolve();
131
+ };
132
+ doc.addEventListener("visibilitychange", on);
133
+ });
134
+ }
135
+ class Watches {
136
+ t;
137
+ all = new Set();
138
+ running = false;
139
+ abort = null;
140
+ unUser = null;
141
+ // Goes up at each change of the user: an answer of an older user is not
142
+ // used.
143
+ gen = 0;
144
+ constructor(t) {
145
+ this.t = t;
146
+ }
147
+ start(w) {
148
+ this.all.add(w);
149
+ this.unUser ??= this.t().onUser(() => this.userChanged());
150
+ void this.first(w);
151
+ }
152
+ // The one way for every change of the user (auth.onChange, the local
153
+ // mode, a user-changed answer): nothing of the old user stays. Each watch
154
+ // forgets its cursor and items and lists again for the new user.
155
+ userChanged(err) {
156
+ this.gen++;
157
+ this.abort?.abort();
158
+ // First the reset of every watch (no app code runs in it) ...
159
+ const shown = [];
160
+ for (const w of [...this.all]) {
161
+ if (w.stopped)
162
+ continue;
163
+ // A watch that showed a list of the old user.
164
+ if (w.cursor !== null)
165
+ shown.push(w);
166
+ if (w.relist)
167
+ clearTimeout(w.relist);
168
+ w.relist = null;
169
+ w.cursor = null;
170
+ w.items = [];
171
+ w.full = false;
172
+ // A user-changed answer again and again waits longer, as other errors.
173
+ if (err)
174
+ w.backoff = w.backoff ? Math.min(60, w.backoff * 2) : 1;
175
+ else
176
+ w.backoff = 0;
177
+ void this.first(w, err ? 1000 * w.backoff : 0);
178
+ }
179
+ // ... then the app's functions: an error in one never stops the others.
180
+ for (const w of [...this.all]) {
181
+ if (w.stopped)
182
+ continue;
183
+ if (err) {
184
+ try {
185
+ w.onError(err);
186
+ }
187
+ catch {
188
+ // The app's onError threw: the reset is done anyway.
189
+ }
190
+ }
191
+ if (!shown.includes(w))
192
+ continue;
193
+ try {
194
+ // Nothing of the old user shows any more (also at a sign-out).
195
+ w.cb([]);
196
+ }
197
+ catch {
198
+ // The app's function threw on an empty list: the reset is done.
199
+ }
200
+ }
201
+ }
202
+ stop(w) {
203
+ w.stopped = true;
204
+ if (w.relist)
205
+ clearTimeout(w.relist);
206
+ this.all.delete(w);
207
+ if (!this.all.size) {
208
+ this.abort?.abort();
209
+ this.unUser?.();
210
+ this.unUser = null;
211
+ }
212
+ }
213
+ // The user counter now: a write reads it before its request.
214
+ get generation() {
215
+ return this.gen;
216
+ }
217
+ // The user's own writes go to the callbacks at once (9.3), unless the
218
+ // user changed since the request started (`gen`).
219
+ own(c, items, removed, gen) {
220
+ if (gen !== this.gen)
221
+ return;
222
+ for (const w of this.all)
223
+ if (w.c === c && w.cursor !== null)
224
+ this.apply(w, items, removed);
225
+ }
226
+ fail(w, e) {
227
+ if (w.stopped)
228
+ return;
229
+ this.stop(w);
230
+ w.onError(e instanceof BuildersError ? e : new BuildersError(String(e?.message ?? e), 0, "offline"));
231
+ }
232
+ async first(w, wait = 0) {
233
+ // Read before the wait: an older chain that waits does not run next to
234
+ // a newer one.
235
+ const gen = this.gen;
236
+ const token = ++w.token;
237
+ if (wait)
238
+ await sleep(wait);
239
+ if (w.stopped || token !== w.token || gen !== this.gen)
240
+ return;
241
+ try {
242
+ const page = await this.t().list(w.c, w.q);
243
+ // Stopped, or the user changed meanwhile (that change lists again).
244
+ if (w.stopped || gen !== this.gen)
245
+ return;
246
+ w.items = page.items;
247
+ w.cursor = page.cursor;
248
+ w.full = page.next !== null;
249
+ w.backoff = 0;
250
+ w.cb([...w.items]);
251
+ }
252
+ catch (e) {
253
+ const err = e instanceof BuildersError ? e : new BuildersError("Could not reach Builders.", 0, "offline");
254
+ if (gen !== this.gen || token !== w.token)
255
+ return;
256
+ if (err.code === "user-changed")
257
+ return this.userChanged(err);
258
+ if (w.stopped || !shortError(err))
259
+ return this.fail(w, err);
260
+ // Tell the app (it can show a note), and try again with the backoff
261
+ // of the long poll. The watch goes on.
262
+ w.onError(err);
263
+ const retryAfter = err.retryAfter;
264
+ w.backoff = w.backoff ? Math.min(60, w.backoff * 2) : 1;
265
+ void this.first(w, 1000 * (retryAfter ?? w.backoff));
266
+ return;
267
+ }
268
+ // A new list joins the long poll now.
269
+ this.abort?.abort();
270
+ this.loop();
271
+ }
272
+ apply(w, items, removed) {
273
+ const map = new Map(w.items.map((i) => [i.id, i]));
274
+ let changed = false;
275
+ for (const id of removed) {
276
+ // An own remove with a short id: the public id is "<user id>.<id>".
277
+ const key = map.has(id) ? id : [...map.values()].find((i) => i.mine && i.id.endsWith(`.${id}`))?.id;
278
+ if (key)
279
+ changed = map.delete(key) || changed;
280
+ }
281
+ for (const i of items) {
282
+ if (matches(i, w.q)) {
283
+ // A change answer can bring an item again that the list has (the
284
+ // same millisecond as the cursor): no callback for it.
285
+ const o = map.get(i.id);
286
+ if (o && o.rev === i.rev && o.updatedAt === i.updatedAt && o.mine === i.mine)
287
+ continue;
288
+ map.set(i.id, i);
289
+ changed = true;
290
+ }
291
+ else
292
+ changed = map.delete(i.id) || changed;
293
+ }
294
+ if (!changed)
295
+ return;
296
+ const limit = w.q.limit ?? 50;
297
+ const sorted = sortItems([...map.values()], w.q);
298
+ w.items = sorted.slice(0, limit);
299
+ w.cb([...w.items]);
300
+ // A full page that got short, or a changed item at its end (an item
301
+ // after the page can belong there now): read the list again after 0 to
302
+ // 5 s.
303
+ const last = w.items.at(-1);
304
+ const tailChanged = !!last && items.some((i) => i.id === last.id);
305
+ if (w.full && (w.items.length < limit || tailChanged) && !w.relist) {
306
+ w.relist = setTimeout(() => {
307
+ w.relist = null;
308
+ void this.first(w);
309
+ }, Math.random() * 5000);
310
+ }
311
+ }
312
+ loop() {
313
+ if (this.running)
314
+ return;
315
+ this.running = true;
316
+ this.unUser ??= this.t().onUser(() => this.userChanged());
317
+ void (async () => {
318
+ let backoff = 1;
319
+ try {
320
+ while (this.all.size) {
321
+ await visible();
322
+ const byColl = new Map();
323
+ for (const w of this.all)
324
+ if (w.cursor !== null)
325
+ byColl.set(w.c, [...(byColl.get(w.c) ?? []), w]);
326
+ if (!byColl.size)
327
+ return;
328
+ const lists = [...byColl].map(([c, ws]) => ({ c, cursor: String(Math.min(...ws.map((w) => Number(w.cursor)))) }));
329
+ const abort = new AbortController();
330
+ this.abort = abort;
331
+ let ans;
332
+ const gen = this.gen;
333
+ try {
334
+ ans = await this.t().watch(lists, abort.signal);
335
+ backoff = 1;
336
+ }
337
+ catch (e) {
338
+ if (abort.signal.aborted || gen !== this.gen)
339
+ continue;
340
+ const err = e instanceof BuildersError ? e : new BuildersError("Could not reach Builders.", 0, "offline");
341
+ const retryAfter = err.retryAfter;
342
+ if (err.code === "user-changed") {
343
+ // The answer was not for this page's user: no change of it is
344
+ // used. Each list starts again for the new user.
345
+ this.userChanged(err);
346
+ return;
347
+ }
348
+ if (err.status === 0 || err.status >= 500 || err.code === "rate-limit") {
349
+ await sleep(1000 * (retryAfter ?? backoff), abort.signal);
350
+ backoff = Math.min(60, backoff * 2);
351
+ continue;
352
+ }
353
+ for (const w of [...this.all])
354
+ this.fail(w, err);
355
+ return;
356
+ }
357
+ // The user changed while it waited: not used (the lists start again).
358
+ if (gen !== this.gen)
359
+ continue;
360
+ for (const l of ans.lists) {
361
+ for (const w of byColl.get(l.c) ?? []) {
362
+ if (w.stopped)
363
+ continue;
364
+ if ("error" in l)
365
+ this.fail(w, new BuildersError(l.message, l.error === "sign-in-required" ? 401 : 400, (CODES.includes(l.error) ? l.error : "invalid")));
366
+ else if ("resync" in l) {
367
+ w.cursor = null;
368
+ void this.first(w);
369
+ }
370
+ else {
371
+ this.apply(w, l.items, l.removed);
372
+ w.cursor = l.cursor;
373
+ }
374
+ }
375
+ }
376
+ if (ans.next > 0)
377
+ await sleep(ans.next * 1000, abort.signal);
378
+ }
379
+ }
380
+ finally {
381
+ this.running = false;
382
+ // A watch that joined while the loop ended.
383
+ if ([...this.all].some((w) => w.cursor !== null))
384
+ this.loop();
385
+ }
386
+ })();
387
+ }
388
+ }
389
+ // --- db ---
390
+ function stub(name, text) {
391
+ return () => {
392
+ throw new BuildersError(text, 400, "not-supported");
393
+ };
394
+ }
395
+ function withStubs(o, names) {
396
+ for (const [k, text] of Object.entries(names))
397
+ Object.defineProperty(o, k, { value: stub(k, text), enumerable: false });
398
+ return o;
399
+ }
400
+ // The calls that Claude can guess (8.3): they exist only at run time and
401
+ // throw the message, not "is not a function".
402
+ const DB_STUBS = {
403
+ transaction: NOT_SUPPORTED.transaction,
404
+ batch: NOT_SUPPORTED.batch,
405
+ runTransaction: NOT_SUPPORTED.transaction,
406
+ join: NOT_SUPPORTED.join,
407
+ increment: NOT_SUPPORTED.increment,
408
+ groups: NOT_SUPPORTED.later,
409
+ history: NOT_SUPPORTED.later,
410
+ undo: NOT_SUPPORTED.later,
411
+ report: NOT_SUPPORTED.later,
412
+ trigger: NOT_SUPPORTED.serverCode,
413
+ schedule: NOT_SUPPORTED.serverCode,
414
+ };
415
+ const COLLECTION_STUBS = {
416
+ increment: NOT_SUPPORTED.increment,
417
+ join: NOT_SUPPORTED.join,
418
+ transaction: NOT_SUPPORTED.transaction,
419
+ batch: NOT_SUPPORTED.batch,
420
+ history: NOT_SUPPORTED.later,
421
+ undo: NOT_SUPPORTED.later,
422
+ report: NOT_SUPPORTED.later,
423
+ onSnapshot: "Use watch(cb) for live updates.",
424
+ };
425
+ function opts(o) {
426
+ if (o === undefined || o === null)
427
+ return undefined;
428
+ if (typeof o !== "object")
429
+ throw new BuildersError("The options are an object: { ifRev }.", 400, "invalid");
430
+ return o.ifRev;
431
+ }
432
+ // A db for one page. `transport` is for tests; apps use `db`.
433
+ export function createDb(transport) {
434
+ let lazy = null;
435
+ const t = transport ?? (() => (lazy ??= defaultTransport()));
436
+ const watches = new Watches(t);
437
+ function collection(name) {
438
+ if (typeof name !== "string" || !name)
439
+ throw new BuildersError("Give the collection name, as in builders.data.json.", 400, "invalid");
440
+ const c = {
441
+ async add(data) {
442
+ const gen = watches.generation;
443
+ const { item } = await t().add(name, data);
444
+ watches.own(name, [item], [], gen);
445
+ return item;
446
+ },
447
+ async get(id) {
448
+ return (await t().get(name, id)).item;
449
+ },
450
+ async set(id, data, o) {
451
+ const gen = watches.generation;
452
+ const { item } = await t().set(name, id, data, opts(o));
453
+ watches.own(name, [item], [], gen);
454
+ return item;
455
+ },
456
+ async update(id, patch, o) {
457
+ const gen = watches.generation;
458
+ const { item } = await t().update(name, id, patch, opts(o));
459
+ watches.own(name, [item], [], gen);
460
+ return item;
461
+ },
462
+ async remove(id) {
463
+ const gen = watches.generation;
464
+ await t().remove(name, id);
465
+ if (typeof id === "string")
466
+ watches.own(name, [], [id], gen);
467
+ },
468
+ async list(q = {}) {
469
+ const { items, next } = await t().list(name, q);
470
+ return { items: items, next };
471
+ },
472
+ async count(q = {}) {
473
+ return (await t().count(name, q)).count;
474
+ },
475
+ watch(a, b, e) {
476
+ const [q, cb, onError] = typeof a === "function" ? [{}, a, b] : [a ?? {}, b, e];
477
+ if (typeof cb !== "function")
478
+ throw new BuildersError("watch needs a callback: watch(query, items => ...).", 400, "invalid");
479
+ const w = {
480
+ c: name,
481
+ q: q,
482
+ cb: cb,
483
+ onError: typeof onError === "function" ? onError : (err) => console.error(err),
484
+ items: [],
485
+ cursor: null,
486
+ full: false,
487
+ relist: null,
488
+ backoff: 0,
489
+ token: 0,
490
+ stopped: false,
491
+ };
492
+ watches.start(w);
493
+ return () => watches.stop(w);
494
+ },
495
+ };
496
+ return withStubs(c, COLLECTION_STUBS);
497
+ }
498
+ function files(name) {
499
+ if (typeof name !== "string" || !name)
500
+ throw new BuildersError("Give the file set name, as in builders.data.json.", 400, "invalid");
501
+ return {
502
+ async upload(file, o) {
503
+ const B = globalThis.Blob;
504
+ if (!B || !(file instanceof B))
505
+ throw new BuildersError(MESSAGES.fileNotBlob(), 400, "invalid");
506
+ // Before the upload: a refused upload of 10 MB wastes the user's
507
+ // data plan.
508
+ const max = DATA_LIMITS.fileBytes;
509
+ if (file.size > max)
510
+ throw new BuildersError(MESSAGES.fileTooLarge(max / (1024 * 1024)), 413, "too-large");
511
+ const own = file.name;
512
+ const n = o?.name ?? (typeof own === "string" && own ? own : undefined);
513
+ return (await t().upload(name, file, n)).file;
514
+ },
515
+ async list(q = {}) {
516
+ if (typeof q !== "object" || q === null)
517
+ throw new BuildersError(MESSAGES.queryKeys("list()", "limit, after"), 400, "invalid");
518
+ return t().listFiles(name, q);
519
+ },
520
+ async remove(id) {
521
+ await t().removeFile(name, id);
522
+ },
523
+ };
524
+ }
525
+ const db = {
526
+ collection,
527
+ files,
528
+ usage: () => t().usage(),
529
+ };
530
+ return withStubs(db, DB_STUBS);
531
+ }
532
+ // The platform on app hosts, the local mode on localhost. The local mode
533
+ // (the engine in memory) loads only on localhost, so it is not in the
534
+ // first download of an app.
535
+ function defaultTransport() {
536
+ const host = globalThis.location?.hostname;
537
+ if (isLocalHost(host))
538
+ return lazyLocal();
539
+ return httpTransport(() => ({ fetch: (...a) => globalThis.fetch(...a) }), (cb) => userListeners(cb));
540
+ }
541
+ function lazyLocal() {
542
+ let p = null;
543
+ const get = () => (p ??= import("./local-db.js").then((m) => m.localTransport()));
544
+ return {
545
+ get: async (...a) => (await get()).get(...a),
546
+ list: async (...a) => (await get()).list(...a),
547
+ count: async (...a) => (await get()).count(...a),
548
+ add: async (...a) => (await get()).add(...a),
549
+ set: async (...a) => (await get()).set(...a),
550
+ update: async (...a) => (await get()).update(...a),
551
+ remove: async (...a) => (await get()).remove(...a),
552
+ usage: async () => (await get()).usage(),
553
+ upload: async (...a) => (await get()).upload(...a),
554
+ listFiles: async (...a) => (await get()).listFiles(...a),
555
+ removeFile: async (...a) => (await get()).removeFile(...a),
556
+ watch: async (...a) => (await get()).watch(...a),
557
+ // Only a change of the user id is a change of the user.
558
+ onUser: (cb) => {
559
+ let last = local.user?.id ?? null;
560
+ const l = () => {
561
+ const id = local.user?.id ?? null;
562
+ if (id === last)
563
+ return;
564
+ last = id;
565
+ cb();
566
+ };
567
+ local.listeners.add(l);
568
+ return () => local.listeners.delete(l);
569
+ },
570
+ };
571
+ }
572
+ // Sign-in changes on the platform (auth.ts calls notifyUser).
573
+ const userCbs = new Set();
574
+ export function userListeners(cb) {
575
+ userCbs.add(cb);
576
+ return () => userCbs.delete(cb);
577
+ }
578
+ export function notifyUser() {
579
+ for (const cb of [...userCbs])
580
+ cb();
581
+ }
@@ -0,0 +1 @@
1
+ export declare const declared: unknown;
@@ -0,0 +1,5 @@
1
+ // builders.data.json of the app, for the local mode (docs/login-and-data.md
2
+ // 8.4). The Vite plugin (@n-dream/builders-sdk/vite) replaces this module
3
+ // in the build with the checked file: null when the app has no file.
4
+ // undefined: the plugin is not in vite.config.ts.
5
+ export const declared = undefined;