@tallyui/core 0.2.0 → 2.0.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,9 +1,263 @@
1
+ // src/types/connector.ts
2
+ function resolveCapabilities(fresh, stored) {
3
+ return fresh ?? stored;
4
+ }
5
+
6
+ // src/sign-in.ts
7
+ var SignInError = class extends Error {
8
+ code;
9
+ status;
10
+ constructor(code, message, status) {
11
+ super(message);
12
+ this.name = "SignInError";
13
+ this.code = code;
14
+ this.status = status;
15
+ }
16
+ };
17
+
18
+ // src/store-settings.ts
19
+ var StoreSettingsError = class extends Error {
20
+ code;
21
+ choices;
22
+ constructor(code, message, choices) {
23
+ super(message);
24
+ this.name = "StoreSettingsError";
25
+ this.code = code;
26
+ this.choices = choices;
27
+ }
28
+ };
29
+
30
+ // src/commands.ts
31
+ var COMMANDS_PATH = "/tally/v1/commands";
32
+ var PROTOCOL_HEADER = "X-Tally-Protocol";
33
+ var PROTOCOL_VERSION = 1;
34
+ var MAX_COMMANDS_PER_BATCH = 50;
35
+ function isCommandBatchResponse(value) {
36
+ return typeof value === "object" && value !== null && "results" in value && Array.isArray(value.results) && value.results.every(
37
+ (result) => typeof result === "object" && result !== null && "id" in result && typeof result.id === "string" && "status" in result && (result.status === "applied" || result.status === "duplicate" || result.status === "rejected")
38
+ );
39
+ }
40
+
41
+ // src/money.ts
42
+ var digitsCache = /* @__PURE__ */ new Map();
43
+ function minorUnitDigits(currency) {
44
+ const code = currency.toUpperCase();
45
+ let digits = digitsCache.get(code);
46
+ if (digits === void 0) {
47
+ try {
48
+ digits = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
49
+ } catch {
50
+ digits = 2;
51
+ }
52
+ digitsCache.set(code, digits);
53
+ }
54
+ return digits;
55
+ }
56
+ var symbolCache = /* @__PURE__ */ new Map();
57
+ function currencySymbol(currency, locale) {
58
+ const code = currency.toUpperCase();
59
+ const key = `${code}:${locale ?? ""}`;
60
+ let symbol = symbolCache.get(key);
61
+ if (symbol === void 0) {
62
+ try {
63
+ const part = new Intl.NumberFormat(locale, { style: "currency", currency: code }).formatToParts(0).find((p) => p.type === "currency");
64
+ symbol = part?.value ?? code;
65
+ } catch {
66
+ symbol = code;
67
+ }
68
+ symbolCache.set(key, symbol);
69
+ }
70
+ return symbol;
71
+ }
72
+ function moneyFromMajor(value, currency) {
73
+ if (value === null || value === void 0 || value === "") return void 0;
74
+ const major = typeof value === "number" ? value : Number(value);
75
+ if (!Number.isFinite(major)) return void 0;
76
+ const code = currency.toUpperCase();
77
+ return { amount: Math.round(major * 10 ** minorUnitDigits(code)), currency: code };
78
+ }
79
+ function moneyFromDecimalString(text, currency) {
80
+ const trimmed = text.trim();
81
+ if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
82
+ const code = currency.toUpperCase();
83
+ const digits = minorUnitDigits(code);
84
+ const [whole, fraction = ""] = trimmed.split(".");
85
+ if (fraction.length > digits) return void 0;
86
+ const amount = Number(whole) * 10 ** digits + Number(fraction.padEnd(digits, "0"));
87
+ return Number.isSafeInteger(amount) ? { amount, currency: code } : void 0;
88
+ }
89
+ function moneyToMajor(money) {
90
+ return money.amount / 10 ** minorUnitDigits(money.currency);
91
+ }
92
+ var formatters = /* @__PURE__ */ new Map();
93
+ function formatMoney(money, locale) {
94
+ if (money.currency === "XXX") return void 0;
95
+ const key = `${money.currency}:${locale ?? ""}`;
96
+ let formatter = formatters.get(key);
97
+ if (!formatter) {
98
+ try {
99
+ formatter = new Intl.NumberFormat(locale, { style: "currency", currency: money.currency });
100
+ } catch {
101
+ return void 0;
102
+ }
103
+ formatters.set(key, formatter);
104
+ }
105
+ return formatter.format(moneyToMajor(money));
106
+ }
107
+ function resolvePrice(prices, currency) {
108
+ const code = (currency ?? prices[0]?.currency)?.toUpperCase();
109
+ const inCurrency = prices.filter((p) => p.currency === code);
110
+ const base = inCurrency.find((p) => p.kind === "base");
111
+ const sale = inCurrency.find((p) => p.kind === "sale");
112
+ const strip = (p) => ({
113
+ amount: p.amount,
114
+ currency: p.currency,
115
+ ...p.taxInclusive !== void 0 ? { taxInclusive: p.taxInclusive } : {}
116
+ });
117
+ if (sale && (!base || sale.amount < base.amount)) {
118
+ return { current: strip(sale), was: base ? strip(base) : void 0 };
119
+ }
120
+ return base ? { current: strip(base) } : void 0;
121
+ }
122
+ function resolvePriceRange(variants, currency) {
123
+ let range;
124
+ for (const variant of variants) {
125
+ const resolved = resolvePrice(variant.prices, currency);
126
+ if (!resolved) continue;
127
+ const money = resolved.current;
128
+ if (!range) {
129
+ range = { min: money, max: money };
130
+ } else if (money.currency === range.min.currency) {
131
+ if (money.amount < range.min.amount) range.min = money;
132
+ if (money.amount > range.max.amount) range.max = money;
133
+ }
134
+ }
135
+ return range;
136
+ }
137
+
138
+ // src/variants.ts
139
+ function findVariantByCode(variants, code) {
140
+ const normalized = code.trim().toLowerCase();
141
+ if (!normalized) return void 0;
142
+ return variants.find((variant) => variant.barcode?.trim().toLowerCase() === normalized) ?? variants.find((variant) => variant.sku?.trim().toLowerCase() === normalized);
143
+ }
144
+
145
+ // src/utils/compare-ids.ts
146
+ var INTEGER_STRING = /^\d+$/;
147
+ function compareIds(a, b) {
148
+ const sa = String(a);
149
+ const sb = String(b);
150
+ const aNum = INTEGER_STRING.test(sa);
151
+ const bNum = INTEGER_STRING.test(sb);
152
+ if (aNum && bNum) {
153
+ const diff = BigInt(sa) - BigInt(sb);
154
+ if (diff !== 0n) return diff < 0n ? -1 : 1;
155
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
156
+ }
157
+ if (aNum !== bNum) return aNum ? -1 : 1;
158
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
159
+ }
160
+
161
+ // src/stock-overlay.ts
162
+ var STOCK_LEVELS_LAST_PASS = "last-pass";
163
+ function withStockOverlay(doc, adapter, overlay) {
164
+ if (!adapter || !overlay) return doc;
165
+ const fields = adapter.overlay(doc, overlay);
166
+ return fields ? { ...doc, ...fields } : doc;
167
+ }
168
+ function getProductStock(doc, traits, adapter, overlay) {
169
+ return traits.getStock(withStockOverlay(doc, adapter, overlay));
170
+ }
171
+
172
+ // src/replication/combine.ts
173
+ function combinePullAdapters(adapters, options = {}) {
174
+ const keys = Object.keys(adapters);
175
+ for (const key of keys) {
176
+ if (adapters[key].push || adapters[key].pull.stream$) {
177
+ throw new Error(`combinePullAdapters: sub-adapter "${key}" has push or pull.stream$; only pull handlers can be combined.`);
178
+ }
179
+ }
180
+ return {
181
+ pull: {
182
+ async handler(lastCheckpoint, batchSize, context) {
183
+ let previous = lastCheckpoint;
184
+ if (options.legacyKey && previous && typeof previous === "object" && Object.keys(previous).length && !keys.some((key) => key in previous)) {
185
+ previous = { [options.legacyKey]: previous };
186
+ }
187
+ if (!previous || !Object.keys(previous).length) {
188
+ const seeded = {};
189
+ for (const key of keys) {
190
+ const { pull } = adapters[key];
191
+ if (pull.seedCheckpoint) seeded[key] = await pull.seedCheckpoint(context);
192
+ }
193
+ previous = seeded;
194
+ }
195
+ const byId = /* @__PURE__ */ new Map();
196
+ const checkpoint = {};
197
+ for (const key of keys) {
198
+ const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
199
+ for (const doc of result.documents) byId.set(doc.id, doc);
200
+ checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
201
+ }
202
+ return { documents: [...byId.values()], checkpoint };
203
+ }
204
+ }
205
+ };
206
+ }
207
+
208
+ // src/replication/reconcile-feed.ts
209
+ var MAX_CHUNK = 1e3;
210
+ function createReconcileFeed({ fetchByIds }) {
211
+ let queue = /* @__PURE__ */ new Map();
212
+ const merge = (prior, e) => ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
213
+ const enqueue = (entries) => {
214
+ for (const e of entries) queue.set(e.id, merge(queue.get(e.id), e));
215
+ };
216
+ const adapter = {
217
+ pull: {
218
+ async handler(lastCheckpoint, _batchSize, context) {
219
+ if (queue.size === 0) return { documents: [], checkpoint: lastCheckpoint ?? { n: 0 } };
220
+ const entries = [...queue.values()];
221
+ queue = /* @__PURE__ */ new Map();
222
+ try {
223
+ const documents = [];
224
+ for (let i = 0; i < entries.length; i += MAX_CHUNK) {
225
+ const chunk = entries.slice(i, i + MAX_CHUNK);
226
+ const fetched = await fetchByIds(chunk.map((e) => e.id), context);
227
+ const byId = new Map(fetched.map((doc) => [doc.id, doc]));
228
+ for (const entry of chunk) {
229
+ const doc = byId.get(entry.id);
230
+ if (doc) documents.push({ ...doc, _deleted: false });
231
+ else if (!entry.refreshOnly) documents.push({ ...entry.local, _deleted: true });
232
+ }
233
+ }
234
+ return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
235
+ } catch (error) {
236
+ const restored = new Map(entries.map((e) => [e.id, e]));
237
+ for (const [id, e] of queue) restored.set(id, merge(restored.get(id), e));
238
+ queue = restored;
239
+ throw error;
240
+ }
241
+ }
242
+ }
243
+ };
244
+ return { adapter, enqueue };
245
+ }
246
+
1
247
  // src/context/connector-context.tsx
2
- import { createContext, useContext } from "react";
248
+ import { createContext, useContext, useMemo } from "react";
3
249
  import { jsx } from "react/jsx-runtime";
4
250
  var ConnectorContext = createContext(null);
5
- function ConnectorProvider({ connector, children }) {
6
- return /* @__PURE__ */ jsx(ConnectorContext.Provider, { value: connector, children });
251
+ var EMPTY_TRAIT_CONTEXT = {};
252
+ var TraitContextContext = createContext(EMPTY_TRAIT_CONTEXT);
253
+ var EMPTY_STOCK_OVERLAY = {};
254
+ var StockOverlayContext = createContext(EMPTY_STOCK_OVERLAY);
255
+ function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }) {
256
+ const overlay = useMemo(
257
+ () => stockOverlay || stockOverlayAsOf ? { overlay: stockOverlay, asOf: stockOverlayAsOf } : EMPTY_STOCK_OVERLAY,
258
+ [stockOverlay, stockOverlayAsOf]
259
+ );
260
+ return /* @__PURE__ */ jsx(ConnectorContext.Provider, { value: connector, children: /* @__PURE__ */ jsx(TraitContextContext.Provider, { value: traitContext ?? EMPTY_TRAIT_CONTEXT, children: /* @__PURE__ */ jsx(StockOverlayContext.Provider, { value: overlay, children }) }) });
7
261
  }
