@tallyui/core 0.2.0 → 3.0.0-next.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunk-C4PWPOKO.js +18 -0
  3. package/dist/commands-BW4YYgRG.d.ts +306 -0
  4. package/dist/index.d.ts +636 -8
  5. package/dist/index.js +468 -4
  6. package/dist/rxdb/index.d.ts +37 -0
  7. package/dist/rxdb/index.js +26 -0
  8. package/dist/server/index.d.ts +213 -0
  9. package/dist/server/index.js +591 -0
  10. package/package.json +33 -3
  11. package/src/commands.ts +32 -0
  12. package/src/context/connector-context.tsx +78 -4
  13. package/src/index.ts +53 -0
  14. package/src/known-warnings.ts +77 -0
  15. package/src/money.ts +142 -0
  16. package/src/replication/combine.ts +77 -0
  17. package/src/replication/reconcile-feed.ts +116 -0
  18. package/src/rxdb/index.ts +4 -0
  19. package/src/rxdb/read-fresh.ts +32 -0
  20. package/src/rxdb/watch-fresh.ts +19 -0
  21. package/src/rxdb-remote-version-mismatch.ts +30 -0
  22. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  23. package/src/server/__fixtures__/order-create-v3.json +97 -0
  24. package/src/server/batch-outcome.ts +19 -0
  25. package/src/server/batch.ts +112 -0
  26. package/src/server/command-result.ts +138 -0
  27. package/src/server/fingerprint.ts +18 -0
  28. package/src/server/fiscal-figures.ts +84 -0
  29. package/src/server/index.ts +20 -0
  30. package/src/server/money.ts +34 -0
  31. package/src/server/order-payload-shape.ts +112 -0
  32. package/src/server/register-figures.ts +32 -0
  33. package/src/server/register-outcome.ts +12 -0
  34. package/src/server/register-payload-shape.ts +86 -0
  35. package/src/server/rejection-codes.ts +49 -0
  36. package/src/server/total-warnings.ts +10 -0
  37. package/src/server/versions.ts +9 -0
  38. package/src/sign-in.ts +21 -0
  39. package/src/stock-overlay.ts +35 -0
  40. package/src/store-settings.ts +29 -0
  41. package/src/sync-notice.ts +26 -0
  42. package/src/types/commands.ts +236 -0
  43. package/src/types/connector.ts +127 -0
  44. package/src/types/customers.ts +26 -0
  45. package/src/types/index.ts +23 -1
  46. package/src/types/money.ts +33 -0
  47. package/src/types/reconcile.ts +73 -0
  48. package/src/types/replication.ts +12 -0
  49. package/src/types/stock.ts +18 -0
  50. package/src/types/store-settings.ts +27 -0
  51. package/src/types/traits/product.ts +62 -6
  52. package/src/unauthorized.ts +13 -0
  53. package/src/utils/compare-ids.ts +16 -0
  54. package/src/variants.ts +14 -0
  55. package/src/__tests__/connector-context.test.tsx +0 -100
  56. package/src/types/replication.test-d.ts +0 -20
