@tallyui/database 1.0.0 → 3.0.0-next.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 CHANGED
@@ -1,36 +1,175 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
1
  // src/create-db.ts
9
- import { createRxDatabase, addRxPlugin } from "rxdb";
2
+ import { createRxDatabase, addRxPlugin as addRxPlugin2 } from "rxdb";
10
3
  import { RxDBDevModePlugin } from "rxdb/plugins/dev-mode";
4
+ import { RxDBLocalDocumentsPlugin as RxDBLocalDocumentsPlugin2 } from "rxdb/plugins/local-documents";
11
5
  import { getRxStorageMemory } from "rxdb/plugins/storage-memory";
12
- if (process.env.NODE_ENV !== "production") {
13
- addRxPlugin(RxDBDevModePlugin);
6
+ import { wrappedValidateAjvStorage } from "rxdb/plugins/validate-ajv";
7
+
8
+ // src/connector-collection.ts
9
+ import { addRxPlugin } from "rxdb";
10
+ import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
11
+ import { RxDBMigrationSchemaPlugin } from "rxdb/plugins/migration-schema";
12
+ function connectorCollection(schema) {
13
+ addRxPlugin(RxDBMigrationSchemaPlugin);
14
+ addRxPlugin(RxDBLocalDocumentsPlugin);
15
+ const migrationStrategies = Object.fromEntries(Array.from({ length: schema.version }, (_, i) => [i + 1, () => null]));
16
+ return { schema, migrationStrategies, localDocuments: true };
17
+ }
18
+
19
+ // src/stock-levels.ts
20
+ import { STOCK_LEVELS_LAST_PASS } from "@tallyui/core";
21
+ var STOCK_LEVELS_COLLECTION = "stock_levels";
22
+ var stockLevelsSchema = {
23
+ version: 0,
24
+ primaryKey: "id",
25
+ type: "object",
26
+ properties: {
27
+ id: { type: "string", maxLength: 255 },
28
+ // Untyped: any JSON value the connector yields.
29
+ value: {},
30
+ updatedAt: { type: "string" }
31
+ },
32
+ required: ["id", "value", "updatedAt"]
33
+ };
34
+ var stockLevelsCollection = { schema: stockLevelsSchema, localDocuments: true };
35
+
36
+ // src/engine.ts
37
+ var WEB_STORAGE_ENGINE = "sqlite-sahpool";
38
+ var REQUIRED_MULTI_INSTANCE_BY_ENGINE = { "sqlite-sahpool": false };
39
+
40
+ // src/storage-watchdog.ts
41
+ import { BehaviorSubject } from "rxjs";
42
+ import { isRxdbRemoteVersionMismatch } from "@tallyui/core";
43
+ var STORAGE_WRITE_STALL_MS = 1e4;
44
+ var STORAGE_READ_WATCHDOG_MS = 3e4;
45
+ function isStorageWorkerFailure(error) {
46
+ return error instanceof Error && (error.name === "StorageWorkerStartError" || error.message.includes("StorageWorkerStartError") || isRxdbRemoteVersionMismatch(error));
47
+ }
48
+ var READ_METHODS = ["query", "count", "findDocumentsById", "getChangedDocumentsSince"];
49
+ function withStorageWatchdog(storage, options = {}) {
50
+ const {
51
+ writeStallMs = STORAGE_WRITE_STALL_MS,
52
+ readWatchdogMs = STORAGE_READ_WATCHDOG_MS,
53
+ now = Date.now,
54
+ setTimer = (fn, ms) => {
55
+ const timer = setTimeout(fn, ms);
56
+ return () => clearTimeout(timer);
57
+ }
58
+ } = options;
59
+ const health$ = new BehaviorSubject({ status: "ok", stalledWrites: 0 });
60
+ const stalledStarts = [];
61
+ let dead = false;
62
+ let pendingReads = 0;
63
+ let silentWindows = 0;
64
+ let settledThisWindow = false;
65
+ let cancelReadTimer;
66
+ const emit = () => health$.next({
67
+ status: dead ? "dead" : stalledStarts.length > 0 ? "stalled" : "ok",
68
+ stalledWrites: stalledStarts.length,
69
+ ...stalledStarts.length > 0 ? { stalledSince: Math.min(...stalledStarts) } : {}
70
+ });
71
+ const settled = () => {
72
+ settledThisWindow = true;
73
+ silentWindows = 0;
74
+ };
75
+ const armReadTimer = () => {
76
+ settledThisWindow = false;
77
+ cancelReadTimer = setTimer(() => {
78
+ cancelReadTimer = void 0;
79
+ silentWindows = settledThisWindow ? 0 : silentWindows + 1;
80
+ if (silentWindows >= 2) {
81
+ dead = true;
82
+ emit();
83
+ } else armReadTimer();
84
+ }, readWatchdogMs);
85
+ };
86
+ const watchWrite = (promise) => {
87
+ const start = now();
88
+ let stalled = false;
89
+ const cancel = setTimer(() => {
90
+ stalled = true;
91
+ stalledStarts.push(start);
92
+ emit();
93
+ }, writeStallMs);
94
+ const done = () => {
95
+ cancel();
96
+ settled();
97
+ if (stalled) {
98
+ stalledStarts.splice(stalledStarts.indexOf(start), 1);
99
+ emit();
100
+ }
101
+ };
102
+ promise.then(done, done);
103
+ return promise;
104
+ };
105
+ const watchRead = (promise) => {
106
+ if (pendingReads++ === 0 && !dead) armReadTimer();
107
+ const done = () => {
108
+ settled();
109
+ if (--pendingReads === 0) {
110
+ cancelReadTimer?.();
111
+ cancelReadTimer = void 0;
112
+ }
113
+ };
114
+ promise.then(done, done);
115
+ return promise;
116
+ };
117
+ return Object.assign(Object.create(storage), {
118
+ health$: health$.asObservable(),
119
+ async createStorageInstance(params) {
120
+ const instance = await storage.createStorageInstance(params);
121
+ const originalBulkWrite = instance.bulkWrite.bind(instance);
122
+ instance.bulkWrite = (...args) => watchWrite(originalBulkWrite(...args));
123
+ for (const method of READ_METHODS) {
124
+ if (typeof instance[method] !== "function") continue;
125
+ const original = instance[method].bind(instance);
126
+ instance[method] = (...args) => watchRead(original(...args));
127
+ }
128
+ return instance;
129
+ }
130
+ });
14
131
  }
132
+
133
+ // src/create-db.ts
134
+ var DEV_MODE = process.env.NODE_ENV !== "production";
135
+ addRxPlugin2(RxDBLocalDocumentsPlugin2);
15
136
  async function createTallyDatabase(options) {
137
+ if (options.multiInstance === true) throw new Error("multiInstance: true is unsupported: TallyUI databases are single-instance (ADR-061).");
138
+ if (DEV_MODE) addRxPlugin2(RxDBDevModePlugin);
16
139
  const {
17
140
  connector,
18
141
  name = `tally_${connector.id}`,
19
142
  storage = getRxStorageMemory()
20
143
  } = options;
144
+ const watched = storage?.tallyEngine === WEB_STORAGE_ENGINE ? withStorageWatchdog(storage) : void 0;
145
+ const effectiveStorage = watched ?? storage;
146
+ const collectionConfigs = {};
147
+ for (const [collectionName, schema] of Object.entries(connector.schemas)) {
148
+ collectionConfigs[collectionName] = connectorCollection(schema);
149
+ }
150
+ if (connector.reconcile?.stock) {
151
+ if (STOCK_LEVELS_COLLECTION in collectionConfigs) {
152
+ throw new Error(`Connector "${connector.id}" defines a "${STOCK_LEVELS_COLLECTION}" collection; that name is reserved for the stock reconcile overlay.`);
153
+ }
154
+ collectionConfigs[STOCK_LEVELS_COLLECTION] = stockLevelsCollection;
155
+ }
21
156
  const db = await createRxDatabase({
22
157
  name,
23
- storage,
158
+ // Dev mode refuses storage without a schema validator (RxDB error DVM1),
159
+ // and validating is what makes dev mode catch bad connector documents.
160
+ storage: DEV_MODE ? wrappedValidateAjvStorage({ storage: effectiveStorage }) : effectiveStorage,
24
161
  multiInstance: false,
25
- ignoreDuplicate: true
162
+ // RxDB rejects this outside dev mode (DB9); in dev it lets hot reload re-create the same database.
163
+ ignoreDuplicate: DEV_MODE
26
164
  });
27
- const collectionConfigs = {};
28
- for (const [collectionName, schema] of Object.entries(connector.schemas)) {
29
- collectionConfigs[collectionName] = { schema };
30
- }
165
+ if (watched) healthByDatabase.set(db, watched.health$);
31
166
  await db.addCollections(collectionConfigs);
32
167
  return db;
33
168
  }
169
+ var healthByDatabase = /* @__PURE__ */ new WeakMap();
170
+ function getStorageHealth(db) {
171
+ return healthByDatabase.get(db);
172
+ }
34
173
 
35
174
  // src/storage.ts
36
175
  import { getRxStorageMemory as getRxStorageMemory2 } from "rxdb/plugins/storage-memory";
@@ -43,26 +182,119 @@ function getStorage() {
43
182
  'React Native detected. Pass a storage adapter explicitly:\n import { getRxStorageSQLite } from "@tallyui/storage-sqlite";\n createTallyDatabase({ connector, storage: getRxStorageSQLite({ database }) })'
44
183
  );
45
184
  }