8
262
  function useConnector() {
9
263
  const connector = useContext(ConnectorContext);
@@ -18,13 +272,49 @@ function useProductTraits() {
18
272
  const connector = useConnector();
19
273
  return connector.traits.product;
20
274
  }
275
+ function useTraitContext() {
276
+ return useContext(TraitContextContext);
277
+ }
278
+ function useProductStock(doc) {
279
+ const connector = useConnector();
280
+ const { overlay, asOf } = useContext(StockOverlayContext);
281
+ const adapter = connector.reconcile?.stock;
282
+ if (!overlay) return connector.traits.product.getStock(doc);
283
+ const stock = getProductStock(doc, connector.traits.product, adapter, overlay);
284
+ return adapter && asOf ? { ...stock, asOf } : stock;
285
+ }
21
286
  function useCustomerTraits() {
22
287
  const connector = useConnector();
23
288
  return connector.traits.customer;
24
289
  }
25
290
  export {
291
+ COMMANDS_PATH,
26
292
  ConnectorProvider,
293
+ MAX_COMMANDS_PER_BATCH,
294
+ PROTOCOL_HEADER,
295
+ PROTOCOL_VERSION,
296
+ STOCK_LEVELS_LAST_PASS,
297
+ SignInError,
298
+ StoreSettingsError,
299
+ combinePullAdapters,
300
+ compareIds,
301
+ createReconcileFeed,
302
+ currencySymbol,
303
+ findVariantByCode,
304
+ formatMoney,
305
+ getProductStock,
306
+ isCommandBatchResponse,
307
+ minorUnitDigits,
308
+ moneyFromDecimalString,
309
+ moneyFromMajor,
310
+ moneyToMajor,
311
+ resolveCapabilities,
312
+ resolvePrice,
313
+ resolvePriceRange,
27
314
  useConnector,
28
315
  useCustomerTraits,
29
- useProductTraits
316
+ useProductStock,
317
+ useProductTraits,
318
+ useTraitContext,
319
+ withStockOverlay
30
320
  };
@@ -0,0 +1,41 @@
1
+ import { RxCollection, MangoQuerySelector, MangoQuery } from 'rxdb';
2
+ import { Observable } from 'rxjs';
3
+
4
+ /**
5
+ * Reads straight from the collection's storage, past RxDB's cached query result.
6
+ *
7
+ * Why: in RxDB 16.21.1, a document written while a query's storage read is in flight (about one
8
+ * to three microtasks after it starts) is counted as seen but is missing from the result. RxDB
9
+ * caches that `RxQuery` per query string, so every later `find(sameQuery).exec()` or
10
+ * `count(sameQuery).exec()` returns the stale result, and a later matching write doesn't heal it.
11
+ * No subscription is needed. This is "bug 4" in TallyUI's local RxDB repro (the query-cache-stale
12
+ * script beside the migration checkpoint repro). For the order outbox it left a sale unsent until
13
+ * the app restarted.
14
+ *
15
+ * The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
16
+ * `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
17
+ * storage instance an `RxQuery` uses, but skips `RxQuery` and `RxDocument`, so it is untested with
18
+ * key compression and field encryption; no TallyUI collection uses either.
19
+ *
20
+ * Returns plain, deep-cloned document data without RxDB's metadata. Use `findOne(id)` for an
21
+ * `RxDocument` to write through; its `incrementalModify` modifier sees the stored state.
22
+ */
23
+ declare function readFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Promise<T[]>;
24
+ /**
25
+ * Counts straight from the collection's storage, past RxDB's cached count (see `readFresh`).
26
+ * Unlike `count().exec()`, it doesn't refuse a storage that reports a slow count.
27
+ */
28
+ declare function countFresh<T>(collection: RxCollection<T>, selector: MangoQuerySelector<T>): Promise<number>;
29
+
30
+ /**
31
+ * A live list a cached `RxQuery` can't leave stale (bug 4 in the local RxDB 16.21.1 repro,
32
+ * `readFresh`'s doc comment): a write during a query's storage read never reaches it, for good.
33
+ * `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
34
+ * `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
35
+ * still in flight when a newer one starts. It is one event per storage change bulk, not per
36
+ * document (`collection.$`), so a `bulkInsert` of 100 documents costs one re-read, not 100. Still
37
+ * one storage read per write, so it's for a list a cashier would act on going stale, not every list.
38
+ */
39
+ declare function watchFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Observable<T[]>;
40
+
41
+ export { countFresh, readFresh, watchFresh };
@@ -0,0 +1,26 @@
1
+ // src/rxdb/read-fresh.ts
2
+ import { clone } from "rxdb";
3
+ async function readFresh(collection, query) {
4
+ const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
5
+ return documents.map((document) => {
6
+ const { _meta, _rev, _attachments, _deleted, ...data } = clone(document);
7
+ return data;
8
+ });
9
+ }
10
+ async function countFresh(collection, selector) {
11
+ return (await collection.storageInstance.count(collection.count({ selector }).getPreparedQuery())).count;
12
+ }
13
+
14
+ // src/rxdb/watch-fresh.ts
15
+ import { startWith, switchMap } from "rxjs";
16
+ function watchFresh(collection, query) {
17
+ return collection.eventBulks$.pipe(
18
+ startWith(null),
19
+ switchMap(() => readFresh(collection, query))
20
+ );
21
+ }
22
+ export {
23
+ countFresh,
24
+ readFresh,
25
+ watchFresh
26
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "0.2.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -11,20 +11,44 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js",
13
13
  "source": "./src/index.ts"
14
+ },
15
+ "./rxdb": {
16
+ "types": "./dist/rxdb/index.d.ts",
17
+ "import": "./dist/rxdb/index.js",
18
+ "source": "./src/rxdb/index.ts"
14
19
  }
15
20
  },
16
21
  "files": [
17
22
  "dist",
18
- "src"
23
+ "src",
24
+ "!src/**/*.test.ts",
25
+ "!src/**/*.test.tsx",
26
+ "!src/**/*.test-d.ts"
19
27
  ],
20
28
  "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/TallyUI/tallyui.git",
32
+ "directory": "packages/core"
33
+ },
21
34
  "peerDependencies": {
22
35
  "react": ">=18",
23
36
  "rxdb": ">=16",
24
37
  "rxjs": ">=7"
25
38
  },
39
+ "peerDependenciesMeta": {
40
+ "rxdb": {
41
+ "optional": true
42
+ },
43
+ "rxjs": {
44
+ "optional": true
45
+ }
46
+ },
26
47
  "devDependencies": {
27
- "@types/react": ">=18"
48
+ "@types/react": ">=18",
49
+ "rxdb": ">=16",
50
+ "rxjs": ">=7",
51
+ "react": "^19.2.4"
28
52
  },
29
53
  "scripts": {
30
54
  "build": "tsup",
@@ -0,0 +1,32 @@
1
+ import type { CommandBatchResponse } from './types/commands';
2
+
3
+ /** Path of the command endpoint, relative to the backend's base URL. */
4
+ export const COMMANDS_PATH = '/tally/v1/commands';
5
+ /** Header carrying the protocol version. */
6
+ export const PROTOCOL_HEADER = 'X-Tally-Protocol';
7
+ /** Current protocol version. */
8
+ export const PROTOCOL_VERSION = 1;
9
+ /** Maximum commands per batch request. */
10
+ export const MAX_COMMANDS_PER_BATCH = 50;
11
+
12
+ /**
13
+ * True if `value` has the shape of a CommandBatchResponse: an object with a
14
+ * `results` array whose every entry has a string `id` and a `status` of
15
+ * 'applied' | 'duplicate' | 'rejected'. Optional fields are not deep-checked.
16
+ */
17
+ export function isCommandBatchResponse(value: unknown): value is CommandBatchResponse {
18
+ return (
19
+ typeof value === 'object' &&
20
+ value !== null &&
21
+ 'results' in value &&
22
+ Array.isArray(value.results) &&
23
+ value.results.every((result: unknown) =>
24
+ typeof result === 'object' &&
25
+ result !== null &&
26
+ 'id' in result &&
27
+ typeof result.id === 'string' &&
28
+ 'status' in result &&
29
+ (result.status === 'applied' || result.status === 'duplicate' || result.status === 'rejected'),
30
+ )
31
+ );
32
+ }
@@ -1,6 +1,7 @@
1
- import { createContext, useContext, type ReactNode } from 'react';
1
+ import { createContext, useContext, useMemo, type ReactNode } from 'react';
2
2
 
3
- import type { TallyConnector } from '../types';
3
+ import { getProductStock } from '../stock-overlay';
4
+ import type { StockLevel, TallyConnector, TraitContext } from '../types';
4
5
 
5
6
  /**
6
7
  * React context that holds the active connector.
@@ -9,15 +10,37 @@ import type { TallyConnector } from '../types';
9
10
  */
10
11
  const ConnectorContext = createContext<TallyConnector | null>(null);
11
12
 
13
+ const EMPTY_TRAIT_CONTEXT: TraitContext = {};
14
+ const TraitContextContext = createContext<TraitContext>(EMPTY_TRAIT_CONTEXT);
15
+
16
+ interface StockOverlayValue { overlay?: ReadonlyMap<string, unknown>; asOf?: string }
17
+ const EMPTY_STOCK_OVERLAY: StockOverlayValue = {};
18
+ const StockOverlayContext = createContext<StockOverlayValue>(EMPTY_STOCK_OVERLAY);
19
+
12
20
  export interface ConnectorProviderProps {
13
21
  connector: TallyConnector;
22
+ /**
23
+ * Store-level facts passed to traits that need them, such as the store
24
+ * currency for backends whose product documents omit it.
25
+ */
26
+ traitContext?: TraitContext;
27
+ /** Reconciled stock (ADR-060), e.g. from `stockOverlay$` in `@tallyui/pos`. */
28
+ stockOverlay?: ReadonlyMap<string, unknown>;
29
+ /** ISO time the overlay was last confirmed, e.g. from `stockOverlayAsOf$`. */
30
+ stockOverlayAsOf?: string;
14
31
  children: ReactNode;
15
32
  }
16
33
 
17
- export function ConnectorProvider({ connector, children }: ConnectorProviderProps) {
34
+ export function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }: ConnectorProviderProps) {
35
+ const overlay = useMemo(
36
+ () => (stockOverlay || stockOverlayAsOf ? { overlay: stockOverlay, asOf: stockOverlayAsOf } : EMPTY_STOCK_OVERLAY),
37
+ [stockOverlay, stockOverlayAsOf],
38
+ );
18
39
  return (
19
40
  <ConnectorContext.Provider value={connector}>
20
- {children}
41
+ <TraitContextContext.Provider value={traitContext ?? EMPTY_TRAIT_CONTEXT}>
42
+ <StockOverlayContext.Provider value={overlay}>{children}</StockOverlayContext.Provider>
43
+ </TraitContextContext.Provider>
21
44
  </ConnectorContext.Provider>
22
45
  );
23
46
  }
