@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.
package/dist/index.js CHANGED
@@ -1,17 +1,59 @@
1
1
  import {
2
2
  COMMANDS_PATH,
3
3
  CommandResultError,
4
+ DISPLAY_PAIR_CAPABILITY,
5
+ DisplaySignallingError,
4
6
  MAX_COMMANDS_PER_BATCH,
5
7
  ORDER_NOTE_MAX,
6
8
  PROTOCOL_HEADER,
7
9
  PROTOCOL_VERSION,
8
10
  isCommandBatchResponse,
9
- parseCommandResult
10
- } from "./chunk-CSXNXRBA.js";
11
+ parseCommandResult,
12
+ rateLimitSource
13
+ } from "./chunk-27L7XLTT.js";
11
14
  import {
12
15
  __export
13
16
  } from "./chunk-MLKGABMK.js";
14
17
 
18
+ // src/customer-display/advertisement.ts
19
+ var DEFAULT_ICE_SERVERS = Object.freeze([
20
+ { urls: "stun:stun.cloudflare.com:3478" },
21
+ { urls: "stun:stun.l.google.com:19302" }
22
+ ]);
23
+ var SCHEMES = ["stun:", "stuns:", "turn:", "turns:"];
24
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
25
+ var nonEmpty = (value) => typeof value === "string" && value.length > 0;
26
+ var defaults = () => DEFAULT_ICE_SERVERS.map((server) => ({ ...server }));
27
+ function parseIceServer(entry) {
28
+ if (!isPlainObject(entry)) return void 0;
29
+ const { urls, username, credential } = entry;
30
+ const list = typeof urls === "string" ? [urls] : urls;
31
+ if (!Array.isArray(list) || list.length === 0 || !list.every(nonEmpty)) return void 0;
32
+ if (!list.every((url) => SCHEMES.some((scheme) => url.startsWith(scheme)))) return void 0;
33
+ const turn = list.some((url) => url.startsWith("turn:") || url.startsWith("turns:"));
34
+ if (turn && !(nonEmpty(username) && nonEmpty(credential))) return void 0;
35
+ return {
36
+ urls: typeof urls === "string" ? urls : [...list],
37
+ ...typeof username === "string" ? { username } : {},
38
+ ...typeof credential === "string" ? { credential } : {}
39
+ };
40
+ }
41
+ function parseDisplayAdvertisement(value, warn) {
42
+ if (value === void 0) return void 0;
43
+ if (!isPlainObject(value) || value.v !== 1) {
44
+ warn?.("ignoring a malformed customerDisplay: no second-device display");
45
+ return void 0;
46
+ }
47
+ const snapshot = value.snapshot === 1;
48
+ if (value.iceServers === void 0) return { iceServers: defaults(), snapshot };
49
+ const parsed = Array.isArray(value.iceServers) ? value.iceServers.map(parseIceServer) : [void 0];
50
+ if (parsed.some((server) => server === void 0)) {
51
+ warn?.("refused customerDisplay.iceServers, so the default STUN servers apply");
52
+ return { iceServers: defaults(), snapshot };
53
+ }
54
+ return { iceServers: parsed, snapshot };
55
+ }
56
+
15
57
  // src/types/connector.ts
16
58
  function resolveCapabilities(fresh, stored) {
17
59
  return fresh ?? stored;
@@ -58,7 +100,7 @@ function parseInfoCapabilities(body, warn) {
58
100
  warn?.("non-object info body: capabilities unknown");
59
101
  return void 0;
60
102
  }
61
- const { contracts, taxRounding, lineTax, registerApproval } = body;
103
+ const { contracts, taxRounding, lineTax, registerApproval, coupons, customerDisplay } = body;
62
104
  const register = maxVersion(contracts?.register);
63
105
  const orderRefund = maxVersion(contracts?.["order.refund"]);
64
106
  const rounding = parseTaxRounding(taxRounding);
@@ -68,13 +110,16 @@ function parseInfoCapabilities(body, warn) {
68
110
  }
69
111
  const parsedLineTax = parseLineTax(lineTax, warn);
70
112
  const parsed = parseRegisterApproval(registerApproval, warn);
113
+ const display = parseDisplayAdvertisement(customerDisplay, warn);
71
114
  return {
72
115
  orderCreate: maxVersion(contracts?.["order.create"]) ?? 1,
73
116
  ...orderRefund !== void 0 ? { orderRefund } : {},
74
117
  ...register !== void 0 ? { register } : {},
75
118
  ...rounding ? { taxRounding: rounding } : {},
76
119
  ...parsedLineTax ? { lineTax: parsedLineTax } : {},
77
- ...parsed ? { registerApproval: parsed } : {}
120
+ ...parsed ? { registerApproval: parsed } : {},
121
+ ...coupons === true ? { coupons: true } : {},
122
+ ...display ? { customerDisplay: display } : {}
78
123
  };
79
124
  }