@@ -0,0 +1,19 @@
1
+ import { type Observable, startWith, switchMap } from 'rxjs';
2
+ import type { MangoQuery, RxCollection } from 'rxdb';
3
+ import { readFresh } from './read-fresh';
4
+
5
+ /**
6
+ * RxDB 17 fixed RxDB 16.21.1's bug 4 (rxdb#7067); `readFresh`, `countFresh` and `watchFresh`
7
+ * remain correct public API. Retiring them is a separate decision.
8
+ * `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
9
+ * `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
10
+ * still in flight when a newer one starts. It is one event per storage change bulk, not per
11
+ * document (`collection.$`), so a `bulkInsert` of 100 documents costs one re-read, not 100. Still
12
+ * one storage read per write, so it's for a list a cashier would act on going stale, not every list.
13
+ */
14
+ export function watchFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Observable<T[]> {
15
+ return collection.eventBulks$.pipe(
16
+ startWith(null),
17
+ switchMap(() => readFresh(collection, query)),
18
+ );
19
+ }
@@ -0,0 +1,30 @@
1
+ // How RxDB's remote storage re-throws a worker's rejected createStorageInstance on the main thread
2
+ // (rxdb 17.5.0 src/plugins/storage-remote/rx-storage-remote.ts:100):
3
+ // `new Error('could not create instance ' + JSON.stringify(error))`.
4
+ const REMOTE_CREATE_PREFIX = 'could not create instance ';
5
+
6
+ /**
7
+ * True for RxDB's RM1: the remote storage worker was built on another RxDB
8
+ * version than the main thread, e.g. a stale worker the browser cached from
9
+ * before an upgrade. Reloading loads the matching worker.
10
+ *
11
+ * Matched by structure, never by substring. An `RxError` (rxdb 17.5.0
12
+ * src/rx-error.ts) has own `code`, `message`, `url`, `parameters` and
13
+ * `rxdb: true`; its `name` is a getter. So RM1 is either an object whose own
14
+ * `code` is `'RM1'` (with `rxdb === true` when `rxdb` is present), or an
15
+ * error, `{ message }` copy or string whose message is the remote storage's
16
+ * `could not create instance ` followed by JSON with `rxdb: true` and
17
+ * `code: 'RM1'`. Needs no rxdb import.
18
+ */
19
+ export function isRxdbRemoteVersionMismatch(error: unknown): boolean {
20
+ const { code, rxdb, message } = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>;
21
+ if (code === 'RM1' && (rxdb ?? true) === true) return true;
22
+ const text = typeof error === 'string' ? error : message;
23
+ if (typeof text !== 'string' || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
24
+ try {
25
+ const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length)) as Record<string, unknown> | null;
26
+ return wrapped?.rxdb === true && wrapped.code === 'RM1';
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
@@ -0,0 +1,139 @@
1
+ [
2
+ {
3
+ "name": "order-create-v3 golden fixture",
4
+ "envelope": {
5
+ "type": "order.create",
6
+ "version": 3,
7
+ "payload": {
8
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000002",
9
+ "createdAt": "2026-09-28T10:00:00.000Z",
10
+ "currency": "EUR",
11
+ "pricesIncludeTax": true,
12
+ "lines": [
13
+ {
14
+ "clientLineId": "line_inclusive",
15
+ "variantId": "variant_inclusive",
16
+ "title": "Inclusive item",
17
+ "quantity": 2,
18
+ "unitPriceMinor": 1200,
19
+ "discountMinor": 203
20
+ },
21
+ {
22
+ "clientLineId": "line_exclusive",
23
+ "variantId": "variant_exclusive",
24
+ "title": "Exclusive item",
25
+ "quantity": 1,
26
+ "unitPriceMinor": 1000,
27
+ "taxInclusive": false,
28
+ "discountMinor": 37
29
+ }
30
+ ],
31
+ "payments": [
32
+ {
33
+ "clientPaymentId": "payment_cash",
34
+ "method": "cash",
35
+ "amountMinor": 3256,
36
+ "tenderedMinor": 4000,
37
+ "changeMinor": 744,
38
+ "reference": "cash_receipt_1"
39
+ }
40
+ ],
41
+ "subtotalMinor": 2794,
42
+ "discountMinor": 240,
43
+ "taxMinor": 462,
44
+ "totalMinor": 3256,
45
+ "display": {
46
+ "currency": "EUR",
47
+ "exponent": 2,
48
+ "taxInclusive": true,
49
+ "subtotalMinor": 3500,
50
+ "discountMinor": 244,
51
+ "taxMinor": 462,
52
+ "totalMinor": 3256,
53
+ "lines": [
54
+ {
55
+ "clientLineId": "line_inclusive",
56
+ "amountMinor": 2400,
57
+ "discounts": [
58
+ {
59
+ "discountId": "discount_line",
60
+ "label": "Line discount",
61
+ "amountMinor": 120
62
+ }
63
+ ]
64
+ },
65
+ {
66
+ "clientLineId": "line_exclusive",
67
+ "amountMinor": 1100,
68
+ "discounts": []
69
+ }
70
+ ],
71
+ "orderDiscountMinor": 124
72
+ },
73
+ "taxByRate": [
74
+ {
75
+ "ratePpm": 200000,
76
+ "code": "VAT20",
77
+ "netMinor": 1831,
78
+ "taxMinor": 366,
79
+ "grossMinor": 2197
80
+ },
81
+ {
82
+ "ratePpm": 100000,
83
+ "netMinor": 963,
84
+ "taxMinor": 96,
85
+ "grossMinor": 1059
86
+ }
87
+ ],
88
+ "customer": {
89
+ "email": "buyer@example.com",
90
+ "customerId": "cus_golden_v3"
91
+ },
92
+ "registerId": "register_golden",
93
+ "cashierRef": "cashier_golden",
94
+ "sessionId": "019f6d2e-7800-7000-8000-000000000003"
95
+ }
96
+ },
97
+ "canonical": "{\"payload\":{\"cashierRef\":\"cashier_golden\",\"clientOrderId\":\"019f6d2e-7800-7000-8000-000000000002\",\"createdAt\":\"2026-09-28T10:00:00.000Z\",\"currency\":\"EUR\",\"customer\":{\"customerId\":\"cus_golden_v3\",\"email\":\"buyer@example.com\"},\"discountMinor\":240,\"display\":{\"currency\":\"EUR\",\"discountMinor\":244,\"exponent\":2,\"lines\":[{\"amountMinor\":2400,\"clientLineId\":\"line_inclusive\",\"discounts\":[{\"amountMinor\":120,\"discountId\":\"discount_line\",\"label\":\"Line discount\"}]},{\"amountMinor\":1100,\"clientLineId\":\"line_exclusive\",\"discounts\":[]}],\"orderDiscountMinor\":124,\"subtotalMinor\":3500,\"taxInclusive\":true,\"taxMinor\":462,\"totalMinor\":3256},\"lines\":[{\"clientLineId\":\"line_inclusive\",\"discountMinor\":203,\"quantity\":2,\"title\":\"Inclusive item\",\"unitPriceMinor\":1200,\"variantId\":\"variant_inclusive\"},{\"clientLineId\":\"line_exclusive\",\"discountMinor\":37,\"quantity\":1,\"taxInclusive\":false,\"title\":\"Exclusive item\",\"unitPriceMinor\":1000,\"variantId\":\"variant_exclusive\"}],\"payments\":[{\"amountMinor\":3256,\"changeMinor\":744,\"clientPaymentId\":\"payment_cash\",\"method\":\"cash\",\"reference\":\"cash_receipt_1\",\"tenderedMinor\":4000}],\"pricesIncludeTax\":true,\"registerId\":\"register_golden\",\"sessionId\":\"019f6d2e-7800-7000-8000-000000000003\",\"subtotalMinor\":2794,\"taxByRate\":[{\"code\":\"VAT20\",\"grossMinor\":2197,\"netMinor\":1831,\"ratePpm\":200000,\"taxMinor\":366},{\"grossMinor\":1059,\"netMinor\":963,\"ratePpm\":100000,\"taxMinor\":96}],\"taxMinor\":462,\"totalMinor\":3256},\"type\":\"order.create\",\"version\":3}",
98
+ "fingerprint": "aea62fe9f460bbdfd93771cbe08b3bb98e5761f172b974b62d72dfe30f6bc436"
99
+ },
100
+ {
101
+ "name": "key order, nested objects, undefined field dropped",
102
+ "envelope": {
103
+ "type": "order.create",
104
+ "version": 1,
105
+ "payload": {
106
+ "z": 1,
107
+ "a": {
108
+ "d": [
109
+ 3,
110
+ 1,
111
+ 2
112
+ ],
113
+ "c": "x"
114
+ },
115
+ "m": null
116
+ }
117
+ },
118
+ "canonical": "{\"payload\":{\"a\":{\"c\":\"x\",\"d\":[3,1,2]},\"m\":null,\"z\":1},\"type\":\"order.create\",\"version\":1}",
119
+ "fingerprint": "cecf2c94e7da1867b95b66d5e46e686bf274f780e312efb2d8387841cc00d483"
120
+ },
121
+ {
122
+ "name": "undefined array item becomes null; unicode and negative numbers",
123
+ "envelope": {
124
+ "type": "register.movement.record",
125
+ "version": 1,
126
+ "payload": {
127
+ "items": [
128
+ 1,
129
+ null,
130
+ "é",
131
+ -0.5
132
+ ],
133
+ "reason": "café \"quoted\""
134
+ }
135
+ },
136
+ "canonical": "{\"payload\":{\"items\":[1,null,\"é\",-0.5],\"reason\":\"café \\\"quoted\\\"\"},\"type\":\"register.movement.record\",\"version\":1}",
137
+ "fingerprint": "95316177d791a50f25937d646cae922766e33dc77e3287b3dbec791f9c410948"
138
+ }
139
+ ]
@@ -0,0 +1,97 @@
1
+ {
2
+ "id": "019f6d2e-7800-7000-8000-000000000001",
3
+ "type": "order.create",
4
+ "version": 3,
5
+ "createdAt": "2026-09-28T10:00:00.000Z",
6
+ "deviceId": "device_golden",
7
+ "attempt": 1,
8
+ "payload": {
9
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000002",
10
+ "createdAt": "2026-09-28T10:00:00.000Z",
11
+ "currency": "EUR",
12
+ "pricesIncludeTax": true,
13
+ "lines": [
14
+ {
15
+ "clientLineId": "line_inclusive",
16
+ "variantId": "variant_inclusive",
17
+ "title": "Inclusive item",
18
+ "quantity": 2,
19
+ "unitPriceMinor": 1200,
20
+ "discountMinor": 203
21
+ },
22
+ {
23
+ "clientLineId": "line_exclusive",
24
+ "variantId": "variant_exclusive",
25
+ "title": "Exclusive item",
26
+ "quantity": 1,
27
+ "unitPriceMinor": 1000,
28
+ "taxInclusive": false,
29
+ "discountMinor": 37
30
+ }
31
+ ],
32
+ "payments": [
33
+ {
34
+ "clientPaymentId": "payment_cash",
35
+ "method": "cash",
36
+ "amountMinor": 3256,
37
+ "tenderedMinor": 4000,
38
+ "changeMinor": 744,
39
+ "reference": "cash_receipt_1"
40
+ }
41
+ ],
42
+ "subtotalMinor": 2794,
43
+ "discountMinor": 240,
44
+ "taxMinor": 462,
45
+ "totalMinor": 3256,
46
+ "display": {
47
+ "currency": "EUR",
48
+ "exponent": 2,
49
+ "taxInclusive": true,
50
+ "subtotalMinor": 3500,
51
+ "discountMinor": 244,
52
+ "taxMinor": 462,
53
+ "totalMinor": 3256,
54
+ "lines": [
55
+ {
56
+ "clientLineId": "line_inclusive",
57
+ "amountMinor": 2400,
58
+ "discounts": [
59
+ {
60
+ "discountId": "discount_line",
61
+ "label": "Line discount",
62
+ "amountMinor": 120
63
+ }
64
+ ]
65
+ },
66
+ {
67
+ "clientLineId": "line_exclusive",
68
+ "amountMinor": 1100,
69
+ "discounts": []
70
+ }
71
+ ],
72
+ "orderDiscountMinor": 124
73
+ },
74
+ "taxByRate": [
75
+ {
76
+ "ratePpm": 200000,
77
+ "code": "VAT20",
78
+ "netMinor": 1831,
79
+ "taxMinor": 366,
80
+ "grossMinor": 2197
81
+ },
82
+ {
83
+ "ratePpm": 100000,
84
+ "netMinor": 963,
85
+ "taxMinor": 96,
86
+ "grossMinor": 1059
87
+ }
88
+ ],
89
+ "customer": {
90
+ "email": "buyer@example.com",
91
+ "customerId": "cus_golden_v3"
92
+ },
93
+ "registerId": "register_golden",
94
+ "cashierRef": "cashier_golden",
95
+ "sessionId": "019f6d2e-7800-7000-8000-000000000003"
96
+ }
97
+ }
@@ -0,0 +1,19 @@
1
+ import type { CommandBatchResponse } from '../types'
2
+
3
+ /**
4
+ * A plugin's batch handler stops at the first in-progress or transient command and returns that
5
+ * outcome for the whole batch; otherwise it returns 200 with every result in order.
6
+ */
7
+ export type BatchOutcome =
8
+ | { status: 200; body: CommandBatchResponse }
9
+ | { status: 409; body: { code: 'in_progress'; id: string } }
10
+ | { status: 503; body: { code: 'transient'; id: string; message: 'Temporary failure, retry later.' } }
11
+
12
+ export function inProgressOutcome(id: string): BatchOutcome {
13
+ return { status: 409, body: { code: 'in_progress', id } }
14
+ }
15
+
16
+ /** The message is fixed so a server never leaks its internal error (log that separately). */
17
+ export function transientOutcome(id: string): BatchOutcome {
18
+ return { status: 503, body: { code: 'transient', id, message: 'Temporary failure, retry later.' } }
19
+ }
@@ -0,0 +1,112 @@
1
+ import { MAX_COMMANDS_PER_BATCH } from '../commands'
2
+ import type { AnyCommandEnvelope, BatchTooLargeBody, CommandEnvelope, CommandResult, OrderCreatePayload, RegisterCommandEnvelope } from '../types'
3
+ import { fiscalFiguresErrors, type OrderCreatePayloadV3 } from './fiscal-figures'
4
+ import { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
5
+
6
+ /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
7
+ * safe integer (precheckCommand decides which versions this server supports). */
8
+ export type ValidatedCommandEnvelope =
9
+ | (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & { type: 'order.create'; version: number })
10
+ | RegisterCommandEnvelope<Record<string, unknown>>
11
+
12
+ /** Validates every envelope before any command is claimed. */
13
+ export function validateBatch(body: unknown):
14
+ | { ok: true; commands: ValidatedCommandEnvelope[] }
15
+ | { ok: false; status: 400; message: string }
16
+ | { ok: false; status: 413; message: string; body: BatchTooLargeBody } {
17
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
18
+ return { ok: false, status: 400, message: 'Expected body object with commands array' }
19
+ }
20
+ const { commands } = body as Record<string, unknown>
21
+ if (!Array.isArray(commands)) return { ok: false, status: 400, message: 'Expected commands array' }
22
+ if (commands.length > MAX_COMMANDS_PER_BATCH) {
23
+ const message = `At most ${MAX_COMMANDS_PER_BATCH} commands are allowed`
24
+ return { ok: false, status: 413, message, body: { code: 'batch_too_large', maxCommands: MAX_COMMANDS_PER_BATCH, message } }
25
+ }
26
+ if (commands.length === 0) return { ok: false, status: 400, message: 'commands must not be empty' }
27
+ for (const [index, command] of commands.entries()) {
28
+ if (typeof command !== 'object' || command === null || Array.isArray(command)) {
29
+ return { ok: false, status: 400, message: `Invalid commands[${index}]: expected object` }
30
+ }
31
+ let field: string | undefined
32
+ if (typeof command.id !== 'string' || command.id.length === 0 || command.id.length > 64) field = 'id'
33
+ else if (!['order.create', 'register.session.open', 'register.session.transition', 'register.movement.record',
34
+ 'register.movement.void', 'register.closure.submit'].includes(command.type)) field = 'type'
35
+ else if (!Number.isSafeInteger(command.version) || command.version < 1) field = 'version'
36
+ else if (typeof command.payload !== 'object' || command.payload === null || Array.isArray(command.payload)) field = 'payload'
37
+ else if (typeof command.createdAt !== 'string') field = 'createdAt'
38
+ else if (typeof command.deviceId !== 'string') field = 'deviceId'
39
+ else if (!Number.isSafeInteger(command.attempt) || command.attempt < 1) field = 'attempt'
40
+ if (field) return { ok: false, status: 400, message: `Invalid commands[${index}].${field}` }
41
+ }
42
+ return { ok: true, commands }
43
+ }
44
+
45
+ /**
46
+ * The rejection a batch returns for this command before any executor runs, or undefined
47
+ * when the command goes on to the plugin's executor. A plugin's batch handler calls
48
+ * validateBatch once, then, for each command in order: the shape check (payloadShapeErrors:
49
+ * types and NUL) first, before any database access, because a NUL in clientOrderId would make
50
+ * the lookup itself fail; then the plugin's own replay and collision lookups; then
51
+ * precheckCommand (versions, string lengths via payloadBoundErrors, fiscal figures); then the
52
+ * claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
53
+ * one of those steps returns and moves on.
54
+ *
55
+ * The replay lookup goes before precheckCommand so an already-applied command always replays
56
+ * as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
57
+ *
58
+ * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
59
+ * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
60
+ * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1] })`.
61
+ */
62
+ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
63
+ supported: { orderCreate: readonly number[]; register: readonly number[] }): CommandResult | undefined {
64
+ // An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
65
+ for (const key of ['orderCreate', 'register'] as const) {
66
+ if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
67
+ }
68
+ if (envelope.type !== 'order.create') {
69
+ if (!supported.register.includes(envelope.version)) {
70
+ return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
71
+ message: `register version ${envelope.version} is not supported; this server supports ${supported.register.join(', ')}`,
72
+ data: { register: Math.max(...supported.register) },
73
+ } }
74
+ }
75
+ return undefined
76
+ }
77
+ const command = envelope as CommandEnvelope<OrderCreatePayload>
78
+ if (!supported.orderCreate.includes(command.version)) {
79
+ return { id: command.id, status: 'rejected', error: { code: 'unsupported_version',
80
+ message: `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(', ')}`,
81
+ data: { orderCreate: Math.max(...supported.orderCreate) },
82
+ } }
83
+ }
84
+ // ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
85
+ const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
86
+ const discounted = discountMinor !== undefined
87
+ || (Array.isArray(lines) && lines.some(line => (line as { discountMinor?: unknown } | null)?.discountMinor !== undefined))
88
+ const payload = command.payload as OrderCreatePayloadV3
89
+ const { display, taxByRate, sessionId } = payload
90
+ // Version 4 carries version 3's fields (#286); only what discountMinor means changes.
91
+ const v3 = command.version >= 3
92
+ const versionError = command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
93
+ : command.version === 1 && discounted ? 'discountMinor requires version 2'
94
+ : !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
95
+ : !v3 && sessionId !== undefined ? 'sessionId requires version 3'
96
+ : !v3 && payload.customer?.customerId !== undefined ? 'customerId requires version 3'
97
+ : v3 && (display !== undefined) !== (taxByRate !== undefined) ? 'display and taxByRate must both be present or both absent'
98
+ : undefined
99
+ if (versionError) {
100
+ return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: versionError } }
101
+ }
102
+ const bounds = payloadBoundErrors(payload)
103
+ if (bounds.length) {
104
+ return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: bounds.slice(0, 10).join('; ') } }
105
+ }
106
+ const errors = v3 && display !== undefined && taxByRate !== undefined && payloadShapeErrors(payload).length === 0
107
+ ? fiscalFiguresErrors(payload) : []
108
+ if (errors.length) {
109
+ return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: errors.slice(0, 10).join('; ') } }
110
+ }
111
+ return undefined
112
+ }
@@ -0,0 +1,138 @@
1
+ import type { CommandResult, RegisterCommandResult } from '../types'
2
+
3
+ /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
4
+ * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
5
+ export class CommandResultError extends Error {
6
+ constructor(message: string) { super(message); this.name = 'CommandResultError' }
7
+ }
8
+
9
+ /** Validates a CommandResult (e.g. one read back from the ledger). Throws
10
+ * CommandResultError naming the first bad field. */
11
+ export function parseCommandResult(value: unknown): CommandResult {
12
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
13
+ throw new CommandResultError('Invalid result: expected object')
14
+ }
15
+ const input = value as Record<string, unknown>
16
+ if (typeof input.id !== 'string' || input.id.length === 0) {
17
+ throw new CommandResultError('Invalid id')
18
+ }
19
+ if (input.status !== 'applied' && input.status !== 'duplicate' && input.status !== 'rejected') {
20
+ throw new CommandResultError('Invalid status')
21
+ }
22
+ const result: CommandResult = { id: input.id, status: input.status }
23
+ const object = (value: unknown): boolean => typeof value === 'object' && value !== null
24
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
25
+ if (input.serverRefs !== undefined) {
26
+ if (typeof input.serverRefs !== 'object' || input.serverRefs === null || Array.isArray(input.serverRefs)) {
27
+ throw new CommandResultError('Invalid serverRefs')
28
+ }
29
+ const refs = input.serverRefs as Record<string, unknown>
30
+ if (typeof refs.orderId !== 'string' || refs.orderId.length === 0) {
31
+ throw new CommandResultError('Invalid serverRefs.orderId')
32
+ }
33
+ if (refs.displayId !== undefined && typeof refs.displayId !== 'string') {
34
+ throw new CommandResultError('Invalid serverRefs.displayId')
35
+ }
36
+ if (!Number.isSafeInteger(refs.totalMinor)) {
37
+ throw new CommandResultError('Invalid serverRefs.totalMinor')
38
+ }
39
+ result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor as number }
40
+ if (refs.displayId !== undefined) result.serverRefs.displayId = refs.displayId as string
41
+ }
42
+ if (input.register !== undefined) {
43
+ if (!object(input.register)) throw new CommandResultError('Invalid register')
44
+ result.register = input.register as RegisterCommandResult
45
+ }
46
+ if (result.status === 'applied' && result.serverRefs === undefined && result.register === undefined) {
47
+ throw new CommandResultError('Invalid serverRefs: required for applied')
48
+ }
49
+ if (input.warnings !== undefined) {
50
+ if (!Array.isArray(input.warnings)) {
51
+ throw new CommandResultError('Invalid warnings')
52
+ }
53
+ result.warnings = input.warnings.map((warning: unknown, index) => {
54
+ const field = `warnings[${index}]`
55
+ if (typeof warning !== 'object' || warning === null || Array.isArray(warning)) {
56
+ throw new CommandResultError(`Invalid ${field}`)
57
+ }
58
+ const item = warning as Record<string, unknown>
59
+ if (item.code === 'total_mismatch') {
60
+ for (const key of ['expectedMinor', 'serverMinor']) {
61
+ if (!Number.isInteger(item[key])) {
62
+ throw new CommandResultError(`Invalid ${field}.${key}`)
63
+ }
64
+ }
65
+ if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
66
+ throw new CommandResultError(`Invalid ${field}.bridgeMinor`)
67
+ }
68
+ return item.bridgeMinor != null
69
+ ? { code: item.code, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number, bridgeMinor: item.bridgeMinor as number }
70
+ : { code: item.code, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number }
71
+ }
72
+ if (item.code === 'insufficient_stock') {
73
+ if (typeof item.variantId !== 'string' || item.variantId.length === 0) {
74
+ throw new CommandResultError(`Invalid ${field}.variantId`)
75
+ }
76
+ if (!Number.isInteger(item.quantity) || (item.quantity as number) < 1) {
77
+ throw new CommandResultError(`Invalid ${field}.quantity`)
78
+ }
79
+ return { code: item.code, variantId: item.variantId, quantity: item.quantity as number }
80
+ }
81
+ if (item.code === 'tax_rate_mismatch') {
82
+ if (!Number.isSafeInteger(item.ratePpm) || (item.ratePpm as number) < 0) {
83
+ throw new CommandResultError(`Invalid ${field}.ratePpm`)
84
+ }
85
+ for (const key of ['expectedMinor', 'serverMinor']) {
86
+ if (!Number.isSafeInteger(item[key])) {
87
+ throw new CommandResultError(`Invalid ${field}.${key}`)
88
+ }
89
+ }
90
+ return { code: item.code, ratePpm: item.ratePpm as number, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number }
91
+ }
92
+ if (item.code === 'customer_ignored') {
93
+ if (typeof item.customerId !== 'string' || item.customerId.length === 0 || item.customerId.length > 64) {
94
+ throw new CommandResultError(`Invalid ${field}.customerId`)
95
+ }
96
+ return { code: item.code, customerId: item.customerId }
97
+ }
98
+ if (item.code === 'figures_mismatch') {
99
+ if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`)
100
+ const seen: string[] = []
101
+ return { code: item.code, fields: item.fields.map((value: unknown, i) => {
102
+ const path = `${field}.fields[${i}]`
103
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new CommandResultError(`Invalid ${path}`)
104
+ const entry = value as Record<string, unknown>
105
+ if (!['subtotalMinor', 'taxMinor', 'discountMinor'].includes(entry.field as string) || seen.includes(entry.field as string)) {
106
+ throw new CommandResultError(`Invalid ${path}.field`)
107
+ }
108
+ seen.push(entry.field as string)
109
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`)
110
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`)
111
+ return { field: entry.field as 'subtotalMinor' | 'taxMinor' | 'discountMinor', tillMinor: entry.tillMinor as number, serverMinor: entry.serverMinor as number }
112
+ }) }
113
+ }
114
+ throw new CommandResultError(`Invalid ${field}.code`)
115
+ })
116
+ }
117
+ if (input.error !== undefined) {
118
+ if (typeof input.error !== 'object' || input.error === null || Array.isArray(input.error)) {
119
+ throw new CommandResultError('Invalid error')
120
+ }
121
+ const error = input.error as Record<string, unknown>
122
+ if (typeof error.code !== 'string' || error.code.length === 0) {
123
+ throw new CommandResultError('Invalid error.code')
124
+ }
125
+ if (typeof error.message !== 'string') {
126
+ throw new CommandResultError('Invalid error.message')
127
+ }
128
+ result.error = { code: error.code, message: error.message }
129
+ if (error.data !== undefined) {
130
+ if (!object(error.data)) throw new CommandResultError('Invalid error.data')
131
+ result.error.data = error.data as Record<string, unknown>
132
+ }
133
+ }
134
+ if (result.status === 'rejected' && result.error === undefined) {
135
+ throw new CommandResultError('Invalid error: required for rejected')
136
+ }
137
+ return result
138
+ }
@@ -0,0 +1,18 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ /** JSON with recursively sorted object keys; arrays keep their order. */
4
+ export function canonicalJson(value: unknown): string {
5
+ if (Array.isArray(value)) return `[${value.map(item => canonicalJson(item) ?? 'null').join(',')}]`
6
+ if (value !== null && typeof value === 'object') {
7
+ const object = value as Record<string, unknown>
8
+ return `{${Object.keys(object).sort().filter(key => object[key] !== undefined)
9
+ .map(key => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(',')}}`
10
+ }
11
+ return JSON.stringify(value)
12
+ }
13
+
14
+ /** Lower-case hex SHA-256 of the canonical command content. */
15
+ export function commandFingerprint(envelope: { type: string; version: number; payload: unknown }): string {
16
+ const { type, version, payload } = envelope
17
+ return createHash('sha256').update(canonicalJson({ type, version, payload })).digest('hex')
18
+ }