@tallyui/core 3.18.0 → 3.20.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.
@@ -0,0 +1,1966 @@
1
+ import { RxReplicationPullStreamItem, RxReplicationWriteToMasterRow, RxJsonSchema } from 'rxdb';
2
+ import { Observable } from 'rxjs';
3
+
4
+ /**
5
+ * A monetary amount in integer minor units (cents for EUR/USD, yen for JPY)
6
+ * with its ISO 4217 currency code. Integers keep arithmetic exact, and the
7
+ * code travels with the amount so nothing assumes a store-wide currency.
8
+ */
9
+ interface Money {
10
+ /** Integer amount in the currency's minor unit, e.g. 1250 for €12.50. */
11
+ amount: number;
12
+ /** Upper-case ISO 4217 code, e.g. 'EUR'. 'XXX' when the backend gives none. */
13
+ currency: string;
14
+ }
15
+ /**
16
+ * One entry in a product's price list.
17
+ *
18
+ * `base` is the everyday price. `sale` is a temporary reduction that replaces
19
+ * the base price in the same currency while it applies. Backends express
20
+ * sales differently (WooCommerce sale_price, Medusa sale price lists, Shopify
21
+ * compare_at_price) and each connector maps its own form into these entries,
22
+ * so components never need regular/sale/on-sale flags.
23
+ */
24
+ interface ProductPrice extends Money {
25
+ kind: 'base' | 'sale';
26
+ /** Set when the backend says so for this price; it wins over the store-level `pricesIncludeTax`. Undefined: use the store-level setting. */
27
+ taxInclusive?: boolean;
28
+ }
29
+ /** The price to charge, and the price it replaces when a sale applies; each keeps its source's `taxInclusive` when set. */
30
+ interface ResolvedPrice {
31
+ current: Money & {
32
+ taxInclusive?: boolean;
33
+ };
34
+ /** Set only when a sale price applies: the base price it replaces. */
35
+ was?: Money & {
36
+ taxInclusive?: boolean;
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Backend-neutral stock state.
42
+ *
43
+ * - `in_stock`: sellable now. `quantity` is set when the backend tracks it.
44
+ * - `out_of_stock`: tracked and none left; not sellable.
45
+ * - `backorder`: none left but the backend accepts orders anyway.
46
+ * - `unknown`: the backend did not say.
47
+ *
48
+ * `quantity` is undefined when stock is not tracked, which is different from
49
+ * a tracked quantity of 0.
50
+ */
51
+ type StockStatus = 'in_stock' | 'out_of_stock' | 'backorder' | 'unknown';
52
+ interface StockLevel {
53
+ status: StockStatus;
54
+ /** Units on hand, when tracked. May be negative on backorder. */
55
+ quantity?: number;
56
+ }
57
+
58
+ /** A flat product category: `id` is the backend's id as a string (unique per backend), `name` its label. */
59
+ interface ProductCategory {
60
+ id: string;
61
+ name: string;
62
+ }
63
+ /** One purchasable variant of a product, in backend-neutral terms. */
64
+ interface VariantSummary {
65
+ /** Backend variant id; the id sent in order lines. */
66
+ id: string;
67
+ /** Variant label, e.g. 'S / White'; undefined when the backend has none. */
68
+ title?: string;
69
+ /**
70
+ * The variant's value in each option group, keyed by group name. A group the variant accepts any value of
71
+ * (WooCommerce "Any …") has no key. Undefined when the backend gives the variant no option groups.
72
+ */
73
+ options?: Record<string, string>;
74
+ sku?: string;
75
+ /** First non-empty of the backend's barcode fields. */
76
+ barcode?: string;
77
+ prices: ProductPrice[];
78
+ stock: StockLevel;
79
+ }
80
+ /** One option group a product's variants are chosen by, e.g. Size with S, M and L. */
81
+ interface VariantOptionGroup {
82
+ /** The backend's id for the group, when it has one that tells apart groups with the same name. */
83
+ id?: string;
84
+ name: string;
85
+ /** The group's values in the backend's order. */
86
+ values: string[];
87
+ }
88
+ /**
89
+ * Store-level facts a connector may need to interpret a raw document, for
90
+ * backends whose documents omit them (WooCommerce product prices carry no
91
+ * currency).
92
+ */
93
+ interface TraitContext {
94
+ /** The store's ISO 4217 currency code. */
95
+ currency?: string;
96
+ }
97
+ /**
98
+ * Product traits — the stable interface that UI components program against.
99
+ *
100
+ * Each connector implements these accessors to extract standard product data
101
+ * from its own schema shape. Components call these instead of reaching into
102
+ * the raw document, so they work identically across WooCommerce, Medusa,
103
+ * Vendure, Shopify, etc.
104
+ *
105
+ * The generic `Doc` type is the connector's raw RxDB document type.
106
+ *
107
+ * Price and stock are read through the backend-neutral `getPrices` and
108
+ * `getStock`. The older string-price and WooCommerce-style stock accessors
109
+ * remain for existing consumers and are deprecated.
110
+ */
111
+ interface ProductTraits<Doc = any> {
112
+ /** Product display name */
113
+ getName: (doc: Doc) => string;
114
+ /** SKU / stock keeping unit */
115
+ getSku: (doc: Doc) => string | undefined;
116
+ /**
117
+ * The product's price list: base prices, plus sale prices while a sale
118
+ * applies, per currency. Pass the list to `resolvePrice` for the price to
119
+ * charge. For variable products this describes the default variant.
120
+ */
121
+ getPrices: (doc: Doc, context?: TraitContext) => ProductPrice[];
122
+ /** Stock state of the whole product across its variants; `quantity` is the total on hand when every variant is tracked, else undefined. */
123
+ getStock: (doc: Doc) => StockLevel;
124
+ /** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
125
+ getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
126
+ /**
127
+ * The option groups the product's variants are chosen by, in the backend's display order; [] when the product has
128
+ * none. Optional: connectors without it leave pickers to `getVariants` titles.
129
+ */
130
+ getVariantOptions?: (doc: Doc) => VariantOptionGroup[];
131
+ /**
132
+ * The backend's tax class id for the variant `variantId`, or for the product (its default variant) when omitted.
133
+ * The id is a key of `StoreSettings.taxRatesPpm`; undefined means the default class. Optional: without it, every
134
+ * line is taxed at the default rate.
135
+ */
136
+ getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
137
+ /**
138
+ * Whether the variant `variantId` (or the product's default variant) is taxed: 'none' means the line carries no
139
+ * tax. Undefined means taxable. Optional: without it, every line is taxable.
140
+ */
141
+ getTaxStatus?: (doc: Doc, variantId?: string) => 'taxable' | 'none' | undefined;
142
+ /** @deprecated Use `getPrices` with `resolvePrice`. */
143
+ getPrice: (doc: Doc) => string | undefined;
144
+ /** Regular (non-sale) price. @deprecated Use `getPrices` with `resolvePrice`. */
145
+ getRegularPrice: (doc: Doc) => string | undefined;
146
+ /** Sale price, if on sale. @deprecated Use `getPrices` with `resolvePrice`. */
147
+ getSalePrice: (doc: Doc) => string | undefined;
148
+ /** Whether the product is currently on sale. @deprecated Use `getPrices` with `resolvePrice`. */
149
+ isOnSale: (doc: Doc) => boolean;
150
+ /** Primary image URL */
151
+ getImageUrl: (doc: Doc) => string | undefined;
152
+ /** All image URLs */
153
+ getImageUrls: (doc: Doc) => string[];
154
+ /** Short description / excerpt */
155
+ getDescription: (doc: Doc) => string | undefined;
156
+ /** Stock status. @deprecated Use `getStock`. */
157
+ getStockStatus: (doc: Doc) => 'instock' | 'outofstock' | 'onbackorder' | 'unknown';
158
+ /** Stock quantity (null if not tracked). @deprecated Use `getStock`. */
159
+ getStockQuantity: (doc: Doc) => number | null;
160
+ /** Whether this product has variants/variations */
161
+ hasVariants: (doc: Doc) => boolean;
162
+ /** Whether the product may be sold at the register now: published/active, not a draft, archived or disabled. */
163
+ isSellable: (doc: Doc) => boolean;
164
+ /** Number of purchasable variants; 1 for a simple product. */
165
+ getVariantCount: (doc: Doc) => number;
166
+ /** Product type (simple, variable, etc. — connector-specific but useful for UI hints) */
167
+ getType: (doc: Doc) => string;
168
+ /** Barcode / UPC / EAN */
169
+ getBarcode: (doc: Doc) => string | undefined;
170
+ /** Categories as simple label strings */
171
+ getCategoryNames: (doc: Doc) => string[];
172
+ /**
173
+ * The product's categories as `{ id, name }`, in the document's order, without entries that have no name.
174
+ * Optional: without it, the pos category helpers use `getCategoryNames` with each name as its id.
175
+ */
176
+ getCategories?: (doc: Doc) => ProductCategory[];
177
+ /** The connector-specific unique ID (as string for consistency) */
178
+ getId: (doc: Doc) => string;
179
+ }
180
+
181
+ /**
182
+ * Customer traits — the stable interface that UI components program against.
183
+ *
184
+ * Each connector implements these to extract standard customer data
185
+ * from its own schema shape.
186
+ */
187
+ interface CustomerTraits<Doc = any> {
188
+ /** Customer display name (first + last or company) */
189
+ getName: (doc: Doc) => string;
190
+ /** Email address */
191
+ getEmail: (doc: Doc) => string | undefined;
192
+ /** Phone number */
193
+ getPhone: (doc: Doc) => string | undefined;
194
+ /** One-line address summary (e.g., "123 Main St, Springfield") */
195
+ getAddressSummary: (doc: Doc) => string | undefined;
196
+ /** The connector-specific unique ID (as string for consistency) */
197
+ getId: (doc: Doc) => string;
198
+ }
199
+
200
+ /**
201
+ * Replication adapter interface for a single collection.
202
+ *
203
+ * Each connector implements this to provide pull/push handlers
204
+ * compatible with RxDB's replicateRxCollection protocol.
205
+ *
206
+ * CheckpointType is connector-specific (cursor, offset+timestamp, etc).
207
+ */
208
+ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
209
+ pull: {
210
+ /**
211
+ * Fetch documents changed since the last checkpoint.
212
+ * Return an empty documents array when fully caught up.
213
+ */
214
+ handler: (lastCheckpoint: CheckpointType | undefined, batchSize: number, context: SyncContext) => Promise<{
215
+ documents: Array<RxDocType & {
216
+ _deleted: boolean;
217
+ }>;
218
+ checkpoint: CheckpointType;
219
+ }>;
220
+ /**
221
+ * Documents per pull page, passed to handler as batchSize. RxDB treats a
222
+ * shorter page as the end of the cycle. Defaults to RxDB's 100.
223
+ */
224
+ batchSize?: number;
225
+ /**
226
+ * Fresh install only: the checkpoint this feed starts from instead of a full first pass,
227
+ * read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
228
+ */
229
+ seedCheckpoint?: (context: SyncContext) => Promise<CheckpointType>;
230
+ /**
231
+ * Optional real-time event stream.
232
+ * Emit { documents, checkpoint } for live updates,
233
+ * or 'RESYNC' to trigger a full pull cycle.
234
+ */
235
+ stream$?: Observable<RxReplicationPullStreamItem<RxDocType, CheckpointType>>;
236
+ };
237
+ /**
238
+ * A push adapter must accept the same rows twice: a cancel after a send re-sends them. A direct RxDB `pause()`
239
+ * before the first push starts, or RxDB 17.5 pausing a hidden non-leader tab when `multiInstance` is on
240
+ * (`createTallyDatabase` turns it off and refuses it), still drops the queued rows unsent (#645).
241
+ * `startReplication`'s own sign-in path holds instead of pausing.
242
+ */
243
+ push?: {
244
+ /**
245
+ * Push local changes to the remote API.
246
+ * Return an array of conflict documents (server's version wins).
247
+ * Return empty array if no conflicts.
248
+ */
249
+ handler: (changeRows: RxReplicationWriteToMasterRow<RxDocType>[], context: SyncContext) => Promise<Array<RxDocType & {
250
+ _deleted: boolean;
251
+ }>>;
252
+ /** Max documents per push batch. Defaults to 100. */
253
+ batchSize?: number;
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Re-reads stock from the backend, because replication misses stock changes
259
+ * that bump no product timestamp (ADR-060). The runner stores `fetchPages`
260
+ * output in the non-replicated `stock_levels` collection; readers merge it
261
+ * into a read-only view of each product with `overlay`. Nothing is written
262
+ * into the replicated products.
263
+ */
264
+ interface StockReconcileAdapter<Doc = any> {
265
+ /** Current stock, one backend request per page, keyed as the connector chooses (variant, inventory item). */
266
+ fetchPages(context: SyncContext): AsyncIterable<Map<string, unknown>>;
267
+ /**
268
+ * Pure: the fields of `doc` that `stock` changes, or undefined when nothing
269
+ * differs. Keys absent from `stock` are left alone. The result is merged
270
+ * into a read-only view of the document and never written.
271
+ */
272
+ overlay(doc: Doc, stock: Map<string, unknown>): Partial<Doc> | undefined;
273
+ }
274
+ /** Catches a deleted product or a deleted variant that replication misses (ADR-060). Nothing is written locally: `enqueue` hands disagreeing documents to a `createReconcileFeed` pull adapter instead. */
275
+ interface IdReconcileAdapter<Doc = any> {
276
+ /** Every live product with its live variant ids, one backend request per page. */
277
+ fetchPages(context: SyncContext): AsyncIterable<Array<{
278
+ id: string;
279
+ variantIds: string[];
280
+ }>>;
281
+ /** The variant ids a local product document lists. */
282
+ variantIds(doc: Doc): string[];
283
+ /** Hand local documents that disagree with the backend to the collection's pull (see createReconcileFeed). */
284
+ enqueue(entries: Array<{
285
+ id: string;
286
+ local: Doc;
287
+ }>): void;
288
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
289
+ refetchBatchSize?: number;
290
+ }
291
+ /** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
292
+ interface FingerprintReconcileAdapter<Doc = any> {
293
+ /** Remote fingerprints by product id, one backend request per page. Products the backend doesn't report are left alone. */
294
+ fetchPages(context: SyncContext): AsyncIterable<Map<string, string>>;
295
+ /** The same fingerprint computed from a local product document. */
296
+ fingerprint(doc: Doc): string;
297
+ /**
298
+ * Hands products to the collection's pull (the reconcile feed). `refreshOnly`
299
+ * marks an entry so a missing product is skipped, never tombstoned: only the
300
+ * id reconcile, with its mass-delete brake, may delete.
301
+ */
302
+ enqueue(entries: Array<{
303
+ id: string;
304
+ local: Doc;
305
+ refreshOnly?: boolean;
306
+ }>): void;
307
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
308
+ refetchBatchSize?: number;
309
+ }
310
+ /** One product in the catalogue listing. `key` is the local primary key, or the `matchKey` value when the adapter sets one; `remote` is whatever the connector needs to refetch it (a numeric backend id, say). */
311
+ interface CatalogueReconcileEntry {
312
+ key: string;
313
+ fingerprint: string;
314
+ remote?: unknown;
315
+ }
316
+ /**
317
+ * The daily catalogue check (#248): one walk that refetches what differs and
318
+ * deletes only with proof. Nothing is written locally: `enqueue` hands
319
+ * documents to the collection's pull (the reconcile feed). `Cursor` must be
320
+ * JSON-serialisable, since the runner persists it to resume a stopped pass.
321
+ */
322
+ interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
323
+ /** Remote listing, one backend request per page, from `from` (a cursor this adapter yielded earlier) or the start. */
324
+ fetchPages(context: SyncContext, from?: Cursor): AsyncIterable<{
325
+ entries: CatalogueReconcileEntry[];
326
+ cursor: Cursor;
327
+ }>;
328
+ /** Pure: the same fingerprint from a local document. */
329
+ fingerprint(doc: Doc): string;
330
+ /**
331
+ * When set, each listing entry's `key` is this value, not the local primary key (a listing that carries no
332
+ * primary key, such as WCPOS's fast path, #313). The runner indexes the local documents by it for the pass.
333
+ * A document for which it returns undefined can't be matched: it is never compared, and it is a deletion
334
+ * candidate, as today.
335
+ */
336
+ matchKey?(doc: Doc): string | undefined;
337
+ /**
338
+ * Deletion proof, required: of these local documents (the ones the listing did not name), the primary keys
339
+ * the backend confirms gone (absent, or no longer sellable), with or without `matchKey`. One or more requests.
340
+ * Only confirmed keys are tombstoned; an adapter that never deletes returns none.
341
+ */
342
+ confirmGone(locals: Doc[], context: SyncContext): Promise<string[]>;
343
+ /**
344
+ * Hand documents to the collection's pull (the reconcile feed). An entry's `key` is the local primary key when
345
+ * there is a local copy, and otherwise the listing's key.
346
+ * A `refreshOnly` entry asks the feed to fetch the document again and is never tombstoned when the fetch omits it.
347
+ */
348
+ enqueue(entries: Array<{
349
+ key: string;
350
+ local?: Doc;
351
+ remote?: unknown;
352
+ tombstone?: boolean;
353
+ refreshOnly?: boolean;
354
+ }>): void;
355
+ /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
356
+ refetchBatchSize?: number;
357
+ }
358
+
359
+ /** WooCommerce's "Calculate tax based on" (`woocommerce_tax_based_on`). */
360
+ type TaxBasedOn = 'base' | 'billing' | 'shipping';
361
+ /** The address WooCommerce matches tax rates against. */
362
+ interface TaxAddress {
363
+ country: string;
364
+ state: string;
365
+ city: string;
366
+ postcode: string;
367
+ }
368
+ /** WooCommerce's per-order override meta key (WCPOS stamps the basis onto each order). */
369
+ declare const TAX_BASED_ON_META_KEY = "_woocommerce_pos_tax_based_on";
370
+ /** Any non-TaxBasedOn value (missing, '', 'foo') → 'base', as WooCommerce and v2 normalizeStorePayload do. */
371
+ declare function normalizeTaxBasedOn(value: unknown): TaxBasedOn;
372
+ type LooseAddress = {
373
+ country?: unknown;
374
+ state?: unknown;
375
+ city?: unknown;
376
+ postcode?: unknown;
377
+ };
378
+ interface TaxLocationOrder {
379
+ billing?: LooseAddress;
380
+ shipping?: LooseAddress;
381
+ /** The order's own basis (its TAX_BASED_ON_META_KEY value); wins over the store's when valid. */
382
+ taxBasedOnOverride?: unknown;
383
+ }
384
+ interface ResolvedTaxLocation {
385
+ taxBasedOn: TaxBasedOn;
386
+ location: TaxAddress;
387
+ addressUsed: TaxBasedOn;
388
+ }
389
+ /**
390
+ * WC_Abstract_Order::get_tax_location(), as v2 cart-config-for-order.ts:25-61. `shipping` falls back to
391
+ * billing, then to the shop base; `billing` falls back to the shop base only. Without an order, the shop base.
392
+ */
393
+ declare function orderTaxLocation(base: TaxAddress, storeTaxBasedOn: unknown, order?: TaxLocationOrder): ResolvedTaxLocation;
394
+
395
+ interface WooTaxRate {
396
+ id: number;
397
+ country: string;
398
+ state: string;
399
+ postcode: string;
400
+ city: string;
401
+ postcodes: string[];
402
+ cities: string[];
403
+ rate: string;
404
+ name: string;
405
+ priority: number;
406
+ compound: boolean;
407
+ shipping: boolean;
408
+ order: number;
409
+ class: string;
410
+ }
411
+ interface CalculateTaxesInput {
412
+ amount: number;
413
+ rates: {
414
+ id: number;
415
+ rate: string;
416
+ compound: boolean;
417
+ order: number;
418
+ priority?: number;
419
+ [key: string]: any;
420
+ }[];
421
+ amountIncludesTax: boolean;
422
+ dp?: number;
423
+ perRatePrecision?: number;
424
+ }
425
+ type ItemizedTax = {
426
+ id: number;
427
+ total: number;
428
+ [key: string]: any;
429
+ };
430
+ interface CalculateTaxesResult {
431
+ total: number;
432
+ taxes: {
433
+ id: number;
434
+ total: number;
435
+ }[];
436
+ }
437
+
438
+ /** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
439
+ interface StoreSettings {
440
+ /** ISO 4217, upper case (the currency prices are sold in). */
441
+ currency: string;
442
+ /** Whether the store's catalogue prices include tax. It feeds both the connector's traits and the POS TaxProvider, so the two cannot disagree. */
443
+ pricesIncludeTax: boolean;
444
+ /** Tax rates for the store's location as integer parts per million (25% = 250000), keyed by the backend's tax class; `default` applies to a product with no class. Always integers: a connector rounds a backend's decimal rate once, at its edge. Structurally the same as @tallyui/pos's TaxRateMap. */
445
+ taxRatesPpm: {
446
+ default: number;
447
+ [taxClass: string]: number;
448
+ };
449
+ /** The backend's tax rate name per tax class (same keys as `taxRatesPpm`, including `default`), for `per_rate_group_items`' grouping (#324). Set by a connector whose rounding groups by rate name; absent otherwise. */
450
+ taxRateCodes?: Record<string, string>;
451
+ /** WooCommerce rates already filtered to the store's tax address; the empty class uses `standard`. `taxSettingsForLocation` (@tallyui/pos) re-derives it, with `taxRatesPpm`, for another address from `taxRateTable`. */
452
+ taxRates?: Record<string, {
453
+ id: number;
454
+ code: string;
455
+ label: string;
456
+ rate: string;
457
+ priority: number;
458
+ compound: boolean;
459
+ shipping: boolean;
460
+ }[]>;
461
+ /** WooCommerce's "Calculate tax based on" (`tax_based_on`), normalized. Absent: the connector did not read it; the cart taxes by `taxRates` as today. */
462
+ taxBasedOn?: TaxBasedOn;
463
+ /** The shop base address, as WooCommerce resolves it for `base` (store country, state, city, postcode). */
464
+ baseTaxAddress?: TaxAddress;
465
+ /** The store's whole WooCommerce rate table, unfiltered, for re-matching by address. Absent: `taxRates` is final.
466
+ * `saleTaxContexts` (@tallyui/pos) re-matches only when the app passes the connector's `orderCreate` capability and it
467
+ * is 8 or more, since only order.create 8 tells the server which address the sale was taxed on (#722). */
468
+ taxRateTable?: WooTaxRate[];
469
+ /** Every tax rate the store defines, wherever it applies, for an app's "all tax rates" table (#669). Display only: the cart reads `taxRatesPpm` and `taxRates`, never this. Absent when the connector did not read the list. */
470
+ allTaxRates?: StoreTaxRate[];
471
+ taxRoundAtSubtotal?: boolean;
472
+ /** WooCommerce's calculate coupon discounts sequentially setting. */
473
+ calcDiscountsSequentially?: boolean;
474
+ shippingTaxClass?: string;
475
+ taxClassSlugs?: string[];
476
+ /** The tax classes with their display names, in the store's order. Display only. Absent when the connector did not read them. */
477
+ taxClasses?: StoreTaxClass[];
478
+ /** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
479
+ pricingContext?: Record<string, string>;
480
+ /** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
481
+ taxRounding?: TaxRounding;
482
+ }
483
+ /** Where a tax rate applies, in the backend's own terms. A missing field means any; a backend fills only what it has (WooCommerce: country, state as `region`, postcodes, cities). */
484
+ interface StoreTaxRateLocation {
485
+ /** ISO 3166-1 alpha-2, as the backend stores it. */
486
+ country?: string;
487
+ /** State or province code. */
488
+ region?: string;
489
+ /** Codes or patterns, as the backend stores them. */
490
+ postcodes?: string[];
491
+ cities?: string[];
492
+ /** The backend's named tax zone, for a backend that groups its rates by zone. */
493
+ zone?: {
494
+ id: string;
495
+ name: string;
496
+ };
497
+ }
498
+ /** One of the store's tax classes: the key `taxClassSlugs` and `taxRates` use, and the name the store shows for it. */
499
+ interface StoreTaxClass {
500
+ slug: string;
501
+ name: string;
502
+ }
503
+ /** One of the store's tax rates as the backend defines it. The optional fields are set by a backend that has them. */
504
+ interface StoreTaxRate {
505
+ /** The backend's id, as a string. */
506
+ id: string;
507
+ name: string;
508
+ /** Percent as a decimal string, as the backend sends it ("7.2500"). */
509
+ rate: string;
510
+ location: StoreTaxRateLocation;
511
+ /** The backend's tax class or category key, as `taxClassSlugs` and `taxRates` key it. */
512
+ taxClass?: string;
513
+ priority?: number;
514
+ compound?: boolean;
515
+ /** Whether the rate also applies to shipping. */
516
+ shipping?: boolean;
517
+ }
518
+ /**
519
+ * Picks among several regions, countries or sales channels when the store has more than one.
520
+ * The app persists the choice per store, in its own settings, so it is asked once. A stored
521
+ * choice that no longer resolves (for example, the region was deleted) raises `choice_required`
522
+ * again instead of failing. Backends without the concept ignore a field.
523
+ */
524
+ interface StoreSettingsChoice {
525
+ region?: string;
526
+ country?: string;
527
+ channel?: string;
528
+ }
529
+
530
+ /** A customer's postal address. Platform-neutral; every field optional. `country` is an ISO 3166-1 alpha-2 code. */
531
+ interface CustomerAddress {
532
+ firstName?: string;
533
+ lastName?: string;
534
+ company?: string;
535
+ address1?: string;
536
+ address2?: string;
537
+ city?: string;
538
+ state?: string;
539
+ postcode?: string;
540
+ country?: string;
541
+ phone?: string;
542
+ email?: string;
543
+ }
544
+ /**
545
+ * A tax registration number (VAT, ABN, GST, EIN…). `type` is the connector's own id for the scheme; WCPOS v2's set is
546
+ * eu_vat, gb_vat, au_abn, br_cpf, br_cnpj, in_gst, it_cf, it_piva, es_nif, ar_cuit, sa_vat, ca_gst_hst, us_ein, other.
547
+ */
548
+ interface CustomerTaxId {
549
+ type: string;
550
+ value: string;
551
+ country?: string;
552
+ label?: string;
553
+ }
554
+ /** A store customer, as the till shows and picks it (programme item 14). Platform-neutral. */
555
+ interface Customer {
556
+ /** The platform's id: order.create v3 sends it as `customer.customerId`. */
557
+ id: string;
558
+ /** Display name: first + last, else company, else email, else id. Never empty. */
559
+ name: string;
560
+ firstName?: string;
561
+ lastName?: string;
562
+ email?: string;
563
+ phone?: string;
564
+ company?: string;
565
+ billing?: CustomerAddress;
566
+ shipping?: CustomerAddress;
567
+ taxIds?: CustomerTaxId[];
568
+ /** When the store created the customer: an ISO 8601 UTC instant (`2026-10-06T03:10:29Z`). Absent when the store doesn't say. */
569
+ createdAt?: string;
570
+ }
571
+ /** One page of a customer search: the customers on it, and how many the whole search matches when the store says. */
572
+ interface CustomerPage {
573
+ customers: Customer[];
574
+ /** Every customer the query matches across all pages; undefined when the store gives no count. */
575
+ total?: number;
576
+ }
577
+ /** What the till collects to create a customer. v1 requires an email; addresses and tax ids are optional. */
578
+ interface CustomerInput {
579
+ email: string;
580
+ firstName?: string;
581
+ lastName?: string;
582
+ phone?: string;
583
+ company?: string;
584
+ billing?: CustomerAddress;
585
+ shipping?: CustomerAddress;
586
+ taxIds?: CustomerTaxId[];
587
+ }
588
+ /**
589
+ * A change to an existing customer: any subset of {@link CustomerInput}. A field left out is unchanged; `billing`,
590
+ * `shipping` and `taxIds`, when given, replace the stored value whole (`taxIds: []` removes every tax id).
591
+ */
592
+ type CustomerPatch = Partial<CustomerInput>;
593
+ declare const customerTraits: CustomerTraits<Customer>;
594
+ /** A customer call that failed for a reason other than credentials (credentials throw ConnectorUnauthorizedError). */
595
+ declare class CustomerServiceError extends Error {
596
+ readonly code: 'network' | 'server' | 'invalid';
597
+ /** The HTTP status the store answered with, when the connector has it; undefined for a network failure (no response). */
598
+ readonly status?: number;
599
+ constructor(code: 'network' | 'server' | 'invalid', message: string, options?: {
600
+ status?: number;
601
+ });
602
+ }
603
+
604
+ /** Supported command operation. */
605
+ type CommandType = 'order.create';
606
+ /** Client command with a stable idempotency key and typed payload. */
607
+ interface CommandEnvelope<P = unknown> {
608
+ id: string;
609
+ type: CommandType;
610
+ /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
611
+ * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
612
+ * 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
613
+ * 7 is 6 plus the sale's `note` (ADR-083), sent only for an order that has one.
614
+ * 8 is 7 plus `taxAddress` and the customer's addresses (#722), sent only for a sale taxed on the customer's address. */
615
+ version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
616
+ payload: P;
617
+ createdAt: string;
618
+ deviceId: string;
619
+ attempt: number;
620
+ }
621
+ /** The register commands (ADR-068); each versions on its own, from 1. */
622
+ type RegisterCommandType = 'register.session.open' | 'register.session.transition' | 'register.movement.record' | 'register.movement.void' | 'register.closure.submit';
623
+ /** A register command's envelope: the same fields as CommandEnvelope, with its own type and a numeric version. */
624
+ type RegisterCommandEnvelope<P = Record<string, unknown>> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
625
+ type: RegisterCommandType;
626
+ version: number;
627
+ };
628
+ /** Any command a transport can carry. */
629
+ type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown> | OrderRefundEnvelope<unknown>;
630
+ /** A line's refunded quantity and restock choice (ADR-080). */
631
+ interface OrderRefundLine {
632
+ orderLineId: string;
633
+ quantity: number;
634
+ restock: boolean;
635
+ }
636
+ /** An online refund against an order, attributed to the refunding session (ADR-080). */
637
+ interface OrderRefundPayload {
638
+ clientRefundId: string;
639
+ orderId: string;
640
+ clientOrderId?: string;
641
+ lines: OrderRefundLine[];
642
+ shippingMinor: number;
643
+ adjustmentMinor: number;
644
+ totalMinor: number;
645
+ destination: 'original_method' | 'cash';
646
+ reason: string;
647
+ registerId: string;
648
+ sessionId: string;
649
+ cashierRef?: string;
650
+ createdAt: string;
651
+ }
652
+ /** An order.refund v1 command with the shared idempotency envelope (ADR-080). */
653
+ type OrderRefundEnvelope<P = OrderRefundPayload> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
654
+ type: 'order.refund';
655
+ version: 1;
656
+ };
657
+ /** The server's refund total, tender attribution and platform refunds (ADR-080). */
658
+ interface OrderRefundResult {
659
+ totalMinor: number;
660
+ byMethod: Record<string, number>;
661
+ refunds: Array<{
662
+ id: string;
663
+ paymentId: string;
664
+ totalMinor: number;
665
+ state: string;
666
+ }>;
667
+ }
668
+ /** Per-command refund refusals (ADR-080 decision 5). */
669
+ type OrderRefundRejectionCode = 'nothing_to_refund' | 'quantity_exceeds' | 'amount_mismatch' | 'order_state' | 'not_till_order' | 'forbidden' | 'no_open_session';
670
+ /** Lines exceeding the server's refundable quantities (ADR-080). */
671
+ interface OrderRefundQuantityExceedsData {
672
+ lines: Array<{
673
+ orderLineId: string;
674
+ quantity: number;
675
+ refundableQuantity: number;
676
+ }>;
677
+ }
678
+ /** The till's expected refund and the server's computed amount (ADR-080). */
679
+ interface OrderRefundAmountMismatchData {
680
+ expectedMinor: number;
681
+ serverMinor: number;
682
+ }
683
+ /** The order state preventing a refund (ADR-080). */
684
+ interface OrderRefundOrderStateData {
685
+ state: string;
686
+ }
687
+ /** The session that is not open on the refunding register (ADR-080). */
688
+ interface OrderRefundNoOpenSessionData {
689
+ sessionId: string;
690
+ }
691
+ /** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
692
+ * 7 is 6 plus the sale's note (ADR-083). 8 is 7 plus `taxAddress` and the customer's addresses (#722). */
693
+ type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & {
694
+ type: 'order.create';
695
+ version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
696
+ };
697
+ /** Outcome of processing a command. */
698
+ type CommandStatus = 'applied' | 'duplicate' | 'rejected';
699
+ /** Server order identifiers and authoritative total. */
700
+ interface CommandServerRefs {
701
+ orderId: string;
702
+ displayId?: string;
703
+ totalMinor: number;
704
+ }
705
+ /**
706
+ * Non-fatal discrepancies reported while processing a command. A server may send codes not
707
+ * listed here (a newer contract); readers go through `knownWarnings`, which drops them, and a
708
+ * warning never rejects a sale.
709
+ */
710
+ type CommandWarning = {
711
+ code: 'total_mismatch';
712
+ expectedMinor: number;
713
+ serverMinor: number;
714
+ /**
715
+ * Present if and only if the server added an untaxed rounding surcharge so its total
716
+ * matches the till's; signed, in minor units, `expectedMinor - serverMinor`, where
717
+ * `serverMinor` is the platform's total before the bridge.
718
+ */
719
+ bridgeMinor?: number;
720
+ } | {
721
+ /**
722
+ * One per variant this sale took below zero stock. `quantity` is the units of this sale that
723
+ * stock did not cover (medusapos plugin 0.2.0 and later); older servers sent the variant's
724
+ * whole shortfall under the same field.
725
+ */
726
+ code: 'insufficient_stock';
727
+ variantId: string;
728
+ quantity: number;
729
+ } | {
730
+ /**
731
+ * One warning per tax rate whose tax differs by more than the server's rounding tolerance
732
+ * (order.create v3 only); `expectedMinor` is the till's `taxByRate[].taxMinor` for that
733
+ * rate and `serverMinor` the platform's tax for it.
734
+ */
735
+ code: 'tax_rate_mismatch';
736
+ ratePpm: number;
737
+ expectedMinor: number;
738
+ serverMinor: number;
739
+ }
740
+ /**
741
+ * The sale's `customerId` (1 to 64 characters) was unknown, deleted or in another channel, so
742
+ * the sale was kept as a guest sale rather than held (ADR-070).
743
+ */
744
+ | {
745
+ code: 'customer_ignored';
746
+ customerId: string;
747
+ }
748
+ /**
749
+ * The order named a session the store did not hold when it applied the order (register v2).
750
+ * The store keeps the id on the order, and an open or alias that arrives later counts it.
751
+ * It does not mean the session was abandoned.
752
+ */
753
+ | {
754
+ code: 'register_session_unknown';
755
+ sessionId: string;
756
+ }
757
+ /**
758
+ * One warning per sale, never a refusal: each of the till's figures that differs from the
759
+ * server's own computation, once, with both values (#257). `total_mismatch` stays separate.
760
+ * `parseCommandResult` refuses a `field` it doesn't know; `knownWarnings` keeps it (a newer
761
+ * store's figure), so the type admits any non-empty string besides the three names.
762
+ */
763
+ | {
764
+ code: 'figures_mismatch';
765
+ fields: Array<{
766
+ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | (string & {});
767
+ tillMinor: number;
768
+ serverMinor: number;
769
+ }>;
770
+ };
771
+ /** Error reported when a command is rejected. */
772
+ interface CommandError {
773
+ code: string;
774
+ message: string;
775
+ /** A refusal's details, e.g. the server's supported version. */
776
+ data?: Record<string, unknown>;
777
+ }
778
+ /** `coupon_invalid` (order.create v6, ADR-077 d4): the store would not apply one of the order's coupons. */
779
+ interface OrderCreateCouponInvalidData {
780
+ /** The payload coupon's code, when the store can tell which one. */
781
+ couponCode?: string;
782
+ /** The store's own error code, e.g. WooCommerce's, for the log; never shown as the cashier's message. */
783
+ storeCode?: string;
784
+ }
785
+ /**
786
+ * `total_mismatch` as a refusal (order.create v6, ADR-077 R4): the store would accept the order but computes a
787
+ * different total from the envelope, so it made no order. The store's own figures, as `figures_mismatch` names them.
788
+ */
789
+ interface OrderCreateTotalMismatchData {
790
+ fields: Array<{
791
+ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | 'totalMinor' | (string & {});
792
+ tillMinor: number;
793
+ serverMinor: number;
794
+ }>;
795
+ }
796
+ /** Server result for a single command. */
797
+ interface CommandResult {
798
+ id: string;
799
+ status: CommandStatus;
800
+ serverRefs?: CommandServerRefs;
801
+ warnings?: CommandWarning[];
802
+ error?: CommandError;
803
+ register?: RegisterCommandResult;
804
+ refund?: OrderRefundResult;
805
+ }
806
+ /** A register command's server figures (registers c2b applies them). */
807
+ interface RegisterCommandResult {
808
+ /** The session's server state after this command. `expected` is absent when the server redacts it (blind). */
809
+ session?: {
810
+ id: string;
811
+ status: 'open' | 'counting' | 'closed' | 'superseded';
812
+ expected?: Record<string, number>;
813
+ salesCount?: number;
814
+ /** Sent on a resume (register v2): the store session's opening time. */
815
+ openedAt?: string;
816
+ /** Sent on a resume (register v2): the store session's counted opening float. */
817
+ openingFloatMinor?: number;
818
+ };
819
+ /** The open was this device's own live session (register v2); the store keeps fromSessionId as a permanent alias of session.id. */
820
+ resumed?: {
821
+ fromSessionId: string;
822
+ };
823
+ /** The session this open took over (register v2). */
824
+ superseded?: {
825
+ sessionId: string;
826
+ openedAt?: string;
827
+ deviceId?: string;
828
+ deviceName?: string;
829
+ };
830
+ /** The register's counters: a floor for the till's own, never lowered. */
831
+ counters?: {
832
+ lastClosureNumber: number;
833
+ perpetualSalesTotalMinor: number;
834
+ perpetualRefundsTotalMinor: number;
835
+ };
836
+ /** `register.closure.submit` only. */
837
+ closure?: {
838
+ serverClosureId: string;
839
+ number: number;
840
+ expected?: Record<string, number>;
841
+ variance?: Record<string, number>;
842
+ };
843
+ }
844
+ interface RegisterSessionOpenPayload {
845
+ sessionId: string;
846
+ registerId: string;
847
+ storeKey?: string;
848
+ businessDay?: string;
849
+ openedAt: string;
850
+ openedBy?: string;
851
+ expectedFloatMinor?: number;
852
+ countedFloatMinor: number;
853
+ openingVarianceMinor?: number;
854
+ /** Register v2 only (ADR-078): the till's name on another till's take-over sheet, 1 to 64 characters after trim. */
855
+ deviceName?: string;
856
+ /** Register v2 only (ADR-078): the live session this open takes over, a compare-and-set. */
857
+ supersedes?: string;
858
+ }
859
+ /** error.data for register_session_already_open. */
860
+ interface RegisterSessionAlreadyOpenData {
861
+ sessionId: string;
862
+ registerId?: string;
863
+ openedAt?: string;
864
+ openedBy?: string;
865
+ deviceId?: string;
866
+ deviceName?: string;
867
+ status?: 'open' | 'counting';
868
+ }
869
+ /** error.data for register_session_superseded. */
870
+ interface RegisterSessionSupersededData {
871
+ sessionId: string;
872
+ supersededAt?: string;
873
+ supersededBy?: string;
874
+ deviceId?: string;
875
+ deviceName?: string;
876
+ newSessionId?: string;
877
+ }
878
+ /** error.data for register_approval_required (ADR-082 d6): variance is counted − tillExpected for each key of counted. */
879
+ interface RegisterApprovalRequiredData {
880
+ sessionId: string;
881
+ thresholdMinor: number;
882
+ variance: Record<string, number>;
883
+ }
884
+ /** error.data for register_approval_invalid (ADR-082 d6). */
885
+ interface RegisterApprovalInvalidData {
886
+ reason: 'unknown' | 'expired' | 'used' | 'session_mismatch' | 'variance_mismatch';
887
+ }
888
+ interface RegisterSessionTransitionPayload {
889
+ sessionId: string;
890
+ status: 'open' | 'counting' | 'closed';
891
+ at: string;
892
+ /** Closing only. */ counted?: Record<string, number>;
893
+ closedBy?: string;
894
+ approvedBy?: string;
895
+ }
896
+ interface RegisterMovementRecordPayload {
897
+ movementId: string;
898
+ sessionId: string;
899
+ type: 'paid_in' | 'paid_out' | 'no_sale';
900
+ amountMinor: number;
901
+ reason: string;
902
+ createdAt: string;
903
+ createdBy?: string;
904
+ }
905
+ interface RegisterMovementVoidPayload {
906
+ movementId: string;
907
+ sessionId: string;
908
+ voids: string;
909
+ createdAt: string;
910
+ createdBy?: string;
911
+ }
912
+ interface RegisterClosureSubmitPayload {
913
+ closureId: string;
914
+ sessionId: string;
915
+ registerId: string;
916
+ number: number;
917
+ businessDay?: string;
918
+ openedAt: string;
919
+ closedAt: string;
920
+ closedBy?: string;
921
+ approvedBy?: string;
922
+ /** Register v3 only (ADR-082): the store's approval proof, opaque; never parsed, logged or stored in the Z. */ approval?: string;
923
+ tillExpected: Record<string, number>;
924
+ counted: Record<string, number>;
925
+ periodSalesTotalMinor: number;
926
+ periodRefundsTotalMinor: number;
927
+ perpetualSalesTotalMinor: number;
928
+ perpetualRefundsTotalMinor: number;
929
+ unsyncedCount: number;
930
+ unsyncedTotalMinor: number;
931
+ softwareVersion: string;
932
+ orderIds: string[];
933
+ movementIds: string[];
934
+ }
935
+ /** Order line with client identity and price in minor units. */
936
+ interface OrderCreateLine {
937
+ clientLineId: string;
938
+ /** Required unless `custom` is set (version 5). */
939
+ variantId?: string;
940
+ /** Version 5 instruction: a non-catalogue line, without variantId; takes line and order discounts. */
941
+ custom?: {
942
+ /** Recorded title, 1–255 characters. */
943
+ name: string;
944
+ /** Recorded SKU, at most 64 characters when present. */
945
+ sku?: string;
946
+ /** Instruction, at most 64 characters; absent means the standard class. */
947
+ taxClass?: string;
948
+ /** Instruction: `none` means no tax on this line. */
949
+ taxStatus: 'taxable' | 'none';
950
+ };
951
+ title?: string;
952
+ quantity: number;
953
+ unitPriceMinor: number;
954
+ /** Version 6 recorded figure: the product's regular (not sale) unit price, in the line's tax mode and integer minor units, when the till knew it. */
955
+ regularUnitPriceMinor?: number;
956
+ /** Version 6 recorded: the variant's attribute names and values (#495), each at most 255 characters. */
957
+ attributes?: Record<string, string>;
958
+ /** Version 6: the names in attributes the cashier picked for the variant's "Any" option groups (#495 c/d). */
959
+ anyAttributes?: string[];
960
+ /**
961
+ * This line's own tax mode, when it differs from the order's `pricesIncludeTax`
962
+ * (a price that carries its own flag, D2c). Absent means the order's flag, so
963
+ * older clients and single-mode orders are unchanged.
964
+ */
965
+ taxInclusive?: boolean;
966
+ /**
967
+ * Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
968
+ * the order discount, in the line's own tax mode and integer minor units. The line is taxed on
969
+ * `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
970
+ * Version 4+ (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
971
+ */
972
+ discountMinor?: number;
973
+ }
974
+ /** Version 6 (ADR-077): a coupon the till applied. Recorded figures, in integer minor units of the order's currency. */
975
+ interface OrderCreateCoupon {
976
+ /** The coupon code as the store knows it, 1–255 characters. */
977
+ code: string;
978
+ /** The store's id for the coupon, 1–64 characters. */
979
+ couponId: string;
980
+ /** The discount it gave, tax-exclusive, integer >= 0. */
981
+ discountMinor: number;
982
+ /** The tax on that discount, integer >= 0. */
983
+ discountTaxMinor: number;
984
+ }
985
+ /** Version 5: a fee, never discounted (ADR-075). */
986
+ interface OrderCreateFee {
987
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
988
+ clientFeeId: string;
989
+ /** Recorded fee title, 1–255 characters. */
990
+ name: string;
991
+ /** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
992
+ amountMinor: number;
993
+ /** Instruction: `none` means no tax on this fee. */
994
+ taxStatus: 'taxable' | 'none';
995
+ /** Instruction, at most 64 characters; absent means the standard class. */
996
+ taxClass?: string;
997
+ /** Informational till tax, integer >= 0; a server difference is total_mismatch, not a refusal. */
998
+ taxMinor: number;
999
+ }
1000
+ /** Version 5: the same instructions and recorded/informational fields as a fee, never discounted. */
1001
+ interface OrderCreateShipping extends Omit<OrderCreateFee, 'clientFeeId'> {
1002
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
1003
+ clientShippingId: string;
1004
+ /** Recorded shipping method id, at most 64 characters; absent means a POS-entered charge. */
1005
+ methodId?: string;
1006
+ }
1007
+ /** Supported order payment method. */
1008
+ type PaymentMethodKind = 'cash' | 'external';
1009
+ /** Order payment with client identity and amounts in minor units. */
1010
+ interface OrderCreatePayment {
1011
+ clientPaymentId: string;
1012
+ method: PaymentMethodKind;
1013
+ amountMinor: number;
1014
+ tenderedMinor?: number;
1015
+ changeMinor?: number;
1016
+ reference?: string;
1017
+ }
1018
+ /** Version 3 (ADR-065): the receipt's display figures, integer minor units of `currency` at `exponent`. */
1019
+ interface OrderCreateDisplay {
1020
+ currency: string;
1021
+ exponent: number;
1022
+ taxInclusive: boolean;
1023
+ subtotalMinor: number;
1024
+ discountMinor: number;
1025
+ taxMinor: number;
1026
+ totalMinor: number;
1027
+ orderDiscountMinor: number;
1028
+ lines: Array<{
1029
+ clientLineId: string;
1030
+ amountMinor: number;
1031
+ discounts: Array<{
1032
+ discountId: string;
1033
+ label?: string;
1034
+ amountMinor: number;
1035
+ }>;
1036
+ }>;
1037
+ /** Version 5 recorded figures: one row per payload fee, in the display tax mode. */
1038
+ fees?: Array<{
1039
+ /** Identity: the payload fee's clientFeeId. */
1040
+ clientFeeId: string;
1041
+ /** Recorded integer minor units, equal to the payload fee amount. */
1042
+ amountMinor: number;
1043
+ }>;
1044
+ /** Version 5 recorded figures: one row per payload shipping charge, in the display tax mode. */
1045
+ shipping?: Array<{
1046
+ /** Identity: the payload shipping charge's clientShippingId. */
1047
+ clientShippingId: string;
1048
+ /** Recorded integer minor units, equal to the payload shipping amount. */
1049
+ amountMinor: number;
1050
+ }>;
1051
+ /** Version 6 recorded figures: one row per payload coupon, its discount in the display tax mode. */
1052
+ coupons?: Array<{
1053
+ code: string;
1054
+ amountMinor: number;
1055
+ }>;
1056
+ }
1057
+ /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
1058
+ interface OrderCreateTaxRate {
1059
+ ratePpm: number;
1060
+ code?: string;
1061
+ netMinor: number;
1062
+ taxMinor: number;
1063
+ grossMinor: number;
1064
+ }
1065
+ /** Client order data submitted by an order.create command. */
1066
+ interface OrderCreatePayload {
1067
+ clientOrderId: string;
1068
+ createdAt: string;
1069
+ currency: string;
1070
+ pricesIncludeTax: boolean;
1071
+ lines: OrderCreateLine[];
1072
+ /** Version 5 instructions: fees in the order's tax mode; omitted when none. */
1073
+ fees?: OrderCreateFee[];
1074
+ /** Version 5 instructions: shipping in the order's tax mode; omitted when none. */
1075
+ shipping?: OrderCreateShipping[];
1076
+ /** Version 6 (ADR-077): the coupons the till applied, in the order it applied them; omitted when none.
1077
+ * The store re-applies them by `code` and refuses the order with `coupon_invalid` if one no longer applies. */
1078
+ coupons?: OrderCreateCoupon[];
1079
+ /** Version 6: net of the coupons' `discountMinor`, as `taxMinor` is of their `discountTaxMinor`; coupons are not part of `discountMinor`. */
1080
+ subtotalMinor: number;
1081
+ /**
1082
+ * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
1083
+ * Version 4+ (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
1084
+ * Version 6: coupons are not included; their amounts are in `coupons[].discountMinor`.
1085
+ */
1086
+ discountMinor?: number;
1087
+ taxMinor: number;
1088
+ totalMinor: number;
1089
+ payments: OrderCreatePayment[];
1090
+ /** Version 3+; both or neither. */
1091
+ display?: OrderCreateDisplay;
1092
+ /** Version 3+; both or neither. */
1093
+ taxByRate?: OrderCreateTaxRate[];
1094
+ customer?: {
1095
+ email?: string;
1096
+ /** Version 3+: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
1097
+ customerId?: string;
1098
+ /** Version 8 (#722): the customer's billing address, sent only with `taxAddress`. */
1099
+ billing?: OrderAddress;
1100
+ /** Version 8 (#722): the customer's shipping address, sent only with `taxAddress`. */
1101
+ shipping?: OrderAddress;
1102
+ } | null;
1103
+ /** Version 8 (#722): the customer address the till taxed the sale on; always present at 8, and that address has a
1104
+ * non-empty `country`. Absent: the store's base address. */
1105
+ taxAddress?: 'billing' | 'shipping';
1106
+ registerId?: string;
1107
+ cashierRef?: string;
1108
+ locationId?: string;
1109
+ /** Version 3+: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
1110
+ sessionId?: string;
1111
+ /** Version 7 (ADR-083): the sale's note, 1 to ORDER_NOTE_MAX UTF-16 units; omitted when the sale has none. */
1112
+ note?: string;
1113
+ }
1114
+ /** A customer's address on order.create v8 (#722): each field a string of at most 255 UTF-16 units; no email, which
1115
+ * `customer.email` carries. */
1116
+ interface OrderAddress {
1117
+ firstName?: string;
1118
+ lastName?: string;
1119
+ company?: string;
1120
+ address1?: string;
1121
+ address2?: string;
1122
+ city?: string;
1123
+ state?: string;
1124
+ postcode?: string;
1125
+ country?: string;
1126
+ phone?: string;
1127
+ }
1128
+ /** Batch of commands submitted to the server. */
1129
+ interface CommandBatchRequest<E extends AnyCommandEnvelope = CommandEnvelope> {
1130
+ commands: E[];
1131
+ }
1132
+ /** Results returned by the server for a command batch. */
1133
+ interface CommandBatchResponse {
1134
+ results: CommandResult[];
1135
+ }
1136
+ /** The `413` body for a batch over the limit (ADR-038; Front desk ruling 18). */
1137
+ type BatchTooLargeBody = {
1138
+ code: 'batch_too_large';
1139
+ maxCommands: number;
1140
+ message: string;
1141
+ };
1142
+
1143
+ /** A line of an order the store holds (ADR-081). Money in integer minor units of the order's currency, as the store
1144
+ * records it: every amount excludes tax, and the tax is beside it.
1145
+ * Each tax field is such that net + tax is the gross rounded once. */
1146
+ interface StoreOrderLine {
1147
+ /** The store's line id: what `OrderRefundLine.orderLineId` names. */
1148
+ id: string;
1149
+ /** The till's line id when a till created the line (its `clientLineId`); absent otherwise. */
1150
+ clientLineId?: string;
1151
+ productId?: string;
1152
+ /** The sellable the till's `variantId` names (a WooCommerce variation, or the product itself when simple). */
1153
+ variantId?: string;
1154
+ name: string;
1155
+ sku?: string;
1156
+ quantity: number;
1157
+ /** Before discounts, excluding tax. */
1158
+ subtotalMinor: number;
1159
+ subtotalTaxMinor: number;
1160
+ /** After discounts, excluding tax. */
1161
+ totalMinor: number;
1162
+ taxMinor: number;
1163
+ }
1164
+ /** A fee or shipping line: excluding tax, the tax beside it. A fee may be negative.
1165
+ * `taxMinor` is such that `totalMinor + taxMinor` is the gross rounded once. */
1166
+ interface StoreOrderCharge {
1167
+ name: string;
1168
+ totalMinor: number;
1169
+ taxMinor: number;
1170
+ }
1171
+ interface StoreOrderPayment {
1172
+ /** The store's own method id, e.g. WooCommerce's `pos_cash`. */
1173
+ method: string;
1174
+ /** The store's name for it, e.g. "Cash". */
1175
+ title?: string;
1176
+ /** Set only when the method is one the till itself takes. */
1177
+ kind?: PaymentMethodKind;
1178
+ amountMinor: number;
1179
+ }
1180
+ /** A refund the store already recorded against the order. */
1181
+ interface StoreOrderRefund {
1182
+ id: string; /** Positive. */
1183
+ amountMinor: number;
1184
+ reason?: string;
1185
+ }
1186
+ /** An order as the store holds it, read online (ADR-081); never stored by the till. */
1187
+ interface StoreOrder {
1188
+ /** The store's order id: what `OrderRefundPayload.orderId` and `CommandServerRefs.orderId` carry. */
1189
+ id: string;
1190
+ /** The number the store shows (`CommandServerRefs.displayId`). */
1191
+ reference: string;
1192
+ /** The till's `PosOrder.id` when a till created the order; absent otherwise. */
1193
+ clientOrderId?: string;
1194
+ /** The platform's own status word (WooCommerce: `completed`, `refunded`, …); the app labels it. */
1195
+ status: string;
1196
+ /** ISO 8601, UTC. */
1197
+ placedAt: string;
1198
+ currency: string;
1199
+ pricesIncludeTax: boolean;
1200
+ customer: {
1201
+ id?: string;
1202
+ name?: string;
1203
+ email?: string;
1204
+ } | null;
1205
+ lines: StoreOrderLine[];
1206
+ fees: StoreOrderCharge[];
1207
+ shipping: StoreOrderCharge[];
1208
+ /** `discountMinor + discountTaxMinor` is the coupon's gross discount rounded once. */
1209
+ coupons: Array<{
1210
+ code: string;
1211
+ discountMinor: number;
1212
+ discountTaxMinor: number;
1213
+ }>;
1214
+ /** Tax by rate; `amountMinor` includes the rate's shipping tax. */
1215
+ taxLines: Array<{
1216
+ label: string;
1217
+ code?: string;
1218
+ ratePpm: number;
1219
+ amountMinor: number;
1220
+ }>;
1221
+ discountMinor: number;
1222
+ discountTaxMinor: number;
1223
+ taxMinor: number;
1224
+ totalMinor: number;
1225
+ payments: StoreOrderPayment[];
1226
+ refunds: StoreOrderRefund[];
1227
+ }
1228
+ /** The filter fields a connector may support on listOrders. */
1229
+ type OrderFilterField = 'status' | 'customerId' | 'cashierId' | 'registerId' | 'paymentMethod' | 'storeId' | 'createdVia' | 'dateRange';
1230
+ /**
1231
+ * One page of order history, filtered on the server (#721). A connector maps each filter field its own way; a field the
1232
+ * connector does not list in `TallyConnector.orderFilters` is refused with `UnsupportedOrderFilterError`
1233
+ * (`assertOrderFiltersSupported`), never dropped.
1234
+ */
1235
+ interface ListOrdersQuery {
1236
+ /** 1-based; default 1. */
1237
+ page?: number;
1238
+ /** 1..100; default 25. */
1239
+ perPage?: number;
1240
+ /** The platform's own order search. */
1241
+ search?: string;
1242
+ /** The platform's own status word, as StoreOrder.status carries it. */
1243
+ status?: string;
1244
+ /** Store ids, as strings like every id in TallyUI. `'0'` is WooCommerce's guest. */
1245
+ customerId?: string;
1246
+ cashierId?: string;
1247
+ registerId?: string;
1248
+ /** A payment method or gateway id, as the platform records it. */
1249
+ paymentMethod?: string;
1250
+ /** The store (outlet) the order was rung at. */
1251
+ storeId?: string;
1252
+ /** Where the order was created, in the platform's own words (WooCommerce: `woocommerce-pos`, `checkout`, `admin`). */
1253
+ createdVia?: string;
1254
+ /** Created at or after `after` and before `before`: ISO 8601 instants in UTC with a `Z` (`2026-11-11T00:00:00.000Z`). Either end may be absent. */
1255
+ dateRange?: {
1256
+ after?: string;
1257
+ before?: string;
1258
+ };
1259
+ }
1260
+ /** One page of an order list: its orders, whether more follow, and how many the whole query matches when the store says. */
1261
+ interface StoreOrderPage {
1262
+ orders: StoreOrder[];
1263
+ hasMore: boolean;
1264
+ /** Every order the query matches across all pages; undefined when the store gives no count. */
1265
+ total?: number;
1266
+ }
1267
+
1268
+ /**
1269
+ * A payment method the till can offer, backend-neutral (a port of WCPOS v2's Payments Contract
1270
+ * v1 descriptor, `order-math/src/payments/types.ts`). A connector maps its own model into it:
1271
+ * WooCommerce gateways, Medusa payment providers, Vendure payment methods. Amounts are integer
1272
+ * minor units of the store currency. Open vocabularies keep values this build has never seen, so
1273
+ * the till can show such a method disabled instead of dropping it.
1274
+ */
1275
+ /** A known value, or any other string this build does not know yet. */
1276
+ type OpenEnum<Known extends string> = Known | (string & {});
1277
+ /** What kind of money the method takes. Not the order's wire method: that is `PaymentMethodKind`. */
1278
+ type PaymentKind = 'cash' | 'card' | 'stored_value' | 'bank_transfer' | 'other';
1279
+ /** How the payment is taken. `manual`: the cashier records it (cash, a standalone terminal). */
1280
+ type CaptureMode = 'manual' | 'webview' | 'server' | 'device' | 'stored_value' | 'gateway';
1281
+ /** The transport a payment terminal is reached over. */
1282
+ type PaymentTransport = 'bluetooth' | 'usb' | 'network' | 'tap_to_pay';
1283
+ /** Whether a leg can be taken while the till is offline: recorded, queued to settle later, or not at all. */
1284
+ type PaymentOfflineMode = 'record' | 'queue' | 'none';
1285
+ /** Where a tip is entered, if anywhere. */
1286
+ type PaymentTipsMode = 'none' | 'on_reader' | 'at_till';
1287
+ /** The terminal hardware behind a method: readers the server lists, or transports an SDK discovers. */
1288
+ type PaymentHardware = {
1289
+ discovery: OpenEnum<'server'>;
1290
+ readers: {
1291
+ id: string;
1292
+ label: string;
1293
+ status: OpenEnum<'online' | 'offline'>;
1294
+ default: boolean;
1295
+ }[];
1296
+ defaultReader: string | null;
1297
+ lockToDefault: boolean;
1298
+ } | {
1299
+ discovery: OpenEnum<'sdk' | 'manual'>;
1300
+ transports: {
1301
+ transport: OpenEnum<PaymentTransport>;
1302
+ offline: OpenEnum<PaymentOfflineMode>;
1303
+ tips: OpenEnum<PaymentTipsMode>;
1304
+ }[];
1305
+ };
1306
+ /** One way to capture a method's payments. */
1307
+ interface CaptureModeEntry {
1308
+ mode: OpenEnum<CaptureMode>;
1309
+ /** The payment provider's own name, e.g. a terminal vendor; `null` for none. */
1310
+ provider: string | null;
1311
+ hardware: PaymentHardware | null;
1312
+ }
1313
+ /** Cash rounding for the method: the due amount rounds to a multiple of `incrementMinor`; `nearest` rounds half up. */
1314
+ type PaymentRounding = {
1315
+ incrementMinor: number;
1316
+ mode: 'nearest' | 'up' | 'down';
1317
+ } | null;
1318
+ interface PaymentMethodDescriptor {
1319
+ /** The connector's own id for the method, stable across reads. */
1320
+ id: string;
1321
+ /** The name the till shows. */
1322
+ title: string;
1323
+ kind: OpenEnum<PaymentKind>;
1324
+ capture: CaptureModeEntry & {
1325
+ /** Every way the method can be captured, the primary first; absent when `mode` is the only one. */
1326
+ modes?: CaptureModeEntry[];
1327
+ };
1328
+ capabilities: {
1329
+ /** `partial`: the method may take less than the balance (a split leg). */
1330
+ amount: {
1331
+ partial: boolean;
1332
+ minMinor?: number;
1333
+ maxMinor?: number;
1334
+ };
1335
+ /** Whether tendering more than is due gives change. */
1336
+ change: boolean;
1337
+ refunds: {
1338
+ via: OpenEnum<'provider' | 'manual' | 'device' | 'none'>;
1339
+ partial: boolean;
1340
+ };
1341
+ tips: OpenEnum<PaymentTipsMode>;
1342
+ offline: OpenEnum<PaymentOfflineMode>;
1343
+ /** Whether a taken leg can be voided. */
1344
+ void: boolean;
1345
+ };
1346
+ defaults: {
1347
+ rounding: PaymentRounding;
1348
+ /** Whether taking the payment opens the cash drawer. */
1349
+ openDrawer: boolean;
1350
+ };
1351
+ }
1352
+ /** The descriptor of one of today's two wire methods: its `id` is the `PaymentMethodKind`. */
1353
+ declare function paymentMethodOf(kind: PaymentMethodKind): PaymentMethodDescriptor;
1354
+ /** Today's two methods, cash then the card terminal: what the till offers when the connector has no `paymentMethods`. */
1355
+ declare function defaultPaymentMethods(): PaymentMethodDescriptor[];
1356
+
1357
+ /** What a template prints: a sale's receipt, a report, or a register closure. */
1358
+ type ReceiptTemplateKind = 'receipt' | 'report' | 'closure';
1359
+ /**
1360
+ * A store's print template, as the till's renderer takes it (`@tallyui/pos` receipt-template).
1361
+ * `html` bodies are Mustache HTML (renderLogiclessTemplate); `thermal` bodies are Mustache over `<receipt>` XML
1362
+ * (renderThermalPreview).
1363
+ */
1364
+ interface ReceiptTemplate {
1365
+ /** The platform's id, as a string (`"64965"`, `"plugin-core"`). */
1366
+ id: string;
1367
+ kind: ReceiptTemplateKind;
1368
+ title: string;
1369
+ engine: 'html' | 'thermal';
1370
+ /** The Mustache source. Never empty. */
1371
+ body: string;
1372
+ /** The paper a thermal body is laid out for; absent for html. */
1373
+ paper?: '58mm' | '80mm';
1374
+ /**
1375
+ * The data vocabulary the body's Mustache tags expect.
1376
+ * - `'wcpos'`: WCPOS's receipt data (store.address_lines, totals.total_incl_display, …).
1377
+ * - `'tallyui'`: @tallyui/pos `receiptTemplateData`.
1378
+ * A body renders blank fields over data in the other vocabulary.
1379
+ */
1380
+ dataModel: 'wcpos' | 'tallyui';
1381
+ }
1382
+
1383
+ /**
1384
+ * A register (till) in the store's register directory (v2 parity A4). Platform-neutral: each connector maps its own
1385
+ * register model onto it. Money is integer minor units of the store's currency.
1386
+ * The cash variance threshold is not here: it is the store's (ADR-082, `capabilities.registerApproval`).
1387
+ */
1388
+ interface RegisterInfo {
1389
+ /** The platform's register id. */
1390
+ id: string;
1391
+ /** The register's display name, as the cashier picks it. */
1392
+ name: string;
1393
+ /** The cash the drawer should open with; absent when the store sets none. */
1394
+ defaultFloatMinor?: number;
1395
+ /** When the register is due to close: a local store time, `HH:MM` on a 24-hour clock; absent when the store sets none. */
1396
+ expectedCloseTime?: string;
1397
+ }
1398
+
1399
+ /**
1400
+ * The neutral POS permissions a connector resolves from its own model (v2 parity A12):
1401
+ * - `viewReports`: Reports, and a count that shows the expected figures (not blind);
1402
+ * - `manageClosures`: recount and close without an approver;
1403
+ * - `approveVariance`: approve another cashier's over-threshold count;
1404
+ * - `refund`: take refunds;
1405
+ * - `discount`: give discounts.
1406
+ */
1407
+ declare const CASHIER_PERMISSIONS: readonly ["viewReports", "manageClosures", "approveVariance", "refund", "discount"];
1408
+ /** One of `CASHIER_PERMISSIONS`. */
1409
+ type CashierPermission = (typeof CASHIER_PERMISSIONS)[number];
1410
+ /** The signed-in cashier, as the connector maps the platform's user (v2 parity A12). */
1411
+ interface Cashier {
1412
+ /** The platform's id for the signed-in user. */
1413
+ id: string;
1414
+ /** The display name, as receipts and the handover show it. */
1415
+ name: string;
1416
+ /** What this cashier may do; a permission left out is denied. */
1417
+ permissions: readonly CashierPermission[];
1418
+ }
1419
+ /** Whether `value` is one of the five permission names. */
1420
+ declare function isCashierPermission(value: unknown): value is CashierPermission;
1421
+ /** The known permission names in `values`, first occurrence order, without duplicates; anything else is dropped. */
1422
+ declare function cashierPermissions(values: readonly unknown[]): CashierPermission[];
1423
+
1424
+ /**
1425
+ * How well a connector's store answers (v2 parity A6, unit 34). The same three states as WCPOS v2's
1426
+ * `EngineConnectivity`: `degraded` means the device is online but the store keeps failing.
1427
+ */
1428
+ type ConnectivityState = 'online' | 'offline' | 'degraded';
1429
+ /**
1430
+ * A store's deliberate refusal to sync until someone updates software. `fixedBy` as in `SyncNotice`: `'till'` when
1431
+ * this app is older than the store accepts, `'store'` when the store's software is older than the app needs.
1432
+ * `reason` is the connector's code for it; `software`, `minVersion` and `status` only when the refusal names them.
1433
+ */
1434
+ type UpdateRequired = {
1435
+ reason: string;
1436
+ fixedBy: 'till' | 'store';
1437
+ software?: string;
1438
+ minVersion?: string;
1439
+ status?: number;
1440
+ };
1441
+ /** What one failed request says: about connectivity, an update-required refusal, or nothing (`null`). */
1442
+ type FailureClass = 'offline' | 'degraded' | {
1443
+ updateRequired: UpdateRequired;
1444
+ } | null;
1445
+ /**
1446
+ * For a connector's fetch call site alone: `fetch(url, init).catch(noResponse)`. A fetch that rejects got no response,
1447
+ * but its `TypeError` looks like one our own code throws, so the call site tags it: rethrown as a `NoResponseError`
1448
+ * with `code: 'network'` (offline to `neutralFailureClass`) and the original as `cause`. An abort or timeout is
1449
+ * rethrown unchanged. Code that reads the response runs after the catch, so its errors are never tagged.
1450
+ */
1451
+ declare function noResponse(error: unknown): never;
1452
+ /**
1453
+ * The rule for a connector without `classifyFailure`: a timeout or a 5xx is `degraded`; a request that got no
1454
+ * response (`code: 'network'`, as `noResponse` and `CustomerServiceError` set, or a no-response socket code on the
1455
+ * error or its `cause`) is `offline`; anything else is `null`, a bare `TypeError` included, since our own code throws
1456
+ * those too. It never answers update-required: only a connector knows its own refusal.
1457
+ */
1458
+ declare function neutralFailureClass(error: unknown): FailureClass;
1459
+ /** The connector's own `classifyFailure` when it has one (its answer is final), else `neutralFailureClass`. A method that throws gives `null`. */
1460
+ declare function classifyFailure(connector: Pick<TallyConnector, 'classifyFailure'> | undefined, error: unknown): FailureClass;
1461
+
1462
+ /** The capability a cashier session needs for every till-side signalling call (ADR-085 d4, d5); each platform maps it onto its own roles. */
1463
+ declare const DISPLAY_PAIR_CAPABILITY = "customer_display.pair";
1464
+ /** One ICE server, in the shape `RTCPeerConnection` takes (ADR-085 d7). */
1465
+ interface IceServer {
1466
+ urls: string | string[];
1467
+ username?: string;
1468
+ credential?: string;
1469
+ }
1470
+ /** The store's display advertisement from `GET /tally/v1/info` (`customerDisplay`, ADR-085 d7, d8). */
1471
+ interface DisplayAdvertisement {
1472
+ /** The ICE servers both peers use; `[]` is LAN-only. */
1473
+ iceServers: IceServer[];
1474
+ /** Whether the till posts the snapshot fallback while a display's data channel is not open. */
1475
+ snapshot: boolean;
1476
+ }
1477
+ type DisplaySignallingErrorCode =
1478
+ /** Till side: no session, or the session lacks `customer_display.pair`. */
1479
+ 'forbidden'
1480
+ /** Mint: this device already holds 5 unspent codes. */
1481
+ | 'limit'
1482
+ /** Every claim refusal: unknown, expired or spent code, rate-limited or paused. One code, so a guesser learns nothing (ADR-085 d4). */
1483
+ | 'claim_refused'
1484
+ /** Collect with an unknown, declined or expired secret, or a token already collected; it does not say which (#705). */
1485
+ | 'collect_refused'
1486
+ /** Till side: an id this device does not own, or one that is unknown or expired. */
1487
+ | 'not_found'
1488
+ /** Display side: a token that is unknown, forgotten or pruned. */
1489
+ | 'token_refused'
1490
+ /** A snapshot whose JSON is over 200 KiB. */
1491
+ | 'too_large'
1492
+ /** Transport failure: no answer from the server (connectors). */
1493
+ | 'network'
1494
+ /** Transport failure: the server answered with an error the seam does not name (connectors). */
1495
+ | 'server';
1496
+ /** Every refusal of a `DisplaySignalling` method. Branch on `code`. */
1497
+ declare class DisplaySignallingError extends Error {
1498
+ readonly code: DisplaySignallingErrorCode;
1499
+ constructor(code: DisplaySignallingErrorCode, message?: string);
1500
+ }
1501
+ /** The display side's context: a display has no login, only the store's address. */
1502
+ interface DisplaySignallingContext {
1503
+ baseUrl: string;
1504
+ fetch?: typeof globalThis.fetch;
1505
+ }
1506
+ /** A claim waiting for the minting till's cashier. */
1507
+ interface PendingPairing {
1508
+ claimId: string;
1509
+ displayName: string;
1510
+ /** 4 digits, shown on the display and on the till, so the cashier can see which display asks (#705). */
1511
+ checkCode: string;
1512
+ /** ISO 8601: the code's expiry, when an unconfirmed claim is deleted. */
1513
+ expiresAt: string;
1514
+ }
1515
+ /** A paired display in the server's registry (ADR-085 d6). */
1516
+ interface DisplayRecord {
1517
+ displayId: string;
1518
+ name: string;
1519
+ /** The cashier who confirmed the pairing. */
1520
+ cashierId: string;
1521
+ /** ISO 8601 of the last successful display-side token call, or `null` when never seen. */
1522
+ lastSeenAt: string | null;
1523
+ /** Whether the display was seen recently (the reference server: within the last 30 s). */
1524
+ connected: boolean;
1525
+ }
1526
+ /** One WebRTC signalling message; `payload` is opaque to the server. */
1527
+ interface SignalMessage {
1528
+ type: 'offer' | 'answer' | 'ice';
1529
+ payload: string;
1530
+ }
1531
+ /**
1532
+ * The platform-neutral signalling seam for a second-device customer display (ADR-085 d2). Each backend's plugin
1533
+ * implements the routes its own way; every implementation meets this floor (d4–d6, d8, #705), which
1534
+ * `displaySignallingContract` in `@tallyui/core/server` tests. A plugin may be stricter.
1535
+ * Till side: every call takes a cashier session and the till's device id; a session without `customer_display.pair`
1536
+ * gets `forbidden`, and an id this device does not own gets `not_found`. Display side: no login; calls are gated by the
1537
+ * display's token (`token_refused`), and each successful token call updates `lastSeenAt`. Every refusal is a
1538
+ * `DisplaySignallingError`.
1539
+ */
1540
+ interface DisplaySignalling {
1541
+ /** A pairing code: 6+ digits from `crypto.getRandomValues`, single use, live at most 10 minutes; a 6th unspent code per device gives `limit`. */
1542
+ mint(ctx: SyncContext, deviceId: string): Promise<{
1543
+ code: string;
1544
+ expiresAt: string;
1545
+ }>;
1546
+ /** The live claims on codes this device minted, each with its check code. */
1547
+ pending(ctx: SyncContext, deviceId: string): Promise<PendingPairing[]>;
1548
+ /**
1549
+ * Confirms a claim on a code this device minted, recording the display as owned by this device and cashier. The
1550
+ * display then collects its token: 128 bits, base64url, stored only as SHA-256 hex. A claim that carried a valid
1551
+ * token moves that display: its old row, token and snapshot go in the same step, and this device owns the same id.
1552
+ */
1553
+ confirm(ctx: SyncContext, deviceId: string, claimId: string): Promise<void>;
1554
+ /** Declines a claim on a code this device minted: the pending pairing is deleted, and nothing is issued. */
1555
+ decline(ctx: SyncContext, deviceId: string, claimId: string): Promise<void>;
1556
+ /** The displays this device owns. A display unseen for 30 days is pruned with its token and snapshot. */
1557
+ list(ctx: SyncContext, deviceId: string): Promise<DisplayRecord[]>;
1558
+ /** Deletes the display's row, token hash and snapshot at once; the token is refused on its next call. */
1559
+ forget(ctx: SyncContext, deviceId: string, displayId: string): Promise<void>;
1560
+ /** Queues a message in an owned display's inbox. */
1561
+ sendSignal(ctx: SyncContext, deviceId: string, displayId: string, message: SignalMessage): Promise<void>;
1562
+ /** Drains this device's inbox: each message once, in send order, only from displays it owns. */
1563
+ receiveSignals(ctx: SyncContext, deviceId: string): Promise<Array<SignalMessage & {
1564
+ displayId: string;
1565
+ }>>;
1566
+ /** Keeps `body` as the display's only snapshot for at most 60 s; over 204 800 UTF-8 bytes of JSON gives `too_large` and keeps the old one. */
1567
+ postSnapshot(ctx: SyncContext, deviceId: string, displayId: string, body: unknown): Promise<void>;
1568
+ /**
1569
+ * Claims a live code: the first claim spends it and records a pending pairing with `displayName` and a fresh 4-digit
1570
+ * check code, unique among live pending pairings, and returns a claim secret (128 bits, base64url, stored only as a
1571
+ * hash); no token. `token` is the display's current token, if any, so a confirm moves it. A claim naming no live code
1572
+ * fails and spends nothing. Failed claims are limited per source (10 a minute, IPv6 by /64 via `rateLimitSource`) and
1573
+ * store-wide (100 per 10 minutes); over either, every claim is refused and spends nothing. Every refusal is `claim_refused`.
1574
+ */
1575
+ claim(dctx: DisplaySignallingContext, request: {
1576
+ code: string;
1577
+ displayName: string;
1578
+ token?: string;
1579
+ }): Promise<{
1580
+ claimSecret: string;
1581
+ checkCode: string;
1582
+ }>;
1583
+ /** Pending: `pending` with the check code. After the confirm the first collect gives `paired` with the token; later, declined, expired or unknown gives `collect_refused`. */
1584
+ collect(dctx: DisplaySignallingContext, claimSecret: string): Promise<{
1585
+ status: 'pending';
1586
+ checkCode: string;
1587
+ } | {
1588
+ status: 'paired';
1589
+ displayId: string;
1590
+ token: string;
1591
+ }>;
1592
+ /** Queues a message in the owning till's inbox. */
1593
+ displaySendSignal(dctx: DisplaySignallingContext, token: string, message: SignalMessage): Promise<void>;
1594
+ /** Drains this display's own inbox: each message once, in send order. */
1595
+ displayReceiveSignals(dctx: DisplaySignallingContext, token: string): Promise<SignalMessage[]>;
1596
+ /** The display's latest snapshot, or `null` when none is held. */
1597
+ readSnapshot(dctx: DisplaySignallingContext, token: string): Promise<unknown | null>;
1598
+ }
1599
+
1600
+ /**
1601
+ * Authentication configuration for a connector.
1602
+ * Each API has wildly different auth — JWT, API keys, OAuth, etc.
1603
+ * The connector declares what it needs and how to use it.
1604
+ */
1605
+ interface ConnectorAuth {
1606
+ /** Human-readable auth type for UI display */
1607
+ type: string;
1608
+ /** Fields required from the user to authenticate */
1609
+ fields: AuthField[];
1610
+ /** Build request headers from stored credentials */
1611
+ getHeaders: (credentials: Record<string, string>) => Record<string, string>;
1612
+ /** Optional: validate that credentials work (e.g., test API call) */
1613
+ validate?: (credentials: Record<string, string>) => Promise<boolean>;
1614
+ /**
1615
+ * Exchanges a user's email and password for a credential (token) to store and pass back to getHeaders as `token`.
1616
+ * Rejects with a `SignInError`: `invalid_credentials`, `unsupported` or `failed`.
1617
+ */
1618
+ signIn?: (baseUrl: string, login: {
1619
+ email: string;
1620
+ password: string;
1621
+ }, init?: {
1622
+ signal?: AbortSignal;
1623
+ fetch?: typeof fetch;
1624
+ }) => Promise<SignInResult>;
1625
+ }
1626
+ interface SignInResult {
1627
+ token: string;
1628
+ /** ISO 8601, when the backend says when the token expires */
1629
+ expiresAt?: string;
1630
+ /** The store's contract capabilities (ADR-062), when the read was conclusive. */
1631
+ capabilities?: ServerCapabilities;
1632
+ }
1633
+ /** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
1634
+ interface ServerCapabilities {
1635
+ orderCreate: number;
1636
+ /** The highest `register` contract version; absent or 0 means no register sync. */
1637
+ register?: number;
1638
+ /** The highest `order.refund` version; absent or 0 means the store takes no refunds and the app hides the action (ADR-080). */
1639
+ orderRefund?: number;
1640
+ /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
1641
+ taxRounding?: TaxRounding;
1642
+ /** Whether one order may carry several payments. Absent means it may: order.create's `payments` has always been a
1643
+ * list. A WooCommerce store says false until its plugin records the list (`order_payments_list`). The app offers
1644
+ * split tender only when this is not false. */
1645
+ multiplePayments?: boolean;
1646
+ /**
1647
+ * What the store accepts for a fee's, a shipping charge's or a custom line's tax (order.create 5, ADR-075):
1648
+ * `none` is `taxStatus: 'none'`, `classes` is a `taxClass`. Absent means neither; the UI hides what is false.
1649
+ */
1650
+ lineTax?: {
1651
+ none: boolean;
1652
+ classes: boolean;
1653
+ };
1654
+ /**
1655
+ * Whether the store accepts an order's coupons (ADR-077). Absent means it does not: the till refuses to apply a
1656
+ * coupon. WooCommerce: true only when the woocommerce-pos plugin reports 1.9.0 or later. Other platforms report it as
1657
+ * `/tally/v1/info`'s `coupons: true` (#709).
1658
+ */
1659
+ coupons?: boolean;
1660
+ /**
1661
+ * The store's register approval threshold (ADR-082 d3), from the top level of `/tally/v1/info`. With
1662
+ * `register >= 3`, a close whose absolute cash variance is over `thresholdMinor` needs the store's approval.
1663
+ * Absent means the store sets none, and the app's own threshold applies.
1664
+ */
1665
+ registerApproval?: {
1666
+ thresholdMinor: number;
1667
+ };
1668
+ /**
1669
+ * A store whose plugin signals second-device customer displays (ADR-085), from `/tally/v1/info`'s top-level
1670
+ * `customerDisplay`. Absent means no second-device display.
1671
+ */
1672
+ customerDisplay?: DisplayAdvertisement;
1673
+ }
1674
+ /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
1675
+ type TaxRounding = {
1676
+ granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items';
1677
+ mode: 'half_away_from_zero' | 'half_up';
1678
+ } | {
1679
+ granularity: 'woocommerce';
1680
+ roundAtSubtotal: boolean;
1681
+ } | {
1682
+ granularity: 'custom';
1683
+ };
1684
+ /**
1685
+ * Resolves the capabilities to act on: a definitive fresh read always wins,
1686
+ * even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
1687
+ * last known value. The app persists `stored` with its session, the way it
1688
+ * persists the store-settings choice, and copies the result into
1689
+ * `SyncContext.capabilities`. `finalizeOrder` treats `undefined` as 1, which
1690
+ * only happens when the value has never been read (ADR-062).
1691
+ */
1692
+ declare function resolveCapabilities(fresh: ServerCapabilities | undefined, stored: ServerCapabilities | undefined): ServerCapabilities | undefined;
1693
+ /**
1694
+ * Reads the `taxRounding` of `GET /tally/v1/info` (#287): a valid value comes back without
1695
+ * extra keys, and `custom` drops any `mode`. Absent gives `undefined`, the default. Core has
1696
+ * no logger, so a malformed value gives `undefined` and one reason to `warn` for the caller to log.
1697
+ */
1698
+ declare function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined;
1699
+ declare function parseLineTax(value: unknown, warn?: (reason: string) => void): {
1700
+ none: boolean;
1701
+ classes: boolean;
1702
+ } | undefined;
1703
+ /**
1704
+ * Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
1705
+ * `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
1706
+ * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287); malformed `lineTax` is ignored.
1707
+ * malformed `registerApproval` is ignored (ADR-082). `coupons` is true only when the body says `coupons: true` (#709).
1708
+ * `orderRefund` is the max of `contracts["order.refund"]` when valid, otherwise absent (ADR-080).
1709
+ * `customerDisplay` is present only when `parseDisplayAdvertisement` accepts it; a malformed one warns (ADR-085).
1710
+ * Absent `taxRounding` uses the default; a present malformed value is unknown, so settings wait.
1711
+ * A non-object body is also unknown, not a statement of the store's defaults.
1712
+ */
1713
+ declare function parseInfoCapabilities(body: unknown, warn?: (reason: string) => void): ServerCapabilities | undefined;
1714
+ interface AuthField {
1715
+ key: string;
1716
+ label: string;
1717
+ type: 'text' | 'password' | 'url';
1718
+ placeholder?: string;
1719
+ required?: boolean;
1720
+ }
1721
+ /**
1722
+ * Sync configuration for a collection.
1723
+ * Defines how to fetch data from the remote API and push changes back.
1724
+ *
1725
+ * @deprecated Use ReplicationAdapter instead. This interface will be removed
1726
+ * once all connectors have migrated to the RxDB replication protocol.
1727
+ */
1728
+ interface CollectionSync<T = any> {
1729
+ /** Fetch all remote IDs (for diffing against local) */
1730
+ fetchAllIds: (context: SyncContext) => Promise<RemoteIdEntry[]>;
1731
+ /** Fetch documents by IDs */
1732
+ fetchByIds: (ids: string[], context: SyncContext) => Promise<T[]>;
1733
+ /** Fetch documents modified after a given date */
1734
+ fetchModifiedAfter?: (date: string, context: SyncContext) => Promise<T[]>;
1735
+ /** Push a local change to the remote */
1736
+ push?: (doc: T, context: SyncContext) => Promise<T>;
1737
+ /** Create a new document on the remote */
1738
+ create?: (doc: Partial<T>, context: SyncContext) => Promise<T>;
1739
+ /** Delete a document on the remote */
1740
+ delete?: (id: string, context: SyncContext) => Promise<void>;
1741
+ }
1742
+ interface RemoteIdEntry {
1743
+ id: string;
1744
+ dateModified?: string;
1745
+ }
1746
+ interface SyncContext {
1747
+ /** Unique connector identifier (used as replication namespace) */
1748
+ connectorId: string;
1749
+ /** Base URL for the API */
1750
+ baseUrl: string;
1751
+ /** Authenticated headers */
1752
+ headers: Record<string, string>;
1753
+ /** Optional abort signal */
1754
+ signal?: AbortSignal;
1755
+ /** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
1756
+ pricingContext?: Record<string, string>;
1757
+ /** The store's contract capabilities (ADR-062), copied from the sign-in result. */
1758
+ capabilities?: ServerCapabilities;
1759
+ /** The fetch the connector sends its requests with; defaults to globalThis.fetch. A host passes a wrapper
1760
+ * here, for example @tallyui/database meteredFetch, to count requests. Resolved per request. */
1761
+ fetch?: typeof globalThis.fetch;
1762
+ }
1763
+ /**
1764
+ * Schema definitions for a connector.
1765
+ * Each connector provides its own RxDB schemas that mirror its API shape.
1766
+ *
1767
+ * Each describes a server-owned, pull-replicated collection (ADR-060), so its
1768
+ * versions never transform documents: a version bump drops and resyncs.
1769
+ * `createTallyDatabase` drops the old documents, and `startReplication` resets
1770
+ * the checkpoint, so the first sync after the bump downloads the collection again.
1771
+ */
1772
+ interface ConnectorSchemas {
1773
+ products: RxJsonSchema<any>;
1774
+ [key: string]: RxJsonSchema<any>;
1775
+ }
1776
+ /**
1777
+ * Trait implementations for a connector.
1778
+ * These are the accessor functions that components program against.
1779
+ */
1780
+ interface ConnectorTraits {
1781
+ product: ProductTraits;
1782
+ customer?: CustomerTraits;
1783
+ }
1784
+ /**
1785
+ * The main connector interface.
1786
+ * Each backend (WooCommerce, Medusa, Vendure, etc.) implements this.
1787
+ */
1788
+ interface TallyConnector {
1789
+ /** Unique identifier for this connector */
1790
+ id: string;
1791
+ /** Human-readable name */
1792
+ name: string;
1793
+ /** Description of the backend this connects to */
1794
+ description: string;
1795
+ /** Icon or logo URL */
1796
+ icon?: string;
1797
+ /** Authentication configuration */
1798
+ auth: ConnectorAuth;
1799
+ /** RxDB schemas for each collection */
1800
+ schemas: ConnectorSchemas;
1801
+ /** Trait implementations — how to extract standard data from connector-specific docs */
1802
+ traits: ConnectorTraits;
1803
+ /**
1804
+ * @deprecated Use `replication` instead.
1805
+ * Sync configuration for each collection (legacy pull-based sync).
1806
+ */
1807
+ sync: {
1808
+ products: CollectionSync;
1809
+ [key: string]: CollectionSync;
1810
+ };
1811
+ /** Replication adapters for each collection (RxDB replication protocol) */
1812
+ replication?: {
1813
+ products?: ReplicationAdapter<any>;
1814
+ [key: string]: ReplicationAdapter<any> | undefined;
1815
+ };
1816
+ /** Periodic re-reads of state that replication misses (ADR-060) */
1817
+ reconcile?: {
1818
+ stock?: StockReconcileAdapter;
1819
+ ids?: IdReconcileAdapter;
1820
+ prices?: FingerprintReconcileAdapter;
1821
+ /** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
1822
+ calculatedPrices?: FingerprintReconcileAdapter;
1823
+ /** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
1824
+ catalogue?: CatalogueReconcileAdapter;
1825
+ /**
1826
+ * The coupons' only source (ADR-077 amendment 2): a catalogue reconcile over the coupon listing, whose
1827
+ * fingerprint carries the usage that never moves the modified time. Optional: a connector without it has no
1828
+ * coupons, and the coupons feature is gated on it.
1829
+ */
1830
+ coupons?: CatalogueReconcileAdapter;
1831
+ };
1832
+ /**
1833
+ * Reads the store's own settings (TV4): currency, tax inclusivity, tax
1834
+ * rates and a connector-specific pricing context. Read once after
1835
+ * sign-in; the app feeds all three consumers from the result. Read-only,
1836
+ * never writes to the store (ADR-048).
1837
+ */
1838
+ storeSettings?: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
1839
+ /**
1840
+ * Re-reads the store's contract capabilities (ADR-062) for a session
1841
+ * restored without signing in again — otherwise a restored session would
1842
+ * block discounts until the cashier signed in again. `undefined` means
1843
+ * the read was inconclusive (offline or a server error), not version 1;
1844
+ * see `resolveCapabilities`.
1845
+ * It may throw when the store refuses the read. Medusa throws `SignInError` (`invalid_credentials`) for a 401; its
1846
+ * 403 gives `undefined`. Vendure throws `ConnectorUnauthorizedError` only once its sign-in probe settles the
1847
+ * cause: `status: 401` when the session is signed out, `status: 403` when a signed-in administrator lacks the
1848
+ * CreateOrder permission; a probe that fails gives `undefined`. Branch on the error's `code` (only
1849
+ * `unauthorized` or `invalid_credentials` means sign in again), never on its class.
1850
+ */
1851
+ capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
1852
+ /**
1853
+ * The payment methods the till may offer, in the order it shows them (v2 parity A2). Read-only, never writes to
1854
+ * the store. `undefined` when the connector has none of its own: the till offers `defaultPaymentMethods()`.
1855
+ */
1856
+ paymentMethods?: (context: SyncContext) => Promise<PaymentMethodDescriptor[]>;
1857
+ /**
1858
+ * The store's print templates of one kind (default `receipt`), in the store's own order: online only, read-only.
1859
+ * Only templates the till can render are returned; `[]` when the store has none. `undefined` when the connector
1860
+ * has no store templates (the till keeps its built-in layouts).
1861
+ */
1862
+ receiptTemplates?: (context: SyncContext, kind?: ReceiptTemplateKind) => Promise<ReceiptTemplate[]>;
1863
+ /**
1864
+ * Customer search: online only. An empty or whitespace query may list a first page of the store's customers
1865
+ * (recent ones, or in the store's own picker order); a connector that cannot list them returns `[]`.
1866
+ * `undefined` when the connector has no customer support.
1867
+ */
1868
+ searchCustomers?: (context: SyncContext, query: string, options?: {
1869
+ limit?: number;
1870
+ }) => Promise<Customer[]>;
1871
+ /**
1872
+ * A page of a customer search, with the store's count of all matches: online only. The query and `limit` mean what
1873
+ * they mean for `searchCustomers`; `page` is 1-based (default 1). `undefined` when the connector can't page or count.
1874
+ */
1875
+ searchCustomersPage?: (context: SyncContext, query: string, options?: {
1876
+ limit?: number;
1877
+ page?: number;
1878
+ }) => Promise<CustomerPage>;
1879
+ /** Customer creation: online only; `undefined` when the connector has no customer support. */
1880
+ createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
1881
+ /**
1882
+ * Customer edit: online only; resolves the customer as the store now has it. Rejects with
1883
+ * `ConnectorUnauthorizedError` for credentials and `CustomerServiceError` (`invalid` for a refused patch or an id
1884
+ * the store does not have, `server` or `network` otherwise). `undefined` when the connector can't edit customers.
1885
+ */
1886
+ updateCustomer?: (context: SyncContext, id: string, patch: CustomerPatch) => Promise<Customer>;
1887
+ /** Customer lookup: online only; `undefined` when the connector has no customer support. */
1888
+ getCustomer?: (context: SyncContext, id: string) => Promise<Customer | null>;
1889
+ /**
1890
+ * Emails the receipt of an order the store already has: online only, and **not idempotent** (each call sends one
1891
+ * email, so an app never retries it on its own after a timeout). `orderId` is the store's id from the order-create
1892
+ * result (`serverRefs.orderId`). `options.saveToBilling` also stores the address on the order's billing email where
1893
+ * the platform supports it. Rejects with `ConnectorUnauthorizedError` for credentials and `CustomerServiceError`
1894
+ * (`invalid` for a refused order or address, `server` or `network` otherwise). `undefined` when the connector can't
1895
+ * email receipts.
1896
+ */
1897
+ emailReceipt?: (context: SyncContext, orderId: string, email: string, options?: {
1898
+ saveToBilling?: boolean;
1899
+ }) => Promise<void>;
1900
+ /**
1901
+ * The store's orders, newest first, one page per call (ADR-081): online only, read-only. Rejects as `emailReceipt`
1902
+ * does (`ConnectorUnauthorizedError` for credentials; a connector's own errors otherwise, e.g. `CustomerServiceError`).
1903
+ * It rejects with `UnsupportedOrderFilterError` for a filter field outside `orderFilters`; calling
1904
+ * `assertOrderFiltersSupported` first gives that. `undefined` when the connector has no order history.
1905
+ */
1906
+ listOrders?: (context: SyncContext, query?: ListOrdersQuery) => Promise<StoreOrderPage>;
1907
+ /** The ListOrdersQuery filter fields listOrders honours. Absent or empty: none; listOrders refuses any filter field. */
1908
+ orderFilters?: readonly OrderFilterField[];
1909
+ /**
1910
+ * The given orders by store id (ADR-081), in the order asked; an id the store does not have is left out. Online only,
1911
+ * read-only; rejects as `listOrders`. `undefined` when the connector has no order history.
1912
+ */
1913
+ getOrders?: (context: SyncContext, ids: readonly string[]) => Promise<StoreOrder[]>;
1914
+ /**
1915
+ * The store's register directory (v2 parity A4): online only, read-only. Rejects with `ConnectorUnauthorizedError`
1916
+ * for credentials; a connector's own errors otherwise. `undefined` when the connector has no register directory.
1917
+ */
1918
+ listRegisters?: (context: SyncContext) => Promise<RegisterInfo[]>;
1919
+ /**
1920
+ * The signed-in cashier and their neutral POS permissions (v2 parity A12), mapped from the platform's own roles or
1921
+ * capabilities. Read-only. `null` when the connector has no cashier to describe; `undefined` (no method) when the
1922
+ * connector has no permission model: the till then allows everything, as before (`can` in `@tallyui/pos`).
1923
+ * Permission names outside `CashierPermission` are dropped by `useCashier` (`cashierPermissions`).
1924
+ */
1925
+ cashier?: (context: SyncContext) => Promise<Cashier | null>;
1926
+ /**
1927
+ * Maps one of this connector's request failures (pull, push, reconcile, online calls) to a connectivity verdict or
1928
+ * its own update-required refusal (v2 parity A6). Synchronous and pure. `null` when the failure says nothing about
1929
+ * connectivity (a validation refusal). `undefined` (no method) uses `neutralFailureClass`, which a connector's own
1930
+ * method may also call for the failures it does not map.
1931
+ */
1932
+ classifyFailure?: (error: unknown) => FailureClass;
1933
+ /**
1934
+ * Signalling for a customer display on a second device (ADR-085 d2). Absent means no second-device display; the
1935
+ * same-device display still works.
1936
+ */
1937
+ displaySignalling?: DisplaySignalling;
1938
+ }
1939
+
1940
+ /** Path of the command endpoint, relative to the backend's base URL. */
1941
+ declare const COMMANDS_PATH = "/tally/v1/commands";
1942
+ /** Header carrying the protocol version. */
1943
+ declare const PROTOCOL_HEADER = "X-Tally-Protocol";
1944
+ /** Current protocol version. */
1945
+ declare const PROTOCOL_VERSION = 1;
1946
+ /** The ADR-038 batch limit; a server answers more with 413 and a BatchTooLargeBody. */
1947
+ declare const MAX_COMMANDS_PER_BATCH = 50;
1948
+ /** The longest order.create `note` (version 7, ADR-083), in UTF-16 code units. WCPOS v2's order note has no cap; this bounds the wire. */
1949
+ declare const ORDER_NOTE_MAX = 1000;
1950
+ /**
1951
+ * True if `value` has the shape of a CommandBatchResponse: an object with a
1952
+ * `results` array whose every entry has a string `id` and a `status` of
1953
+ * 'applied' | 'duplicate' | 'rejected'. Optional fields are not deep-checked.
1954
+ */
1955
+ declare function isCommandBatchResponse(value: unknown): value is CommandBatchResponse;
1956
+
1957
+ /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
1958
+ * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
1959
+ declare class CommandResultError extends Error {
1960
+ constructor(message: string);
1961
+ }
1962
+ /** Validates a CommandResult (e.g. one read back from the ledger). Throws
1963
+ * CommandResultError naming the first bad field. */
1964
+ declare function parseCommandResult(value: unknown): CommandResult;
1965
+
1966
+ export { type Customer as $, type AnyCommandEnvelope as A, type BatchTooLargeBody as B, type CommandWarning as C, type DisplayAdvertisement as D, type CommandBatchRequest as E, type CommandBatchResponse as F, type CommandEnvelope as G, type CommandError as H, type IceServer as I, type CommandResult as J, CommandResultError as K, type ListOrdersQuery as L, type Money as M, type CommandServerRefs as N, type OrderFilterField as O, type ProductPrice as P, type CommandStatus as Q, type ResolvedPrice as R, type StockReconcileAdapter as S, type TallyConnector as T, type CommandType as U, type VariantSummary as V, type WooTaxRate as W, type ConnectivityState as X, type ConnectorAuth as Y, type ConnectorSchemas as Z, type ConnectorTraits as _, type ProductTraits as a, type RemoteIdEntry as a$, type CustomerAddress as a0, type CustomerInput as a1, type CustomerPage as a2, type CustomerPatch as a3, CustomerServiceError as a4, type CustomerTaxId as a5, DISPLAY_PAIR_CAPABILITY as a6, type DisplayRecord as a7, type DisplaySignalling as a8, type DisplaySignallingContext as a9, PROTOCOL_HEADER as aA, PROTOCOL_VERSION as aB, type PaymentHardware as aC, type PaymentKind as aD, type PaymentMethodDescriptor as aE, type PaymentMethodKind as aF, type PaymentOfflineMode as aG, type PaymentRounding as aH, type PaymentTipsMode as aI, type PaymentTransport as aJ, type PendingPairing as aK, type ProductCategory as aL, type ReceiptTemplate as aM, type ReceiptTemplateKind as aN, type RegisterApprovalInvalidData as aO, type RegisterApprovalRequiredData as aP, type RegisterClosureSubmitPayload as aQ, type RegisterCommandEnvelope as aR, type RegisterCommandResult as aS, type RegisterCommandType as aT, type RegisterInfo as aU, type RegisterMovementRecordPayload as aV, type RegisterMovementVoidPayload as aW, type RegisterSessionAlreadyOpenData as aX, type RegisterSessionOpenPayload as aY, type RegisterSessionSupersededData as aZ, type RegisterSessionTransitionPayload as a_, DisplaySignallingError as aa, type DisplaySignallingErrorCode as ab, type FailureClass as ac, type FingerprintReconcileAdapter as ad, type IdReconcileAdapter as ae, MAX_COMMANDS_PER_BATCH as af, ORDER_NOTE_MAX as ag, type OrderAddress as ah, type OrderCreateCoupon as ai, type OrderCreateCouponInvalidData as aj, type OrderCreateDisplay as ak, type OrderCreateEnvelope as al, type OrderCreateLine as am, type OrderCreatePayload as an, type OrderCreatePayment as ao, type OrderCreateTaxRate as ap, type OrderCreateTotalMismatchData as aq, type OrderRefundAmountMismatchData as ar, type OrderRefundEnvelope as as, type OrderRefundLine as at, type OrderRefundNoOpenSessionData as au, type OrderRefundOrderStateData as av, type OrderRefundPayload as aw, type OrderRefundQuantityExceedsData as ax, type OrderRefundRejectionCode as ay, type OrderRefundResult as az, type StockLevel as b, type ServerCapabilities as b0, type SignInResult as b1, type SignalMessage as b2, type StockStatus as b3, type StoreOrder as b4, type StoreOrderCharge as b5, type StoreOrderLine as b6, type StoreOrderPage as b7, type StoreOrderPayment as b8, type StoreOrderRefund as b9, type StoreSettings as ba, type StoreSettingsChoice as bb, type StoreTaxClass as bc, type StoreTaxRate as bd, type StoreTaxRateLocation as be, type TaxRounding as bf, type UpdateRequired as bg, type VariantOptionGroup as bh, cashierPermissions as bi, classifyFailure as bj, customerTraits as bk, defaultPaymentMethods as bl, isCashierPermission as bm, isCommandBatchResponse as bn, neutralFailureClass as bo, noResponse as bp, parseCommandResult as bq, parseInfoCapabilities as br, parseLineTax as bs, parseTaxRounding as bt, paymentMethodOf as bu, resolveCapabilities as bv, type ReplicationAdapter as c, type SyncContext as d, type TraitContext as e, type CustomerTraits as f, type CalculateTaxesInput as g, type CalculateTaxesResult as h, type ItemizedTax as i, type ResolvedTaxLocation as j, TAX_BASED_ON_META_KEY as k, type TaxAddress as l, type TaxBasedOn as m, type TaxLocationOrder as n, normalizeTaxBasedOn as o, orderTaxLocation as p, type AuthField as q, CASHIER_PERMISSIONS as r, COMMANDS_PATH as s, type CaptureMode as t, type CaptureModeEntry as u, type Cashier as v, type CashierPermission as w, type CatalogueReconcileAdapter as x, type CatalogueReconcileEntry as y, type CollectionSync as z };