80
125
 
@@ -110,10 +155,10 @@ var REMOTE_CREATE_PREFIX = "could not create instance ";
110
155
  function isRxdbRemoteVersionMismatch(error) {
111
156
  const { code, rxdb, message } = typeof error === "object" && error !== null ? error : {};
112
157
  if (code === "RM1" && (rxdb ?? true) === true) return true;
113
- const text = typeof error === "string" ? error : message;
114
- if (typeof text !== "string" || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
158
+ const text2 = typeof error === "string" ? error : message;
159
+ if (typeof text2 !== "string" || !text2.startsWith(REMOTE_CREATE_PREFIX)) return false;
115
160
  try {
116
- const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length));
161
+ const wrapped = JSON.parse(text2.slice(REMOTE_CREATE_PREFIX.length));
117
162
  return wrapped?.rxdb === true && wrapped.code === "RM1";
118
163
  } catch {
119
164
  return false;
@@ -205,6 +250,53 @@ function defaultPaymentMethods() {
205
250
  return [paymentMethodOf("cash"), paymentMethodOf("external")];
206
251
  }
207
252
 
253
+ // src/order-filters.ts
254
+ var ORDER_FILTER_FIELDS = [
255
+ "status",
256
+ "customerId",
257
+ "cashierId",
258
+ "registerId",
259
+ "paymentMethod",
260
+ "storeId",
261
+ "createdVia",
262
+ "dateRange"
263
+ ];
264
+ var UnsupportedOrderFilterError = class extends Error {
265
+ code = "unsupported_order_filter";
266
+ fields;
267
+ constructor(fields) {
268
+ super(`listOrders does not support: ${fields.join(", ")}`);
269
+ this.name = "UnsupportedOrderFilterError";
270
+ this.fields = fields;
271
+ }
272
+ };
273
+ function orderFilterFields(query) {
274
+ if (!query) return [];
275
+ return ORDER_FILTER_FIELDS.filter((field) => {
276
+ if (field === "dateRange") return query.dateRange?.after !== void 0 || query.dateRange?.before !== void 0;
277
+ return query[field] !== void 0;
278
+ });
279
+ }
280
+ function assertOrderFiltersSupported(query, supported) {
281
+ const set = orderFilterFields(query);
282
+ const missing = set.filter((field) => !supported?.includes(field));
283
+ if (missing.length > 0) throw new UnsupportedOrderFilterError(missing);
284
+ if (set.includes("dateRange")) assertOrderDateRange(query?.dateRange);
285
+ }
286
+ var UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/;
287
+ function instantMs(end, value) {
288
+ const ms = typeof value === "string" && UTC_INSTANT.test(value) ? Date.parse(value) : Number.NaN;
289
+ if (Number.isNaN(ms)) throw new TypeError(`dateRange.${end} must be an ISO 8601 UTC instant ending in Z: ${String(value)}`);
290
+ return ms;
291
+ }
292
+ function assertOrderDateRange(range) {
293
+ const after = range?.after === void 0 ? void 0 : instantMs("after", range.after);
294
+ const before = range?.before === void 0 ? void 0 : instantMs("before", range.before);
295
+ if (after !== void 0 && before !== void 0 && after > before) {
296
+ throw new TypeError(`dateRange.after (${range?.after}) is later than dateRange.before (${range?.before})`);
297
+ }
298
+ }
299
+
208
300
  // src/types/cashier.ts
209
301
  var CASHIER_PERMISSIONS = ["viewReports", "manageClosures", "approveVariance", "refund", "discount"];
210
302
  function isCashierPermission(value) {
@@ -252,8 +344,8 @@ function moneyFromMajor(value, currency) {
252
344
  const code = currency.toUpperCase();
253
345
  return { amount: Math.round(major * 10 ** minorUnitDigits(code)), currency: code };
254
346
  }
255
- function moneyFromDecimalString(text, currency) {
256
- const trimmed = text.trim();
347
+ function moneyFromDecimalString(text2, currency) {
348
+ const trimmed = text2.trim();
257
349
  if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
258
350
  const code = currency.toUpperCase();
259
351
  const digits = minorUnitDigits(code);
@@ -571,11 +663,14 @@ var woocommerce_exports = {};
571
663
  __export(woocommerce_exports, {
572
664
  NO_SHIPPING_TAX: () => NO_SHIPPING_TAX,
573
665
  STANDARD_TAX_CLASS: () => STANDARD_TAX_CLASS,
666
+ TAX_BASED_ON_META_KEY: () => TAX_BASED_ON_META_KEY,
574
667
  addNumberPrecision: () => addNumberPrecision,
575
668
  calculateTaxes: () => calculateTaxes,
576
669
  filterTaxRates: () => filterTaxRates,
577
670
  getRoundingPrecision: () => getRoundingPrecision,
671
+ normalizeTaxBasedOn: () => normalizeTaxBasedOn,
578
672
  normalizeTaxClass: () => normalizeTaxClass,
673
+ orderTaxLocation: () => orderTaxLocation,
579
674
  removeNumberPrecision: () => removeNumberPrecision,
580
675
  resolveInheritedShippingTaxClass: () => resolveInheritedShippingTaxClass,
581
676
  roundHalfDown: () => roundHalfDown,
@@ -917,6 +1012,37 @@ function taxClassToWire(value) {
917
1012
  return value === STANDARD_TAX_CLASS || value === null || value === void 0 ? "" : value;
918
1013
  }
919
1014
 
1015
+ // src/tax/woocommerce/tax-location.ts
1016
+ var TAX_BASED_ON_META_KEY = "_woocommerce_pos_tax_based_on";
1017
+ function isTaxBasedOn(value) {
1018
+ return value === "base" || value === "billing" || value === "shipping";
1019
+ }
1020
+ function normalizeTaxBasedOn(value) {
1021
+ return isTaxBasedOn(value) ? value : "base";
1022
+ }
1023
+ function hasCountry(address) {
1024
+ return typeof address?.country === "string" && address.country.length > 0;
1025
+ }
1026
+ function text(value) {
1027
+ return typeof value === "string" ? value : "";
1028
+ }
1029
+ function orderTaxLocation(base, storeTaxBasedOn, order) {
1030
+ const override = order?.taxBasedOnOverride;
1031
+ const taxBasedOn = isTaxBasedOn(override) ? override : normalizeTaxBasedOn(storeTaxBasedOn);
1032
+ let addressUsed = "base";
1033
+ if (order && taxBasedOn !== "base") {
1034
+ if (taxBasedOn !== "billing" && hasCountry(order.shipping)) addressUsed = "shipping";
1035
+ else if (hasCountry(order.billing)) addressUsed = "billing";
1036
+ }
1037
+ const address = addressUsed === "base" ? void 0 : order?.[addressUsed];
1038
+ if (!address) return { taxBasedOn, location: base, addressUsed };
1039
+ return {
1040
+ taxBasedOn,
1041
+ addressUsed,
1042
+ location: { country: text(address.country), state: text(address.state), city: text(address.city), postcode: text(address.postcode) }
1043
+ };
1044
+ }
1045
+
920
1046
  // src/coupons/woocommerce/index.ts
921
1047
  var woocommerce_exports2 = {};
922
1048
  __export(woocommerce_exports2, {
@@ -1828,13 +1954,20 @@ export {
1828
1954
  ConnectorProvider,
1829
1955
  ConnectorUnauthorizedError,
1830
1956
  CustomerServiceError,
1957
+ DEFAULT_ICE_SERVERS,
1958
+ DISPLAY_PAIR_CAPABILITY,
1959
+ DisplaySignallingError,
1831
1960
  MAX_COMMANDS_PER_BATCH,
1961
+ ORDER_FILTER_FIELDS,
1832
1962
  ORDER_NOTE_MAX,
1833
1963
  PROTOCOL_HEADER,
1834
1964
  PROTOCOL_VERSION,
1835
1965
  STOCK_LEVELS_LAST_PASS,
1836
1966
  SignInError,
1837
1967
  StoreSettingsError,
1968
+ UnsupportedOrderFilterError,
1969
+ assertOrderDateRange,
1970
+ assertOrderFiltersSupported,
1838
1971
  cashierPermissions,
1839
1972
  classifyFailure,
1840
1973
  combinePullAdapters,
@@ -1857,11 +1990,14 @@ export {
1857
1990
  moneyToMajor,
1858
1991
  neutralFailureClass,
1859
1992
  noResponse,
1993
+ orderFilterFields,
1860
1994
  parseCommandResult,
1995
+ parseDisplayAdvertisement,
1861
1996
  parseInfoCapabilities,
1862
1997
  parseLineTax,
1863
1998
  parseTaxRounding,
1864
1999
  paymentMethodOf,
2000
+ rateLimitSource,
1865
2001
  resolveCapabilities,
1866
2002
  resolvePrice,
1867
2003
  resolvePriceRange,
@@ -1,5 +1,7 @@
1
- import { e as CommandError, p as OrderCreatePayload, d as CommandEnvelope, J as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, K as RegisterCommandResult, D as OrderRefundRejectionCode } from '../command-result-CoCa8PXJ.js';
2
- export { g as CommandResultError, M as MAX_COMMANDS_PER_BATCH, O as ORDER_NOTE_MAX, m as OrderCreateDisplay, r as OrderCreateTaxRate, X as parseCommandResult } from '../command-result-CoCa8PXJ.js';
1
+ import { H as CommandError, an as OrderCreatePayload, G as CommandEnvelope, aR as RegisterCommandEnvelope, A as AnyCommandEnvelope, J as CommandResult, B as BatchTooLargeBody, F as CommandBatchResponse, C as CommandWarning, aS as RegisterCommandResult, ay as OrderRefundRejectionCode, a8 as DisplaySignalling, d as SyncContext, a9 as DisplaySignallingContext } from '../command-result-E_nH57WD.js';
2
+ export { K as CommandResultError, af as MAX_COMMANDS_PER_BATCH, ag as ORDER_NOTE_MAX, ak as OrderCreateDisplay, ap as OrderCreateTaxRate, bq as parseCommandResult } from '../command-result-E_nH57WD.js';
3
+ import 'rxdb';
4
+ import 'rxjs';
3
5
 
4
6
  /** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
5
7
  declare function currencyDecimals(currency: string): number;
@@ -26,7 +28,7 @@ declare function commandFingerprint(envelope: {
26
28
  declare function payloadShapeErrors(payload: unknown): string[];
27
29
  /** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
28
30
  * characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
29
- * `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
31
+ * `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v8 address fields 255, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
30
32
  * payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
31
33
  * its replay lookup, so a bound tightened later never turns an applied command's resend into
32
34
  * `invalid_payload`. */
@@ -45,7 +47,7 @@ declare function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[];
45
47
  * advertises it only once it handles it.
46
48
  * 5 (ADR-075) adds fees, shipping and custom lines; 6 (ADR-077) adds coupons, regular prices, line
47
49
  * attributes and Any picks (#495); a plugin advertises each only once it handles it.
48
- * 7 (ADR-083) adds the sale note.
50
+ * 7 (ADR-083) adds the sale note; 8 (#722) adds `taxAddress` and the customer's addresses.
49
51
  */
50
52
  declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
51
53
  /** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
@@ -217,4 +219,43 @@ declare function platformErrorResult(id: string, platformCode: string, platformM
217
219
  */
218
220
  declare function internalErrorResult(id: string, correlationId: string): CommandResult;
219
221
 
220
- export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };
222
+ /** What the contract suite drives; each plugin's U7 implements it for its own routes. */
223
+ interface DisplaySignallingHarness {
224
+ signalling: DisplaySignalling;
225
+ /** A cashier session on the server, with or without `customer_display.pair`. */
226
+ till(cashier: {
227
+ cashierId: string;
228
+ canPair: boolean;
229
+ }): SyncContext | Promise<SyncContext>;
230
+ /** A display-side context whose requests come from `source`, an IPv4 or IPv6 address. */
231
+ display(source: string): DisplaySignallingContext;
232
+ /** Moves the server's clock. */
233
+ advance(ms: number): Promise<void>;
234
+ /** Everything the server persists, serialised. */
235
+ storedText(): Promise<string>;
236
+ storedCounts(): Promise<{
237
+ codes: number;
238
+ pending: number;
239
+ displays: number;
240
+ snapshots: number;
241
+ }>;
242
+ }
243
+ /** The ADR-085 U2 reference server: every rule of the seam, in memory, with lazy pruning on every call. */
244
+ declare function createMemoryDisplaySignalling(options?: {
245
+ now?: () => number;
246
+ }): {
247
+ signalling: DisplaySignalling;
248
+ harness: DisplaySignallingHarness;
249
+ };
250
+
251
+ /**
252
+ * The security floor of ADR-085 d4–d6 and d8, and #705, as runner-agnostic cases: each builds a fresh harness and
253
+ * throws on failure. Each plugin's connector runs it against its own routes:
254
+ * `for (const c of displaySignallingContract(make)) it(c.name, c.run);`
255
+ */
256
+ declare function displaySignallingContract(makeHarness: () => Promise<DisplaySignallingHarness>): Array<{
257
+ name: string;
258
+ run: () => Promise<void>;
259
+ }>;
260
+
261
+ export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, type DisplaySignallingHarness, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, currencyDecimals, deriveSessionFigures, deriveVariance, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };