@tallyui/core 3.20.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/chunk-XF3RD6GX.js +515 -0
  2. package/dist/index.d.ts +41 -47
  3. package/dist/index.js +119 -101
  4. package/dist/server/index.cjs +1923 -0
  5. package/dist/server/index.d.cts +1039 -0
  6. package/dist/server/index.d.ts +46 -48
  7. package/dist/server/index.js +516 -206
  8. package/dist/{command-result-E_nH57WD.d.ts → tax-rate-DCJhfJbZ.d.ts} +442 -26
  9. package/package.json +10 -5
  10. package/src/commands.ts +12 -0
  11. package/src/context/money-format-context.tsx +50 -0
  12. package/src/coupons/woocommerce/to-coupon-configs.ts +5 -8
  13. package/src/fnv1a32.ts +14 -0
  14. package/src/index.ts +18 -5
  15. package/src/known-warnings.ts +23 -0
  16. package/src/money.ts +85 -2
  17. package/src/server/batch.ts +63 -27
  18. package/src/server/command-result.ts +28 -1
  19. package/src/server/display-signalling/contract.ts +203 -78
  20. package/src/server/display-signalling/memory-server.ts +71 -23
  21. package/src/server/fiscal-figures.ts +1 -1
  22. package/src/server/index.ts +5 -1
  23. package/src/server/money.ts +4 -1
  24. package/src/server/order-payload-shape.ts +96 -5
  25. package/src/server/refund-payload-shape.ts +5 -11
  26. package/src/server/register-payload-shape.ts +6 -12
  27. package/src/server/rejection-codes.ts +4 -4
  28. package/src/server/reopen-payload-shape.ts +25 -0
  29. package/src/server/shape-errors.ts +17 -0
  30. package/src/server/tax-rate.ts +13 -0
  31. package/src/server/update-payload-shape.ts +51 -0
  32. package/src/server/versions.ts +9 -2
  33. package/src/types/closures.ts +34 -0
  34. package/src/types/commands.ts +93 -8
  35. package/src/types/connector.ts +37 -4
  36. package/src/types/display-signalling.ts +30 -14
  37. package/src/types/index.ts +6 -3
  38. package/src/types/orders.ts +25 -3
  39. package/src/types/payment-methods.ts +17 -0
  40. package/src/types/stock.ts +2 -0
  41. package/src/types/store-settings.ts +7 -0
  42. package/src/types/traits/product.ts +19 -0
  43. package/dist/chunk-27L7XLTT.js +0 -235
