@tallyui/core 2.0.0 → 3.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/chunk-C4PWPOKO.js +18 -0
  2. package/dist/commands-BW4YYgRG.d.ts +306 -0
  3. package/dist/index.d.ts +247 -130
  4. package/dist/index.js +210 -22
  5. package/dist/rxdb/index.d.ts +5 -9
  6. package/dist/server/index.d.ts +213 -0
  7. package/dist/server/index.js +591 -0
  8. package/package.json +8 -2
  9. package/src/commands.ts +1 -1
  10. package/src/context/connector-context.tsx +30 -1
  11. package/src/index.ts +17 -5
  12. package/src/known-warnings.ts +77 -0
  13. package/src/replication/combine.ts +13 -7
  14. package/src/replication/reconcile-feed.ts +73 -20
  15. package/src/rxdb/read-fresh.ts +3 -7
  16. package/src/rxdb/watch-fresh.ts +2 -2
  17. package/src/rxdb-remote-version-mismatch.ts +30 -0
  18. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  19. package/src/server/__fixtures__/order-create-v3.json +97 -0
  20. package/src/server/batch-outcome.ts +19 -0
  21. package/src/server/batch.ts +112 -0
  22. package/src/server/command-result.ts +138 -0
  23. package/src/server/fingerprint.ts +18 -0
  24. package/src/server/fiscal-figures.ts +84 -0
  25. package/src/server/index.ts +20 -0
  26. package/src/server/money.ts +34 -0
  27. package/src/server/order-payload-shape.ts +112 -0
  28. package/src/server/register-figures.ts +32 -0
  29. package/src/server/register-outcome.ts +12 -0
  30. package/src/server/register-payload-shape.ts +86 -0
  31. package/src/server/rejection-codes.ts +49 -0
  32. package/src/server/total-warnings.ts +10 -0
  33. package/src/server/versions.ts +9 -0
  34. package/src/sync-notice.ts +26 -0
  35. package/src/types/commands.ts +138 -9
  36. package/src/types/connector.ts +63 -1
  37. package/src/types/customers.ts +26 -0
  38. package/src/types/index.ts +9 -2
  39. package/src/types/reconcile.ts +40 -0
  40. package/src/types/replication.ts +6 -0
  41. package/src/types/store-settings.ts +6 -0
  42. package/src/types/traits/product.ts +7 -0
  43. package/src/unauthorized.ts +15 -0
@@ -1,6 +1,6 @@
1
1
  import { createContext, useContext, useMemo, type ReactNode } from 'react';
2
2
 
3
- import { getProductStock } from '../stock-overlay';
3
+ import { getProductStock, withStockOverlay } from '../stock-overlay';
4
4
  import type { StockLevel, TallyConnector, TraitContext } from '../types';
5
5
 
6
6
  /**
@@ -89,6 +89,35 @@ export function useProductStock(doc: any): StockLevel & { asOf?: string } {
89
89
  return adapter && asOf ? { ...stock, asOf } : stock;
90
90
  }
91
91
 
92
+ /**
93
+ * The products with the nearest ConnectorProvider's reconciled stock overlay merged in (copies only; the
94
+ * documents are never changed), for components that derive stock from documents themselves. Returns
95
+ * `products` itself, unchanged, when there is no provider, no overlay, or the connector has no stock
96
+ * reconcile adapter, and the same array while its inputs are unchanged.
97
+ */
98
+ export function useStockOverlaid<Doc>(products: readonly Doc[]): readonly Doc[] {
99
+ const connector = useContext(ConnectorContext);
100
+ const { overlay } = useContext(StockOverlayContext);
101
+ const adapter = connector?.reconcile?.stock;
102
+ return useMemo(() => {
103
+ if (!adapter || !overlay) return products;
104
+ let changed = false;
105
+ const mapped = products.map((doc) => {
106
+ const next = withStockOverlay(doc, adapter, overlay as Map<string, unknown>);
107
+ if (next !== doc) changed = true;
108
+ return next;
109
+ });
110
+ return changed ? mapped : products;
111
+ }, [products, overlay, adapter]);
112
+ }
113
+
114
+ /** The reconciled stock overlay's confirmed-as-of time from the nearest ConnectorProvider, or undefined without one or when its connector has no `reconcile.stock` (the same gate `useProductStock` uses). */
115
+ export function useStockOverlayAsOf(): string | undefined {
116
+ const connector = useContext(ConnectorContext);
117
+ const { asOf } = useContext(StockOverlayContext);
118
+ return connector?.reconcile?.stock ? asOf : undefined;
119
+ }
120
+
92
121
  /**
93
122
  * Convenience hook: grab just the customer traits from the active connector.
94
123
  * Returns undefined if the connector doesn't implement customer traits.
package/src/index.ts CHANGED
@@ -24,18 +24,27 @@ export type {
24
24
  StoreSettings,
25
25
  StoreSettingsChoice,
26
26
  } from './types';
27
- export type { SignInResult, ServerCapabilities } from './types/connector';
28
- export { resolveCapabilities } from './types/connector';
27
+ export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
28
+ export type { CatalogueReconcileAdapter, CatalogueReconcileEntry } from './types/reconcile';
29
+ export { parseInfoCapabilities, parseTaxRounding, resolveCapabilities } from './types/connector';
29
30
  export { SignInError } from './sign-in';
31
+ export { ConnectorUnauthorizedError } from './unauthorized';
32
+ export { isRxdbRemoteVersionMismatch } from './rxdb-remote-version-mismatch';
33
+ export { errorKind, type ErrorKind, type SyncNotice } from './sync-notice';
30
34
  export type { SignInErrorCode } from './sign-in';
31
35
  export { StoreSettingsError } from './store-settings';
36
+ export { customerTraits, CustomerServiceError, type Customer, type CustomerInput } from './types/customers';
32
37
  export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
33
38
 
34
39
  export type {
35
40
  CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
41
+ RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
36
42
  CommandWarning, CommandError, CommandResult, OrderCreateLine,
37
- PaymentMethodKind, OrderCreatePayment, OrderCreatePayload,
38
- CommandBatchRequest, CommandBatchResponse,
43
+ PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
44
+ OrderCreateDisplay, OrderCreateTaxRate,
45
+ CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
46
+ RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionTransitionPayload,
47
+ RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
39
48
  } from './types';
40
49
 
41
50
  export {
@@ -46,11 +55,12 @@ export {
46
55
  // Money helpers
47
56
  export { currencySymbol, formatMoney, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolvePrice, resolvePriceRange } from './money';
48
57
  export { findVariantByCode } from './variants';
58
+ export { knownWarnings } from './known-warnings';
49
59
  export { compareIds } from './utils/compare-ids';
50
60
  export { STOCK_LEVELS_LAST_PASS, withStockOverlay, getProductStock } from './stock-overlay';
51
61
  export { combinePullAdapters } from './replication/combine';
52
62
  export { createReconcileFeed } from './replication/reconcile-feed';
53
- export type { ReconcileFeed, ReconcileFeedEntry } from './replication/reconcile-feed';
63
+ export type { ReconcileFeed, ReconcileFeedEntry, ReconcileFetchEntry, KeyedReconcileFeedOptions } from './replication/reconcile-feed';
54
64
 
55
65
  // Context & hooks
56
66
  export {
@@ -60,5 +70,7 @@ export {
60
70
  useCustomerTraits,
61
71
  useTraitContext,
62
72
  useProductStock,
73
+ useStockOverlaid,
74
+ useStockOverlayAsOf,
63
75
  } from './context/connector-context';
64
76
  export type { ConnectorProviderProps } from './context/connector-context';
@@ -0,0 +1,77 @@
1
+ import type { CommandWarning } from './types/commands';
2
+
3
+ function isSafeInt(value: unknown): value is number {
4
+ return typeof value === 'number' && Number.isSafeInteger(value);
5
+ }
6
+
7
+ type FiguresMismatchField = Extract<CommandWarning, { code: 'figures_mismatch' }>['fields'][number];
8
+
9
+ function figuresMismatchFields(fields: unknown): FiguresMismatchField[] | null {
10
+ if (!Array.isArray(fields) || fields.length === 0) return null;
11
+ const rebuilt: FiguresMismatchField[] = [];
12
+ for (const entry of fields) {
13
+ if (typeof entry !== 'object' || entry === null) return null;
14
+ const { field, tillMinor, serverMinor } = entry as Record<string, unknown>;
15
+ if (typeof field !== 'string' || field === '' || rebuilt.some((kept) => kept.field === field)) return null;
16
+ if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
17
+ rebuilt.push({ field, tillMinor, serverMinor });
18
+ }
19
+ return rebuilt;
20
+ }
21
+
22
+ /**
23
+ * The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
24
+ * A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
25
+ * absent, `null`, not a safe integer, zero, or not equal to `expectedMinor - serverMinor`.
26
+ * A `tax_rate_mismatch` with a negative `ratePpm` is dropped entirely; zero stays valid.
27
+ * A `customer_ignored` is dropped unless its `customerId` is a string of 1 to 64 characters.
28
+ * A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
29
+ * different figure with two differing safe integers; each entry is rebuilt from its known keys.
30
+ * A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
31
+ */
32
+ export function knownWarnings(warnings: unknown): CommandWarning[] {
33
+ if (!Array.isArray(warnings)) return [];
34
+ const kept: CommandWarning[] = [];
35
+ for (const item of warnings) {
36
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
37
+ const warning = item as Record<string, unknown>;
38
+ switch (warning.code) {
39
+ case 'total_mismatch': {
40
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
41
+ const { bridgeMinor } = warning;
42
+ const validBridge = isSafeInt(bridgeMinor) && bridgeMinor !== 0
43
+ && bridgeMinor === warning.expectedMinor - warning.serverMinor;
44
+ kept.push(validBridge
45
+ ? { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor, bridgeMinor }
46
+ : { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
47
+ break;
48
+ }
49
+ case 'insufficient_stock': {
50
+ if (typeof warning.variantId !== 'string' || warning.variantId === '') continue;
51
+ if (!isSafeInt(warning.quantity) || warning.quantity < 1) continue;
52
+ kept.push({ code: 'insufficient_stock', variantId: warning.variantId, quantity: warning.quantity });
53
+ break;
54
+ }
55
+ case 'tax_rate_mismatch': {
56
+ if (!isSafeInt(warning.ratePpm) || warning.ratePpm < 0) continue;
57
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
58
+ kept.push({ code: 'tax_rate_mismatch', ratePpm: warning.ratePpm, expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
59
+ break;
60
+ }
61
+ case 'customer_ignored': {
62
+ const { customerId } = warning;
63
+ if (typeof customerId !== 'string' || customerId === '' || customerId.length > 64) continue;
64
+ kept.push({ code: 'customer_ignored', customerId });
65
+ break;
66
+ }
67
+ case 'figures_mismatch': {
68
+ const fields = figuresMismatchFields(warning.fields);
69
+ if (fields !== null) kept.push({ code: 'figures_mismatch', fields });
70
+ break;
71
+ }
72
+ default:
73
+ continue;
74
+ }
75
+ }
76
+ return kept;
77
+ }
@@ -12,11 +12,14 @@ import type { ReplicationAdapter } from '../types';
12
12
  * checkpoint with none of the keys becomes that key's checkpoint. With no stored
13
13
  * checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
14
14
  *
15
+ * `options.batchSize` sets the combined pull page size; sub-adapters' own
16
+ * `pull.batchSize` is ignored.
17
+ * Duplicates across sub-adapters are resolved by this key, the last one winning; it defaults to `doc.id`. Pass the collection's primary key when `id` is not it (WooCommerce's uuid, #331): two documents that share an `id`, such as a product's new copy and its old copy's tombstone, must both reach the collection.
15
18
  * Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
16
19
  */
17
20
  export function combinePullAdapters<Doc>(
18
21
  adapters: Record<string, ReplicationAdapter<Doc, any>>,
19
- options: { legacyKey?: string } = {},
22
+ options: { legacyKey?: string; batchSize?: number; key?: (doc: Doc) => unknown } = {},
20
23
  ): ReplicationAdapter<Doc, Record<string, any>> {
21
24
  const keys = Object.keys(adapters);
22
25
  for (const key of keys) {
@@ -26,6 +29,7 @@ export function combinePullAdapters<Doc>(
26
29
  }
27
30
  return {
28
31
  pull: {
32
+ batchSize: options.batchSize,
29
33
  async handler(lastCheckpoint, batchSize, context) {
30
34
  let previous = lastCheckpoint;
31
35
  if (options.legacyKey && previous && typeof previous === 'object'
@@ -47,26 +51,28 @@ export function combinePullAdapters<Doc>(
47
51
  }
48
52
  previous = seeded;
49
53
  }
50
- const byId = new Map<unknown, Doc & { _deleted: boolean }>();
54
+ const keyOf = options.key ?? ((doc: Doc) => (doc as { id?: unknown }).id);
55
+ const byKey = new Map<unknown, Doc & { _deleted: boolean }>();
51
56
  const checkpoint: Record<string, any> = {};
52
57
  // Call sub-adapters strictly one after another, in key order: a
53
58
  // correctness rule, not politeness. Each feed writes whole documents.
54
59
  // Sequential calls with the last duplicate winning mean every document
55
- // comes from the latest fetch of this call, and every fetch in the next
56
- // call happens after this call's writes. Concurrent feeds could let a
60
+ // comes from the latest fetch of this call. RxDB 16.21.1 can fetch the next
61
+ // call before these writes finish, but its persistence queue keeps fetch
62
+ // order (pending duplicates keep the latest). Concurrent feeds could let a
57
63
  // fetch made before another feed's newer write land after it and revert
58
64
  // it, with neither checkpoint ever revisiting the document.
59
65
  for (const key of keys) {
60
66
  const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
61
- for (const doc of result.documents) byId.set((doc as { id?: unknown }).id, doc);
67
+ for (const doc of result.documents) byKey.set(keyOf(doc), doc);
62
68
  // RxDB merges only the top level of the combined checkpoint, so merge
63
69
  // each sub-checkpoint here as it would for a single adapter. Spread
64
70
  // keeps a sub-adapter's explicit undefined (cleared pass state).
65
71
  checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
66
72
  }
67
- // Each sub-adapter returns unique ids, so one full sub-page makes the
73
+ // Each sub-adapter returns unique keys, so one full sub-page makes the
68
74
  // combined page full: RxDB keeps pulling while any sub-adapter has more.
69
- return { documents: [...byId.values()], checkpoint };
75
+ return { documents: [...byKey.values()], checkpoint };
70
76
  },
71
77
  },
72
78
  };
@@ -4,41 +4,76 @@ import type { ReplicationAdapter } from '../types/replication';
4
4
  /** At most this many ids per `fetchByIds` call (ADR-060). */
5
5
  const MAX_CHUNK = 1000;
6
6
 
7
- export interface ReconcileFeedEntry<Doc = any> {
8
- id: string;
9
- local: Doc;
7
+ /**
8
+ * One queued correction, keyed by the local primary key: `key`, or `id`, its
9
+ * older name. An entry without a local copy may carry the listing's key instead
10
+ * (#313). `local` is the till's copy, if it has one; `remote` is whatever the
11
+ * connector needs to refetch it.
12
+ */
13
+ export type ReconcileFeedEntry<Doc = any> = ({ key: string; id?: undefined } | { id: string; key?: undefined }) & {
14
+ local?: Doc;
15
+ remote?: unknown;
10
16
  /**
11
17
  * Re-deliver if the product still exists; never tombstone if missing (the
12
18
  * fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
13
19
  * brake, enqueues deletable entries.
14
20
  */
15
21
  refreshOnly?: boolean;
16
- }
22
+ /** Proven gone (the catalogue reconcile, #248): written as deleted from `local`, without a fetch. */
23
+ tombstone?: boolean;
24
+ };
25
+ /** What a keyed feed's `fetchByIds` receives for each entry. */
26
+ export interface ReconcileFetchEntry<Doc = any> { key: string; local?: Doc; remote?: unknown }
17
27
  export interface CreateReconcileFeedOptions<Doc = any> {
18
- /** The current projected documents for the ids that still exist. */
28
+ /** The current projected documents for the ids that still exist, matched back by `doc.id`. */
19
29
  fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
20
30
  }
31
+ /** A feed keyed by the primary key where that is not `doc.id` (WooCommerce's uuid, #248). */
32
+ export interface KeyedReconcileFeedOptions<Doc = any> {
33
+ /** The local primary key of a fetched document; fetched documents are matched to entries by it. */
34
+ key(doc: Doc): string;
35
+ /**
36
+ * The value an entry's `remote` names this document by. An entry with no local copy whose key finds no
37
+ * fetched document is matched by it (a listing that carries no primary key, #313).
38
+ */
39
+ remote?(doc: Doc): unknown;
40
+ /** The current documents for the entries that still exist. A document may carry `_deleted: true` (an unpublished product). */
41
+ fetchByIds(entries: Array<ReconcileFetchEntry<Doc>>, context: SyncContext): Promise<Doc[]>;
42
+ }
21
43
  export interface ReconcileFeed<Doc = any> {
22
44
  /** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
23
45
  adapter: ReplicationAdapter<Doc, { n: number }>;
24
46
  /**
25
- * Add entries to the in-memory queue, de-duplicated by id, last entry's
26
- * `local` wins. `refreshOnly` is merged separately: it is true only when
27
- * every merged entry for that id was `refreshOnly`, so a deletable entry
28
- * (the id reconcile's) is never downgraded by a later refresh-only one.
47
+ * Add entries to the in-memory queue, de-duplicated by key, last entry wins.
48
+ * `refreshOnly` is merged separately: it is true only when every merged
49
+ * entry for that key was `refreshOnly`, so a deletable entry (the id
50
+ * reconcile's) is never downgraded by a later refresh-only one.
29
51
  */
30
52
  enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
31
53
  }
32
54
 
33
- /** Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060). */
34
- export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc> {
55
+ /**
56
+ * Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060).
57
+ * Two overloads: with `key`, `fetchByIds` receives the entries and fetched documents are matched by
58
+ * `key(doc)`; without it, `fetchByIds` receives bare ids and documents are matched by `doc.id`.
59
+ */
60
+ export function createReconcileFeed<Doc = any>(options: KeyedReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
61
+ export function createReconcileFeed<Doc = any>(options: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
62
+ export function createReconcileFeed<Doc = any>(
63
+ options: KeyedReconcileFeedOptions<Doc> | CreateReconcileFeedOptions<Doc>,
64
+ ): ReconcileFeed<Doc> {
65
+ const keyed = 'key' in options && typeof options.key === 'function' ? options : undefined;
66
+ const docKey = keyed ? keyed.key : (doc: Doc) => (doc as { id?: unknown }).id;
67
+ const fetch = (chunk: Array<ReconcileFeedEntry<Doc>>, context: SyncContext): Promise<Doc[]> => keyed
68
+ ? keyed.fetchByIds(chunk.map((e) => ({ key: keyOf(e), local: e.local, remote: e.remote })), context)
69
+ : (options as CreateReconcileFeedOptions<Doc>).fetchByIds(chunk.map(keyOf), context);
35
70
  let queue = new Map<string, ReconcileFeedEntry<Doc>>();
36
71
  // refreshOnly is true only if both the prior and the incoming entry were
37
72
  // refreshOnly: a deletable entry is never downgraded by a later refresh-only one.
38
73
  const merge = (prior: ReconcileFeedEntry<Doc> | undefined, e: ReconcileFeedEntry<Doc>): ReconcileFeedEntry<Doc> =>
39
74
  ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
40
75
  const enqueue = (entries: Array<ReconcileFeedEntry<Doc>>) => {
41
- for (const e of entries) queue.set(e.id, merge(queue.get(e.id), e));
76
+ for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
42
77
  };
43
78
 
44
79
  const adapter: ReplicationAdapter<Doc, { n: number }> = {
@@ -50,25 +85,38 @@ export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFe
50
85
  queue = new Map();
51
86
  try {
52
87
  const documents: Array<Doc & { _deleted: boolean }> = [];
53
- // Fetch in chunks of at most MAX_CHUNK ids per call.
88
+ // Fetch in chunks of at most MAX_CHUNK entries per call; a tombstone is never fetched.
54
89
  for (let i = 0; i < entries.length; i += MAX_CHUNK) {
55
90
  const chunk = entries.slice(i, i + MAX_CHUNK);
56
- const fetched = await fetchByIds(chunk.map((e) => e.id), context);
57
- const byId = new Map(fetched.map((doc) => [(doc as { id?: unknown }).id, doc]));
91
+ const toFetch = chunk.filter((e) => !e.tombstone);
92
+ const fetched = toFetch.length ? await fetch(toFetch, context) : [];
93
+ const byKey = new Map(fetched.map((doc) => [docKey(doc), doc]));
94
+ const byRemote = keyed?.remote && new Map(fetched.map((doc) => [keyed.remote!(doc), doc]));
95
+ const pushed = new Set<Doc>();
58
96
  for (const entry of chunk) {
59
- const doc = byId.get(entry.id);
60
- if (doc) documents.push({ ...doc, _deleted: false });
97
+ const doc = entry.tombstone ? undefined : byKey.get(keyOf(entry))
98
+ ?? (entry.local === undefined && entry.remote !== undefined && byRemote ? byRemote.get(entry.remote) : undefined);
99
+ // The backend primary key changed (a WCPOS uuid reassigned, #331): the old copy goes and the current one arrives.
100
+ const moved = !entry.tombstone && !doc && entry.local !== undefined && entry.remote !== undefined && byRemote
101
+ ? byRemote.get(entry.remote) : undefined;
102
+ const fetchedDoc = doc ?? moved;
103
+ // A fetched document keeps a `_deleted` the connector set (an unpublished product, #248).
104
+ if (fetchedDoc && !pushed.has(fetchedDoc)) {
105
+ documents.push({ ...fetchedDoc, _deleted: (fetchedDoc as { _deleted?: boolean })._deleted ?? false });
106
+ pushed.add(fetchedDoc);
107
+ }
61
108
  // A refreshOnly entry (the fingerprint path) is skipped, not tombstoned, when the
62
109
  // product is missing: only the id reconcile's braked entries may delete (ADR-060).
63
- else if (!entry.refreshOnly) documents.push({ ...entry.local, _deleted: true });
110
+ // An entry with no local copy has nothing to delete.
111
+ if (!doc && !entry.refreshOnly && entry.local) documents.push({ ...entry.local, _deleted: true });
64
112
  }
65
113
  }
66
114
  return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
67
115
  } catch (error) {
68
116
  // Put entries back at the front; anything queued mid-fetch wins, merged
69
117
  // by the same rule, so a failed fetch never downgrades a deletable entry. RxDB retries.
70
- const restored = new Map(entries.map((e) => [e.id, e]));
71
- for (const [id, e] of queue) restored.set(id, merge(restored.get(id), e));
118
+ const restored = new Map(entries.map((e) => [keyOf(e), e]));
119
+ for (const [key, e] of queue) restored.set(key, merge(restored.get(key), e));
72
120
  queue = restored;
73
121
  throw error;
74
122
  }
@@ -77,3 +125,8 @@ export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFe
77
125
  };
78
126
  return { adapter, enqueue };
79
127
  }
128
+
129
+ /** An entry's local primary key: `key`, or `id`, its older name. */
130
+ function keyOf(entry: ReconcileFeedEntry): string {
131
+ return (entry.key ?? entry.id) as string;
132
+ }
@@ -3,13 +3,9 @@ import { clone, type MangoQuery, type MangoQuerySelector, type RxCollection } fr
3
3
  /**
4
4
  * Reads straight from the collection's storage, past RxDB's cached query result.
5
5
  *
6
- * Why: in RxDB 16.21.1, a document written while a query's storage read is in flight (about one
7
- * to three microtasks after it starts) is counted as seen but is missing from the result. RxDB
8
- * caches that `RxQuery` per query string, so every later `find(sameQuery).exec()` or
9
- * `count(sameQuery).exec()` returns the stale result, and a later matching write doesn't heal it.
10
- * No subscription is needed. This is "bug 4" in TallyUI's local RxDB repro (the query-cache-stale
11
- * script beside the migration checkpoint repro). For the order outbox it left a sale unsent until
12
- * the app restarted.
6
+ * Originally bypassed RxDB 16.21.1's bug 4, fixed in RxDB 17 (rxdb#7067) by snapshotting the
7
+ * change counter before a read and rerunning when it moves. `readFresh`, `countFresh` and
8
+ * `watchFresh` remain correct public API; retiring them is a separate decision.
13
9
  *
14
10
  * The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
15
11
  * `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
@@ -3,8 +3,8 @@ import type { MangoQuery, RxCollection } from 'rxdb';
3
3
  import { readFresh } from './read-fresh';
4
4
 
5
5
  /**
6
- * A live list a cached `RxQuery` can't leave stale (bug 4 in the local RxDB 16.21.1 repro,
7
- * `readFresh`'s doc comment): a write during a query's storage read never reaches it, for good.
6
+ * RxDB 17 fixed RxDB 16.21.1's bug 4 (rxdb#7067); `readFresh`, `countFresh` and `watchFresh`
7
+ * remain correct public API. Retiring them is a separate decision.
8
8
  * `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
9
9
  * `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
10
10
  * still in flight when a newer one starts. It is one event per storage change bulk, not per
@@ -0,0 +1,30 @@
1
+ // How RxDB's remote storage re-throws a worker's rejected createStorageInstance on the main thread
2
+ // (rxdb 17.5.0 src/plugins/storage-remote/rx-storage-remote.ts:100):
3
+ // `new Error('could not create instance ' + JSON.stringify(error))`.
4
+ const REMOTE_CREATE_PREFIX = 'could not create instance ';
5
+
6
+ /**
7
+ * True for RxDB's RM1: the remote storage worker was built on another RxDB
8
+ * version than the main thread, e.g. a stale worker the browser cached from
9
+ * before an upgrade. Reloading loads the matching worker.
10
+ *
11
+ * Matched by structure, never by substring. An `RxError` (rxdb 17.5.0
12
+ * src/rx-error.ts) has own `code`, `message`, `url`, `parameters` and
13
+ * `rxdb: true`; its `name` is a getter. So RM1 is either an object whose own
14
+ * `code` is `'RM1'` (with `rxdb === true` when `rxdb` is present), or an
15
+ * error, `{ message }` copy or string whose message is the remote storage's
16
+ * `could not create instance ` followed by JSON with `rxdb: true` and
17
+ * `code: 'RM1'`. Needs no rxdb import.
18
+ */
19
+ export function isRxdbRemoteVersionMismatch(error: unknown): boolean {
20
+ const { code, rxdb, message } = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>;
21
+ if (code === 'RM1' && (rxdb ?? true) === true) return true;
22
+ const text = typeof error === 'string' ? error : message;
23
+ if (typeof text !== 'string' || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
24
+ try {
25
+ const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length)) as Record<string, unknown> | null;
26
+ return wrapped?.rxdb === true && wrapped.code === 'RM1';
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
@@ -0,0 +1,139 @@
1
+ [
2
+ {
3
+ "name": "order-create-v3 golden fixture",
4
+ "envelope": {
5
+ "type": "order.create",
6
+ "version": 3,
7
+ "payload": {
8
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000002",
9
+ "createdAt": "2026-09-28T10:00:00.000Z",
10
+ "currency": "EUR",
11
+ "pricesIncludeTax": true,
12
+ "lines": [
13
+ {
14
+ "clientLineId": "line_inclusive",
15
+ "variantId": "variant_inclusive",
16
+ "title": "Inclusive item",
17
+ "quantity": 2,
18
+ "unitPriceMinor": 1200,
19
+ "discountMinor": 203
20
+ },
21
+ {
22
+ "clientLineId": "line_exclusive",
23
+ "variantId": "variant_exclusive",
24
+ "title": "Exclusive item",
25
+ "quantity": 1,
26
+ "unitPriceMinor": 1000,
27
+ "taxInclusive": false,
28
+ "discountMinor": 37
29
+ }
30
+ ],
31
+ "payments": [
32
+ {
33
+ "clientPaymentId": "payment_cash",
34
+ "method": "cash",
35
+ "amountMinor": 3256,
36
+ "tenderedMinor": 4000,
37
+ "changeMinor": 744,
38
+ "reference": "cash_receipt_1"
39
+ }
40
+ ],
41
+ "subtotalMinor": 2794,
42
+ "discountMinor": 240,
43
+ "taxMinor": 462,
44
+ "totalMinor": 3256,
45
+ "display": {
46
+ "currency": "EUR",
47
+ "exponent": 2,
48
+ "taxInclusive": true,
49
+ "subtotalMinor": 3500,
50
+ "discountMinor": 244,
51
+ "taxMinor": 462,
52
+ "totalMinor": 3256,
53
+ "lines": [
54
+ {
55
+ "clientLineId": "line_inclusive",
56
+ "amountMinor": 2400,
57
+ "discounts": [
58
+ {
59
+ "discountId": "discount_line",
60
+ "label": "Line discount",
61
+ "amountMinor": 120
62
+ }
63
+ ]
64
+ },
65
+ {
66
+ "clientLineId": "line_exclusive",
67
+ "amountMinor": 1100,
68
+ "discounts": []
69
+ }
70
+ ],
71
+ "orderDiscountMinor": 124
72
+ },
73
+ "taxByRate": [
74
+ {
75
+ "ratePpm": 200000,
76
+ "code": "VAT20",
77
+ "netMinor": 1831,
78
+ "taxMinor": 366,
79
+ "grossMinor": 2197
80
+ },
81
+ {
82
+ "ratePpm": 100000,
83
+ "netMinor": 963,
84
+ "taxMinor": 96,
85
+ "grossMinor": 1059
86
+ }
87
+ ],
88
+ "customer": {
89
+ "email": "buyer@example.com",
90
+ "customerId": "cus_golden_v3"
91
+ },
92
+ "registerId": "register_golden",
93
+ "cashierRef": "cashier_golden",
94
+ "sessionId": "019f6d2e-7800-7000-8000-000000000003"
95
+ }
96
+ },
97
+ "canonical": "{\"payload\":{\"cashierRef\":\"cashier_golden\",\"clientOrderId\":\"019f6d2e-7800-7000-8000-000000000002\",\"createdAt\":\"2026-09-28T10:00:00.000Z\",\"currency\":\"EUR\",\"customer\":{\"customerId\":\"cus_golden_v3\",\"email\":\"buyer@example.com\"},\"discountMinor\":240,\"display\":{\"currency\":\"EUR\",\"discountMinor\":244,\"exponent\":2,\"lines\":[{\"amountMinor\":2400,\"clientLineId\":\"line_inclusive\",\"discounts\":[{\"amountMinor\":120,\"discountId\":\"discount_line\",\"label\":\"Line discount\"}]},{\"amountMinor\":1100,\"clientLineId\":\"line_exclusive\",\"discounts\":[]}],\"orderDiscountMinor\":124,\"subtotalMinor\":3500,\"taxInclusive\":true,\"taxMinor\":462,\"totalMinor\":3256},\"lines\":[{\"clientLineId\":\"line_inclusive\",\"discountMinor\":203,\"quantity\":2,\"title\":\"Inclusive item\",\"unitPriceMinor\":1200,\"variantId\":\"variant_inclusive\"},{\"clientLineId\":\"line_exclusive\",\"discountMinor\":37,\"quantity\":1,\"taxInclusive\":false,\"title\":\"Exclusive item\",\"unitPriceMinor\":1000,\"variantId\":\"variant_exclusive\"}],\"payments\":[{\"amountMinor\":3256,\"changeMinor\":744,\"clientPaymentId\":\"payment_cash\",\"method\":\"cash\",\"reference\":\"cash_receipt_1\",\"tenderedMinor\":4000}],\"pricesIncludeTax\":true,\"registerId\":\"register_golden\",\"sessionId\":\"019f6d2e-7800-7000-8000-000000000003\",\"subtotalMinor\":2794,\"taxByRate\":[{\"code\":\"VAT20\",\"grossMinor\":2197,\"netMinor\":1831,\"ratePpm\":200000,\"taxMinor\":366},{\"grossMinor\":1059,\"netMinor\":963,\"ratePpm\":100000,\"taxMinor\":96}],\"taxMinor\":462,\"totalMinor\":3256},\"type\":\"order.create\",\"version\":3}",
98
+ "fingerprint": "aea62fe9f460bbdfd93771cbe08b3bb98e5761f172b974b62d72dfe30f6bc436"
99
+ },
100
+ {
101
+ "name": "key order, nested objects, undefined field dropped",
102
+ "envelope": {
103
+ "type": "order.create",
104
+ "version": 1,
105
+ "payload": {
106
+ "z": 1,
107
+ "a": {
108
+ "d": [
109
+ 3,
110
+ 1,
111
+ 2
112
+ ],
113
+ "c": "x"
114
+ },
115
+ "m": null
116
+ }
117
+ },
118
+ "canonical": "{\"payload\":{\"a\":{\"c\":\"x\",\"d\":[3,1,2]},\"m\":null,\"z\":1},\"type\":\"order.create\",\"version\":1}",
119
+ "fingerprint": "cecf2c94e7da1867b95b66d5e46e686bf274f780e312efb2d8387841cc00d483"
120
+ },
121
+ {
122
+ "name": "undefined array item becomes null; unicode and negative numbers",
123
+ "envelope": {
124
+ "type": "register.movement.record",
125
+ "version": 1,
126
+ "payload": {
127
+ "items": [
128
+ 1,
129
+ null,
130
+ "é",
131
+ -0.5
132
+ ],
133
+ "reason": "café \"quoted\""
134
+ }
135
+ },
136
+ "canonical": "{\"payload\":{\"items\":[1,null,\"é\",-0.5],\"reason\":\"café \\\"quoted\\\"\"},\"type\":\"register.movement.record\",\"version\":1}",
137
+ "fingerprint": "95316177d791a50f25937d646cae922766e33dc77e3287b3dbec791f9c410948"
138
+ }
139
+ ]