@@ -44,6 +67,28 @@ export function useProductTraits() {
44
67
  return connector.traits.product;
45
68
  }
46
69
 
70
+ /**
71
+ * The store-level TraitContext given to the nearest ConnectorProvider.
72
+ */
73
+ export function useTraitContext(): TraitContext {
74
+ return useContext(TraitContextContext);
75
+ }
76
+
77
+ /**
78
+ * The product's stock, from the reconciled overlay given to the nearest
79
+ * ConnectorProvider where it has an entry, otherwise from the document.
80
+ * `asOf` is set only when an overlay is given and the connector reconciles stock.
81
+ */
82
+ export function useProductStock(doc: any): StockLevel & { asOf?: string } {
83
+ const connector = useConnector();
84
+ const { overlay, asOf } = useContext(StockOverlayContext);
85
+ const adapter = connector.reconcile?.stock;
86
+ if (!overlay) return connector.traits.product.getStock(doc);
87
+ // The helpers never mutate the map; they take Map for the adapter contract.
88
+ const stock = getProductStock(doc, connector.traits.product, adapter, overlay as Map<string, unknown>);
89
+ return adapter && asOf ? { ...stock, asOf } : stock;
90
+ }
91
+
47
92
  /**
48
93
  * Convenience hook: grab just the customer traits from the active connector.
49
94
  * Returns undefined if the connector doesn't implement customer traits.
package/src/index.ts CHANGED
@@ -8,10 +8,49 @@ export type {
8
8
  CollectionSync,
9
9
  RemoteIdEntry,
10
10
  ReplicationAdapter,
11
+ StockReconcileAdapter,
12
+ IdReconcileAdapter,
13
+ FingerprintReconcileAdapter,
11
14
  SyncContext,
12
15
  ProductTraits,
16
+ TraitContext,
17
+ VariantSummary,
13
18
  CustomerTraits,
19
+ Money,
20
+ ProductPrice,
21
+ ResolvedPrice,
22
+ StockLevel,
23
+ StockStatus,
24
+ StoreSettings,
25
+ StoreSettingsChoice,
14
26
  } from './types';
27
+ export type { SignInResult, ServerCapabilities } from './types/connector';
28
+ export { resolveCapabilities } from './types/connector';
29
+ export { SignInError } from './sign-in';
30
+ export type { SignInErrorCode } from './sign-in';
31
+ export { StoreSettingsError } from './store-settings';
32
+ export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
33
+
34
+ export type {
35
+ CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
36
+ CommandWarning, CommandError, CommandResult, OrderCreateLine,
37
+ PaymentMethodKind, OrderCreatePayment, OrderCreatePayload,
38
+ CommandBatchRequest, CommandBatchResponse,
39
+ } from './types';
40
+
41
+ export {
42
+ COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH,
43
+ isCommandBatchResponse,
44
+ } from './commands';
45
+
46
+ // Money helpers
47
+ export { currencySymbol, formatMoney, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolvePrice, resolvePriceRange } from './money';
48
+ export { findVariantByCode } from './variants';
49
+ export { compareIds } from './utils/compare-ids';
50
+ export { STOCK_LEVELS_LAST_PASS, withStockOverlay, getProductStock } from './stock-overlay';
51
+ export { combinePullAdapters } from './replication/combine';
52
+ export { createReconcileFeed } from './replication/reconcile-feed';
53
+ export type { ReconcileFeed, ReconcileFeedEntry } from './replication/reconcile-feed';
15
54
 
16
55
  // Context & hooks
17
56
  export {
@@ -19,5 +58,7 @@ export {
19
58
  useConnector,
20
59
  useProductTraits,
21
60
  useCustomerTraits,
61
+ useTraitContext,
62
+ useProductStock,
22
63
  } from './context/connector-context';
23
64
  export type { ConnectorProviderProps } from './context/connector-context';