@@ -0,0 +1,1923 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server/index.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ CommandResultError: () => CommandResultError,
24
+ MAX_COMMANDS_PER_BATCH: () => MAX_COMMANDS_PER_BATCH,
25
+ ORDER_NOTE_MAX: () => ORDER_NOTE_MAX,
26
+ SUPPORTED_ORDER_CREATE_VERSIONS: () => SUPPORTED_ORDER_CREATE_VERSIONS,
27
+ SUPPORTED_ORDER_REFUND_VERSIONS: () => SUPPORTED_ORDER_REFUND_VERSIONS,
28
+ SUPPORTED_ORDER_REOPEN_VERSIONS: () => SUPPORTED_ORDER_REOPEN_VERSIONS,
29
+ SUPPORTED_ORDER_UPDATE_VERSIONS: () => SUPPORTED_ORDER_UPDATE_VERSIONS,
30
+ SUPPORTED_REGISTER_VERSIONS: () => SUPPORTED_REGISTER_VERSIONS,
31
+ canonicalJson: () => canonicalJson,
32
+ commandFingerprint: () => commandFingerprint,
33
+ createMemoryDisplaySignalling: () => createMemoryDisplaySignalling,
34
+ currencyDecimals: () => currencyDecimals,
35
+ deriveSessionFigures: () => deriveSessionFigures,
36
+ deriveVariance: () => deriveVariance,
37
+ displaySignallingContract: () => displaySignallingContract,
38
+ fiscalFiguresErrors: () => fiscalFiguresErrors,
39
+ inProgressOutcome: () => inProgressOutcome,
40
+ internalErrorResult: () => internalErrorResult,
41
+ majorToMinor: () => majorToMinor,
42
+ minorToMajor: () => minorToMajor,
43
+ minorUnitDigits: () => minorUnitDigits,
44
+ parseCommandResult: () => parseCommandResult,
45
+ payloadBoundErrors: () => payloadBoundErrors,
46
+ payloadShapeErrors: () => payloadShapeErrors,
47
+ platformErrorResult: () => platformErrorResult,
48
+ precheckCommand: () => precheckCommand,
49
+ ratePpmFromPercent: () => ratePpmFromPercent,
50
+ refundPayloadErrors: () => refundPayloadErrors,
51
+ registerPayloadErrors: () => registerPayloadErrors,
52
+ reopenPayloadErrors: () => reopenPayloadErrors,
53
+ totalWarnings: () => totalWarnings,
54
+ transientOutcome: () => transientOutcome,
55
+ updatePayloadErrors: () => updatePayloadErrors,
56
+ validateBatch: () => validateBatch
57
+ });
58
+ module.exports = __toCommonJS(server_exports);
59
+
60
+ // src/server/money.ts
61
+ function currencyDecimals(currency) {
62
+ return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
63
+ }
64
+ function minorToMajor(minor, decimals) {
65
+ if (!Number.isSafeInteger(minor)) throw new RangeError("minor must be a safe integer");
66
+ const sign = minor < 0 ? "-" : "";
67
+ const digits = Math.abs(minor).toString().padStart(decimals + 1, "0");
68
+ return sign + (decimals === 0 ? digits : `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`);
69
+ }
70
+ function majorToMinor(value, decimals) {
71
+ const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(String(value));
72
+ if (!match) throw new RangeError("value must be a finite decimal");
73
+ const [, sign, mantissa, exponent = "0"] = match;
74
+ const [whole, fraction = ""] = mantissa.split(".");
75
+ const coefficient = BigInt(whole + fraction);
76
+ const shift = BigInt(decimals) + BigInt(exponent) - BigInt(fraction.length);
77
+ let rounded;
78
+ if (shift >= 0n) {
79
+ rounded = coefficient * 10n ** shift;
80
+ } else {
81
+ const divisor = 10n ** -shift;
82
+ rounded = coefficient / divisor + (coefficient % divisor * 2n >= divisor ? 1n : 0n);
83
+ }
84
+ const minor = Number(sign === "-" ? -rounded : rounded);
85
+ if (!Number.isSafeInteger(minor)) throw new RangeError("minor amount exceeds safe integer range");
86
+ return minor;
87
+ }
88
+
89
+ // src/money.ts
90
+ var digitsCache = /* @__PURE__ */ new Map();
91
+ function minorUnitDigits(currency) {
92
+ const code = currency.toUpperCase();
93
+ let digits = digitsCache.get(code);
94
+ if (digits === void 0) {
95
+ try {
96
+ digits = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
97
+ } catch {
98
+ digits = 2;
99
+ }
100
+ digitsCache.set(code, digits);
101
+ }
102
+ return digits;
103
+ }
104
+
105
+ // src/server/tax-rate.ts
106
+ function ratePpmFromPercent(percent) {
107
+ const value = String(percent);
108
+ const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(value);
109
+ if (!match || match[0] !== value) {
110
+ throw new RangeError("Percent must be a plain decimal with at most four fractional digits");
111
+ }
112
+ const ratePpm = BigInt(match[1]) * 10000n + BigInt((match[2] ?? "").padEnd(4, "0"));
113
+ if (ratePpm > BigInt(Number.MAX_SAFE_INTEGER)) {
114
+ throw new RangeError("Rate must be a safe integer");
115
+ }
116
+ return Number(ratePpm);
117
+ }
118
+
119
+ // src/server/fingerprint.ts
120
+ var import_node_crypto = require("node:crypto");
121
+ function canonicalJson(value) {
122
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item) ?? "null").join(",")}]`;
123
+ if (value !== null && typeof value === "object") {
124
+ const object = value;
125
+ return `{${Object.keys(object).sort().filter((key) => object[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`;
126
+ }
127
+ return JSON.stringify(value);
128
+ }
129
+ function commandFingerprint(envelope) {
130
+ const { type, version, payload } = envelope;
131
+ return (0, import_node_crypto.createHash)("sha256").update(canonicalJson({ type, version, payload })).digest("hex");
132
+ }
133
+
134
+ // src/commands.ts
135
+ var MAX_COMMANDS_PER_BATCH = 50;
136
+ var ORDER_NOTE_MAX = 1e3;
137
+ var ORDER_TAX_IDS_MAX = 10;
138
+ var ORDER_TAX_ID_TYPE_MAX = 32;
139
+ var ORDER_TAX_ID_VALUE_MAX = 64;
140
+ var ORDER_META_MAX = 50;
141
+ var ORDER_META_KEY_MAX = 255;
142
+ var ORDER_LINE_SKU_MAX = 100;
143
+
144
+ // src/server/order-payload-shape.ts
145
+ function payloadShapeErrors(payload) {
146
+ const errors = [];
147
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
148
+ const check2 = (valid, path, expected) => {
149
+ if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
150
+ };
151
+ const number = (value, path) => check2(typeof value === "number" && Number.isFinite(value), path, "a finite number");
152
+ const discount = (value, path) => {
153
+ const valid = value === void 0 || Number.isSafeInteger(value) && value > 0;
154
+ check2(valid, path, "a positive safe integer");
155
+ return valid && value !== void 0 ? BigInt(value) : 0n;
156
+ };
157
+ if (!object(payload)) return ["payload: expected an object"];
158
+ check2(typeof payload.clientOrderId === "string" && payload.clientOrderId.length > 0, "clientOrderId", "a non-empty string");
159
+ for (const field of ["createdAt", "currency"]) check2(typeof payload[field] === "string", field, "a string");
160
+ check2(typeof payload.pricesIncludeTax === "boolean", "pricesIncludeTax", "a boolean");
161
+ for (const field of ["lines", "payments"]) {
162
+ const items = payload[field];
163
+ const isLines = field === "lines";
164
+ check2(Array.isArray(items) && (!isLines || items.length > 0), field, isLines ? "a non-empty array" : "an array");
165
+ if (!Array.isArray(items)) continue;
166
+ for (const [index, item] of items.entries()) {
167
+ if (errors.length === 10) break;
168
+ const path = `${field}[${index}]`;
169
+ check2(object(item), path, "an object");
170
+ if (!object(item)) continue;
171
+ for (const key of isLines ? ["clientLineId", "variantId"] : ["clientPaymentId", "method"]) {
172
+ if (key === "variantId" && item.custom !== void 0 && item.variantId === void 0) continue;
173
+ check2(typeof item[key] === "string", `${path}.${key}`, "a string");
174
+ }
175
+ const optionalString = isLines ? "title" : "reference";
176
+ if (item[optionalString] !== void 0) {
177
+ check2(typeof item[optionalString] === "string", `${path}.${optionalString}`, "a string");
178
+ }
179
+ if (!isLines && item.methodId !== void 0) {
180
+ check2(typeof item.methodId === "string" && item.methodId.length > 0, `${path}.methodId`, "a non-empty string");
181
+ }
182
+ if (isLines && item.taxInclusive !== void 0) {
183
+ check2(typeof item.taxInclusive === "boolean", `${path}.taxInclusive`, "a boolean");
184
+ }
185
+ for (const key of isLines ? ["quantity", "unitPriceMinor"] : ["amountMinor"]) number(item[key], `${path}.${key}`);
186
+ if (!isLines) {
187
+ for (const key of ["tenderedMinor", "changeMinor"]) {
188
+ if (item[key] !== void 0) number(item[key], `${path}.${key}`);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ for (const field of ["subtotalMinor", "taxMinor", "totalMinor"]) number(payload[field], field);
194
+ const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
195
+ const orderDiscount = discount(payload.discountMinor, "discountMinor");
196
+ if (errors.length === 0) check2(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
197
+ if (payload.customer !== void 0 && payload.customer !== null) {
198
+ check2(object(payload.customer), "customer", "an object");
199
+ if (object(payload.customer) && payload.customer.email !== void 0) {
200
+ check2(typeof payload.customer.email === "string", "customer.email", "a string");
201
+ }
202
+ if (object(payload.customer) && payload.customer.customerId !== void 0) {
203
+ const id = payload.customer.customerId;
204
+ check2(typeof id === "string" && id.length > 0 && id.length <= 64, "customer.customerId", "a string of at most 64 characters");
205
+ }
206
+ for (const kind of ["billing", "shipping"]) {
207
+ const address = object(payload.customer) ? payload.customer[kind] : void 0;
208
+ if (address === void 0) continue;
209
+ check2(object(address), `customer.${kind}`, "an object");
210
+ if (object(address)) for (const [key, value] of Object.entries(address)) {
211
+ check2(ORDER_ADDRESS_KEYS.includes(key), `customer.${kind}.${key}`, "no unknown key");
212
+ check2(typeof value === "string", `customer.${kind}.${key}`, "a string");
213
+ }
214
+ }
215
+ }
216
+ if (payload.taxAddress !== void 0) {
217
+ const kind = payload.taxAddress;
218
+ const known = kind === "billing" || kind === "shipping";
219
+ check2(known, "taxAddress", "billing or shipping");
220
+ const address = known && object(payload.customer) ? payload.customer[kind] : void 0;
221
+ if (known) check2(object(address) && typeof address.country === "string" && address.country.length > 0, `customer.${kind}.country`, "a non-empty string");
222
+ }
223
+ if (payload.sessionId !== void 0) {
224
+ check2(
225
+ typeof payload.sessionId === "string" && payload.sessionId.length > 0 && payload.sessionId.length <= 36,
226
+ "sessionId",
227
+ "a string of at most 36 characters"
228
+ );
229
+ }
230
+ for (const field of ["registerId", "cashierRef", "locationId"]) {
231
+ if (payload[field] !== void 0) check2(typeof payload[field] === "string", field, "a string");
232
+ }
233
+ if (payload.note !== void 0) check2(typeof payload.note === "string" && payload.note.length > 0, "note", "a non-empty string");
234
+ for (const field of ["fees", "shipping", "lines"]) {
235
+ const items = payload[field];
236
+ if (items === void 0 || field === "lines" && !Array.isArray(items)) continue;
237
+ check2(Array.isArray(items), field, "an array");
238
+ if (!Array.isArray(items)) continue;
239
+ const id = field === "fees" ? "clientFeeId" : "clientShippingId";
240
+ const seen = /* @__PURE__ */ new Set();
241
+ items.forEach((entry, index) => {
242
+ const custom = field === "lines";
243
+ const item = custom && object(entry) ? entry.custom : entry;
244
+ const path = `${field}[${index}]${custom ? ".custom" : ""}`;
245
+ if (custom && (!object(entry) || item === void 0)) return;
246
+ check2(object(item), path, "an object");
247
+ if (!object(item)) return;
248
+ const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
249
+ for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
250
+ check2(typeof item.name === "string" && item.name.length > 0, `${path}.name`, "a non-empty string");
251
+ check2(item.taxStatus === "taxable" || item.taxStatus === "none", `${path}.taxStatus`, "taxable or none");
252
+ for (const key of keys.filter((key2) => ["sku", "taxClass", "methodId"].includes(key2))) {
253
+ if (item[key] !== void 0) check2(typeof item[key] === "string", `${path}.${key}`, "a string");
254
+ }
255
+ if (!custom) {
256
+ check2(typeof item[id] === "string" && item[id].length > 0, `${path}.${id}`, "a non-empty string");
257
+ check2(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`);
258
+ seen.add(item[id]);
259
+ for (const key of ["amountMinor", "taxMinor"]) check2(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
260
+ }
261
+ });
262
+ }
263
+ for (const prefix of ["", "display."]) {
264
+ const parent = prefix ? payload.display : payload;
265
+ const items = object(parent) ? parent.coupons : void 0;
266
+ if (items === void 0) continue;
267
+ check2(Array.isArray(items), `${prefix}coupons`, "an array");
268
+ if (!Array.isArray(items)) continue;
269
+ const keys = prefix ? ["code", "amountMinor"] : ["code", "couponId", "discountMinor", "discountTaxMinor", "lines"];
270
+ const hasLines = !prefix && items.some((item) => object(item) && item.lines !== void 0);
271
+ const seen = /* @__PURE__ */ new Set();
272
+ items.forEach((item, index) => {
273
+ const path = `${prefix}coupons[${index}]`;
274
+ check2(object(item), path, "an object");
275
+ if (!object(item)) return;
276
+ for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
277
+ for (const key of prefix ? ["code"] : ["code", "couponId"]) check2(typeof item[key] === "string" && item[key].length > 0, `${path}.${key}`, "a non-empty string");
278
+ for (const key of prefix ? ["amountMinor"] : ["discountMinor", "discountTaxMinor"]) check2(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
279
+ if (!prefix) {
280
+ check2(!seen.has(item.code), `${path}.code`, "no duplicate code");
281
+ seen.add(item.code);
282
+ if (hasLines) check2(Array.isArray(item.lines), `${path}.lines`, "an array");
283
+ if (Array.isArray(item.lines)) {
284
+ const ids = Array.isArray(payload.lines) ? payload.lines.map((line) => object(line) ? line.clientLineId : void 0) : [];
285
+ const seenIds = /* @__PURE__ */ new Set();
286
+ let previous = -1;
287
+ let validAmounts = true;
288
+ let discountSum = 0n;
289
+ let taxSum = 0n;
290
+ item.lines.forEach((line, index2) => {
291
+ const p = `${path}.lines[${index2}]`;
292
+ check2(object(line), p, "an object");
293
+ if (!object(line)) {
294
+ validAmounts = false;
295
+ previous = -1;
296
+ return;
297
+ }
298
+ for (const key of Object.keys(line)) check2(["clientLineId", "discountMinor", "discountTaxMinor"].includes(key), `${p}.${key}`, "no unknown key");
299
+ const at = typeof line.clientLineId === "string" ? ids.indexOf(line.clientLineId) : -1;
300
+ check2(at >= 0, `${p}.clientLineId`, "a payload lines[].clientLineId");
301
+ check2(!seenIds.has(line.clientLineId), `${p}.clientLineId`, "no duplicate clientLineId");
302
+ seenIds.add(line.clientLineId);
303
+ if (at >= 0 && previous >= 0) check2(at > previous, `${p}.clientLineId`, "payload lines order");
304
+ previous = at;
305
+ const valid = ["discountMinor", "discountTaxMinor"].map((key) => {
306
+ const valid2 = Number.isSafeInteger(line[key]) && line[key] >= 0;
307
+ check2(valid2, `${p}.${key}`, "a safe integer >= 0");
308
+ return valid2;
309
+ }).every(Boolean);
310
+ if (!valid) {
311
+ validAmounts = false;
312
+ return;
313
+ }
314
+ check2(line.discountMinor !== 0 || line.discountTaxMinor !== 0, p, "a non-zero discountMinor or discountTaxMinor");
315
+ discountSum += BigInt(line.discountMinor);
316
+ taxSum += BigInt(line.discountTaxMinor);
317
+ });
318
+ if (validAmounts && ["discountMinor", "discountTaxMinor"].every((key) => Number.isSafeInteger(item[key]) && item[key] >= 0)) {
319
+ check2(discountSum === BigInt(item.discountMinor), `${path}.lines`, `discountMinor summing to ${path}.discountMinor`);
320
+ check2(taxSum === BigInt(item.discountTaxMinor), `${path}.lines`, `discountTaxMinor summing to ${path}.discountTaxMinor`);
321
+ }
322
+ }
323
+ }
324
+ });
325
+ }
326
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
327
+ if (!object(line)) return;
328
+ const path = `lines[${index}]`;
329
+ if (line.regularUnitPriceMinor !== void 0) check2(Number.isSafeInteger(line.regularUnitPriceMinor) && line.regularUnitPriceMinor >= 0, `${path}.regularUnitPriceMinor`, "a safe integer >= 0");
330
+ if (line.attributes !== void 0) {
331
+ check2(object(line.attributes), `${path}.attributes`, "an object");
332
+ if (object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) check2(typeof value === "string", `${path}.attributes.${key}`, "a string");
333
+ }
334
+ const { anyAttributes: names, attributes } = line;
335
+ if (names !== void 0) check2(Array.isArray(names), `${path}.anyAttributes`, "an array");
336
+ if (Array.isArray(names)) names.forEach((name, index2) => {
337
+ const at = `${path}.anyAttributes[${index2}]`;
338
+ check2(typeof name === "string" && name.length > 0, at, "a non-empty string");
339
+ if (typeof name !== "string" || !name) return;
340
+ check2(names.indexOf(name) === index2, at, "no duplicate name");
341
+ check2(
342
+ object(attributes) && Object.hasOwn(attributes, name) && typeof attributes[name] === "string" && attributes[name].length > 0,
343
+ at,
344
+ `a key of ${path}.attributes with a non-empty value`
345
+ );
346
+ });
347
+ if (line.sku !== void 0) {
348
+ check2(typeof line.sku === "string" && line.sku.length > 0, `${path}.sku`, "a non-empty string");
349
+ check2(line.custom === void 0, `${path}.sku`, "absent on a custom line (custom.sku)");
350
+ }
351
+ });
352
+ const lists = [
353
+ ["customer.taxIds", object(payload.customer) ? payload.customer.taxIds : void 0, ["type", "value", "country"]],
354
+ ["meta", payload.meta, ["key", "value"]]
355
+ ];
356
+ for (const [field, items, keys] of lists) {
357
+ if (items === void 0) continue;
358
+ check2(Array.isArray(items), field, "an array");
359
+ if (!Array.isArray(items)) continue;
360
+ const seen = /* @__PURE__ */ new Set();
361
+ items.forEach((item, index) => {
362
+ const path = `${field}[${index}]`;
363
+ check2(object(item), path, "an object");
364
+ if (!object(item)) return;
365
+ for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
366
+ if (field === "meta") {
367
+ const key = item.key;
368
+ check2(typeof key === "string" && key.length > 0, `${path}.key`, "a non-empty string");
369
+ if (typeof key === "string" && key.length > 0) check2(!key.startsWith("_"), `${path}.key`, "a key not starting with _");
370
+ check2(typeof item.value === "string", `${path}.value`, "a string");
371
+ if (typeof key === "string") check2(!seen.has(key), `${path}.key`, "no duplicate key");
372
+ seen.add(key);
373
+ return;
374
+ }
375
+ for (const key of ["type", "value"]) check2(typeof item[key] === "string" && item[key].length > 0, `${path}.${key}`, "a non-empty string");
376
+ if (item.country !== void 0) check2(typeof item.country === "string" && /^[A-Z]{2}$/.test(item.country), `${path}.country`, "an ISO 3166-1 alpha-2 code");
377
+ });
378
+ }
379
+ for (const [value, path] of payloadStrings(payload)) check2(!value.includes("\0"), path, "no NUL character");
380
+ return errors;
381
+ }
382
+ var ORDER_ADDRESS_KEYS = ["firstName", "lastName", "company", "address1", "address2", "city", "state", "postcode", "country", "phone"];
383
+ function payloadBoundErrors(payload) {
384
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
385
+ const record = payload;
386
+ const errors = payloadStrings(record).filter(([value, , max2]) => max2 !== void 0 && value.length > max2).map(([, path, max2]) => `${path}: expected at most ${max2} characters`).slice(0, 10);
387
+ const max = Array.isArray(record.lines) ? record.lines.length : 0;
388
+ if (Array.isArray(record.coupons)) record.coupons.forEach((coupon, index) => {
389
+ if (errors.length < 10 && typeof coupon === "object" && coupon !== null && !Array.isArray(coupon) && Array.isArray(coupon.lines) && coupon.lines.length > max) errors.push(`coupons[${index}].lines: expected at most ${max} entries`);
390
+ });
391
+ const customer = typeof record.customer === "object" && record.customer !== null ? record.customer : {};
392
+ for (const [path, items, most] of [["customer.taxIds", customer.taxIds, ORDER_TAX_IDS_MAX], ["meta", record.meta, ORDER_META_MAX]]) {
393
+ if (errors.length < 10 && Array.isArray(items) && items.length > most) errors.push(`${path}: expected at most ${most} entries`);
394
+ }
395
+ return errors;
396
+ }
397
+ function payloadStrings(payload) {
398
+ const found = [];
399
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
400
+ for (const field of ["clientOrderId", "createdAt", "currency", "registerId", "cashierRef", "locationId"]) found.push([payload[field], field, 255]);
401
+ found.push([payload.note, "note", ORDER_NOTE_MAX]);
402
+ for (const field of ["lines", "payments"]) {
403
+ const items = payload[field];
404
+ if (Array.isArray(items)) items.forEach((item, index) => {
405
+ if (object(item)) for (const key of field === "lines" ? ["clientLineId", "variantId", "title"] : ["clientPaymentId", "method", "reference"]) {
406
+ found.push([item[key], `${field}[${index}].${key}`, 255]);
407
+ }
408
+ if (object(item) && field === "payments") found.push([item.methodId, `payments[${index}].methodId`, 64]);
409
+ });
410
+ }
411
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
412
+ if (object(line) && object(line.custom)) for (const key of ["name", "sku", "taxClass", "taxStatus"]) {
413
+ found.push([line.custom[key], `lines[${index}].custom.${key}`, key === "name" ? 255 : 64]);
414
+ }
415
+ });
416
+ for (const field of ["fees", "shipping"]) for (const prefix of ["", "display."]) {
417
+ const parent = prefix ? payload.display : payload;
418
+ const items = object(parent) ? parent[field] : void 0;
419
+ if (Array.isArray(items)) items.forEach((item, index) => {
420
+ if (object(item)) for (const key of prefix ? [field === "fees" ? "clientFeeId" : "clientShippingId"] : [field === "fees" ? "clientFeeId" : "clientShippingId", "name", "taxClass", "taxStatus", ...field === "shipping" ? ["methodId"] : []]) {
421
+ found.push([item[key], `${prefix}${field}[${index}].${key}`, key.startsWith("client") ? 36 : key === "name" ? 255 : 64]);
422
+ }
423
+ });
424
+ }
425
+ for (const prefix of ["", "display."]) {
426
+ const parent = prefix ? payload.display : payload;
427
+ const items = object(parent) ? parent.coupons : void 0;
428
+ if (Array.isArray(items)) items.forEach((item, index) => {
429
+ if (object(item)) for (const key of prefix ? ["code"] : ["code", "couponId"]) found.push([item[key], `${prefix}coupons[${index}].${key}`, key === "code" ? 255 : 64]);
430
+ if (!prefix && object(item) && Array.isArray(item.lines)) item.lines.forEach((line, j) => {
431
+ if (object(line)) found.push([line.clientLineId, `coupons[${index}].lines[${j}].clientLineId`, 255]);
432
+ });
433
+ });
434
+ }
435
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
436
+ if (object(line) && object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) {
437
+ found.push([key, `lines[${index}].attributes`, 255], [value, `lines[${index}].attributes.${key}`, 255]);
438
+ }
439
+ if (object(line) && Array.isArray(line.anyAttributes)) line.anyAttributes.forEach((name, i) => found.push([name, `lines[${index}].anyAttributes[${i}]`, 255]));
440
+ if (object(line)) found.push([line.sku, `lines[${index}].sku`, ORDER_LINE_SKU_MAX]);
441
+ });
442
+ if (object(payload.customer) && Array.isArray(payload.customer.taxIds)) payload.customer.taxIds.forEach((taxId, index) => {
443
+ if (object(taxId)) for (const [key, max] of [["type", ORDER_TAX_ID_TYPE_MAX], ["value", ORDER_TAX_ID_VALUE_MAX], ["country", 2]]) found.push([taxId[key], `customer.taxIds[${index}].${key}`, max]);
444
+ });
445
+ if (Array.isArray(payload.meta)) payload.meta.forEach((entry, index) => {
446
+ if (object(entry)) found.push([entry.key, `meta[${index}].key`, ORDER_META_KEY_MAX], [entry.value, `meta[${index}].value`, ORDER_NOTE_MAX]);
447
+ });
448
+ if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
449
+ if (object(payload.customer)) for (const kind of ["billing", "shipping"]) {
450
+ const address = payload.customer[kind];
451
+ if (object(address)) for (const [key, value] of Object.entries(address)) found.push([value, `customer.${kind}.${key}`, 255]);
452
+ }
453
+ found.push([payload.sessionId, "sessionId", void 0]);
454
+ return found.filter((entry) => typeof entry[0] === "string");
455
+ }
456
+
457
+ // src/server/fiscal-figures.ts
458
+ function fiscalFiguresErrors(payload) {
459
+ const errors = [];
460
+ const check2 = (valid, path, expected) => {
461
+ if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
462
+ };
463
+ const object = (value, path, keys) => {
464
+ const valid = typeof value === "object" && value !== null && !Array.isArray(value);
465
+ check2(valid, path, "an object");
466
+ if (valid) for (const key of Object.keys(value)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
467
+ return valid;
468
+ };
469
+ const money = (value, path, keys) => {
470
+ for (const key of keys) check2(Number.isSafeInteger(value[key]), `${path}.${key}`, "a safe integer");
471
+ };
472
+ const { display, taxByRate } = payload;
473
+ if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines", "fees", "shipping", "coupons"])) {
474
+ check2(typeof display.currency === "string", "display.currency", "a string");
475
+ check2(Number.isInteger(display.exponent) && display.exponent >= 0, "display.exponent", "an integer >= 0");
476
+ check2(typeof display.taxInclusive === "boolean", "display.taxInclusive", "a boolean");
477
+ money(display, "display", ["subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor"]);
478
+ check2(Array.isArray(display.lines), "display.lines", "an array");
479
+ if (Array.isArray(display.lines)) display.lines.forEach((line, index) => {
480
+ const path = `display.lines[${index}]`;
481
+ if (!object(line, path, ["clientLineId", "amountMinor", "discounts"])) return;
482
+ check2(typeof line.clientLineId === "string", `${path}.clientLineId`, "a string");
483
+ money(line, path, ["amountMinor"]);
484
+ check2(Array.isArray(line.discounts), `${path}.discounts`, "an array");
485
+ if (Array.isArray(line.discounts)) line.discounts.forEach((discount, index2) => {
486
+ const discountPath = `${path}.discounts[${index2}]`;
487
+ if (!object(discount, discountPath, ["discountId", "label", "amountMinor"])) return;
488
+ check2(typeof discount.discountId === "string", `${discountPath}.discountId`, "a string");
489
+ if (discount.label !== void 0) check2(typeof discount.label === "string", `${discountPath}.label`, "a string");
490
+ money(discount, discountPath, ["amountMinor"]);
491
+ });
492
+ });
493
+ if (payload.fees?.length || payload.shipping?.length) check2(display.taxInclusive === payload.pricesIncludeTax, "display.taxInclusive", "payload.pricesIncludeTax");
494
+ for (const field of ["fees", "shipping"]) {
495
+ const id = field === "fees" ? "clientFeeId" : "clientShippingId";
496
+ const amounts = new Map((payload[field] ?? []).map((entry) => [
497
+ "clientFeeId" in entry ? entry.clientFeeId : entry.clientShippingId,
498
+ entry.amountMinor
499
+ ]));
500
+ const rows = display[field];
501
+ if (rows !== void 0) check2(Array.isArray(rows), `display.${field}`, "an array");
502
+ const seen3 = /* @__PURE__ */ new Set();
503
+ if (Array.isArray(rows)) rows.forEach((row, index) => {
504
+ const path = `display.${field}[${index}]`;
505
+ if (!object(row, path, [id, "amountMinor"])) return;
506
+ check2(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
507
+ money(row, path, ["amountMinor"]);
508
+ check2(amounts.has(row[id]), `${path}.${id}`, `a payload.${field}[].${id}`);
509
+ check2(!seen3.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
510
+ seen3.add(row[id]);
511
+ if (amounts.has(row[id])) check2(row.amountMinor === amounts.get(row[id]), `${path}.amountMinor`, `the payload.${field} amountMinor`);
512
+ });
513
+ for (const key of amounts.keys()) check2(seen3.has(key), `display.${field}`, `a row for ${id} ${key}`);
514
+ }
515
+ const codes = new Set((payload.coupons ?? []).map((coupon) => coupon.code));
516
+ const seen2 = /* @__PURE__ */ new Set();
517
+ if (Array.isArray(display.coupons)) display.coupons.forEach((row, index) => {
518
+ const path = `display.coupons[${index}]`;
519
+ check2(codes.has(row.code), `${path}.code`, "a payload.coupons[].code");
520
+ check2(!seen2.has(row.code), `${path}.code`, "no duplicate code");
521
+ seen2.add(row.code);
522
+ });
523
+ }
524
+ check2(Array.isArray(taxByRate), "taxByRate", "an array");
525
+ if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
526
+ const path = `taxByRate[${index}]`;
527
+ if (!object(rate, path, ["ratePpm", "code", "netMinor", "taxMinor", "grossMinor"])) return;
528
+ check2(Number.isInteger(rate.ratePpm), `${path}.ratePpm`, "an integer");
529
+ if (rate.code !== void 0) check2(typeof rate.code === "string", `${path}.code`, "a string");
530
+ money(rate, path, ["netMinor", "taxMinor", "grossMinor"]);
531
+ });
532
+ if (errors.length || !display || !Array.isArray(taxByRate)) return errors;
533
+ check2(display.currency === payload.currency, "display.currency", "payload.currency");
534
+ check2(display.totalMinor === payload.totalMinor, "display.totalMinor", "payload.totalMinor");
535
+ check2(display.taxMinor === payload.taxMinor, "display.taxMinor", "payload.taxMinor");
536
+ check2(taxByRate.length > 0 || payload.taxMinor === 0, "taxByRate", "a non-empty array when payload.taxMinor is nonzero");
537
+ check2(Number.isSafeInteger(payload.taxMinor) && taxByRate.reduce((sum, rate) => sum + BigInt(rate.taxMinor), 0n) === BigInt(payload.taxMinor), "taxByRate", "the sum of taxMinor to equal payload.taxMinor");
538
+ taxByRate.forEach((rate, index) => check2(BigInt(rate.grossMinor) === BigInt(rate.netMinor) + BigInt(rate.taxMinor), `taxByRate[${index}].grossMinor`, "netMinor + taxMinor"));
539
+ const ids = new Set(Array.isArray(payload.lines) ? payload.lines.map((line) => line?.clientLineId) : []);
540
+ const seen = /* @__PURE__ */ new Set();
541
+ display.lines.forEach((line, index) => {
542
+ check2(ids.has(line.clientLineId), `display.lines[${index}].clientLineId`, "a payload.lines[].clientLineId");
543
+ check2(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
544
+ seen.add(line.clientLineId);
545
+ });
546
+ try {
547
+ check2(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
548
+ } catch {
549
+ }
550
+ const text = (value, path) => {
551
+ if (typeof value !== "string") return;
552
+ check2(value.length <= 255, path, "at most 255 characters");
553
+ check2(!value.includes("\0"), path, "no NUL character");
554
+ };
555
+ display.lines.forEach((line, index) => line.discounts.forEach((discount, i) => {
556
+ for (const key of ["discountId", "label"]) text(discount[key], `display.lines[${index}].discounts[${i}].${key}`);
557
+ }));
558
+ taxByRate.forEach((rate, index) => text(rate.code, `taxByRate[${index}].code`));
559
+ return errors;
560
+ }
561
+
562
+ // src/server/versions.ts
563
+ var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
564
+ var SUPPORTED_REGISTER_VERSIONS = [1];
565
+ var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
566
+ var SUPPORTED_ORDER_REOPEN_VERSIONS = [1];
567
+ var SUPPORTED_ORDER_UPDATE_VERSIONS = [1];
568
+
569
+ // src/server/shape-errors.ts
570
+ function isPlainObject(value) {
571
+ return typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
572
+ }
573
+ function shapeErrors() {
574
+ const errors = [];
575
+ const check2 = (valid, field, expected) => {
576
+ if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
577
+ };
578
+ const noNul = (value, field) => {
579
+ if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
580
+ };
581
+ return { errors, check: check2, noNul };
582
+ }
583
+
584
+ // src/server/update-payload-shape.ts
585
+ function updateOnlyErrors(payload) {
586
+ const { errors, check: check2 } = shapeErrors();
587
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
588
+ const body = payload;
589
+ const id = (value, field) => {
590
+ const max = field === "baseRevision" ? 128 : 64;
591
+ check2(typeof value === "string" && value.length > 0 && value.length <= max, field, `a non-empty string of at most ${max} characters`);
592
+ if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
593
+ };
594
+ id(body.orderId, "orderId");
595
+ if (body.baseRevision !== void 0) id(body.baseRevision, "baseRevision");
596
+ check2(Number.isSafeInteger(body.createVersion) && body.createVersion >= 1, "createVersion", "a positive safe integer");
597
+ const seenIds = { storeLineId: /* @__PURE__ */ new Set(), paymentId: /* @__PURE__ */ new Set() };
598
+ for (const [field, key] of [["lines", "storeLineId"], ["fees", "storeLineId"], ["shipping", "storeLineId"], ["payments", "paymentId"]]) {
599
+ const items = body[field], seen = seenIds[key];
600
+ if (!Array.isArray(items)) continue;
601
+ for (const [index, item] of items.entries()) {
602
+ if (typeof item !== "object" || item === null || Array.isArray(item) || item[key] === void 0) continue;
603
+ id(item[key], `${field}[${index}].${key}`);
604
+ check2(!seen.has(item[key]), `${field}[${index}].${key}`, "unique");
605
+ seen.add(item[key]);
606
+ }
607
+ }
608
+ return errors;
609
+ }
610
+ function updatePayloadErrors(payload) {
611
+ const errors = updateOnlyErrors(payload);
612
+ if (errors[0] === "payload: expected an object") return errors;
613
+ return [...errors, ...payloadShapeErrors(orderCreatePart(payload))].slice(0, 10);
614
+ }
615
+ function orderCreatePart(payload) {
616
+ const part = { ...payload };
617
+ for (const key of ["orderId", "baseRevision", "createVersion"]) delete part[key];
618
+ for (const [field, key] of [["lines", "storeLineId"], ["fees", "storeLineId"], ["shipping", "storeLineId"], ["payments", "paymentId"]]) {
619
+ const items = part[field];
620
+ if (Array.isArray(items)) part[field] = items.map((item) => {
621
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return item;
622
+ const copy = { ...item };
623
+ delete copy[key];
624
+ return copy;
625
+ });
626
+ }
627
+ return part;
628
+ }
629
+
630
+ // src/server/batch.ts
631
+ function validateBatch(body) {
632
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
633
+ return { ok: false, status: 400, message: "Expected body object with commands array" };
634
+ }
635
+ const { commands } = body;
636
+ if (!Array.isArray(commands)) return { ok: false, status: 400, message: "Expected commands array" };
637
+ if (commands.length > MAX_COMMANDS_PER_BATCH) {
638
+ const message = `At most ${MAX_COMMANDS_PER_BATCH} commands are allowed`;
639
+ return { ok: false, status: 413, message, body: { code: "batch_too_large", maxCommands: MAX_COMMANDS_PER_BATCH, message } };
640
+ }
641
+ if (commands.length === 0) return { ok: false, status: 400, message: "commands must not be empty" };
642
+ for (const [index, command] of commands.entries()) {
643
+ if (typeof command !== "object" || command === null || Array.isArray(command)) {
644
+ return { ok: false, status: 400, message: `Invalid commands[${index}]: expected object` };
645
+ }
646
+ let field;
647
+ if (typeof command.id !== "string" || command.id.length === 0 || command.id.length > 64) field = "id";
648
+ else if (![
649
+ "order.create",
650
+ "order.refund",
651
+ "order.reopen",
652
+ "order.update",
653
+ "register.session.open",
654
+ "register.session.transition",
655
+ "register.movement.record",
656
+ "register.movement.void",
657
+ "register.closure.submit"
658
+ ].includes(command.type)) field = "type";
659
+ else if (!Number.isSafeInteger(command.version) || command.version < 1) field = "version";
660
+ else if (typeof command.payload !== "object" || command.payload === null || Array.isArray(command.payload)) field = "payload";
661
+ else if (typeof command.createdAt !== "string") field = "createdAt";
662
+ else if (typeof command.deviceId !== "string") field = "deviceId";
663
+ else if (!Number.isSafeInteger(command.attempt) || command.attempt < 1) field = "attempt";
664
+ if (field) return { ok: false, status: 400, message: `Invalid commands[${index}].${field}` };
665
+ }
666
+ return { ok: true, commands };
667
+ }
668
+ var rejected = (id, code, message, data) => ({ id, status: "rejected", error: data === void 0 ? { code, message } : { code, message, data } });
669
+ var firstTen = (errors) => errors.slice(0, 10).join("; ");
670
+ function unsupportedOptional(envelope, key, versions, noun) {
671
+ if (versions.includes(envelope.version)) return void 0;
672
+ return rejected(
673
+ envelope.id,
674
+ "unsupported_version",
675
+ `${envelope.type} version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(", ")}` : `takes no ${noun}`}`,
676
+ { [key]: versions.length ? Math.max(...versions) : 0 }
677
+ );
678
+ }
679
+ function precheckCommand(envelope, supported) {
680
+ for (const key of ["orderCreate", "register"]) {
681
+ if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`);
682
+ }
683
+ if (envelope.type === "order.refund") return unsupportedOptional(envelope, "orderRefund", supported.orderRefund ?? [], "refunds");
684
+ if (envelope.type === "order.reopen") return unsupportedOptional(envelope, "orderReopen", supported.orderReopen ?? [], "reopens");
685
+ if (envelope.type === "order.update") {
686
+ const refusal = unsupportedOptional(envelope, "orderUpdate", supported.orderUpdate ?? [], "updates");
687
+ if (refusal) return refusal;
688
+ const payload2 = envelope.payload;
689
+ const createPayload = orderCreatePart(payload2);
690
+ const shape2 = payloadShapeErrors(createPayload);
691
+ const errors2 = updatePayloadErrors(payload2).filter((error) => !shape2.includes(error));
692
+ if (errors2.length) return rejected(envelope.id, "invalid_payload", firstTen(errors2));
693
+ return precheckCommand({ id: envelope.id, type: "order.create", version: payload2.createVersion, payload: createPayload }, supported);
694
+ }
695
+ if (envelope.type !== "order.create") {
696
+ if (!supported.register.includes(envelope.version)) {
697
+ return rejected(
698
+ envelope.id,
699
+ "unsupported_version",
700
+ `register version ${envelope.version} is not supported; this server supports ${supported.register.join(", ")}`,
701
+ { register: Math.max(...supported.register) }
702
+ );
703
+ }
704
+ return void 0;
705
+ }
706
+ const command = envelope;
707
+ if (!supported.orderCreate.includes(command.version)) {
708
+ return rejected(
709
+ command.id,
710
+ "unsupported_version",
711
+ `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(", ")}`,
712
+ { orderCreate: Math.max(...supported.orderCreate) }
713
+ );
714
+ }
715
+ const { lines, discountMinor } = command.payload;
716
+ const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
717
+ const payload = command.payload;
718
+ const { display, taxByRate, sessionId } = payload;
719
+ const v3 = command.version >= 3;
720
+ const v5Fields = ["fees", "shipping"].filter((field) => payload[field] !== void 0);
721
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
722
+ if (line?.custom !== void 0) v5Fields.push(`lines[${index}].custom`);
723
+ });
724
+ for (const field of ["fees", "shipping"]) if (display?.[field] !== void 0) v5Fields.push(`display.${field}`);
725
+ const v6Fields = payload.coupons !== void 0 ? ["coupons"] : [];
726
+ if (display?.coupons !== void 0) v6Fields.push("display.coupons");
727
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
728
+ for (const field of ["regularUnitPriceMinor", "attributes", "anyAttributes"]) {
729
+ if (line?.[field] !== void 0) v6Fields.push(`lines[${index}].${field}`);
730
+ }
731
+ });
732
+ const coupons = Array.isArray(payload.coupons) ? payload.coupons.filter((coupon) => typeof coupon === "object" && coupon !== null && !Array.isArray(coupon)) : [];
733
+ const couponLines = coupons.filter((coupon) => coupon.lines !== void 0);
734
+ const couponsWithoutLines = coupons.filter((coupon) => coupon.lines === void 0);
735
+ const paymentsWithMethodId = Array.isArray(payload.payments) && payload.payments.some((payment) => typeof payment === "object" && payment !== null && payment.methodId !== void 0);
736
+ const v12Fields = payload.customer?.taxIds !== void 0 ? ["customer.taxIds"] : [];
737
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
738
+ if (line?.sku !== void 0) v12Fields.push(`lines[${index}].sku`);
739
+ });
740
+ if (payload.meta !== void 0) v12Fields.push("meta");
741
+ let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version < 6 && v6Fields.length ? v6Fields.map((field) => `${field} requires version 6`).join("; ") : command.version < 7 && payload.note !== void 0 ? "note requires version 7" : command.version < 8 && payload.taxAddress !== void 0 ? "taxAddress requires version 8" : command.version < 8 && (payload.customer?.billing !== void 0 || payload.customer?.shipping !== void 0) ? "customer address requires version 8" : command.version < 9 && couponLines.length ? "coupons[].lines requires version 9" : command.version < 10 && paymentsWithMethodId ? "payments[].methodId requires version 10" : command.version < 12 && v12Fields.length ? v12Fields.map((field) => `${field} requires version 12`).join("; ") : command.version >= 9 && couponsWithoutLines.length ? "version 9 requires coupons[].lines" : command.version === 8 && payload.taxAddress === void 0 ? "version 8 requires taxAddress" : command.version >= 9 && command.version < 11 && payload.taxAddress === void 0 && (payload.customer?.billing !== void 0 || payload.customer?.shipping !== void 0) ? "version 9 customer address requires taxAddress" : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
742
+ if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
743
+ if (line?.custom === void 0 && (typeof line?.variantId !== "string" || !line.variantId.length)) {
744
+ versionError = `lines[${index}].variantId is required`;
745
+ } else if (command.version >= 5 && line?.custom !== void 0 && line.variantId !== void 0) {
746
+ versionError = `lines[${index}] has custom and variantId; a custom line has no variantId`;
747
+ }
748
+ if (versionError) break;
749
+ }
750
+ if (versionError) {
751
+ return rejected(command.id, "invalid_payload", versionError);
752
+ }
753
+ const bounds = payloadBoundErrors(payload);
754
+ if (bounds.length) {
755
+ return rejected(command.id, "invalid_payload", firstTen(bounds));
756
+ }
757
+ const shape = payloadShapeErrors(payload);
758
+ const errors = command.version >= 5 && shape.length ? shape : v3 && display !== void 0 && taxByRate !== void 0 && shape.length === 0 ? fiscalFiguresErrors(payload) : [];
759
+ if (errors.length) {
760
+ return rejected(command.id, "invalid_payload", firstTen(errors));
761
+ }
762
+ return void 0;
763
+ }
764
+
765
+ // src/server/batch-outcome.ts
766
+ function inProgressOutcome(id) {
767
+ return { status: 409, body: { code: "in_progress", id } };
768
+ }
769
+ function transientOutcome(id) {
770
+ return { status: 503, body: { code: "transient", id, message: "Temporary failure, retry later." } };
771
+ }
772
+
773
+ // src/server/total-warnings.ts
774
+ function totalWarnings(expectedMinor, serverMinor) {
775
+ return serverMinor === expectedMinor ? [] : [{ code: "total_mismatch", expectedMinor, serverMinor }];
776
+ }
777
+
778
+ // src/server/command-result.ts
779
+ var CommandResultError = class extends Error {
780
+ constructor(message) {
781
+ super(message);
782
+ this.name = "CommandResultError";
783
+ }
784
+ };
785
+ function parseCommandResult(value) {
786
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
787
+ throw new CommandResultError("Invalid result: expected object");
788
+ }
789
+ const input = value;
790
+ if (typeof input.id !== "string" || input.id.length === 0) {
791
+ throw new CommandResultError("Invalid id");
792
+ }
793
+ if (input.status !== "applied" && input.status !== "duplicate" && input.status !== "rejected") {
794
+ throw new CommandResultError("Invalid status");
795
+ }
796
+ const result = { id: input.id, status: input.status };
797
+ const object = (value2) => typeof value2 === "object" && value2 !== null && (Object.getPrototypeOf(value2) === Object.prototype || Object.getPrototypeOf(value2) === null);
798
+ if (input.serverRefs !== void 0) {
799
+ if (typeof input.serverRefs !== "object" || input.serverRefs === null || Array.isArray(input.serverRefs)) {
800
+ throw new CommandResultError("Invalid serverRefs");
801
+ }
802
+ const refs = input.serverRefs;
803
+ if (typeof refs.orderId !== "string" || refs.orderId.length === 0) {
804
+ throw new CommandResultError("Invalid serverRefs.orderId");
805
+ }
806
+ if (refs.displayId !== void 0 && typeof refs.displayId !== "string") {
807
+ throw new CommandResultError("Invalid serverRefs.displayId");
808
+ }
809
+ if (!Number.isSafeInteger(refs.totalMinor)) {
810
+ throw new CommandResultError("Invalid serverRefs.totalMinor");
811
+ }
812
+ result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor };
813
+ if (refs.displayId !== void 0) result.serverRefs.displayId = refs.displayId;
814
+ }
815
+ if (input.register !== void 0) {
816
+ if (!object(input.register)) throw new CommandResultError("Invalid register");
817
+ result.register = input.register;
818
+ }
819
+ if (input.refund !== void 0) {
820
+ if (!object(input.refund)) throw new CommandResultError("Invalid refund");
821
+ const refund = input.refund;
822
+ if (!Number.isSafeInteger(refund.totalMinor) || refund.totalMinor < 0) throw new CommandResultError("Invalid refund.totalMinor");
823
+ if (!object(refund.byMethod)) throw new CommandResultError("Invalid refund.byMethod");
824
+ const byMethod = Object.fromEntries(Object.entries(refund.byMethod).map(([key, amount]) => {
825
+ if (!key.length) throw new CommandResultError("Invalid refund.byMethod");
826
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`);
827
+ return [key, amount];
828
+ }));
829
+ if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
830
+ if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
831
+ const refunds = refund.refunds.map((value2, index) => {
832
+ const field = `refund.refunds[${index}]`;
833
+ if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
834
+ const entry = value2;
835
+ for (const key of ["id", "paymentId"]) {
836
+ if (typeof entry[key] !== "string" || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`);
837
+ }
838
+ if (!Number.isSafeInteger(entry.totalMinor) || entry.totalMinor < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`);
839
+ if (typeof entry.state !== "string" || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`);
840
+ return { id: entry.id, paymentId: entry.paymentId, totalMinor: entry.totalMinor, state: entry.state };
841
+ });
842
+ if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.refunds");
843
+ result.refund = { totalMinor: refund.totalMinor, byMethod, refunds };
844
+ }
845
+ if (input.reopen !== void 0) {
846
+ if (!object(input.reopen)) throw new CommandResultError("Invalid reopen");
847
+ const reopen = input.reopen;
848
+ if (typeof reopen.orderId !== "string" || reopen.orderId.length === 0) throw new CommandResultError("Invalid reopen.orderId");
849
+ if (typeof reopen.status !== "string" || reopen.status.length === 0) throw new CommandResultError("Invalid reopen.status");
850
+ if (reopen.revision !== void 0 && (typeof reopen.revision !== "string" || reopen.revision.length === 0)) throw new CommandResultError("Invalid reopen.revision");
851
+ result.reopen = { orderId: reopen.orderId, status: reopen.status };
852
+ if (reopen.revision !== void 0) result.reopen.revision = reopen.revision;
853
+ }
854
+ if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0 && result.refund === void 0 && result.reopen === void 0) {
855
+ throw new CommandResultError("Invalid serverRefs: required for applied");
856
+ }
857
+ if (input.warnings !== void 0) {
858
+ if (!Array.isArray(input.warnings)) {
859
+ throw new CommandResultError("Invalid warnings");
860
+ }
861
+ result.warnings = input.warnings.map((warning, index) => {
862
+ const field = `warnings[${index}]`;
863
+ if (typeof warning !== "object" || warning === null || Array.isArray(warning)) {
864
+ throw new CommandResultError(`Invalid ${field}`);
865
+ }
866
+ const item = warning;
867
+ if (item.code === "total_mismatch") {
868
+ for (const key of ["expectedMinor", "serverMinor"]) {
869
+ if (!Number.isInteger(item[key])) {
870
+ throw new CommandResultError(`Invalid ${field}.${key}`);
871
+ }
872
+ }
873
+ if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
874
+ throw new CommandResultError(`Invalid ${field}.bridgeMinor`);
875
+ }
876
+ return item.bridgeMinor != null ? { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor, bridgeMinor: item.bridgeMinor } : { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
877
+ }
878
+ if (item.code === "insufficient_stock") {
879
+ if (typeof item.variantId !== "string" || item.variantId.length === 0) {
880
+ throw new CommandResultError(`Invalid ${field}.variantId`);
881
+ }
882
+ if (!Number.isInteger(item.quantity) || item.quantity < 1) {
883
+ throw new CommandResultError(`Invalid ${field}.quantity`);
884
+ }
885
+ return { code: item.code, variantId: item.variantId, quantity: item.quantity };
886
+ }
887
+ if (item.code === "tax_rate_mismatch") {
888
+ if (!Number.isSafeInteger(item.ratePpm) || item.ratePpm < 0) {
889
+ throw new CommandResultError(`Invalid ${field}.ratePpm`);
890
+ }
891
+ for (const key of ["expectedMinor", "serverMinor"]) {
892
+ if (!Number.isSafeInteger(item[key])) {
893
+ throw new CommandResultError(`Invalid ${field}.${key}`);
894
+ }
895
+ }
896
+ return { code: item.code, ratePpm: item.ratePpm, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
897
+ }
898
+ if (item.code === "customer_ignored") {
899
+ if (typeof item.customerId !== "string" || item.customerId.length === 0 || item.customerId.length > 64) {
900
+ throw new CommandResultError(`Invalid ${field}.customerId`);
901
+ }
902
+ return { code: item.code, customerId: item.customerId };
903
+ }
904
+ if (item.code === "register_session_unknown") {
905
+ if (typeof item.sessionId !== "string" || item.sessionId.length === 0 || item.sessionId.length > 64) {
906
+ throw new CommandResultError(`Invalid ${field}.sessionId`);
907
+ }
908
+ return { code: item.code, sessionId: item.sessionId };
909
+ }
910
+ if (item.code === "figures_mismatch") {
911
+ if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`);
912
+ const seen = [];
913
+ return { code: item.code, fields: item.fields.map((value2, i) => {
914
+ const path = `${field}.fields[${i}]`;
915
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
916
+ const entry = value2;
917
+ if (!["subtotalMinor", "taxMinor", "discountMinor"].includes(entry.field) || seen.includes(entry.field)) {
918
+ throw new CommandResultError(`Invalid ${path}.field`);
919
+ }
920
+ seen.push(entry.field);
921
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
922
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
923
+ return { field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
924
+ }) };
925
+ }
926
+ if (item.code === "line_figures_mismatch") {
927
+ if (!Array.isArray(item.lines) || item.lines.length === 0) throw new CommandResultError(`Invalid ${field}.lines`);
928
+ const seen = [];
929
+ return { code: item.code, lines: item.lines.map((value2, i) => {
930
+ const path = `${field}.lines[${i}]`;
931
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
932
+ const entry = value2;
933
+ if (typeof entry.lineId !== "string" || entry.lineId.length === 0 || entry.lineId.length > 64) throw new CommandResultError(`Invalid ${path}.lineId`);
934
+ const key = JSON.stringify([entry.lineId, entry.field]);
935
+ if (!["subtotalMinor", "taxMinor", "discountMinor", "totalMinor"].includes(entry.field) || seen.includes(key)) {
936
+ throw new CommandResultError(`Invalid ${path}.field`);
937
+ }
938
+ seen.push(key);
939
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
940
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
941
+ return { lineId: entry.lineId, field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
942
+ }) };
943
+ }
944
+ throw new CommandResultError(`Invalid ${field}.code`);
945
+ });
946
+ }
947
+ if (input.error !== void 0) {
948
+ if (typeof input.error !== "object" || input.error === null || Array.isArray(input.error)) {
949
+ throw new CommandResultError("Invalid error");
950
+ }
951
+ const error = input.error;
952
+ if (typeof error.code !== "string" || error.code.length === 0) {
953
+ throw new CommandResultError("Invalid error.code");
954
+ }
955
+ if (typeof error.message !== "string") {
956
+ throw new CommandResultError("Invalid error.message");
957
+ }
958
+ result.error = { code: error.code, message: error.message };
959
+ if (error.data !== void 0) {
960
+ if (!object(error.data)) throw new CommandResultError("Invalid error.data");
961
+ result.error.data = error.data;
962
+ }
963
+ }
964
+ if (result.status === "rejected" && result.error === void 0) {
965
+ throw new CommandResultError("Invalid error: required for rejected");
966
+ }
967
+ return result;
968
+ }
969
+
970
+ // src/server/register-payload-shape.ts
971
+ function registerPayloadErrors(type, payload) {
972
+ const { errors, check: check2, noNul } = shapeErrors();
973
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
974
+ const string = (field, optional = false) => {
975
+ const value = payload[field];
976
+ if (optional && value === void 0) return;
977
+ check2(typeof value === "string" && (optional || value.length > 0), field, optional ? "a string" : "a non-empty string");
978
+ if (typeof value === "string" && (field.endsWith("Id") || field === "voids")) check2(value.length <= 64, field, "at most 64 characters");
979
+ if (typeof value === "string" && ["openedAt", "at", "createdAt", "closedAt"].includes(field)) {
980
+ check2(!Number.isNaN(Date.parse(value)), field, "a valid date");
981
+ }
982
+ noNul(value, field);
983
+ };
984
+ const integer = (field, min = -Infinity) => check2(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
985
+ const record = (field) => {
986
+ const value = payload[field];
987
+ check2(isPlainObject(value), field, "a record of integers");
988
+ if (isPlainObject(value)) for (const [key, amount] of Object.entries(value)) {
989
+ check2(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
990
+ noNul(key, `${field}.${JSON.stringify(key)}`);
991
+ }
992
+ };
993
+ string("sessionId");
994
+ switch (type) {
995
+ case "register.session.open":
996
+ for (const field of ["registerId", "openedAt"]) string(field);
997
+ for (const field of ["storeKey", "businessDay", "openedBy"]) string(field, true);
998
+ if (payload.deviceName !== void 0) {
999
+ check2(
1000
+ typeof payload.deviceName === "string" && payload.deviceName.trim().length >= 1 && payload.deviceName.trim().length <= 64,
1001
+ "deviceName",
1002
+ "a string of 1 to 64 characters after trim"
1003
+ );
1004
+ noNul(payload.deviceName, "deviceName");
1005
+ }
1006
+ if (payload.supersedes !== void 0) {
1007
+ check2(
1008
+ typeof payload.supersedes === "string" && payload.supersedes.length > 0 && payload.supersedes.length <= 64,
1009
+ "supersedes",
1010
+ "a non-empty string of at most 64 characters"
1011
+ );
1012
+ noNul(payload.supersedes, "supersedes");
1013
+ }
1014
+ integer("countedFloatMinor", 0);
1015
+ for (const field of ["expectedFloatMinor", "openingVarianceMinor"]) if (payload[field] !== void 0) integer(field);
1016
+ break;
1017
+ case "register.session.transition":
1018
+ string("at");
1019
+ check2(["open", "counting", "closed"].includes(payload.status), "status", "open, counting or closed");
1020
+ for (const field of ["counted", "closedBy", "approvedBy"]) if (payload[field] !== void 0) {
1021
+ check2(payload.status === "closed", field, "a closing transition");
1022
+ if (field === "counted") record(field);
1023
+ else string(field, true);
1024
+ }
1025
+ break;
1026
+ case "register.movement.record":
1027
+ case "register.movement.void":
1028
+ for (const field of ["movementId", "createdAt"]) string(field);
1029
+ string("createdBy", true);
1030
+ if (type === "register.movement.void") string("voids");
1031
+ else {
1032
+ check2(
1033
+ typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
1034
+ "reason",
1035
+ "a non-empty string after trim of at most 500 characters"
1036
+ );
1037
+ noNul(payload.reason, "reason");
1038
+ check2(["paid_in", "paid_out", "no_sale"].includes(payload.type), "type", "paid_in, paid_out or no_sale");
1039
+ integer("amountMinor", payload.type === "no_sale" ? 0 : 1);
1040
+ if (payload.type === "no_sale") check2(payload.amountMinor === 0, "amountMinor", "0 for no_sale");
1041
+ }
1042
+ break;
1043
+ case "register.closure.submit":
1044
+ for (const field of ["closureId", "registerId", "openedAt", "closedAt", "softwareVersion"]) string(field);
1045
+ for (const field of ["businessDay", "closedBy", "approvedBy"]) string(field, true);
1046
+ if (payload.approval !== void 0) {
1047
+ check2(typeof payload.approval === "string" && payload.approval.length > 0, "approval", "a non-empty string");
1048
+ noNul(payload.approval, "approval");
1049
+ }
1050
+ integer("number", 1);
1051
+ for (const field of [
1052
+ "periodSalesTotalMinor",
1053
+ "periodRefundsTotalMinor",
1054
+ "perpetualSalesTotalMinor",
1055
+ "perpetualRefundsTotalMinor",
1056
+ "unsyncedCount",
1057
+ "unsyncedTotalMinor"
1058
+ ]) integer(field, 0);
1059
+ for (const field of ["number", "unsyncedCount"])
1060
+ check2(payload[field] <= 2147483647, field, "at most 2147483647");
1061
+ for (const field of ["tillExpected", "counted"]) record(field);
1062
+ for (const field of ["orderIds", "movementIds"]) {
1063
+ const value = payload[field];
1064
+ check2(Array.isArray(value), field, "an array of ids");
1065
+ if (Array.isArray(value)) value.forEach((id, index) => {
1066
+ check2(typeof id === "string" && id.length > 0 && id.length <= 64, `${field}[${index}]`, "a non-empty string of at most 64 characters");
1067
+ noNul(id, `${field}[${index}]`);
1068
+ });
1069
+ }
1070
+ break;
1071
+ default:
1072
+ check2(false, "type", "a register command type");
1073
+ }
1074
+ return errors;
1075
+ }
1076
+
1077
+ // src/server/refund-payload-shape.ts
1078
+ function refundPayloadErrors(payload) {
1079
+ const { errors, check: check2, noNul } = shapeErrors();
1080
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
1081
+ const fields = [
1082
+ "clientRefundId",
1083
+ "orderId",
1084
+ "registerId",
1085
+ "sessionId",
1086
+ "clientOrderId",
1087
+ "cashierRef",
1088
+ "lines",
1089
+ "shippingMinor",
1090
+ "totalMinor",
1091
+ "adjustmentMinor",
1092
+ "destination",
1093
+ "reason",
1094
+ "createdAt"
1095
+ ];
1096
+ for (const key of Object.keys(payload)) {
1097
+ if (!fields.includes(key) && errors.length < 10) {
1098
+ errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
1099
+ }
1100
+ }
1101
+ for (const field of ["clientRefundId", "orderId", "registerId", "sessionId", "clientOrderId", "cashierRef"]) {
1102
+ const value = payload[field];
1103
+ if (["clientOrderId", "cashierRef"].includes(field) && value === void 0) continue;
1104
+ check2(
1105
+ typeof value === "string" && value.length > 0 && value.length <= 64,
1106
+ field,
1107
+ "a non-empty string of at most 64 characters"
1108
+ );
1109
+ noNul(value, field);
1110
+ }
1111
+ check2(Array.isArray(payload.lines) && payload.lines.length <= 500, "lines", "an array of at most 500 lines");
1112
+ const seen = /* @__PURE__ */ new Set();
1113
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
1114
+ const path = `lines[${index}]`;
1115
+ if (!isPlainObject(line)) {
1116
+ check2(false, path, "an object");
1117
+ return;
1118
+ }
1119
+ for (const key of Object.keys(line)) {
1120
+ if (!["orderLineId", "quantity", "restock"].includes(key) && errors.length < 10) {
1121
+ errors.push(`${path}.${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
1122
+ }
1123
+ }
1124
+ check2(
1125
+ typeof line.orderLineId === "string" && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
1126
+ `${path}.orderLineId`,
1127
+ "a non-empty string of at most 64 characters"
1128
+ );
1129
+ noNul(line.orderLineId, `${path}.orderLineId`);
1130
+ if (typeof line.orderLineId === "string") {
1131
+ check2(!seen.has(line.orderLineId), `${path}.orderLineId`, "unique in lines");
1132
+ seen.add(line.orderLineId);
1133
+ }
1134
+ check2(Number.isSafeInteger(line.quantity) && line.quantity >= 1, `${path}.quantity`, "a safe integer >= 1");
1135
+ check2(typeof line.restock === "boolean", `${path}.restock`, "a boolean");
1136
+ });
1137
+ for (const field of ["shippingMinor", "totalMinor"]) {
1138
+ check2(Number.isSafeInteger(payload[field]) && payload[field] >= 0, field, "a safe integer >= 0");
1139
+ }
1140
+ check2(Number.isSafeInteger(payload.adjustmentMinor), "adjustmentMinor", "a safe integer");
1141
+ check2(payload.destination === "original_method" || payload.destination === "cash", "destination", "original_method or cash");
1142
+ noNul(payload.destination, "destination");
1143
+ check2(
1144
+ typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
1145
+ "reason",
1146
+ "a non-empty string after trim of at most 500 characters"
1147
+ );
1148
+ noNul(payload.reason, "reason");
1149
+ check2(
1150
+ typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
1151
+ "createdAt",
1152
+ "a valid date"
1153
+ );
1154
+ noNul(payload.createdAt, "createdAt");
1155
+ return errors;
1156
+ }
1157
+
1158
+ // src/server/reopen-payload-shape.ts
1159
+ function reopenPayloadErrors(payload) {
1160
+ const { errors, check: check2, noNul } = shapeErrors();
1161
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
1162
+ const fields = ["orderId", "clientOrderId", "baseRevision", "cashierRef", "registerId", "storeId", "createdAt"];
1163
+ for (const key of Object.keys(payload)) {
1164
+ if (!fields.includes(key) && errors.length < 10) {
1165
+ errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.reopen version 1`);
1166
+ }
1167
+ }
1168
+ for (const field of ["orderId", "cashierRef", "registerId", "clientOrderId", "baseRevision", "storeId"]) {
1169
+ const value = payload[field];
1170
+ if (["clientOrderId", "baseRevision", "storeId"].includes(field) && value === void 0) continue;
1171
+ const max = field === "baseRevision" ? 128 : 64;
1172
+ check2(
1173
+ typeof value === "string" && value.length > 0 && value.length <= max,
1174
+ field,
1175
+ `a non-empty string of at most ${max} characters`
1176
+ );
1177
+ noNul(value, field);
1178
+ }
1179
+ check2(
1180
+ typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
1181
+ "createdAt",
1182
+ "a valid date"
1183
+ );
1184
+ noNul(payload.createdAt, "createdAt");
1185
+ return errors;
1186
+ }
1187
+
1188
+ // src/server/register-figures.ts
1189
+ function deriveSessionFigures(input) {
1190
+ const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
1191
+ for (const order of input.orders) {
1192
+ if (!Array.isArray(order.payments)) continue;
1193
+ for (const payment of order.payments) {
1194
+ if (typeof payment?.method !== "string" || !payment.method.length || !Number.isSafeInteger(payment.amountMinor)) continue;
1195
+ expected[payment.method] = (expected[payment.method] ?? 0) + payment.amountMinor;
1196
+ }
1197
+ }
1198
+ const voided = new Set(input.movements.filter((row) => row.type === "void").map((row) => row.voids));
1199
+ for (const row of input.movements) {
1200
+ if (row.type === "void" || voided.has(row.id)) continue;
1201
+ if (row.type === "paid_in") expected.cash += row.amountMinor;
1202
+ if (row.type === "paid_out") expected.cash -= row.amountMinor;
1203
+ }
1204
+ let refundsTotalMinor = 0;
1205
+ for (const refund of input.refunds ?? []) {
1206
+ if (typeof refund !== "object" || refund === null) continue;
1207
+ const byMethod = refund.byMethod;
1208
+ if (typeof byMethod !== "object" || byMethod === null || Object.getPrototypeOf(byMethod) !== Object.prototype && Object.getPrototypeOf(byMethod) !== null) continue;
1209
+ for (const [method, amount] of Object.entries(byMethod)) {
1210
+ if (!method.length || !Number.isSafeInteger(amount) || amount < 0) continue;
1211
+ expected[method] = (expected[method] ?? 0) - amount;
1212
+ refundsTotalMinor += amount;
1213
+ }
1214
+ }
1215
+ return {
1216
+ expected: { ...expected },
1217
+ salesCount: input.orders.length,
1218
+ ...input.refunds !== void 0 ? { refundsTotalMinor } : {}
1219
+ };
1220
+ }
1221
+ function deriveVariance(counted, expected) {
1222
+ return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]));
1223
+ }
1224
+
1225
+ // src/server/rejection-codes.ts
1226
+ function platformErrorResult(id, platformCode, platformMessage) {
1227
+ return { id, status: "rejected", error: { code: "platform_error", message: `${platformCode}: ${platformMessage}`, data: { platformCode, platformMessage } } };
1228
+ }
1229
+ function internalErrorResult(id, correlationId) {
1230
+ return { id, status: "rejected", error: { code: "internal_error", message: `Internal error (ref ${correlationId})`, data: { correlationId } } };
1231
+ }
1232
+
1233
+ // src/types/display-signalling.ts
1234
+ var DISPLAY_PAIR_CAPABILITY = "customer_display.pair";
1235
+ var DisplaySignallingError = class extends Error {
1236
+ code;
1237
+ constructor(code, message = code) {
1238
+ super(message);
1239
+ this.name = "DisplaySignallingError";
1240
+ this.code = code;
1241
+ }
1242
+ };
1243
+
1244
+ // src/customer-display/rate-limit-source.ts
1245
+ var IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
1246
+ var HEXTET = /^[0-9a-f]{1,4}$/;
1247
+ function expandIpv6(address) {
1248
+ let text = address.toLowerCase();
1249
+ const last = text.slice(text.lastIndexOf(":") + 1);
1250
+ if (IPV4.test(last)) {
1251
+ const [a, b, c, d] = last.split(".").map(Number);
1252
+ text = `${text.slice(0, text.length - last.length)}${(a << 8 | b).toString(16)}:${(c << 8 | d).toString(16)}`;
1253
+ }
1254
+ const halves = text.split("::");
1255
+ if (halves.length > 2) return void 0;
1256
+ const head = halves[0] ? halves[0].split(":") : [];
1257
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
1258
+ const missing = 8 - head.length - tail.length;
1259
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return void 0;
1260
+ const groups = [...head, ...Array(missing).fill("0"), ...tail];
1261
+ if (!groups.every((group) => HEXTET.test(group))) return void 0;
1262
+ return groups.map((group) => group.padStart(4, "0"));
1263
+ }
1264
+ function rateLimitSource(address) {
1265
+ const input = address.trim();
1266
+ if (IPV4.test(input)) return input;
1267
+ const zone = input.indexOf("%");
1268
+ const hextets = expandIpv6(zone >= 0 ? input.slice(0, zone) : input);
1269
+ if (!hextets) return input;
1270
+ if (hextets.slice(0, 5).every((group) => group === "0000") && hextets[5] === "ffff") {
1271
+ const high = parseInt(hextets[6], 16);
1272
+ const low = parseInt(hextets[7], 16);
1273
+ return [high >> 8, high & 255, low >> 8, low & 255].join(".");
1274
+ }
1275
+ return `${hextets.slice(0, 4).join(":")}::/64`;
1276
+ }
1277
+
1278
+ // src/server/display-signalling/memory-server.ts
1279
+ var MINUTE = 6e4;
1280
+ var CODE_TTL = 10 * MINUTE;
1281
+ var MAX_UNSPENT = 5;
1282
+ var SNAPSHOT_TTL = MINUTE;
1283
+ var SNAPSHOT_MAX_BYTES = 204800;
1284
+ var SOURCE_WINDOW = MINUTE;
1285
+ var SOURCE_MAX = 10;
1286
+ var STORE_WINDOW = 10 * MINUTE;
1287
+ var STORE_MAX = 100;
1288
+ var CONNECTED_MS = 3e4;
1289
+ var ROW_TTL = 30 * 24 * 60 * MINUTE;
1290
+ var SESSION_HEADER = "x-memory-display-session";
1291
+ var BASE_URL = "memory://display-signalling";
1292
+ var randomBytes = (length) => globalThis.crypto.getRandomValues(new Uint8Array(length));
1293
+ var toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1294
+ var newId = () => toHex(randomBytes(16));
1295
+ var newSecret = () => btoa(String.fromCharCode(...randomBytes(16))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1296
+ var sha256Hex = async (text) => toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))));
1297
+ function sameText(x, y) {
1298
+ if (x.length !== y.length) return false;
1299
+ let diff = 0;
1300
+ for (let i = 0; i < x.length; i += 1) diff |= x.charCodeAt(i) ^ y.charCodeAt(i);
1301
+ return diff === 0;
1302
+ }
1303
+ function randomDigits(digits) {
1304
+ const range = 10 ** digits, limit = Math.floor(2 ** 32 / range) * range;
1305
+ for (; ; ) {
1306
+ const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));
1307
+ if (value < limit) return String(value % range).padStart(digits, "0");
1308
+ }
1309
+ }
1310
+ var fail = (code) => new DisplaySignallingError(code);
1311
+ var iso = (ms) => new Date(ms).toISOString();
1312
+ var drain = (map, key) => {
1313
+ const box = map.get(key) ?? [];
1314
+ map.delete(key);
1315
+ return box;
1316
+ };
1317
+ function createMemoryDisplaySignalling(options = {}) {
1318
+ let offset = 0;
1319
+ const clock = () => (options.now ?? Date.now)() + offset;
1320
+ const sessions = /* @__PURE__ */ new Map();
1321
+ const sourceOf = /* @__PURE__ */ new WeakMap();
1322
+ const codes = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), displays = /* @__PURE__ */ new Map();
1323
+ const snapshots = /* @__PURE__ */ new Map(), sources = /* @__PURE__ */ new Map();
1324
+ const displayInbox = /* @__PURE__ */ new Map(), tillInbox = /* @__PURE__ */ new Map();
1325
+ const devices = /* @__PURE__ */ new Map(), adoptions = [];
1326
+ let storeWindow = null;
1327
+ const dropDisplay = (displayId) => [displays, snapshots, displayInbox].forEach((map) => map.delete(displayId));
1328
+ const prune = () => {
1329
+ const now = clock();
1330
+ for (const [code, entry] of codes) if (now >= entry.expiresAt) codes.delete(code);
1331
+ for (const [claimId, entry] of pending) if (now >= entry.expiresAt) pending.delete(claimId);
1332
+ for (const [displayId, entry] of snapshots) if (now >= entry.postedAt + SNAPSHOT_TTL) snapshots.delete(displayId);
1333
+ for (const [displayId, row] of displays) if (now >= (row.lastSeenAt ?? row.confirmedAt) + ROW_TTL) dropDisplay(displayId);
1334
+ for (const [key, window] of sources) if (now >= window.openedAt + SOURCE_WINDOW) sources.delete(key);
1335
+ if (storeWindow && now >= storeWindow.openedAt + STORE_WINDOW) storeWindow = null;
1336
+ const owns = (id) => [...displays.values(), ...codes.values(), ...pending.values()].some((entry) => entry.deviceId === id);
1337
+ for (const [id, device] of devices) if (now > device.lastCallAt + ROW_TTL && !owns(id)) devices.delete(id);
1338
+ return now;
1339
+ };
1340
+ const admit = (ctx) => {
1341
+ const now = prune();
1342
+ const session = sessions.get(ctx.headers?.[SESSION_HEADER] ?? "");
1343
+ if (!session || !session.capabilities.includes(DISPLAY_PAIR_CAPABILITY)) throw fail("forbidden");
1344
+ return { now, cashierId: session.cashierId };
1345
+ };
1346
+ const tillCall = async (ctx, device) => {
1347
+ const keyHash = typeof device.deviceKey === "string" && device.deviceKey !== "" ? await sha256Hex(device.deviceKey) : "";
1348
+ const admitted = admit(ctx);
1349
+ const known = devices.get(device.deviceId);
1350
+ if (!known || known.keyHash === null || !sameText(keyHash, known.keyHash)) throw fail("device_refused");
1351
+ known.lastCallAt = admitted.now;
1352
+ return { ...admitted, deviceId: device.deviceId };
1353
+ };
1354
+ const ownedIn = (map, deviceId, id) => {
1355
+ const entry = map.get(id);
1356
+ if (!entry || entry.deviceId !== deviceId) throw fail("not_found");
1357
+ return entry;
1358
+ };
1359
+ const findByTokenHash = (tokenHash) => [...displays].find(([, row]) => row.tokenHash === tokenHash);
1360
+ const byToken = async (token) => {
1361
+ const tokenHash = await sha256Hex(token);
1362
+ const now = prune();
1363
+ const found = findByTokenHash(tokenHash);
1364
+ if (!found) throw fail("token_refused");
1365
+ found[1].lastSeenAt = now;
1366
+ return found;
1367
+ };
1368
+ const failedClaim = (key, now) => {
1369
+ const window = sources.get(key);
1370
+ sources.set(key, { openedAt: window?.openedAt ?? now, failures: (window?.failures ?? 0) + 1 });
1371
+ storeWindow = { openedAt: storeWindow?.openedAt ?? now, failures: (storeWindow?.failures ?? 0) + 1 };
1372
+ return fail("claim_refused");
1373
+ };
1374
+ const signalling = {
1375
+ async registerDevice(ctx, deviceId) {
1376
+ const deviceKey = newSecret();
1377
+ const keyHash = await sha256Hex(deviceKey);
1378
+ const { now, cashierId } = admit(ctx);
1379
+ const known = devices.get(deviceId);
1380
+ if (known && (known.keyHash !== null || known.adopted)) throw fail("device_refused");
1381
+ if (known) adoptions.push({ deviceId, cashierId });
1382
+ devices.set(deviceId, { keyHash, adopted: known !== void 0, lastCallAt: now });
1383
+ return { deviceKey };
1384
+ },
1385
+ async mint(ctx, device) {
1386
+ const { now, deviceId } = await tillCall(ctx, device);
1387
+ const unspent = [...codes.values()].filter((entry) => entry.deviceId === deviceId && !entry.spent).length;
1388
+ if (unspent >= MAX_UNSPENT) throw fail("limit");
1389
+ let code;
1390
+ do
1391
+ code = randomDigits(6);
1392
+ while (codes.has(code));
1393
+ codes.set(code, { deviceId, expiresAt: now + CODE_TTL, spent: false });
1394
+ return { code, expiresAt: iso(now + CODE_TTL) };
1395
+ },
1396
+ async pending(ctx, device) {
1397
+ const { deviceId } = await tillCall(ctx, device);
1398
+ return [...pending].filter(([, entry]) => entry.deviceId === deviceId).map(([claimId, entry]) => ({ claimId, displayName: entry.displayName, checkCode: entry.checkCode, expiresAt: iso(entry.expiresAt) }));
1399
+ },
1400
+ async confirm(ctx, device, claimId) {
1401
+ const { now, cashierId, deviceId } = await tillCall(ctx, device);
1402
+ const entry = ownedIn(pending, deviceId, claimId);
1403
+ pending.delete(claimId);
1404
+ const moving = entry.movingDisplayId !== null && displays.has(entry.movingDisplayId) ? entry.movingDisplayId : null;
1405
+ if (moving !== null) dropDisplay(moving);
1406
+ const row = { deviceId, name: entry.displayName, cashierId, confirmedAt: now, lastSeenAt: null, tokenHash: null, secretHash: entry.secretHash };
1407
+ displays.set(moving ?? newId(), row);
1408
+ },
1409
+ async decline(ctx, device, claimId) {
1410
+ const { deviceId } = await tillCall(ctx, device);
1411
+ ownedIn(pending, deviceId, claimId);
1412
+ pending.delete(claimId);
1413
+ },
1414
+ async list(ctx, device) {
1415
+ const { now, deviceId } = await tillCall(ctx, device);
1416
+ return [...displays].filter(([, row]) => row.deviceId === deviceId).map(([displayId, row]) => ({
1417
+ displayId,
1418
+ name: row.name,
1419
+ cashierId: row.cashierId,
1420
+ lastSeenAt: row.lastSeenAt === null ? null : iso(row.lastSeenAt),
1421
+ connected: row.lastSeenAt !== null && now - row.lastSeenAt <= CONNECTED_MS
1422
+ }));
1423
+ },
1424
+ async forget(ctx, device, displayId) {
1425
+ const { deviceId } = await tillCall(ctx, device);
1426
+ ownedIn(displays, deviceId, displayId);
1427
+ dropDisplay(displayId);
1428
+ },
1429
+ async sendSignal(ctx, device, displayId, message) {
1430
+ const { deviceId } = await tillCall(ctx, device);
1431
+ ownedIn(displays, deviceId, displayId);
1432
+ displayInbox.set(displayId, [...displayInbox.get(displayId) ?? [], { type: message.type, payload: message.payload }]);
1433
+ },
1434
+ async receiveSignals(ctx, device) {
1435
+ const { deviceId } = await tillCall(ctx, device);
1436
+ return drain(tillInbox, deviceId).filter((message) => displays.get(message.displayId)?.deviceId === deviceId);
1437
+ },
1438
+ async postSnapshot(ctx, device, displayId, body) {
1439
+ const { now, deviceId } = await tillCall(ctx, device);
1440
+ ownedIn(displays, deviceId, displayId);
1441
+ const text = JSON.stringify(body) ?? "null";
1442
+ if (new TextEncoder().encode(text).length > SNAPSHOT_MAX_BYTES) throw fail("too_large");
1443
+ snapshots.set(displayId, { text, postedAt: now });
1444
+ },
1445
+ async claim(dctx, { code, displayName, token }) {
1446
+ const claimSecret = newSecret();
1447
+ const secretHash = await sha256Hex(claimSecret);
1448
+ const tokenHash = token ? await sha256Hex(token) : null;
1449
+ const now = prune();
1450
+ const key = rateLimitSource(sourceOf.get(dctx) ?? "");
1451
+ if ((storeWindow?.failures ?? 0) >= STORE_MAX || (sources.get(key)?.failures ?? 0) >= SOURCE_MAX) throw fail("claim_refused");
1452
+ const entry = codes.get(code);
1453
+ if (!entry || entry.spent) throw failedClaim(key, now);
1454
+ entry.spent = true;
1455
+ let checkCode;
1456
+ do
1457
+ checkCode = randomDigits(4);
1458
+ while ([...pending.values()].some((other) => other.deviceId === entry.deviceId && other.checkCode === checkCode));
1459
+ const movingDisplayId = tokenHash === null ? null : findByTokenHash(tokenHash)?.[0] ?? null;
1460
+ pending.set(newId(), { deviceId: entry.deviceId, secretHash, displayName, checkCode, expiresAt: entry.expiresAt, movingDisplayId });
1461
+ return { claimSecret, checkCode };
1462
+ },
1463
+ async collect(_dctx, claimSecret) {
1464
+ const secretHash = await sha256Hex(claimSecret);
1465
+ const token = newSecret();
1466
+ const tokenHash = await sha256Hex(token);
1467
+ prune();
1468
+ const waiting = [...pending.values()].find((entry) => entry.secretHash === secretHash);
1469
+ if (waiting) return { status: "pending", checkCode: waiting.checkCode };
1470
+ const found = [...displays].find(([, row]) => row.secretHash === secretHash && row.tokenHash === null);
1471
+ if (!found) throw fail("collect_refused");
1472
+ found[1].secretHash = null;
1473
+ found[1].tokenHash = tokenHash;
1474
+ return { status: "paired", displayId: found[0], token };
1475
+ },
1476
+ async displaySendSignal(_dctx, token, message) {
1477
+ const [displayId, row] = await byToken(token);
1478
+ tillInbox.set(row.deviceId, [...tillInbox.get(row.deviceId) ?? [], { type: message.type, payload: message.payload, displayId }]);
1479
+ },
1480
+ async displayReceiveSignals(_dctx, token) {
1481
+ const [displayId] = await byToken(token);
1482
+ return drain(displayInbox, displayId);
1483
+ },
1484
+ async readSnapshot(_dctx, token) {
1485
+ const [displayId] = await byToken(token);
1486
+ const held = snapshots.get(displayId);
1487
+ return held ? JSON.parse(held.text) : null;
1488
+ }
1489
+ };
1490
+ const harness = {
1491
+ signalling,
1492
+ till({ cashierId, canPair }) {
1493
+ const sessionId = newId();
1494
+ sessions.set(sessionId, { cashierId, capabilities: canPair ? [DISPLAY_PAIR_CAPABILITY] : [] });
1495
+ return { connectorId: "memory-display-signalling", baseUrl: BASE_URL, headers: { [SESSION_HEADER]: sessionId } };
1496
+ },
1497
+ display(source) {
1498
+ const dctx = { baseUrl: BASE_URL };
1499
+ sourceOf.set(dctx, source);
1500
+ return dctx;
1501
+ },
1502
+ advance: async (ms) => {
1503
+ offset += ms;
1504
+ },
1505
+ async storedText() {
1506
+ prune();
1507
+ return JSON.stringify({
1508
+ sessions: [...sessions],
1509
+ devices: [...devices],
1510
+ codes: [...codes],
1511
+ pending: [...pending],
1512
+ displays: [...displays],
1513
+ snapshots: [...snapshots],
1514
+ displayInbox: [...displayInbox],
1515
+ tillInbox: [...tillInbox],
1516
+ sources: [...sources],
1517
+ storeWindow
1518
+ });
1519
+ },
1520
+ async storedCounts() {
1521
+ prune();
1522
+ return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size, devices: devices.size };
1523
+ },
1524
+ async seedLegacyDevice(deviceId) {
1525
+ const token = newSecret(), displayId = newId(), now = clock();
1526
+ devices.set(deviceId, { keyHash: null, adopted: false, lastCallAt: now });
1527
+ displays.set(displayId, { deviceId, name: "Legacy", cashierId: "cashier-legacy", confirmedAt: now, lastSeenAt: null, tokenHash: await sha256Hex(token), secretHash: null });
1528
+ return { displayId, token };
1529
+ },
1530
+ adoptionLog: async () => adoptions.map((entry) => ({ ...entry }))
1531
+ };
1532
+ return { signalling, harness };
1533
+ }
1534
+
1535
+ // src/server/display-signalling/contract.ts
1536
+ var MINUTE2 = 6e4;
1537
+ var DAY = 24 * 60 * MINUTE2;
1538
+ var A = "till-a";
1539
+ var B = "till-b";
1540
+ var SECRET = /^[A-Za-z0-9_-]{22,}$/;
1541
+ function check(condition, message) {
1542
+ if (!condition) throw new Error(`display signalling contract: ${message}`);
1543
+ }
1544
+ async function expectRefusal(promise, code, what) {
1545
+ let result;
1546
+ try {
1547
+ result = await promise;
1548
+ } catch (error) {
1549
+ const got = error?.code;
1550
+ check(got === code, `${what}: expected ${code}, got ${String(got ?? error)}`);
1551
+ return error;
1552
+ }
1553
+ throw new Error(`display signalling contract: ${what}: expected ${code}, but it resolved ${JSON.stringify(result)}`);
1554
+ }
1555
+ var sameRefusal = (x, y, what) => check(x.message === y.message && x.code === y.code, `${what}: the refusals differ`);
1556
+ function unusedCode(...used) {
1557
+ for (let n = 0; ; n += 1) {
1558
+ const code = String(n).padStart(used[0]?.length ?? 6, "0");
1559
+ if (!used.includes(code)) return code;
1560
+ }
1561
+ }
1562
+ var KEY_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1563
+ var randomKey = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(22)), (n) => KEY_ALPHABET[n & 63]).join("");
1564
+ async function world(make) {
1565
+ const h = await make();
1566
+ const till = (cashierId, canPair = true) => h.till({ cashierId, canPair });
1567
+ const [a, b, viewer] = [await till("cashier-a"), await till("cashier-b"), await till("cashier-viewer", false)];
1568
+ const da = { deviceId: A, deviceKey: (await h.signalling.registerDevice(a, A)).deviceKey };
1569
+ const db = { deviceId: B, deviceKey: (await h.signalling.registerDevice(b, B)).deviceKey };
1570
+ return { h, s: h.signalling, a, b, viewer, da, db };
1571
+ }
1572
+ async function claimed(w, ctx, device, d, name, token) {
1573
+ const { code } = await w.s.mint(ctx, device);
1574
+ const claim = await w.s.claim(d, { code, displayName: name, ...token ? { token } : {} });
1575
+ const entry = (await w.s.pending(ctx, device)).find((p) => p.checkCode === claim.checkCode);
1576
+ check(entry && entry.displayName === name, `the pending listing lacks the claim by ${name}`);
1577
+ return { code, claim, claimId: entry.claimId };
1578
+ }
1579
+ async function paired(w, ctx, device, source, name, token) {
1580
+ const d = w.h.display(source);
1581
+ const { claim, claimId } = await claimed(w, ctx, device, d, name, token);
1582
+ await w.s.confirm(ctx, device, claimId);
1583
+ const result = await w.s.collect(d, claim.claimSecret);
1584
+ check(result.status === "paired", `collect after the confirm gave ${result.status}`);
1585
+ return { d, claim, displayId: result.displayId, token: result.token };
1586
+ }
1587
+ async function armed(w) {
1588
+ const shown = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1589
+ await w.s.postSnapshot(w.a, w.da, shown.displayId, { v: 1 });
1590
+ await w.s.displaySendSignal(shown.d, shown.token, { type: "answer", payload: "a1" });
1591
+ const { claimId } = await claimed(w, w.a, w.da, w.h.display("192.0.2.2"), "Waiting");
1592
+ return { ...shown, claimId };
1593
+ }
1594
+ var tillCalls = (w, device, displayId, claimId) => [
1595
+ ["mint", () => w.s.mint(w.a, device)],
1596
+ ["pending", () => w.s.pending(w.a, device)],
1597
+ ["confirm", () => w.s.confirm(w.a, device, claimId)],
1598
+ ["decline", () => w.s.decline(w.a, device, claimId)],
1599
+ ["list", () => w.s.list(w.a, device)],
1600
+ ["forget", () => w.s.forget(w.a, device, displayId)],
1601
+ ["sendSignal", () => w.s.sendSignal(w.a, device, displayId, { type: "offer", payload: "o2" })],
1602
+ ["receiveSignals", () => w.s.receiveSignals(w.a, device)],
1603
+ ["postSnapshot", () => w.s.postSnapshot(w.a, device, displayId, { v: 2 })]
1604
+ ];
1605
+ var refusedDevices = (w) => [
1606
+ ["a missing key", { deviceId: A, deviceKey: "" }],
1607
+ ["a wrong key", { deviceId: A, deviceKey: randomKey() }],
1608
+ ["B's key on A's id", { deviceId: A, deviceKey: w.db.deviceKey }],
1609
+ ["an unregistered id", { deviceId: "till-never", deviceKey: w.da.deviceKey }]
1610
+ ];
1611
+ async function adopted(w) {
1612
+ const legacy = await w.h.seedLegacyDevice("till-legacy");
1613
+ const device = { deviceId: "till-legacy", deviceKey: (await w.s.registerDevice(w.a, "till-legacy")).deviceKey };
1614
+ return { ...legacy, device };
1615
+ }
1616
+ function displaySignallingContract(makeHarness) {
1617
+ const cases = {
1618
+ "mint without the capability is forbidden and makes no code": async ({ h, s, viewer, da }) => {
1619
+ await expectRefusal(s.mint(viewer, da), "forbidden", "mint without the capability");
1620
+ check((await h.storedCounts()).codes === 0, "a refused mint stored a code");
1621
+ },
1622
+ "a minted code is at least 6 digits and expires within 10 minutes": async ({ h, s, a, da }) => {
1623
+ const { code, expiresAt } = await s.mint(a, da);
1624
+ check(/^\d{6,}$/.test(code), `code ${code} is not 6 or more digits`);
1625
+ check(!Number.isNaN(Date.parse(expiresAt)), `expiresAt ${expiresAt} is not a date`);
1626
+ await h.advance(10 * MINUTE2);
1627
+ await expectRefusal(s.claim(h.display("192.0.2.1"), { code, displayName: "Late" }), "claim_refused", "a claim 10 minutes after the mint");
1628
+ },
1629
+ "a device holds at most 5 unspent codes, and expired codes stop counting": async ({ h, s, a, da }) => {
1630
+ for (let i = 0; i < 5; i += 1) await s.mint(a, da);
1631
+ await expectRefusal(s.mint(a, da), "limit", "the 6th unspent code");
1632
+ await h.advance(10 * MINUTE2);
1633
+ await s.mint(a, da);
1634
+ },
1635
+ "spent, expired and unknown codes get the same claim refusal": async ({ h, s, a, da }) => {
1636
+ const spent = (await s.mint(a, da)).code;
1637
+ await s.claim(h.display("192.0.2.1"), { code: spent, displayName: "First" });
1638
+ const again = await expectRefusal(s.claim(h.display("192.0.2.2"), { code: spent, displayName: "Second" }), "claim_refused", "a spent code");
1639
+ const expired = (await s.mint(a, da)).code;
1640
+ await h.advance(10 * MINUTE2);
1641
+ const late = await expectRefusal(s.claim(h.display("192.0.2.3"), { code: expired, displayName: "Late" }), "claim_refused", "an expired code");
1642
+ const unknown = await expectRefusal(s.claim(h.display("192.0.2.4"), { code: unusedCode(spent, expired), displayName: "Guess" }), "claim_refused", "an unknown code");
1643
+ sameRefusal(again, late, "spent and expired");
1644
+ sameRefusal(again, unknown, "spent and unknown");
1645
+ },
1646
+ "a claim issues no token: collect gives pending with its check code": async (w) => {
1647
+ const d = w.h.display("192.0.2.1");
1648
+ const { claim } = await claimed(w, w.a, w.da, d, "Counter");
1649
+ const result = await w.s.collect(d, claim.claimSecret);
1650
+ check(result.status === "pending" && result.checkCode === claim.checkCode, `collect before the confirm gave ${JSON.stringify(result)}`);
1651
+ },
1652
+ "the check code matches on both screens, and two live claims never share one": async (w) => {
1653
+ const d = w.h.display("192.0.2.1");
1654
+ const first = await claimed(w, w.a, w.da, d, "One");
1655
+ check(/^\d{4}$/.test(first.claim.checkCode), `check code ${first.claim.checkCode} is not 4 digits`);
1656
+ const listed = (await w.s.pending(w.a, w.da)).find((p) => p.claimId === first.claimId);
1657
+ const collected = await w.s.collect(d, first.claim.claimSecret);
1658
+ check(listed?.checkCode === first.claim.checkCode, "the till lists another check code");
1659
+ check(collected.status === "pending" && collected.checkCode === first.claim.checkCode, "collect gives another check code");
1660
+ const second = await claimed(w, w.a, w.da, w.h.display("192.0.2.2"), "Two");
1661
+ check(second.claim.checkCode !== first.claim.checkCode, "two live claims share a check code");
1662
+ },
1663
+ "a confirm issues the token once, then collect is refused like an unknown secret": async (w) => {
1664
+ const { d, claim, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1665
+ check(SECRET.test(token), "the token is not 22+ base64url characters");
1666
+ const again = await expectRefusal(w.s.collect(d, claim.claimSecret), "collect_refused", "a second collect");
1667
+ const unknown = await expectRefusal(w.s.collect(d, "AAAAAAAAAAAAAAAAAAAAAA"), "collect_refused", "an unknown secret");
1668
+ sameRefusal(again, unknown, "second collect and unknown secret");
1669
+ },
1670
+ "a decline, or an unconfirmed claim whose code expires, issues nothing": async (w) => {
1671
+ const d = w.h.display("192.0.2.1");
1672
+ const declined = await claimed(w, w.a, w.da, d, "Declined");
1673
+ await w.s.decline(w.a, w.da, declined.claimId);
1674
+ await expectRefusal(w.s.collect(d, declined.claim.claimSecret), "collect_refused", "collect after a decline");
1675
+ const lapsed = await claimed(w, w.a, w.da, d, "Lapsed");
1676
+ await w.h.advance(10 * MINUTE2);
1677
+ await expectRefusal(w.s.collect(d, lapsed.claim.claimSecret), "collect_refused", "collect after the code expired");
1678
+ check((await w.h.storedCounts()).pending === 0, "a pending pairing outlived its decline or its code");
1679
+ },
1680
+ "a confirm needs the capability and the minting device": async (w) => {
1681
+ const d = w.h.display("192.0.2.1");
1682
+ const { claim, claimId } = await claimed(w, w.a, w.da, d, "Counter");
1683
+ await expectRefusal(w.s.confirm(w.viewer, w.da, claimId), "forbidden", "a confirm without the capability");
1684
+ await expectRefusal(w.s.confirm(w.b, w.db, claimId), "not_found", "a confirm from another device");
1685
+ check((await w.s.collect(d, claim.claimSecret)).status === "pending", "a refused confirm changed the claim");
1686
+ },
1687
+ "one source is limited to 10 failed claims a minute, and a limited claim spends nothing": async ({ h, s, a, da }) => {
1688
+ const { code } = await s.mint(a, da);
1689
+ const guesser = h.display("198.51.100.7");
1690
+ for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(guesser, { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
1691
+ await expectRefusal(s.claim(guesser, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited source");
1692
+ await s.claim(h.display("198.51.100.8"), { code, displayName: "Other" });
1693
+ await h.advance(MINUTE2);
1694
+ await s.claim(guesser, { code: (await s.mint(a, da)).code, displayName: "Later" });
1695
+ },
1696
+ "two IPv6 addresses in one /64 share a limit": async ({ h, s, a, da }) => {
1697
+ const { code } = await s.mint(a, da);
1698
+ const one = h.display("2001:db8:0:1::5");
1699
+ const two = h.display("2001:db8:0:1:ffff::9");
1700
+ for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(i % 2 ? two : one, { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
1701
+ await expectRefusal(s.claim(one, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited /64");
1702
+ await expectRefusal(s.claim(two, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited /64");
1703
+ await s.claim(h.display("2001:db8:0:2::5"), { code, displayName: "Other" });
1704
+ },
1705
+ "100 failed claims store-wide pause every claim for 10 minutes": async ({ h, s, a, da }) => {
1706
+ const { code } = await s.mint(a, da);
1707
+ for (let i = 0; i < 100; i += 1) await expectRefusal(s.claim(h.display(`203.0.113.${Math.floor(i / 9) + 1}`), { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
1708
+ await expectRefusal(s.claim(h.display("203.0.113.200"), { code, displayName: "Shop" }), "claim_refused", "a valid code while paused");
1709
+ await h.advance(10 * MINUTE2);
1710
+ await s.claim(h.display("203.0.113.201"), { code: (await s.mint(a, da)).code, displayName: "Shop" });
1711
+ },
1712
+ "the claim secret and the token are stored only as hashes": async (w) => {
1713
+ const { claim, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1714
+ const text = await w.h.storedText();
1715
+ check(SECRET.test(claim.claimSecret), "the claim secret is not 22+ base64url characters");
1716
+ check(!text.includes(claim.claimSecret) && !text.includes(token), "the claim secret or the token is stored");
1717
+ check(text.includes(await sha256Hex(token)), "the token's SHA-256 hex is not stored");
1718
+ },
1719
+ "the registry lists a display on its owning device only, and tracks connected": async (w) => {
1720
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1721
+ const row = (await w.s.list(w.a, w.da)).find((r) => r.displayId === displayId);
1722
+ check(row?.name === "Counter" && row.cashierId === "cashier-a", `the owner lists ${JSON.stringify(row)}`);
1723
+ check(!(await w.s.list(w.b, w.db)).some((r) => r.displayId === displayId), "another device lists the display");
1724
+ await w.s.displayReceiveSignals(d, token);
1725
+ check((await w.s.list(w.a, w.da))[0]?.connected === true, "a display just seen is not connected");
1726
+ await w.h.advance(31e3);
1727
+ check((await w.s.list(w.a, w.da))[0]?.connected === false, "a display unseen for 31 s is connected");
1728
+ },
1729
+ "forget revokes the token, the row and the snapshot, for the owner only": async (w) => {
1730
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1731
+ await w.s.postSnapshot(w.a, w.da, displayId, { v: 1 });
1732
+ await w.s.displaySendSignal(d, token, { type: "answer", payload: "a1" });
1733
+ await expectRefusal(w.s.forget(w.b, w.db, displayId), "not_found", "forget from another device");
1734
+ check((await w.s.list(w.a, w.da)).length === 1, "a refused forget removed the display");
1735
+ await w.s.forget(w.a, w.da, displayId);
1736
+ await expectRefusal(w.s.displayReceiveSignals(d, token), "token_refused", "a forgotten token");
1737
+ check((await w.s.list(w.a, w.da)).length === 0, "the owner still lists a forgotten display");
1738
+ check((await w.s.receiveSignals(w.a, w.da)).every((m) => m.displayId !== displayId), "the till received from a forgotten display");
1739
+ const counts = await w.h.storedCounts();
1740
+ check(counts.displays === 0 && counts.snapshots === 0, `forget left ${JSON.stringify(counts)}`);
1741
+ },
1742
+ "a display confirmed by a second till moves to it": async (w) => {
1743
+ const first = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1744
+ await w.s.postSnapshot(w.a, w.da, first.displayId, { v: 1 });
1745
+ await w.s.sendSignal(w.a, w.da, first.displayId, { type: "offer", payload: "o1" });
1746
+ await w.s.displaySendSignal(first.d, first.token, { type: "answer", payload: "a1" });
1747
+ const moved = await paired(w, w.b, w.db, "192.0.2.1", "Counter", first.token);
1748
+ check(await w.s.readSnapshot(moved.d, moved.token) === null, "the first till's snapshot survived the move");
1749
+ check((await w.s.displayReceiveSignals(moved.d, moved.token)).length === 0, "the first till's signal survived the move");
1750
+ check((await w.h.storedCounts()).snapshots === 0, "a snapshot is stored after the move");
1751
+ check((await w.s.receiveSignals(w.a, w.da)).every((m) => m.displayId !== first.displayId), "the first till received from a moved display");
1752
+ check((await w.s.list(w.a, w.da)).length === 0, "the first till still lists a moved display");
1753
+ check((await w.s.list(w.b, w.db)).some((r) => r.displayId === first.displayId) && moved.displayId === first.displayId, "the moved display has a new id");
1754
+ await expectRefusal(w.s.readSnapshot(first.d, first.token), "token_refused", "the old token after a move");
1755
+ },
1756
+ "signals arrive once and in order, and only at their own display or till": async (w) => {
1757
+ const x = await paired(w, w.a, w.da, "192.0.2.1", "X");
1758
+ const y = await paired(w, w.a, w.da, "192.0.2.2", "Y");
1759
+ const z = await paired(w, w.b, w.db, "192.0.2.3", "Z");
1760
+ await w.s.sendSignal(w.a, w.da, x.displayId, { type: "offer", payload: "o1" });
1761
+ await w.s.sendSignal(w.a, w.da, x.displayId, { type: "ice", payload: "i1" });
1762
+ const atX = await w.s.displayReceiveSignals(x.d, x.token);
1763
+ check(atX.map((m) => m.payload).join() === "o1,i1", `display X received ${JSON.stringify(atX)}`);
1764
+ check((await w.s.displayReceiveSignals(x.d, x.token)).length === 0, "display X received a message twice");
1765
+ check((await w.s.displayReceiveSignals(y.d, y.token)).length === 0, "display Y received display X's messages");
1766
+ await w.s.displaySendSignal(x.d, x.token, { type: "answer", payload: "a1" });
1767
+ await w.s.displaySendSignal(x.d, x.token, { type: "ice", payload: "i2" });
1768
+ await w.s.displaySendSignal(z.d, z.token, { type: "answer", payload: "z1" });
1769
+ check((await w.s.receiveSignals(w.b, w.db)).every((m) => m.displayId === z.displayId), "device B received device A's display");
1770
+ const atA = await w.s.receiveSignals(w.a, w.da);
1771
+ check(atA.map((m) => `${m.displayId === x.displayId}:${m.payload}`).join() === "true:a1,true:i2", `till A received ${JSON.stringify(atA)}`);
1772
+ check((await w.s.receiveSignals(w.a, w.da)).length === 0, "till A received a message twice");
1773
+ },
1774
+ "the snapshot needs the token, keeps the latest body for 60 s, and refuses over 200 KiB": async (w) => {
1775
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1776
+ await expectRefusal(w.s.readSnapshot(d, "not-a-token-not-a-token"), "token_refused", "a read without the token");
1777
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 1 });
1778
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 2 });
1779
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":2}', "the latest snapshot is not served");
1780
+ await w.h.advance(61e3);
1781
+ check(await w.s.readSnapshot(d, token) === null, "a snapshot outlived 60 s");
1782
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 3 });
1783
+ await expectRefusal(w.s.postSnapshot(w.a, w.da, displayId, { pad: "x".repeat(204800) }), "too_large", "a snapshot over 200 KiB");
1784
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":3}', "a refused snapshot replaced the previous one");
1785
+ },
1786
+ "expired codes and displays unseen for 30 days are pruned": async (w) => {
1787
+ const { d, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1788
+ await w.s.mint(w.a, w.da);
1789
+ await w.h.advance(10 * MINUTE2);
1790
+ await w.s.list(w.a, w.da);
1791
+ check((await w.h.storedCounts()).codes === 0, "an expired code is still stored");
1792
+ await w.h.advance(30 * DAY);
1793
+ await w.s.list(w.a, w.da);
1794
+ check((await w.h.storedCounts()).displays === 0, "a display unseen for 30 days is still stored");
1795
+ await expectRefusal(w.s.readSnapshot(d, token), "token_refused", "a pruned display");
1796
+ },
1797
+ "K1: registerDevice needs the capability, and issues a 22+ character base64url key": async (w) => {
1798
+ const before = (await w.h.storedCounts()).devices;
1799
+ await expectRefusal(w.s.registerDevice(w.viewer, "till-c"), "forbidden", "a register without the capability");
1800
+ check((await w.h.storedCounts()).devices === before, "a refused register stored a device");
1801
+ check(SECRET.test((await w.s.registerDevice(w.a, "till-c")).deviceKey), "the device key is not 22+ base64url characters");
1802
+ },
1803
+ "K2: an id that holds a key cannot register again, by any cashier": async (w) => {
1804
+ await expectRefusal(w.s.registerDevice(w.a, A), "device_refused", "a second register by the same cashier");
1805
+ await expectRefusal(w.s.registerDevice(w.b, A), "device_refused", "a second register by another cashier");
1806
+ await w.s.list(w.a, w.da);
1807
+ },
1808
+ "K3: every till call refuses a missing, wrong, swapped or unregistered key the same way": async (w) => {
1809
+ const { displayId, claimId } = await armed(w);
1810
+ for (const [method] of tillCalls(w, w.da, displayId, claimId)) {
1811
+ const refusals = [];
1812
+ for (const [what, device] of refusedDevices(w)) {
1813
+ const call = tillCalls(w, device, displayId, claimId).find(([name]) => name === method)[1];
1814
+ refusals.push(await expectRefusal(call(), "device_refused", `${method} with ${what}`));
1815
+ }
1816
+ refusals.forEach((refusal, i) => sameRefusal(refusals[0], refusal, `${method}: refusal ${i}`));
1817
+ }
1818
+ },
1819
+ "K4: a refused till call has no effect": async (w) => {
1820
+ const { d, token, displayId, claimId } = await armed(w);
1821
+ const before = JSON.stringify(await w.h.storedCounts());
1822
+ for (const [, device] of refusedDevices(w)) {
1823
+ for (const [method, call] of tillCalls(w, device, displayId, claimId)) await expectRefusal(call(), "device_refused", method);
1824
+ }
1825
+ const after = JSON.stringify(await w.h.storedCounts());
1826
+ check(after === before, `refused calls changed the stored counts from ${before} to ${after}`);
1827
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"v":1}', "a refused postSnapshot replaced the snapshot");
1828
+ check((await w.s.displayReceiveSignals(d, token)).length === 0, "a refused sendSignal queued a message");
1829
+ check((await w.s.receiveSignals(w.a, w.da)).map((m) => m.payload).join() === "a1", "a refused receiveSignals drained the inbox");
1830
+ },
1831
+ "K5: a wrong key gets device_refused, never not_found, on an owned and on a foreign display": async (w) => {
1832
+ const own = await paired(w, w.a, w.da, "192.0.2.1", "Own");
1833
+ const foreign = await paired(w, w.b, w.db, "192.0.2.2", "Foreign");
1834
+ const wrong = { deviceId: A, deviceKey: w.db.deviceKey };
1835
+ const onOwn = await expectRefusal(w.s.forget(w.a, wrong, own.displayId), "device_refused", "a wrong key on an owned display");
1836
+ const onForeign = await expectRefusal(w.s.forget(w.a, wrong, foreign.displayId), "device_refused", "a wrong key on a foreign display");
1837
+ sameRefusal(onOwn, onForeign, "owned and foreign displays");
1838
+ await expectRefusal(w.s.postSnapshot(w.a, wrong, foreign.displayId, { v: 1 }), "device_refused", "a wrong key posting to a foreign display");
1839
+ },
1840
+ "K6: the device key is stored only as its SHA-256 hex": async (w) => {
1841
+ const text = await w.h.storedText();
1842
+ check(!text.includes(w.da.deviceKey) && !text.includes(w.db.deviceKey), "a device key is stored");
1843
+ check(text.includes(await sha256Hex(w.da.deviceKey)), "the device key's SHA-256 hex is not stored");
1844
+ },
1845
+ "K7: a pre-migration till adopts its displays at its first register": async (w) => {
1846
+ const legacy = await w.h.seedLegacyDevice("till-legacy");
1847
+ await expectRefusal(w.s.registerDevice(w.viewer, "till-legacy"), "forbidden", "a register without the capability");
1848
+ check((await w.h.adoptionLog()).length === 0, "a refused register adopted");
1849
+ const before = JSON.stringify(await w.h.storedCounts());
1850
+ for (const [what, deviceKey] of [["no key", ""], ["a random key", randomKey()]]) {
1851
+ const keyless = { deviceId: "till-legacy", deviceKey };
1852
+ await expectRefusal(w.s.list(w.a, keyless), "device_refused", `list with ${what} before the adoption`);
1853
+ await expectRefusal(w.s.mint(w.a, keyless), "device_refused", `mint with ${what} before the adoption`);
1854
+ }
1855
+ const after = JSON.stringify(await w.h.storedCounts());
1856
+ check(after === before, `refused pre-adoption calls changed the stored counts from ${before} to ${after}`);
1857
+ const device = { deviceId: "till-legacy", deviceKey: (await w.s.registerDevice(w.a, "till-legacy")).deviceKey };
1858
+ check(SECRET.test(device.deviceKey), "the adopting key is not 22+ base64url characters");
1859
+ check((await w.s.list(w.a, device)).some((r) => r.displayId === legacy.displayId), "the adopted till does not list its display");
1860
+ await w.s.readSnapshot(w.h.display("192.0.2.1"), legacy.token);
1861
+ const log = JSON.stringify(await w.h.adoptionLog());
1862
+ check(log === JSON.stringify([{ deviceId: "till-legacy", cashierId: "cashier-a" }]), `the adoption log is ${log}`);
1863
+ },
1864
+ "K8: an adoption cannot repeat": async (w) => {
1865
+ const { device } = await adopted(w);
1866
+ await expectRefusal(w.s.registerDevice(w.b, "till-legacy"), "device_refused", "a second adoption by another cashier");
1867
+ await expectRefusal(w.s.registerDevice(w.a, "till-legacy"), "device_refused", "a second adoption by the same cashier");
1868
+ check((await w.h.adoptionLog()).length === 1, "the adoption log has more than one entry");
1869
+ await w.s.list(w.a, device);
1870
+ },
1871
+ "K9: a device that owns nothing and makes no till call for over 30 days is pruned, and its id registers again": async (w) => {
1872
+ const old = { deviceId: "till-idle", deviceKey: (await w.s.registerDevice(w.a, "till-idle")).deviceKey };
1873
+ const shown = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1874
+ await w.h.advance(29 * DAY);
1875
+ await expectRefusal(w.s.list(w.a, { deviceId: "till-idle", deviceKey: randomKey() }), "device_refused", "a wrong key on an idle device");
1876
+ await w.s.readSnapshot(shown.d, shown.token);
1877
+ await w.h.advance(2 * DAY);
1878
+ check((await w.s.list(w.a, w.da)).some((r) => r.displayId === shown.displayId), "a device that owns a live row was pruned");
1879
+ const fresh = (await w.s.registerDevice(w.a, "till-idle")).deviceKey;
1880
+ check(fresh !== old.deviceKey, "the re-registered id got its old key");
1881
+ await expectRefusal(w.s.list(w.a, old), "device_refused", "the key of a pruned device");
1882
+ await w.s.list(w.a, { deviceId: "till-idle", deviceKey: fresh });
1883
+ }
1884
+ };
1885
+ return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
1886
+ }
1887
+ // Annotate the CommonJS export names for ESM import in node:
1888
+ 0 && (module.exports = {
1889
+ CommandResultError,
1890
+ MAX_COMMANDS_PER_BATCH,
1891
+ ORDER_NOTE_MAX,
1892
+ SUPPORTED_ORDER_CREATE_VERSIONS,
1893
+ SUPPORTED_ORDER_REFUND_VERSIONS,
1894
+ SUPPORTED_ORDER_REOPEN_VERSIONS,
1895
+ SUPPORTED_ORDER_UPDATE_VERSIONS,
1896
+ SUPPORTED_REGISTER_VERSIONS,
1897
+ canonicalJson,
1898
+ commandFingerprint,
1899
+ createMemoryDisplaySignalling,
1900
+ currencyDecimals,
1901
+ deriveSessionFigures,
1902
+ deriveVariance,
1903
+ displaySignallingContract,
1904
+ fiscalFiguresErrors,
1905
+ inProgressOutcome,
1906
+ internalErrorResult,
1907
+ majorToMinor,
1908
+ minorToMajor,
1909
+ minorUnitDigits,
1910
+ parseCommandResult,
1911
+ payloadBoundErrors,
1912
+ payloadShapeErrors,
1913
+ platformErrorResult,
1914
+ precheckCommand,
1915
+ ratePpmFromPercent,
1916
+ refundPayloadErrors,
1917
+ registerPayloadErrors,
1918
+ reopenPayloadErrors,
1919
+ totalWarnings,
1920
+ transientOutcome,
1921
+ updatePayloadErrors,
1922
+ validateBatch
1923
+ });