@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
@@ -3,7 +3,7 @@
3
3
  import type { SyncContext } from '../../types/connector';
4
4
  import {
5
5
  DISPLAY_PAIR_CAPABILITY, DisplaySignallingError,
6
- type DisplaySignalling, type DisplaySignallingContext, type DisplaySignallingErrorCode, type SignalMessage,
6
+ type DisplaySignalling, type DisplaySignallingContext, type DisplaySignallingErrorCode, type SignalMessage, type TillDevice,
7
7
  } from '../../types/display-signalling';
8
8
  import { rateLimitSource } from '../../customer-display/rate-limit-source';
9
9
 
@@ -18,7 +18,11 @@ export interface DisplaySignallingHarness {
18
18
  advance(ms: number): Promise<void>;
19
19
  /** Everything the server persists, serialised. */
20
20
  storedText(): Promise<string>;
21
- storedCounts(): Promise<{ codes: number; pending: number; displays: number; snapshots: number }>;
21
+ storedCounts(): Promise<{ codes: number; pending: number; displays: number; snapshots: number; devices: number }>;
22
+ /** Writes a pre-migration till: a device with no key, owning one paired display with a token. */
23
+ seedLegacyDevice(deviceId: string): Promise<{ displayId: string; token: string }>;
24
+ /** Every adoption of a pre-migration device id by `registerDevice`, in order. */
25
+ adoptionLog(): Promise<Array<{ deviceId: string; cashierId: string }>>;
22
26
  }
23
27
 
24
28
  const MINUTE = 60_000;
@@ -39,6 +43,14 @@ const newSecret = (): string =>
39
43
  export const sha256Hex = async (text: string): Promise<string> =>
40
44
  toHex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))));
41
45
 
46
+ /** Compares two strings in constant time for equal lengths; differing lengths are unequal. */
47
+ function sameText(x: string, y: string): boolean {
48
+ if (x.length !== y.length) return false;
49
+ let diff = 0;
50
+ for (let i = 0; i < x.length; i += 1) diff |= x.charCodeAt(i) ^ y.charCodeAt(i);
51
+ return diff === 0;
52
+ }
53
+
42
54
  /** `digits` uniform random decimal digits, by rejection sampling so no value is favoured. */
43
55
  function randomDigits(digits: number): string {
44
56
  const range = 10 ** digits, limit = Math.floor(2 ** 32 / range) * range;
@@ -61,6 +73,8 @@ interface Code { deviceId: string; expiresAt: number; spent: boolean }
61
73
  interface Pending { deviceId: string; secretHash: string; displayName: string; checkCode: string; expiresAt: number; movingDisplayId: string | null }
62
74
  interface Row { deviceId: string; name: string; cashierId: string; confirmedAt: number; lastSeenAt: number | null; tokenHash: string | null; secretHash: string | null }
63
75
  interface Window { openedAt: number; failures: number }
76
+ /** A till device; `keyHash` is null only for a pre-migration id, until it adopts. */
77
+ interface Device { keyHash: string | null; adopted: boolean; lastCallAt: number }
64
78
 
65
79
  /** The ADR-085 U2 reference server: every rule of the seam, in memory, with lazy pruning on every call. */
66
80
  export function createMemoryDisplaySignalling(options: { now?: () => number } = {}): { signalling: DisplaySignalling; harness: DisplaySignallingHarness } {
@@ -71,6 +85,7 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
71
85
  const codes = new Map<string, Code>(), pending = new Map<string, Pending>(), displays = new Map<string, Row>();
72
86
  const snapshots = new Map<string, { text: string; postedAt: number }>(), sources = new Map<string, Window>();
73
87
  const displayInbox = new Map<string, SignalMessage[]>(), tillInbox = new Map<string, Array<SignalMessage & { displayId: string }>>();
88
+ const devices = new Map<string, Device>(), adoptions: Array<{ deviceId: string; cashierId: string }> = [];
74
89
  let storeWindow: Window | null = null;
75
90
  const dropDisplay = (displayId: string): void => [displays, snapshots, displayInbox].forEach((map) => map.delete(displayId));
76
91
 
@@ -83,6 +98,8 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
83
98
  for (const [displayId, row] of displays) if (now >= (row.lastSeenAt ?? row.confirmedAt) + ROW_TTL) dropDisplay(displayId);
84
99
  for (const [key, window] of sources) if (now >= window.openedAt + SOURCE_WINDOW) sources.delete(key);
85
100
  if (storeWindow && now >= storeWindow.openedAt + STORE_WINDOW) storeWindow = null;
101
+ const owns = (id: string) => [...displays.values(), ...codes.values(), ...pending.values()].some((entry) => entry.deviceId === id);
102
+ for (const [id, device] of devices) if (now > device.lastCallAt + ROW_TTL && !owns(id)) devices.delete(id);
86
103
  return now;
87
104
  };
88
105
 
@@ -93,6 +110,18 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
93
110
  if (!session || !session.capabilities.includes(DISPLAY_PAIR_CAPABILITY)) throw fail('forbidden');
94
111
  return { now, cashierId: session.cashierId };
95
112
  };