46
- const { getRxStorageDexie } = __require("rxdb/plugins/storage-dexie");
47
- return getRxStorageDexie();
185
+ throw new Error(
186
+ 'Web storage is RxDB Premium SQLite-wasm, not Dexie (ADR-061). Pass it explicitly, bundling the worker entry:\n import { getRxStorageSQLiteWasm } from "@tallyui/storage-sqlite/web";\n const workerInput = new URL("@tallyui/storage-sqlite/web-worker", import.meta.url);\n createTallyDatabase({ connector, storage: getRxStorageSQLiteWasm({ workerInput }) })'
187
+ );
48
188
  }
49
189
 
50
190
  // src/replication.ts
51
191
  import { replicateRxCollection } from "rxdb/plugins/replication";
192
+ import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
193
+ import { errorKind } from "@tallyui/core";
194
+ var MAX_RETRY_TIME_MS = 5 * 60 * 1e3;
195
+ var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
196
+ var TIMER_SLACK_MS = 10;
197
+ var isDev = () => {
198
+ if (typeof __DEV__ !== "undefined") return Boolean(__DEV__);
199
+ try {
200
+ return process.env.NODE_ENV !== "production";
201
+ } catch {
202
+ return false;
203
+ }
204
+ };
205
+ var liveInto = /* @__PURE__ */ new WeakMap();
206
+ var warned = /* @__PURE__ */ new WeakSet();
207
+ function watchShared(adapter, collection) {
208
+ if (!isDev()) return () => {
209
+ };
210
+ const live = liveInto.get(adapter);
211
+ if (!live) liveInto.set(adapter, collection);
212
+ else if (live !== collection && !warned.has(adapter)) {
213
+ warned.add(adapter);
214
+ console.warn("TallyUI: one connector instance is replicating into two databases. Build a connector per store session (createXConnector()); a shared instance can leak queued reconcile work across stores.");
215
+ }
216
+ return () => {
217
+ if (liveInto.get(adapter) === collection) liveInto.delete(adapter);
218
+ };
219
+ }
220
+ function retryAfter(error) {
221
+ const value = error?.retryAfterMs;
222
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
223
+ }
224
+ function noticeFor(error, fixedBy) {
225
+ const fields = error;
226
+ const notice = { code: fields.code, since: Date.now(), fixedBy };
227
+ for (const key of ["software", "minVersion", "fix"]) {
228
+ if (typeof fields[key] === "string") notice[key] = fields[key];
229
+ }
230
+ return notice;
231
+ }
52
232
  function startReplication({
53
233
  collection,
54
234
  adapter,
55
235
  context,
56
236
  live = true,
57
237
  retryTime = 5e3,
58
- autoStart = true
238
+ autoStart = true,
239
+ maxRetryTimeMs = MAX_RETRY_TIME_MS
59
240
  }) {
60
- return replicateRxCollection({
241
+ let state;
242
+ const notice$ = new BehaviorSubject2(void 0);
243
+ let failures = 0;
244
+ let tillStopped = false;
245
+ let storeError;
246
+ let storeRetryAt = 0;
247
+ const setRetryTime = (ms) => {
248
+ if (state) state.retryTime = ms;
249
+ };
250
+ const pullHandler = async (checkpoint, batchSize) => {
251
+ if (tillStopped) {
252
+ void state?.pause();
253
+ return { documents: [], checkpoint };
254
+ }
255
+ const wait = storeRetryAt - Date.now();
256
+ if (wait > TIMER_SLACK_MS) {
257
+ setRetryTime(wait);
258
+ throw storeError;
259
+ }
260
+ try {
261
+ const result = await adapter.pull.handler(checkpoint, batchSize, context);
262
+ failures = 0;
263
+ storeError = void 0;
264
+ storeRetryAt = 0;
265
+ if (notice$.getValue()?.fixedBy === "store") notice$.next(void 0);
266
+ setRetryTime(retryTime);
267
+ return result;
268
+ } catch (error) {
269
+ const kind = errorKind(error);
270
+ if (kind === "transient") {
271
+ const backoff = Math.min(retryTime * 2 ** failures++, maxRetryTimeMs);
272
+ setRetryTime(Math.min(Math.max(backoff, retryAfter(error)), MAX_RETRY_AFTER_MS));
273
+ throw error;
274
+ }
275
+ const code = error.code;
276
+ const current = notice$.getValue();
277
+ if (current?.code !== code || current.fixedBy !== kind) notice$.next(noticeFor(error, kind));
278
+ if (kind === "till") {
279
+ tillStopped = true;
280
+ void state?.pause();
281
+ return { documents: [], checkpoint };
282
+ }
283
+ const delay = Math.min(Math.max(maxRetryTimeMs, retryAfter(error)), MAX_RETRY_AFTER_MS);
284
+ storeError = error;
285
+ storeRetryAt = Date.now() + delay;
286
+ setRetryTime(delay);
287
+ throw error;
288
+ }
289
+ };
290
+ const { version } = collection.schema;
291
+ const replication = replicateRxCollection({
61
292
  collection,
62
- replicationIdentifier: `${context.connectorId}-${collection.name}`,
293
+ replicationIdentifier: `${context.connectorId}-${collection.name}${version > 0 ? `-v${version}` : ""}`,
63
294
  pull: {
64
- handler: (checkpoint, batchSize) => adapter.pull.handler(checkpoint, batchSize, context),
65
- stream$: adapter.pull.stream$
295
+ handler: pullHandler,
296
+ stream$: adapter.pull.stream$,
297
+ batchSize: adapter.pull.batchSize
66
298
  },
67
299
  push: adapter.push ? {
68
300
  handler: (rows) => adapter.push.handler(rows, context),
@@ -72,9 +304,769 @@ function startReplication({
72
304
  retryTime,
73
305
  autoStart
74
306
  });
307
+ state = replication;
308
+ const release = watchShared(adapter, collection);
309
+ replication.canceled$.subscribe((canceled) => {
310
+ if (canceled) release();
311
+ });
312
+ const resume = async () => {
313
+ notice$.next(void 0);
314
+ tillStopped = false;
315
+ storeError = void 0;
316
+ storeRetryAt = 0;
317
+ failures = 0;
318
+ replication.retryTime = retryTime;
319
+ await replication.start();
320
+ };
321
+ return Object.assign(replication, { notice$: notice$.asObservable(), resume });
322
+ }
323
+
324
+ // src/live-tab.ts
325
+ import { BehaviorSubject as BehaviorSubject3 } from "rxjs";
326
+ function isHandoverMessage(data) {
327
+ const msg = data;
328
+ return typeof msg === "object" && msg !== null && (msg.type === "handover-request" || msg.type === "handover-ack") && typeof msg.id === "string";
329
+ }
330
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
331
+ function startLiveTab(options) {
332
+ const {
333
+ scope,
334
+ onPark,
335
+ isBusy,
336
+ maxDeferMs = 1e4,
337
+ ackTimeoutMs = 3e3,
338
+ locks = globalThis.navigator?.locks,
339
+ createChannel = (name2) => new BroadcastChannel(name2),
340
+ events = globalThis,
341
+ now = Date.now
342
+ } = options;
343
+ const state = new BehaviorSubject3("acquiring");
344
+ if (!locks) {
345
+ state.next("live");
346
+ return { state$: state.asObservable(), takeOver: () => Promise.resolve("live"), stop: () => state.complete() };
347
+ }
348
+ const name = `tally-live-tab:${scope}`;
349
+ let channel = createChannel(name);
350
+ let releaseLock;
351
+ let parking = false;
352
+ let requestCounter = 0;
353
+ let stopped = false;
354
+ let deferBlockedTimer;
355
+ let abortController = new AbortController();
356
+ const tabToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
357
+ const ackWaiters = /* @__PURE__ */ new Map();
358
+ const requestLock = (lockOptions, controller = abortController) => new Promise((resolve, reject) => {
359
+ locks.request(name, lockOptions.ifAvailable ? lockOptions : { ...lockOptions, signal: controller.signal }, (lock) => {
360
+ if (!lock || stopped || controller !== abortController) {
361
+ resolve(false);
362
+ return void 0;
363
+ }
364
+ resolve(true);
365
+ return new Promise((release) => {
366
+ releaseLock = release;
367
+ });
368
+ }).catch((error) => {
369
+ if (controller.signal.aborted) resolve(false);
370
+ else reject(error);
371
+ });
372
+ });
373
+ const waitForAck = (id) => new Promise((resolve) => {
374
+ const timer = setTimeout(() => {
375
+ ackWaiters.delete(id);
376
+ resolve(false);
377
+ }, ackTimeoutMs);
378
+ ackWaiters.set(id, () => {
379
+ clearTimeout(timer);
380
+ ackWaiters.delete(id);
381
+ resolve(true);
382
+ });
383
+ });
384
+ const handleHandoverRequest = async (id) => {
385
+ if (state.value !== "live" || parking) return;
386
+ parking = true;
387
+ channel.postMessage({ type: "handover-ack", id });
388
+ try {
389
+ const start = now();
390
+ while (isBusy?.() && now() - start < maxDeferMs) await sleep(100);
391
+ try {
392
+ await onPark();
393
+ } catch (error) {
394
+ console.warn(`live-tab: onPark failed for scope "${scope}"; parking anyway.`, error);
395
+ }
396
+ } finally {
397
+ releaseLock?.();
398
+ releaseLock = void 0;
399
+ parking = false;
400
+ state.next("parked");
401
+ }
402
+ };
403
+ const handleChannelMessage = (event) => {
404
+ if (!isHandoverMessage(event.data)) return;
405
+ if (event.data.type === "handover-ack") ackWaiters.get(event.data.id)?.();
406
+ else void handleHandoverRequest(event.data.id);
407
+ };
408
+ channel.onmessage = handleChannelMessage;
409
+ let inFlightTakeOver;
410
+ const performTakeOver = async () => {
411
+ state.next("acquiring");
412
+ if (await requestLock({ ifAvailable: true })) {
413
+ state.next("live");
414
+ return "live";
415
+ }
416
+ if (stopped) return state.value;
417
+ const id = `${tabToken}-${++requestCounter}`;
418
+ const acked = waitForAck(id);
419
+ channel.postMessage({ type: "handover-request", id });
420
+ const gotLockPromise = requestLock({});
421
+ const lockFirst = await Promise.race([gotLockPromise.then(() => true), acked.then(() => false)]);
422
+ if (lockFirst) {
423
+ ackWaiters.delete(id);
424
+ } else if (await acked) {
425
+ deferBlockedTimer = setTimeout(() => state.next("blocked"), maxDeferMs + ackTimeoutMs);
426
+ } else {
427
+ state.next("blocked");
428
+ }
429
+ if (stopped) return state.value;
430
+ const gotLock = await gotLockPromise;
431
+ clearTimeout(deferBlockedTimer);
432
+ deferBlockedTimer = void 0;
433
+ if (stopped) return state.value;
434
+ state.next(gotLock ? "live" : "blocked");
435
+ return gotLock ? "live" : "blocked";
436
+ };
437
+ const takeOver = () => {
438
+ if (stopped) return Promise.resolve(state.value);
439
+ if (state.value === "live") return Promise.resolve("live");
440
+ if (!inFlightTakeOver) {
441
+ inFlightTakeOver = performTakeOver().finally(() => {
442
+ inFlightTakeOver = void 0;
443
+ });
444
+ }
445
+ return inFlightTakeOver;
446
+ };
447
+ const suspend = () => {
448
+ stopped = true;
449
+ abortController.abort();
450
+ releaseLock?.();
451
+ releaseLock = void 0;
452
+ ackWaiters.clear();
453
+ clearTimeout(deferBlockedTimer);
454
+ deferBlockedTimer = void 0;
455
+ channel.onmessage = null;
456
+ channel.close();
457
+ state.next("parked");
458
+ };
459
+ const resume = () => {
460
+ abortController = new AbortController();
461
+ channel = createChannel(name);
462
+ channel.onmessage = handleChannelMessage;
463
+ stopped = false;
464
+ void takeOver().catch((error) => {
465
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
466
+ state.next("blocked");
467
+ });
468
+ };
469
+ const handlePageShow = (event) => {
470
+ if (event.persisted && stopped) resume();
471
+ };
472
+ const handlePageHide = () => {
473
+ suspend();
474
+ void Promise.resolve().then(onPark).catch((error) => {
475
+ console.warn(`live-tab: onPark failed for scope "${scope}" on pagehide.`, error);
476
+ });
477
+ };
478
+ const stop = () => {
479
+ suspend();
480
+ events.removeEventListener?.("pagehide", handlePageHide);
481
+ events.removeEventListener?.("pageshow", handlePageShow);
482
+ state.complete();
483
+ };
484
+ events.addEventListener?.("pagehide", handlePageHide);
485
+ events.addEventListener?.("pageshow", handlePageShow);
486
+ void takeOver().catch((error) => {
487
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
488
+ state.next("blocked");
489
+ });
490
+ return { state$: state.asObservable(), takeOver, stop };
491
+ }
492
+
493
+ // src/reconcile.ts
494
+ import { BehaviorSubject as BehaviorSubject4 } from "rxjs";
495
+ import { STOCK_LEVELS_LAST_PASS as STOCK_LEVELS_LAST_PASS2 } from "@tallyui/core";
496
+
497
+ // src/chunks.ts
498
+ import { readFresh } from "@tallyui/core/rxdb";
499
+ var BACKGROUND_CHUNK_SIZE = 250;
500
+ function pauseBetweenChunks() {
501
+ return new Promise((resolve) => setTimeout(resolve, 0));
502
+ }
503
+ async function* readFreshInChunks(collection, size = BACKGROUND_CHUNK_SIZE) {
504
+ const key = collection.schema.primaryPath;
505
+ let after;
506
+ while (true) {
507
+ if (after !== void 0) await pauseBetweenChunks();
508
+ const chunk = await readFresh(collection, {
509
+ selector: after === void 0 ? {} : { [key]: { $gt: after } },
510
+ sort: [{ [key]: "asc" }],
511
+ limit: size
512
+ });
513
+ if (!chunk.length) return;
514
+ yield chunk;
515
+ if (chunk.length < size) return;
516
+ after = chunk[chunk.length - 1][key];
517
+ }
518
+ }
519
+
520
+ // src/pass-queue.ts
521
+ function createPassQueue(run) {
522
+ let current;
523
+ let queued;
524
+ const trigger = () => {
525
+ if (!current) return current = run().finally(() => {
526
+ current = void 0;
527
+ });
528
+ if (!queued) {
529
+ queued = current.catch(() => {
530
+ }).then(() => {
531
+ queued = void 0;
532
+ return trigger();
533
+ });
534
+ }
535
+ return queued;
536
+ };
537
+ return trigger;
538
+ }
539
+
540
+ // src/reconcile.ts
541
+ function startStockReconcile({
542
+ collection,
543
+ adapter,
544
+ context,
545
+ intervalMs = 3e5,
546
+ maxPages = 100
547
+ }) {
548
+ const controller = new AbortController();
549
+ const { signal } = controller;
550
+ const checkAborted = () => {
551
+ if (signal.aborted) throw signal.reason ?? new Error("Stock reconcile stopped");
552
+ };
553
+ const state = new BehaviorSubject4({ running: false, truncated: false });
554
+ const update = (patch) => state.next({ ...state.value, ...patch });
555
+ const lastPass = collection.getLocal(STOCK_LEVELS_LAST_PASS2).catch((error) => {
556
+ if (error?.code !== "LD8") return null;
557
+ throw new Error(`Create "${collection.name}" with stockLevelsCollection (localDocuments: true); stock reconcile stores its last pass there.`, { cause: error });
558
+ });
559
+ lastPass.then((doc) => {
560
+ if (doc && !state.value.lastCompletedAt) update({ lastCompletedAt: doc.get("completedAt") });
561
+ }, () => {
562
+ });
563
+ const pass = async () => {
564
+ checkAborted();
565
+ await lastPass;
566
+ const stock = /* @__PURE__ */ new Map();
567
+ let pages = 0;
568
+ for await (const page of adapter.fetchPages({ ...context, signal })) {
569
+ checkAborted();
570
+ if (pages === maxPages) {
571
+ console.warn(`Stock reconcile stopped at the ${maxPages}-page limit; nothing was written.`);
572
+ return { pages, written: 0, removed: 0, truncated: true };
573
+ }
574
+ pages++;
575
+ for (const [key, value] of page) stock.set(key, value);
576
+ }
577
+ const rows = [];
578
+ for await (const chunk of readFreshInChunks(collection)) {
579
+ checkAborted();
580
+ rows.push(...chunk);
581
+ }
582
+ const stored = new Map(rows.map((row) => [row.id, JSON.stringify(row.value)]));
583
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
584
+ const upserts = [...stock].filter(([id, value]) => stored.get(id) !== JSON.stringify(value)).map(([id, value]) => ({ id, value, updatedAt }));
585
+ const removals = rows.filter((row) => !stock.has(row.id)).map((row) => row.id);
586
+ let wroteChunk = false;
587
+ for (let i = 0; i < upserts.length; i += BACKGROUND_CHUNK_SIZE) {
588
+ if (wroteChunk) await pauseBetweenChunks();
589
+ checkAborted();
590
+ const { error } = await collection.bulkUpsert(upserts.slice(i, i + BACKGROUND_CHUNK_SIZE));
591
+ if (error.length) throw error[0];
592
+ wroteChunk = true;
593
+ }
594
+ for (let i = 0; i < removals.length; i += BACKGROUND_CHUNK_SIZE) {
595
+ if (wroteChunk) await pauseBetweenChunks();
596
+ checkAborted();
597
+ const { error } = await collection.bulkRemove(removals.slice(i, i + BACKGROUND_CHUNK_SIZE));
598
+ if (error.length) throw error[0];
599
+ wroteChunk = true;
600
+ }
601
+ const completedAt = updatedAt;
602
+ checkAborted();
603
+ await collection.upsertLocal(STOCK_LEVELS_LAST_PASS2, { completedAt });
604
+ return { pages, written: upserts.length, removed: removals.length, truncated: false, completedAt };
605
+ };
606
+ const tracked = async () => {
607
+ update({ running: true });
608
+ try {
609
+ const result = await pass();
610
+ if (result.truncated) update({ running: false, truncated: true });
611
+ else state.next({ running: false, truncated: false, lastCompletedAt: result.completedAt });
612
+ return result;
613
+ } catch (error) {
614
+ update({ running: false, lastError: error });
615
+ throw error;
616
+ }
617
+ };
618
+ const reconcileStock = createPassQueue(tracked);
619
+ const timer = setInterval(() => {
620
+ reconcileStock().catch((error) => console.warn("Stock reconcile failed:", error));
621
+ }, intervalMs);
622
+ const stop = () => {
623
+ clearInterval(timer);
624
+ context.signal?.removeEventListener("abort", stop);
625
+ controller.abort();
626
+ state.complete();
627
+ };
628
+ if (context.signal?.aborted) stop();
629
+ else context.signal?.addEventListener("abort", stop);
630
+ return { reconcileStock, stop, state$: state.asObservable() };
631
+ }
632
+
633
+ // src/catalogue-reconcile.ts
634
+ import { BehaviorSubject as BehaviorSubject5 } from "rxjs";
635
+ import { errorKind as errorKind2 } from "@tallyui/core";
636
+ import { readFresh as readFresh2 } from "@tallyui/core/rxdb";
637
+ var MASS_DELETE_MINIMUM = 10;
638
+ var MAX_CHECK_EVERY_MS = 36e5;
639
+ var MIN_CHECK_EVERY_MS = 6e4;
640
+ var FIRST_RETRY_MS = 5 * 6e4;
641
+ var BUDGET_WINDOW_MS = 6e4;
642
+ var LOG_KEYS = 50;
643
+ var CATALOGUE_OFFLINE_GAP_MS = 6 * 36e5;
644
+ function shouldReconcileAfterGap(lastPullAt, now = Date.now(), offlineGapMs = CATALOGUE_OFFLINE_GAP_MS) {
645
+ return lastPullAt !== void 0 && now - lastPullAt > offlineGapMs;
646
+ }
647
+ var claimed = /* @__PURE__ */ new WeakMap();
648
+ function startCatalogueReconcile(options) {
649
+ const { request, state$, stop } = startCatalogueRunner(options);
650
+ return { reconcile: () => {
651
+ request().catch(() => {
652
+ });
653
+ }, state$, stop };
654
+ }
655
+ function startCatalogueRunner({
656
+ collection,
657
+ adapter,
658
+ context,
659
+ reSync,
660
+ requestsPerMinute = 30,
661
+ confirmChunk = 100,
662
+ intervalMs = 864e5,
663
+ startDelayMs = 12e4,
664
+ maxDeleteShare = 0.2,
665
+ allowMassDelete = false,
666
+ log = () => {
667
+ },
668
+ now = Date.now,
669
+ stateId = "catalogue-reconcile",
670
+ setTimer = (fn, ms) => {
671
+ const timer = setTimeout(fn, ms);
672
+ return () => clearTimeout(timer);
673
+ },
674
+ keepCandidates = false
675
+ }) {
676
+ const controller = new AbortController();
677
+ const { signal } = controller;
678
+ const checkAborted = () => {
679
+ if (signal.aborted) throw signal.reason ?? new Error("Catalogue reconcile stopped");
680
+ };
681
+ const ctx = { ...context, signal };
682
+ const primary = collection.schema.primaryPath;
683
+ const keyOf = (doc) => doc[primary];
684
+ const listed = (keys) => ({ count: keys.length, keys: keys.slice(0, LOG_KEYS) });
685
+ const state = new BehaviorSubject5({ running: false });
686
+ const update = (patch) => state.next({ ...state.value, ...patch });
687
+ const ids = claimed.get(collection) ?? /* @__PURE__ */ new Set();
688
+ claimed.set(collection, ids);
689
+ const owner = !ids.has(stateId);
690
+ let memory;
691
+ if (owner) ids.add(stateId);
692
+ else {
693
+ memory = {};
694
+ console.warn(`Catalogue reconcile: "${stateId}" is in use on ${collection.name}; pass a distinct stateId. This gate is kept in memory.`);
695
+ }
696
+ const load = async () => {
697
+ if (memory) return memory;
698
+ try {
699
+ const doc = await collection.getLocal(stateId);
700
+ return doc ? { lastCompletedAt: doc.get("lastCompletedAt"), pass: doc.get("pass") } : {};
701
+ } catch (error) {
702
+ if (typeof collection.getLocal === "function" && error?.code !== "LD8") throw error;
703
+ console.warn(`Catalogue reconcile: ${collection.name} has no local documents (create it with connectorCollection); the gate is kept in memory.`);
704
+ return memory = {};
705
+ }
706
+ };
707
+ const save = async (value) => {
708
+ if (memory) memory = value;
709
+ else await collection.upsertLocal(stateId, JSON.parse(JSON.stringify(value)));
710
+ };
711
+ const sleep2 = (ms) => new Promise((resolve) => {
712
+ const onAbort = () => {
713
+ cancel();
714
+ resolve();
715
+ };
716
+ const cancel = setTimer(() => {
717
+ signal.removeEventListener("abort", onAbort);
718
+ resolve();
719
+ }, ms);
720
+ signal.addEventListener("abort", onAbort);
721
+ });
722
+ const sent = [];
723
+ const budget = async () => {
724
+ for (; ; ) {
725
+ checkAborted();
726
+ while (sent.length && sent[0] <= now() - BUDGET_WINDOW_MS) sent.shift();
727
+ if (sent.length < requestsPerMinute) {
728
+ sent.push(now());
729
+ return;
730
+ }
731
+ await sleep2(sent[0] + BUDGET_WINDOW_MS - now());
732
+ }
733
+ };
734
+ const readByKeys = async (keys) => {
735
+ const found = /* @__PURE__ */ new Map();
736
+ for (let i = 0; i < keys.length; i += BACKGROUND_CHUNK_SIZE) {
737
+ if (i) await pauseBetweenChunks();
738
+ checkAborted();
739
+ const selector = { [primary]: { $in: keys.slice(i, i + BACKGROUND_CHUNK_SIZE) } };
740
+ for (const doc of await readFresh2(collection, { selector })) found.set(keyOf(doc), doc);
741
+ }
742
+ return found;
743
+ };
744
+ const braked = (tombstones, localCount) => !allowMassDelete && localCount > 0 && (tombstones === localCount || tombstones > MASS_DELETE_MINIMUM && tombstones > maxDeleteShare * localCount);
745
+ const pass = async () => {
746
+ checkAborted();
747
+ const startedAt = now();
748
+ const saved = await load();
749
+ const resumed = Boolean(saved.pass && startedAt - saved.pass.startedAt < intervalMs);
750
+ let current = resumed ? { ...saved.pass, uninterrupted: false } : { startedAt, uninterrupted: true };
751
+ await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
752
+ log({ type: "pass-started", resumed });
753
+ const seen = /* @__PURE__ */ new Set();
754
+ let pages = 0;
755
+ let compared = 0;
756
+ let refetched = 0;
757
+ const iterator = adapter.fetchPages(ctx, current.cursor)[Symbol.asyncIterator]();
758
+ try {
759
+ for (; ; ) {
760
+ await budget();
761
+ const next = await iterator.next();
762
+ checkAborted();
763
+ if (next.done) break;
764
+ pages++;
765
+ const { entries, cursor } = next.value;
766
+ const locals = await readByKeys(entries.map((e) => e.key));
767
+ const queue = [];
768
+ for (const { key, fingerprint, remote } of entries) {
769
+ seen.add(key);
770
+ const local = locals.get(key);
771
+ if (local) compared++;
772
+ if (!local || adapter.fingerprint(local) !== fingerprint) queue.push({ key, local, remote });
773
+ }
774
+ checkAborted();
775
+ if (queue.length) {
776
+ const size = adapter.refetchBatchSize;
777
+ const slots = size !== void 0 && size > 0 ? Math.max(1, Math.ceil(queue.length / size)) : 1;
778
+ for (let slot = 0; slot < slots; slot++) await budget();
779
+ adapter.enqueue(queue);
780
+ reSync();
781
+ refetched += queue.length;
782
+ log({ type: "refetched", ...listed(queue.map((e) => e.key)) });
783
+ }
784
+ current = { ...current, cursor };
785
+ await save({ lastCompletedAt: saved.lastCompletedAt, pass: current });
786
+ }
787
+ } finally {
788
+ iterator.return?.()?.catch(() => {
789
+ });
790
+ }
791
+ let tombstoned = 0;
792
+ let kept = 0;
793
+ let unlisted = 0;
794
+ const keep = (docs, why) => {
795
+ kept += docs.length;
796
+ if (docs.length) log({ type: "kept", ...listed(docs.map(keyOf)), ...why });
797
+ };
798
+ if (!current.uninterrupted) log({ type: "kept", count: 0, keys: [], reason: "resumed-pass" });
799
+ else {
800
+ const candidates = [];
801
+ let localCount = 0;
802
+ for await (const chunk of readFreshInChunks(collection)) {
803
+ checkAborted();
804
+ localCount += chunk.length;
805
+ for (const doc of chunk) if (!seen.has(keyOf(doc))) candidates.push(doc);
806
+ }
807
+ unlisted = candidates.length;
808
+ let gone = [];
809
+ if (!candidates.length || keepCandidates) {
810
+ } else if (braked(candidates.length, localCount)) {
811
+ const one = candidates.length === 1;
812
+ const message = (one ? "The only product on this till is no longer listed by the online store, so it was kept: removing everything at once needs a check. " : `${candidates.length} products the online store no longer lists were kept on this till: removing that many at once needs a check. `) + `If ${one ? "it was" : "they were"} hidden or removed on purpose, the person who manages this till can allow the removal.`;
813
+ console.warn(`Catalogue reconcile: ${message} (pass allowMassDelete: true to the reconcile runner to apply it)`);
814
+ keep(candidates, { reason: "brake", message });
815
+ } else {
816
+ const confirmed = /* @__PURE__ */ new Set();
817
+ for (let i = 0; i < candidates.length; i += confirmChunk) {
818
+ const chunk = candidates.slice(i, i + confirmChunk);
819
+ await budget();
820
+ for (const key of await adapter.confirmGone(chunk, ctx)) confirmed.add(key);
821
+ checkAborted();
822
+ }
823
+ gone = candidates.filter((doc) => confirmed.has(keyOf(doc)));
824
+ const goneSet = new Set(gone);
825
+ keep(candidates.filter((doc) => !goneSet.has(doc)), { reason: "unconfirmed" });
826
+ }
827
+ if (gone.length) {
828
+ adapter.enqueue(gone.map((local) => ({ key: keyOf(local), local, tombstone: true })));
829
+ reSync();
830
+ tombstoned = gone.length;
831
+ log({ type: "tombstoned", ...listed(gone.map(keyOf)) });
832
+ }
833
+ }
834
+ checkAborted();
835
+ const lastCompletedAt = now();
836
+ await save({ lastCompletedAt });
837
+ const summary = { pages, compared, refetched, tombstoned, kept, unlisted, durationMs: lastCompletedAt - startedAt };
838
+ log({ type: "pass-completed", ...summary });
839
+ return summary;
840
+ };
841
+ let failures = 0;
842
+ let tillStopped = false;
843
+ let cancelRetry;
844
+ const onError = (error) => {
845
+ if (signal.aborted) return log({ type: "stopped", reason: "stopped" });
846
+ const kind = errorKind2(error);
847
+ if (kind === "store") return log({ type: "skipped", reason: "store" });
848
+ const code = error?.code;
849
+ log({ type: "stopped", reason: kind, ...typeof code === "string" && { code } });
850
+ if (kind === "till") {
851
+ tillStopped = true;
852
+ return;
853
+ }
854
+ const delay = Math.min(Math.max(FIRST_RETRY_MS * 2 ** failures++, retryAfter(error)), MAX_RETRY_AFTER_MS);
855
+ cancelRetry = setTimer(() => {
856
+ cancelRetry = void 0;
857
+ run().catch(() => {
858
+ });
859
+ }, delay);
860
+ };
861
+ const run = createPassQueue(async () => {
862
+ update({ running: true });
863
+ try {
864
+ const result = await pass();
865
+ failures = 0;
866
+ update({ running: false, lastResult: result, lastResultAt: now() });
867
+ return result;
868
+ } catch (error) {
869
+ update({ running: false, lastError: error, lastErrorAt: now() });
870
+ onError(error);
871
+ throw error;
872
+ }
873
+ });
874
+ const check = async () => {
875
+ if (tillStopped || cancelRetry || state.value.running) return;
876
+ const { lastCompletedAt, pass: pending } = await load();
877
+ if (pending || lastCompletedAt === void 0 || now() - lastCompletedAt >= intervalMs) await run();
878
+ else log({ type: "skipped", reason: "gate" });
879
+ };
880
+ const checkEveryMs = Math.max(MIN_CHECK_EVERY_MS, Math.min(MAX_CHECK_EVERY_MS, intervalMs / 2) || 0);
881
+ let cancelTimer = () => {
882
+ };
883
+ const schedule = (ms) => {
884
+ cancelTimer = setTimer(() => {
885
+ schedule(checkEveryMs);
886
+ check().catch((error) => console.warn("Catalogue reconcile failed:", error));
887
+ }, ms);
888
+ };
889
+ schedule(startDelayMs ?? checkEveryMs);
890
+ const stop = () => {
891
+ cancelTimer();
892
+ cancelRetry?.();
893
+ if (owner) ids.delete(stateId);
894
+ context.signal?.removeEventListener("abort", stop);
895
+ controller.abort();
896
+ state.complete();
897
+ };
898
+ if (context.signal?.aborted) stop();
899
+ else context.signal?.addEventListener("abort", stop);
900
+ const request = () => {
901
+ tillStopped = false;
902
+ cancelRetry?.();
903
+ cancelRetry = void 0;
904
+ return run();
905
+ };
906
+ return { request, state$: state.asObservable(), stop };
907
+ }
908
+
909
+ // src/fingerprint-reconcile.ts
910
+ import { BehaviorSubject as BehaviorSubject6 } from "rxjs";
911
+ function isFingerprintResultCurrent(state) {
912
+ return state.lastResultAt !== void 0 && state.lastResultAt > (state.lastErrorAt ?? 0);
913
+ }
914
+ function confirmAll(collection) {
915
+ const primary = collection.schema.primaryPath;
916
+ return async (locals) => locals.map((doc) => doc[primary]);
917
+ }
918
+ async function* skipPages(pages, entries, from = 0) {
919
+ let read = 0;
920
+ for await (const page of pages) {
921
+ read++;
922
+ yield { entries: read <= from ? [] : entries(page), cursor: Math.max(read, from) };
923
+ }
924
+ }
925
+ function startFingerprintReconcile({
926
+ adapter,
927
+ reSync,
928
+ startDelayMs = null,
929
+ maxPages: _ignored,
930
+ stateId = "fingerprint-reconcile",
931
+ ...options
932
+ }) {
933
+ let queued = 0;
934
+ let pending = false;
935
+ const { request, stop, state$: catalogue$ } = startCatalogueRunner({
936
+ ...options,
937
+ startDelayMs,
938
+ stateId,
939
+ keepCandidates: true,
940
+ // Only touch reSync when something reached the pull.
941
+ reSync: () => {
942
+ if (pending) {
943
+ pending = false;
944
+ reSync();
945
+ }
946
+ },
947
+ log: (event) => {
948
+ if (event.type === "pass-started") queued = 0;
949
+ },
950
+ adapter: {
951
+ fetchPages: (context, from) => skipPages(
952
+ adapter.fetchPages(context),
953
+ (page) => [...page].map(([key, fingerprint]) => ({ key, fingerprint })),
954
+ from
955
+ ),
956
+ fingerprint: (doc) => adapter.fingerprint(doc),
957
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
958
+ refetchBatchSize: adapter.refetchBatchSize,
959
+ // It never deletes: keepCandidates only counts the products the listing did not name (`unreported`), before the
960
+ // brake and confirmGone, so this is never called; a call is a runner bug, and it fails the pass loudly.
961
+ confirmGone: async () => {
962
+ throw new Error("The fingerprint reconcile never deletes; confirmGone must not be called.");
963
+ },
964
+ // refreshOnly: a missing re-fetch is skipped, never tombstoned (ADR-060). A product the till lacks is left to the pull.
965
+ enqueue: (entries) => {
966
+ const known = entries.flatMap(({ key, local }) => local ? [{ id: key, local, refreshOnly: true }] : []);
967
+ if (!known.length) return;
968
+ queued += known.length;
969
+ pending = true;
970
+ adapter.enqueue(known);
971
+ }
972
+ }
973
+ });
974
+ const toResult = ({ pages, compared, unlisted }) => ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0 });
975
+ const state = new BehaviorSubject6({ running: false });
976
+ let summary;
977
+ let result;
978
+ catalogue$.subscribe({
979
+ next: ({ lastResult, ...rest }) => {
980
+ if (lastResult !== summary) {
981
+ summary = lastResult;
982
+ result = lastResult && toResult(lastResult);
983
+ }
984
+ state.next(result ? { ...rest, lastResult: result } : rest);
985
+ },
986
+ complete: () => state.complete()
987
+ });
988
+ const reconcile = () => request().then(toResult);
989
+ return { reconcile, stop, state$: state.asObservable() };
990
+ }
991
+
992
+ // src/id-reconcile.ts
993
+ function startIdReconcile({
994
+ adapter,
995
+ reSync,
996
+ startDelayMs = 5e3,
997
+ maxPages: _ignored,
998
+ stateId = "id-reconcile",
999
+ ...options
1000
+ }) {
1001
+ const fingerprint = (ids) => [...ids].sort().join("\n");
1002
+ let queued = 0;
1003
+ let braked = false;
1004
+ let pending = false;
1005
+ const { request, stop } = startCatalogueRunner({
1006
+ ...options,
1007
+ startDelayMs,
1008
+ stateId,
1009
+ // Only touch reSync when something reached the pull.
1010
+ reSync: () => {
1011
+ if (pending) {
1012
+ pending = false;
1013
+ reSync();
1014
+ }
1015
+ },
1016
+ log: (event) => {
1017
+ if (event.type === "pass-started") {
1018
+ queued = 0;
1019
+ braked = false;
1020
+ }
1021
+ if (event.type === "kept" && event.reason === "brake") braked = true;
1022
+ },
1023
+ adapter: {
1024
+ fetchPages: (context, from) => skipPages(
1025
+ adapter.fetchPages(context),
1026
+ (rows) => rows.map((row) => ({ key: row.id, fingerprint: fingerprint(row.variantIds) })),
1027
+ from
1028
+ ),
1029
+ fingerprint: (doc) => fingerprint(adapter.variantIds(doc)),
1030
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
1031
+ refetchBatchSize: adapter.refetchBatchSize,
1032
+ // The proof is the feed's by-id re-read: every candidate is confirmed here and reaches the feed below as a
1033
+ // plain entry, never `tombstone: true`, so the feed tombstones it only when fetchByIds does not return it.
1034
+ confirmGone: confirmAll(options.collection),
1035
+ // The old entry shape. A product the till lacks is left to the pull, as before.
1036
+ enqueue: (entries) => {
1037
+ const known = entries.flatMap(({ key, local }) => local ? [{ id: key, local }] : []);
1038
+ if (!known.length) return;
1039
+ queued += known.length;
1040
+ pending = true;
1041
+ adapter.enqueue(known);
1042
+ }
1043
+ }
1044
+ });
1045
+ const reconcileIds = () => request().then(({ pages }) => ({ pages, queued, truncated: false, braked }));
1046
+ return { reconcileIds, stop };
75
1047
  }
76
1048
  export {
1049
+ CATALOGUE_OFFLINE_GAP_MS,
1050
+ REQUIRED_MULTI_INSTANCE_BY_ENGINE,
1051
+ STOCK_LEVELS_COLLECTION,
1052
+ STOCK_LEVELS_LAST_PASS,
1053
+ STORAGE_READ_WATCHDOG_MS,
1054
+ STORAGE_WRITE_STALL_MS,
1055
+ WEB_STORAGE_ENGINE,
1056
+ connectorCollection,
77
1057
  createTallyDatabase,
78
1058
  getStorage,
79
- startReplication
1059
+ getStorageHealth,
1060
+ isFingerprintResultCurrent,
1061
+ isStorageWorkerFailure,
1062
+ shouldReconcileAfterGap,
1063
+ startCatalogueReconcile,
1064
+ startFingerprintReconcile,
1065
+ startIdReconcile,
1066
+ startLiveTab,
1067
+ startReplication,
1068
+ startStockReconcile,
1069
+ stockLevelsCollection,
1070
+ stockLevelsSchema,
1071
+ withStorageWatchdog
80
1072
  };