113
+ /**
114
+ * Every till call's gate: hashes the key first, so no await follows, then admits the session and checks the key
115
+ * (`device_refused`), giving the call's time, cashier and device id. A missing key hashes to '' and never matches.
116
+ */
117
+ const tillCall = async (ctx: SyncContext, device: TillDevice): Promise<{ now: number; cashierId: string; deviceId: string }> => {
118
+ const keyHash = typeof device.deviceKey === 'string' && device.deviceKey !== '' ? await sha256Hex(device.deviceKey) : '';
119
+ const admitted = admit(ctx);
120
+ const known = devices.get(device.deviceId);
121
+ if (!known || known.keyHash === null || !sameText(keyHash, known.keyHash)) throw fail('device_refused');
122
+ known.lastCallAt = admitted.now;
123
+ return { ...admitted, deviceId: device.deviceId };
124
+ };
96
125
  /** The entry under `id` when `deviceId` owns it; `not_found` otherwise. */
97
126
  const ownedIn = <T extends { deviceId: string }>(map: Map<string, T>, deviceId: string, id: string): T => {
98
127
  const entry = map.get(id);
@@ -118,8 +147,19 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
118
147
  };
119
148
 
120
149
  const signalling: DisplaySignalling = {
121
- async mint(ctx, deviceId) {
122
- const { now } = admit(ctx);
150
+ async registerDevice(ctx, deviceId) {
151
+ const deviceKey = newSecret();
152
+ const keyHash = await sha256Hex(deviceKey);
153
+ const { now, cashierId } = admit(ctx);
154
+ const known = devices.get(deviceId);
155
+ if (known && (known.keyHash !== null || known.adopted)) throw fail('device_refused');
156
+ // A pre-migration id adopts: it keeps its rows, and only once.
157
+ if (known) adoptions.push({ deviceId, cashierId });
158
+ devices.set(deviceId, { keyHash, adopted: known !== undefined, lastCallAt: now });
159
+ return { deviceKey };
160
+ },
161
+ async mint(ctx, device) {
162
+ const { now, deviceId } = await tillCall(ctx, device);
123
163
  const unspent = [...codes.values()].filter((entry) => entry.deviceId === deviceId && !entry.spent).length;
124
164
  if (unspent >= MAX_UNSPENT) throw fail('limit');
125
165
  let code: string;
@@ -127,13 +167,13 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
127
167
  codes.set(code, { deviceId, expiresAt: now + CODE_TTL, spent: false });
128
168
  return { code, expiresAt: iso(now + CODE_TTL) };
129
169
  },
130
- async pending(ctx, deviceId) {
131
- admit(ctx);
170
+ async pending(ctx, device) {
171
+ const { deviceId } = await tillCall(ctx, device);
132
172
  return [...pending].filter(([, entry]) => entry.deviceId === deviceId)
133
173
  .map(([claimId, entry]) => ({ claimId, displayName: entry.displayName, checkCode: entry.checkCode, expiresAt: iso(entry.expiresAt) }));
134
174
  },
135
- async confirm(ctx, deviceId, claimId) {
136
- const { now, cashierId } = admit(ctx);
175
+ async confirm(ctx, device, claimId) {
176
+ const { now, cashierId, deviceId } = await tillCall(ctx, device);
137
177
  const entry = ownedIn(pending, deviceId, claimId);
138
178
  pending.delete(claimId);
139
179
  // A moving display: its old row, token and snapshot go in this same step, and its id carries over.
@@ -143,35 +183,35 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
143
183
  const row: Row = { deviceId, name: entry.displayName, cashierId, confirmedAt: now, lastSeenAt: null, tokenHash: null, secretHash: entry.secretHash };
144
184
  displays.set(moving ?? newId(), row);
145
185
  },
146
- async decline(ctx, deviceId, claimId) {
147
- admit(ctx);
186
+ async decline(ctx, device, claimId) {
187
+ const { deviceId } = await tillCall(ctx, device);
148
188
  ownedIn(pending, deviceId, claimId);
149
189
  pending.delete(claimId);
150
190
  },
151
- async list(ctx, deviceId) {
152
- const { now } = admit(ctx);
191
+ async list(ctx, device) {
192
+ const { now, deviceId } = await tillCall(ctx, device);
153
193
  return [...displays].filter(([, row]) => row.deviceId === deviceId).map(([displayId, row]) => ({
154
194
  displayId, name: row.name, cashierId: row.cashierId,
155
195
  lastSeenAt: row.lastSeenAt === null ? null : iso(row.lastSeenAt),
156
196
  connected: row.lastSeenAt !== null && now - row.lastSeenAt <= CONNECTED_MS,
157
197
  }));
158
198
  },
159
- async forget(ctx, deviceId, displayId) {
160
- admit(ctx);
199
+ async forget(ctx, device, displayId) {
200
+ const { deviceId } = await tillCall(ctx, device);
161
201
  ownedIn(displays, deviceId, displayId);
162
202
  dropDisplay(displayId);
163
203
  },
164
- async sendSignal(ctx, deviceId, displayId, message) {
165
- admit(ctx);
204
+ async sendSignal(ctx, device, displayId, message) {
205
+ const { deviceId } = await tillCall(ctx, device);
166
206
  ownedIn(displays, deviceId, displayId);
167
207
  displayInbox.set(displayId, [...(displayInbox.get(displayId) ?? []), { type: message.type, payload: message.payload }]);
168
208
  },
169
- async receiveSignals(ctx, deviceId) {
170
- admit(ctx);
209
+ async receiveSignals(ctx, device) {
210
+ const { deviceId } = await tillCall(ctx, device);
171
211
  return drain(tillInbox, deviceId).filter((message) => displays.get(message.displayId)?.deviceId === deviceId);
172
212
  },
173
- async postSnapshot(ctx, deviceId, displayId, body) {
174
- const { now } = admit(ctx);
213
+ async postSnapshot(ctx, device, displayId, body) {
214
+ const { now, deviceId } = await tillCall(ctx, device);
175
215
  ownedIn(displays, deviceId, displayId);
176
216
  const text = JSON.stringify(body) ?? 'null';
177
217
  if (new TextEncoder().encode(text).length > SNAPSHOT_MAX_BYTES) throw fail('too_large');
@@ -189,7 +229,8 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
189
229
  if (!entry || entry.spent) throw failedClaim(key, now);
190
230
  entry.spent = true;
191
231
  let checkCode: string;
192
- do checkCode = randomDigits(4); while ([...pending.values()].some((other) => other.checkCode === checkCode));
232
+ // Unique per till: a till lists only its own pending pairings, so only those must differ.
233
+ do checkCode = randomDigits(4); while ([...pending.values()].some((other) => other.deviceId === entry.deviceId && other.checkCode === checkCode));
193
234
  const movingDisplayId = tokenHash === null ? null : (findByTokenHash(tokenHash)?.[0] ?? null);
194
235
  pending.set(newId(), { deviceId: entry.deviceId, secretHash, displayName, checkCode, expiresAt: entry.expiresAt, movingDisplayId });
195
236
  return { claimSecret, checkCode };
@@ -238,13 +279,20 @@ export function createMemoryDisplaySignalling(options: { now?: () => number } =
238
279
  async storedText() {
239
280
  prune();
240
281
  return JSON.stringify({
241
- sessions: [...sessions], codes: [...codes], pending: [...pending], displays: [...displays], snapshots: [...snapshots], displayInbox: [...displayInbox], tillInbox: [...tillInbox], sources: [...sources], storeWindow,
282
+ sessions: [...sessions], devices: [...devices], codes: [...codes], pending: [...pending], displays: [...displays], snapshots: [...snapshots], displayInbox: [...displayInbox], tillInbox: [...tillInbox], sources: [...sources], storeWindow,
242
283
  });
243
284
  },
244
285
  async storedCounts() {
245
286
  prune();
246
- return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size };
287
+ return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size, devices: devices.size };
288
+ },
289
+ async seedLegacyDevice(deviceId) {
290
+ const token = newSecret(), displayId = newId(), now = clock();
291
+ devices.set(deviceId, { keyHash: null, adopted: false, lastCallAt: now });
292
+ displays.set(displayId, { deviceId, name: 'Legacy', cashierId: 'cashier-legacy', confirmedAt: now, lastSeenAt: null, tokenHash: await sha256Hex(token), secretHash: null });
293
+ return { displayId, token };
247
294
  },
295
+ adoptionLog: async () => adoptions.map((entry) => ({ ...entry })),
248
296
  };
249
297
  return { signalling, harness };
250
298
  }
@@ -7,7 +7,7 @@ export type CommandErrorWithData = CommandError
7
7
  /** @deprecated Use `OrderCreatePayload` from `@tallyui/core`; kept for plugins migrating from local copies. */
8
8
  export type OrderCreatePayloadV3 = OrderCreatePayload
9
9
 
10
- export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
10
+ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
11
11
  const errors: string[] = []
12
12
  const check = (valid: boolean, path: string, expected: string) => {
13
13
  if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`)
@@ -1,9 +1,11 @@
1
1
  export { currencyDecimals, minorToMajor, majorToMinor } from './money'
2
+ export { minorUnitDigits } from '../money'
3
+ export { ratePpmFromPercent } from './tax-rate'
2
4
  export { canonicalJson, commandFingerprint } from './fingerprint'
3
5
  export { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
4
6
  export { fiscalFiguresErrors } from './fiscal-figures'
5
7
  export type { CommandErrorWithData, OrderCreateDisplay, OrderCreateTaxRate, OrderCreatePayloadV3 } from './fiscal-figures'
6
- export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS } from './versions'
8
+ export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS } from './versions'
7
9
  export { MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX } from '../commands'
8
10
  export { validateBatch, precheckCommand } from './batch'
9
11
  export type { ValidatedCommandEnvelope } from './batch'
@@ -15,6 +17,8 @@ export type { OrderRejectionCode, Rejection } from './total-warnings'
15
17
  export { parseCommandResult, CommandResultError } from './command-result'
16
18
  export { registerPayloadErrors } from './register-payload-shape'
17
19
  export { refundPayloadErrors } from './refund-payload-shape'
20
+ export { reopenPayloadErrors } from './reopen-payload-shape'
21
+ export { updatePayloadErrors } from './update-payload-shape'
18
22
  export { deriveSessionFigures, deriveVariance } from './register-figures'
19
23
  export type { RegisterConflictCode, RegisterOutcome } from './register-outcome'
20
24
  export { platformErrorResult, internalErrorResult } from './rejection-codes'
@@ -1,4 +1,7 @@
1
- /** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
1
+ /**
2
+ * ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data.
3
+ * @deprecated Use `minorUnitDigits` (exported here and from `@tallyui/core`). It returns 2 for a code Intl rejects, where this throws.
4
+ */
2
5
  export function currencyDecimals(currency: string): number {
3
6
  return new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits!
4
7
  }
@@ -1,4 +1,4 @@
1
- import { ORDER_NOTE_MAX } from '../commands'
1
+ import { ORDER_LINE_SKU_MAX, ORDER_META_KEY_MAX, ORDER_META_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_TAX_IDS_MAX } from '../commands'
2
2
 
3
3
  /** Shape errors of an order.create payload, e.g. ['lines: expected a non-empty array',
4
4
  * 'payments[0].method: expected a string']; [] when the shape is valid, at most ten. Checks
@@ -43,6 +43,9 @@ export function payloadShapeErrors(payload: unknown): string[] {
43
43
  if (item[optionalString] !== undefined) {
44
44
  check(typeof item[optionalString] === 'string', `${path}.${optionalString}`, 'a string')
45
45
  }
46
+ if (!isLines && item.methodId !== undefined) {
47
+ check(typeof item.methodId === 'string' && item.methodId.length > 0, `${path}.methodId`, 'a non-empty string')
48
+ }
46
49
  if (isLines && item.taxInclusive !== undefined) {
47
50
  check(typeof item.taxInclusive === 'boolean', `${path}.taxInclusive`, 'a boolean')
48
51
  }
@@ -130,7 +133,8 @@ export function payloadShapeErrors(payload: unknown): string[] {
130
133
  if (items === undefined) continue
131
134
  check(Array.isArray(items), `${prefix}coupons`, 'an array')
132
135
  if (!Array.isArray(items)) continue
133
- const keys = prefix ? ['code', 'amountMinor'] : ['code', 'couponId', 'discountMinor', 'discountTaxMinor']
136
+ const keys = prefix ? ['code', 'amountMinor'] : ['code', 'couponId', 'discountMinor', 'discountTaxMinor', 'lines']
137
+ const hasLines = !prefix && items.some(item => object(item) && item.lines !== undefined)
134
138
  const seen = new Set<unknown>()
135
139
  items.forEach((item, index) => {
136
140
  const path = `${prefix}coupons[${index}]`
@@ -142,6 +146,40 @@ export function payloadShapeErrors(payload: unknown): string[] {
142
146
  if (!prefix) {
143
147
  check(!seen.has(item.code), `${path}.code`, 'no duplicate code')
144
148
  seen.add(item.code)
149
+ if (hasLines) check(Array.isArray(item.lines), `${path}.lines`, 'an array')
150
+ if (Array.isArray(item.lines)) {
151
+ const ids = Array.isArray(payload.lines) ? payload.lines.map(line => object(line) ? line.clientLineId : undefined) : []
152
+ const seenIds = new Set<unknown>()
153
+ let previous = -1
154
+ let validAmounts = true
155
+ let discountSum = 0n
156
+ let taxSum = 0n
157
+ item.lines.forEach((line, index) => {
158
+ const p = `${path}.lines[${index}]`
159
+ check(object(line), p, 'an object')
160
+ if (!object(line)) { validAmounts = false; previous = -1; return }
161
+ for (const key of Object.keys(line)) check(['clientLineId', 'discountMinor', 'discountTaxMinor'].includes(key), `${p}.${key}`, 'no unknown key')
162
+ const at = typeof line.clientLineId === 'string' ? ids.indexOf(line.clientLineId) : -1
163
+ check(at >= 0, `${p}.clientLineId`, 'a payload lines[].clientLineId')
164
+ check(!seenIds.has(line.clientLineId), `${p}.clientLineId`, 'no duplicate clientLineId')
165
+ seenIds.add(line.clientLineId)
166
+ if (at >= 0 && previous >= 0) check(at > previous, `${p}.clientLineId`, 'payload lines order')
167
+ previous = at
168
+ const valid = ['discountMinor', 'discountTaxMinor'].map(key => {
169
+ const valid = Number.isSafeInteger(line[key]) && (line[key] as number) >= 0
170
+ check(valid, `${p}.${key}`, 'a safe integer >= 0')
171
+ return valid
172
+ }).every(Boolean)
173
+ if (!valid) { validAmounts = false; return }
174
+ check(line.discountMinor !== 0 || line.discountTaxMinor !== 0, p, 'a non-zero discountMinor or discountTaxMinor')
175
+ discountSum += BigInt(line.discountMinor as number)
176
+ taxSum += BigInt(line.discountTaxMinor as number)
177
+ })
178
+ if (validAmounts && ['discountMinor', 'discountTaxMinor'].every(key => Number.isSafeInteger(item[key]) && (item[key] as number) >= 0)) {
179
+ check(discountSum === BigInt(item.discountMinor as number), `${path}.lines`, `discountMinor summing to ${path}.discountMinor`)
180
+ check(taxSum === BigInt(item.discountTaxMinor as number), `${path}.lines`, `discountTaxMinor summing to ${path}.discountTaxMinor`)
181
+ }
182
+ }
145
183
  }
146
184
  })
147
185
  }
@@ -163,7 +201,37 @@ export function payloadShapeErrors(payload: unknown): string[] {
163
201
  check(object(attributes) && Object.hasOwn(attributes, name) && typeof attributes[name] === 'string' && attributes[name].length > 0,
164
202
  at, `a key of ${path}.attributes with a non-empty value`)
165
203
  })
204
+ if (line.sku !== undefined) {
205
+ check(typeof line.sku === 'string' && line.sku.length > 0, `${path}.sku`, 'a non-empty string')
206
+ check(line.custom === undefined, `${path}.sku`, 'absent on a custom line (custom.sku)')
207
+ }
166
208
  })
209
+ // Version 12 (ADR-092): the customer's tax ids and the order's meta, closed objects in arrays.
210
+ const lists: Array<[string, unknown, string[]]> = [['customer.taxIds', object(payload.customer) ? payload.customer.taxIds : undefined, ['type', 'value', 'country']],
211
+ ['meta', payload.meta, ['key', 'value']]]
212
+ for (const [field, items, keys] of lists) {
213
+ if (items === undefined) continue
214
+ check(Array.isArray(items), field, 'an array')
215
+ if (!Array.isArray(items)) continue
216
+ const seen = new Set<unknown>()
217
+ items.forEach((item, index) => {
218
+ const path = `${field}[${index}]`
219
+ check(object(item), path, 'an object')
220
+ if (!object(item)) return
221
+ for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
222
+ if (field === 'meta') {
223
+ const key = item.key
224
+ check(typeof key === 'string' && key.length > 0, `${path}.key`, 'a non-empty string')
225
+ if (typeof key === 'string' && key.length > 0) check(!key.startsWith('_'), `${path}.key`, 'a key not starting with _')
226
+ check(typeof item.value === 'string', `${path}.value`, 'a string')
227
+ if (typeof key === 'string') check(!seen.has(key), `${path}.key`, 'no duplicate key')
228
+ seen.add(key)
229
+ return
230
+ }
231
+ for (const key of ['type', 'value']) check(typeof item[key] === 'string' && item[key].length > 0, `${path}.${key}`, 'a non-empty string')
232
+ if (item.country !== undefined) check(typeof item.country === 'string' && /^[A-Z]{2}$/.test(item.country), `${path}.country`, 'an ISO 3166-1 alpha-2 code')
233
+ })
234
+ }
167
235
  // NUL, only on strings (the checks above name any other type): Postgres text can't hold it, and the lookup keys must be clean.
168
236
  for (const [value, path] of payloadStrings(payload)) check(!value.includes('\u0000'), path, 'no NUL character')
169
237
  return errors
@@ -173,16 +241,28 @@ export function payloadShapeErrors(payload: unknown): string[] {
173
241
  const ORDER_ADDRESS_KEYS = ['firstName', 'lastName', 'company', 'address1', 'address2', 'city', 'state', 'postcode', 'country', 'phone']
174
242
 
175
243
  /** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
176
- * characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
244
+ * characters']; [] when every bound holds, at most ten. Bounds in UTF-16 code units:
177
245
  * `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v8 address fields 255, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
178
- * payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
246
+ * payloadShapeErrors); v12 (ADR-092) tax id type 32, value 64 and country 2, a line's `sku` 100, meta key 255 and value ORDER_NOTE_MAX.
247
+ * Each coupon's lines array is also capped at payload.lines.length, `customer.taxIds` at 10 entries and `meta` at 50. A plugin calls it through precheckCommand, after
179
248
  * its replay lookup, so a bound tightened later never turns an applied command's resend into
180
249
  * `invalid_payload`. */
181
250
  export function payloadBoundErrors(payload: unknown): string[] {
182
251
  if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return []
183
- return payloadStrings(payload as Record<string, unknown>)
252
+ const record = payload as Record<string, unknown>
253
+ const errors = payloadStrings(record)
184
254
  .filter(([value, , max]) => max !== undefined && value.length > max)
185
255
  .map(([, path, max]) => `${path}: expected at most ${max} characters`).slice(0, 10)
256
+ const max = Array.isArray(record.lines) ? record.lines.length : 0
257
+ if (Array.isArray(record.coupons)) record.coupons.forEach((coupon, index) => {
258
+ if (errors.length < 10 && typeof coupon === 'object' && coupon !== null && !Array.isArray(coupon)
259
+ && Array.isArray(coupon.lines) && coupon.lines.length > max) errors.push(`coupons[${index}].lines: expected at most ${max} entries`)
260
+ })
261
+ const customer = typeof record.customer === 'object' && record.customer !== null ? record.customer as Record<string, unknown> : {}
262
+ for (const [path, items, most] of [['customer.taxIds', customer.taxIds, ORDER_TAX_IDS_MAX], ['meta', record.meta, ORDER_META_MAX]] as const) {
263
+ if (errors.length < 10 && Array.isArray(items) && items.length > most) errors.push(`${path}: expected at most ${most} entries`)
264
+ }
265
+ return errors
186
266
  }
187
267
 
188
268
  /** Every string field order.create's checks cover, as [value, path, bound]; no bound for `customerId`
@@ -199,6 +279,7 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
199
279
  if (object(item)) for (const key of field === 'lines' ? ['clientLineId', 'variantId', 'title'] : ['clientPaymentId', 'method', 'reference']) {
200
280
  found.push([item[key], `${field}[${index}].${key}`, 255])
201
281
  }
282
+ if (object(item) && field === 'payments') found.push([item.methodId, `payments[${index}].methodId`, 64])
202
283
  })
203
284
  }
204
285
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
@@ -221,6 +302,9 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
221
302
  const items = object(parent) ? parent.coupons : undefined
222
303
  if (Array.isArray(items)) items.forEach((item, index) => {
223
304
  if (object(item)) for (const key of prefix ? ['code'] : ['code', 'couponId']) found.push([item[key], `${prefix}coupons[${index}].${key}`, key === 'code' ? 255 : 64])
305
+ if (!prefix && object(item) && Array.isArray(item.lines)) item.lines.forEach((line, j) => {
306
+ if (object(line)) found.push([line.clientLineId, `coupons[${index}].lines[${j}].clientLineId`, 255])
307
+ })
224
308
  })
225
309
  }
226
310
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
@@ -228,6 +312,13 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
228
312
  found.push([key, `lines[${index}].attributes`, 255], [value, `lines[${index}].attributes.${key}`, 255])
229
313
  }
230
314
  if (object(line) && Array.isArray(line.anyAttributes)) line.anyAttributes.forEach((name, i) => found.push([name, `lines[${index}].anyAttributes[${i}]`, 255]))
315
+ if (object(line)) found.push([line.sku, `lines[${index}].sku`, ORDER_LINE_SKU_MAX])
316
+ })
317
+ if (object(payload.customer) && Array.isArray(payload.customer.taxIds)) payload.customer.taxIds.forEach((taxId, index) => {
318
+ if (object(taxId)) for (const [key, max] of [['type', ORDER_TAX_ID_TYPE_MAX], ['value', ORDER_TAX_ID_VALUE_MAX], ['country', 2]] as const) found.push([taxId[key], `customer.taxIds[${index}].${key}`, max])
319
+ })
320
+ if (Array.isArray(payload.meta)) payload.meta.forEach((entry, index) => {
321
+ if (object(entry)) found.push([entry.key, `meta[${index}].key`, ORDER_META_KEY_MAX], [entry.value, `meta[${index}].value`, ORDER_NOTE_MAX])
231
322
  })
232
323
  if (object(payload.customer)) found.push([payload.customer.email, 'customer.email', 254], [payload.customer.customerId, 'customer.customerId', undefined])
233
324
  if (object(payload.customer)) for (const kind of ['billing', 'shipping']) {
@@ -1,15 +1,9 @@
1
+ import { isPlainObject, shapeErrors } from './shape-errors'
2
+
1
3
  /** Strict shape errors per ADR-070 and ADR-080 for order.refund v1; plugins run this before any lookup. */
2
4
  export function refundPayloadErrors(payload: unknown): string[] {
3
- const errors: string[] = []
4
- const object = (value: unknown): value is Record<string, unknown> =>
5
- typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
6
- const check = (valid: boolean, field: string, expected: string) => {
7
- if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`)
8
- }
9
- if (!object(payload)) return ['payload: expected an object']
10
- const noNul = (value: unknown, field: string) => {
11
- if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
12
- }
5
+ const { errors, check, noNul } = shapeErrors()
6
+ if (!isPlainObject(payload)) return ['payload: expected an object']
13
7
  const fields = ['clientRefundId', 'orderId', 'registerId', 'sessionId', 'clientOrderId', 'cashierRef',
14
8
  'lines', 'shippingMinor', 'totalMinor', 'adjustmentMinor', 'destination', 'reason', 'createdAt']
15
9
  for (const key of Object.keys(payload)) {
@@ -28,7 +22,7 @@ export function refundPayloadErrors(payload: unknown): string[] {
28
22
  const seen = new Set<string>()
29
23
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
30
24
  const path = `lines[${index}]`
31
- if (!object(line)) {
25
+ if (!isPlainObject(line)) {
32
26
  check(false, path, 'an object')
33
27
  return
34
28
  }
@@ -1,15 +1,9 @@
1
+ import { isPlainObject, shapeErrors } from './shape-errors'
2
+
1
3
  /** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
2
4
  export function registerPayloadErrors(type: string, payload: unknown): string[] {
3
- const errors: string[] = []
4
- const object = (value: unknown): value is Record<string, unknown> =>
5
- typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
6
- const check = (valid: boolean, field: string, expected: string) => {
7
- if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`)
8
- }
9
- if (!object(payload)) return ['payload: expected an object']
10
- const noNul = (value: unknown, field: string) => {
11
- if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
12
- }
5
+ const { errors, check, noNul } = shapeErrors()
6
+ if (!isPlainObject(payload)) return ['payload: expected an object']
13
7
  const string = (field: string, optional = false) => {
14
8
  const value = payload[field]
15
9
  if (optional && value === undefined) return
@@ -24,8 +18,8 @@ export function registerPayloadErrors(type: string, payload: unknown): string[]
24
18
  check(Number.isSafeInteger(payload[field]) && (payload[field] as number) >= min, field, `a safe integer >= ${min}`)
25
19
  const record = (field: string) => {
26
20
  const value = payload[field]
27
- check(object(value), field, 'a record of integers')
28
- if (object(value)) for (const [key, amount] of Object.entries(value)) {
21
+ check(isPlainObject(value), field, 'a record of integers')
22
+ if (isPlainObject(value)) for (const [key, amount] of Object.entries(value)) {
29
23
  check(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, 'a non-empty key with a safe integer')
30
24
  noNul(key, `${field}.${JSON.stringify(key)}`) // quoted, so the NUL is never echoed raw
31
25
  }
@@ -1,4 +1,4 @@
1
- import type { CommandResult, OrderRefundRejectionCode } from '../types'
1
+ import type { CommandResult, OrderRefundRejectionCode, OrderReopenRejectionCode, OrderUpdateRejectionCode } from '../types'
2
2
  import type { OrderRejectionCode } from './total-warnings'
3
3
  import type { RegisterConflictCode } from './register-outcome'
4
4
 
@@ -8,12 +8,12 @@ export type CommandRejectionCode =
8
8
  | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error'
9
9
  // Both are order.create v6 refusals (ADR-077 d4).
10
10
  | 'coupon_invalid' | 'total_mismatch'
11
- | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode
11
+ | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode | OrderReopenRejectionCode | OrderUpdateRejectionCode
12
12
 
13
13
  /**
14
14
  * The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
15
15
  * the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
16
- * for `order.create` and `order.refund` (ADR-080): a rejected register command halts that register's queue until c2c,
16
+ * for `order.create` and `order.refund` (ADR-080) and `order.reopen` and `order.update` (ADR-090): a rejected register command halts that register's queue until c2c,
17
17
  * so register refusals use the ADR-068 codes.
18
18
  *
19
19
  * Return it only when the platform made no durable change for this command: the plugin threw so its
@@ -40,7 +40,7 @@ export function platformErrorResult(id: string, platformCode: string, platformMe
40
40
  * the correlation id links it to the plugin's log.
41
41
  *
42
42
  * Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
43
- * `internal_error`. `order.create` and `order.refund` (ADR-080), as for `platform_error`.
43
+ * `internal_error`. `order.create` and `order.refund` (ADR-080) and `order.reopen` and `order.update` (ADR-090), as for `platform_error`.
44
44
  *
45
45
  * See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
46
46
  * before the first write).
@@ -0,0 +1,25 @@
1
+ import { isPlainObject, shapeErrors } from './shape-errors'
2
+
3
+ /** Strict shape errors per ADR-070 and ADR-090 for order.reopen v1; plugins run this before any lookup. */
4
+ export function reopenPayloadErrors(payload: unknown): string[] {
5
+ const { errors, check, noNul } = shapeErrors()
6
+ if (!isPlainObject(payload)) return ['payload: expected an object']
7
+ const fields = ['orderId', 'clientOrderId', 'baseRevision', 'cashierRef', 'registerId', 'storeId', 'createdAt']
8
+ for (const key of Object.keys(payload)) {
9
+ if (!fields.includes(key) && errors.length < 10) {
10
+ errors.push(`${key.includes('\u0000') ? JSON.stringify(key) : key}: unknown field for order.reopen version 1`)
11
+ }
12
+ }
13
+ for (const field of ['orderId', 'cashierRef', 'registerId', 'clientOrderId', 'baseRevision', 'storeId']) {
14
+ const value = payload[field]
15
+ if (['clientOrderId', 'baseRevision', 'storeId'].includes(field) && value === undefined) continue
16
+ const max = field === 'baseRevision' ? 128 : 64
17
+ check(typeof value === 'string' && value.length > 0 && value.length <= max,
18
+ field, `a non-empty string of at most ${max} characters`)
19
+ noNul(value, field)
20
+ }
21
+ check(typeof payload.createdAt === 'string' && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
22
+ 'createdAt', 'a valid date')
23
+ noNul(payload.createdAt, 'createdAt')
24
+ return errors
25
+ }
@@ -0,0 +1,17 @@
1
+ /** A plain object: `{}` or `Object.create(null)`, never an array, a class instance or null. */
2
+ export function isPlainObject(value: unknown): value is Record<string, unknown> {
3
+ return typeof value === 'object' && value !== null
4
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
5
+ }
6
+
7
+ /** The validators' shared error list: at most 10 `<field>: expected <what>` lines, in the order checked. */
8
+ export function shapeErrors() {
9
+ const errors: string[] = []
10
+ const check = (valid: boolean, field: string, expected: string) => {
11
+ if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`)
12
+ }
13
+ const noNul = (value: unknown, field: string) => {
14
+ if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
15
+ }
16
+ return { errors, check, noNul }
17
+ }
@@ -0,0 +1,13 @@
1
+ /** Converts a plain decimal percentage with at most four fractional digits to safe integer ppm. */
2
+ export function ratePpmFromPercent(percent: number | string): number {
3
+ const value = String(percent);
4
+ const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(value);
5
+ if (!match || match[0] !== value) {
6
+ throw new RangeError('Percent must be a plain decimal with at most four fractional digits');
7
+ }
8
+ const ratePpm = BigInt(match[1]) * 10000n + BigInt((match[2] ?? '').padEnd(4, '0'));
9
+ if (ratePpm > BigInt(Number.MAX_SAFE_INTEGER)) {
10
+ throw new RangeError('Rate must be a safe integer');
11
+ }
12
+ return Number(ratePpm);
13
+ }
@@ -0,0 +1,51 @@
1
+ import { payloadShapeErrors } from './order-payload-shape'
2
+ import { isPlainObject, shapeErrors } from './shape-errors'
3
+
4
+ function updateOnlyErrors(payload: unknown): string[] {
5
+ const { errors, check } = shapeErrors()
6
+ if (!isPlainObject(payload)) return ['payload: expected an object']
7
+ const body = payload as Record<string, unknown>
8
+ const id = (value: unknown, field: string) => {
9
+ const max = field === 'baseRevision' ? 128 : 64
10
+ check(typeof value === 'string' && value.length > 0 && value.length <= max, field, `a non-empty string of at most ${max} characters`)
11
+ if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
12
+ }
13
+ id(body.orderId, 'orderId')
14
+ if (body.baseRevision !== undefined) id(body.baseRevision, 'baseRevision')
15
+ check(Number.isSafeInteger(body.createVersion) && (body.createVersion as number) >= 1, 'createVersion', 'a positive safe integer')
16
+ const seenIds = { storeLineId: new Set<unknown>(), paymentId: new Set<unknown>() }
17
+ for (const [field, key] of [['lines', 'storeLineId'], ['fees', 'storeLineId'], ['shipping', 'storeLineId'], ['payments', 'paymentId']] as const) {
18
+ const items = body[field], seen = seenIds[key]
19
+ if (!Array.isArray(items)) continue
20
+ for (const [index, item] of items.entries()) {
21
+ if (typeof item !== 'object' || item === null || Array.isArray(item) || item[key] === undefined) continue
22
+ id(item[key], `${field}[${index}].${key}`)
23
+ check(!seen.has(item[key]), `${field}[${index}].${key}`, 'unique')
24
+ seen.add(item[key])
25
+ }
26
+ }
27
+ return errors
28
+ }
29
+
30
+ /** Strict update identity and order.create body shape errors, at most ten (ADR-090). */
31
+ export function updatePayloadErrors(payload: unknown): string[] {
32
+ const errors = updateOnlyErrors(payload)
33
+ if (errors[0] === 'payload: expected an object') return errors
34
+ return [...errors, ...payloadShapeErrors(orderCreatePart(payload as Record<string, unknown>))].slice(0, 10)
35
+ }
36
+
37
+ /** Copies the body without orderId, baseRevision, createVersion, lines/fees/shipping storeLineId or payments paymentId (ADR-090). */
38
+ export function orderCreatePart(payload: Record<string, unknown>): Record<string, unknown> {
39
+ const part = { ...payload }
40
+ for (const key of ['orderId', 'baseRevision', 'createVersion']) delete part[key]
41
+ for (const [field, key] of [['lines', 'storeLineId'], ['fees', 'storeLineId'], ['shipping', 'storeLineId'], ['payments', 'paymentId']] as const) {
42
+ const items = part[field]
43
+ if (Array.isArray(items)) part[field] = items.map(item => {
44
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) return item
45
+ const copy = { ...item }
46
+ delete copy[key]
47
+ return copy
48
+ })
49
+ }
50
+ return part
51
+ }