@sess.si/sdk 0.0.0-stage → 0.1.0-rc.10

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 (65) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +27 -0
  4. package/README.md +327 -2
  5. package/dist/ask.d.ts +161 -0
  6. package/dist/ask.js +499 -0
  7. package/dist/cli/main.d.ts +2 -0
  8. package/dist/cli/main.js +7 -0
  9. package/dist/cli/verify.d.ts +13 -0
  10. package/dist/cli/verify.js +322 -0
  11. package/dist/client.d.ts +19 -0
  12. package/dist/client.js +43 -0
  13. package/dist/commerce/builders.d.ts +99 -0
  14. package/dist/commerce/builders.js +208 -0
  15. package/dist/commerce/currency.d.ts +4 -0
  16. package/dist/commerce/currency.js +25 -0
  17. package/dist/commerce/items.d.ts +119 -0
  18. package/dist/commerce/items.js +280 -0
  19. package/dist/commerce/lint.d.ts +16 -0
  20. package/dist/commerce/lint.js +56 -0
  21. package/dist/errors.d.ts +61 -0
  22. package/dist/errors.js +63 -0
  23. package/dist/generated/openapi.d.ts +8360 -0
  24. package/dist/generated/openapi.js +1 -0
  25. package/dist/index.d.ts +11 -0
  26. package/dist/index.js +6 -0
  27. package/dist/internal/decode.d.ts +20 -0
  28. package/dist/internal/decode.js +380 -0
  29. package/dist/internal/json.d.ts +3 -0
  30. package/dist/internal/json.js +74 -0
  31. package/dist/internal/time.d.ts +10 -0
  32. package/dist/internal/time.js +70 -0
  33. package/dist/internal/version.d.ts +2 -0
  34. package/dist/internal/version.js +2 -0
  35. package/dist/polling.d.ts +11 -0
  36. package/dist/polling.js +137 -0
  37. package/dist/qr/encoder.d.ts +10 -0
  38. package/dist/qr/encoder.js +343 -0
  39. package/dist/qr/index.d.ts +55 -0
  40. package/dist/qr/index.js +150 -0
  41. package/dist/receipts/bundle.d.ts +123 -0
  42. package/dist/receipts/bundle.js +423 -0
  43. package/dist/receipts/index.d.ts +8 -0
  44. package/dist/receipts/index.js +3 -0
  45. package/dist/receipts/json.d.ts +21 -0
  46. package/dist/receipts/json.js +151 -0
  47. package/dist/receipts/key-cache.d.ts +27 -0
  48. package/dist/receipts/key-cache.js +109 -0
  49. package/dist/receipts/renderers.d.ts +57 -0
  50. package/dist/receipts/renderers.js +153 -0
  51. package/dist/receipts/resource.d.ts +38 -0
  52. package/dist/receipts/resource.js +145 -0
  53. package/dist/receipts/verify.d.ts +112 -0
  54. package/dist/receipts/verify.js +339 -0
  55. package/dist/sessions.d.ts +18 -0
  56. package/dist/sessions.js +151 -0
  57. package/dist/transport.d.ts +30 -0
  58. package/dist/transport.js +511 -0
  59. package/dist/types.d.ts +283 -0
  60. package/dist/types.js +8 -0
  61. package/dist/webhook-resource.d.ts +12 -0
  62. package/dist/webhook-resource.js +51 -0
  63. package/dist/webhooks/index.d.ts +21 -0
  64. package/dist/webhooks/index.js +183 -0
  65. package/package.json +82 -4
@@ -0,0 +1,208 @@
1
+ import { buildItems, refuse, text, token, tooLong } from './items.js';
2
+ import { lintText } from './lint.js';
3
+ const LIMITS = Object.freeze({
4
+ title: 80,
5
+ description: 280,
6
+ recordKey: 40,
7
+ recordValue: 200,
8
+ recordFields: 50,
9
+ actions: 5,
10
+ actionLabel: 24,
11
+ });
12
+ const ACTION_ID = /^[a-z][a-z0-9_]{0,31}$/;
13
+ const INTENTS = ['submit', 'continue', 'approve', 'reject', 'request_change'];
14
+ const LOCALE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8}){0,4}$/;
15
+ const COMPONENTS = '/interaction/source/components';
16
+ // Keys an ordinary object does not hold as plain data (the same set ask() refuses): copied with
17
+ // `fields[key] = value`, "__proto__" would run the prototype setter and the row would vanish.
18
+ const RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
19
+ /**
20
+ * The words a builder puts on the page when you give none (proposed copy; `Request changes` is
21
+ * Sess's signed label for a change request). Every one can be replaced through the input.
22
+ */
23
+ export const COMMERCE_DEFAULTS = Object.freeze({
24
+ titles: Object.freeze({
25
+ invoice: 'Approve this invoice?',
26
+ receipt: 'Your receipt',
27
+ quote: 'Accept this quote?',
28
+ refund: 'Approve the refund?',
29
+ purchaseOrder: 'Approve the order?',
30
+ }),
31
+ references: Object.freeze({
32
+ invoice: 'Invoice',
33
+ receipt: 'Receipt',
34
+ quote: 'Quote',
35
+ refund: 'Refund',
36
+ purchaseOrder: 'Purchase order',
37
+ }),
38
+ actions: Object.freeze({
39
+ approve: Object.freeze({ id: 'approve', label: 'Approve', intent: 'approve' }),
40
+ accept: Object.freeze({ id: 'accept', label: 'Accept', intent: 'approve' }),
41
+ continue: Object.freeze({ id: 'continue', label: 'Continue', intent: 'continue' }),
42
+ decline: Object.freeze({ id: 'decline', label: 'Decline', intent: 'reject' }),
43
+ change: Object.freeze({ id: 'change', label: 'Request changes', intent: 'request_change' }),
44
+ }),
45
+ refundTotal: 'Refund total',
46
+ });
47
+ const D = COMMERCE_DEFAULTS.actions;
48
+ const SHAPES = {
49
+ invoice: { name: 'invoice', accept: D.approve, decline: true, change: false },
50
+ receipt: { name: 'receipt', accept: D.continue, decline: false, change: false },
51
+ quote: { name: 'quote', accept: D.accept, decline: true, change: false },
52
+ refund: { name: 'refund', accept: D.approve, decline: true, change: false },
53
+ purchaseOrder: { name: 'order', accept: D.approve, decline: true, change: true },
54
+ };
55
+ function recordComponent(kind, input, at) {
56
+ const fields = {};
57
+ if (input.reference !== undefined)
58
+ fields[COMMERCE_DEFAULTS.references[kind]] = text(input.reference, `${at}/fields/${token(COMMERCE_DEFAULTS.references[kind])}`, LIMITS.recordValue);
59
+ const extra = input.record ?? {};
60
+ if (extra === null || typeof extra !== 'object' || Array.isArray(extra))
61
+ refuse(`${at}/fields`, 'must be object');
62
+ for (const [key, value] of Object.entries(extra)) {
63
+ const p = `${at}/fields/${token(key)}`;
64
+ const keyLength = [...key].length;
65
+ if (keyLength > LIMITS.recordKey)
66
+ tooLong(p, LIMITS.recordKey, keyLength);
67
+ if (RESERVED_KEYS.has(key))
68
+ refuse(p, 'is a reserved name; give the fact another name');
69
+ if (Object.hasOwn(fields, key))
70
+ refuse(p, 'repeats the reference row; give the reference once');
71
+ if (typeof value === 'string') {
72
+ const length = [...value].length;
73
+ if (length > LIMITS.recordValue)
74
+ tooLong(p, LIMITS.recordValue, length);
75
+ if (!value.isWellFormed())
76
+ refuse(p, 'must be well-formed Unicode');
77
+ }
78
+ else if (!(value === null ||
79
+ typeof value === 'boolean' ||
80
+ (typeof value === 'number' && Number.isFinite(value))))
81
+ refuse(p, 'must be a string, number, boolean or null');
82
+ fields[key] = value;
83
+ }
84
+ const count = Object.keys(fields).length;
85
+ if (count > LIMITS.recordFields)
86
+ refuse(`${at}/fields`, `must NOT have more than ${LIMITS.recordFields} properties`);
87
+ return count ? { type: 'record', fields } : undefined;
88
+ }
89
+ function checkActions(actions, editable, editableAt) {
90
+ const at = '/interaction/actions';
91
+ if (!Array.isArray(actions) || actions.length < 1 || actions.length > LIMITS.actions)
92
+ refuse(at, `must have 1–${LIMITS.actions} actions`);
93
+ const ids = new Set();
94
+ const out = actions.map((a, i) => {
95
+ const p = `${at}/${i}`;
96
+ if (a === null || typeof a !== 'object')
97
+ return refuse(p, 'must be object');
98
+ if (typeof a.id !== 'string' || !ACTION_ID.test(a.id))
99
+ refuse(`${p}/id`, `must match pattern "${ACTION_ID.source}"`);
100
+ if (ids.has(a.id))
101
+ refuse(at, 'action ids must be unique');
102
+ ids.add(a.id);
103
+ const label = text(a.label, `${p}/label`, LIMITS.actionLabel);
104
+ if (a.intent !== undefined && !INTENTS.includes(a.intent))
105
+ refuse(`${p}/intent`, `must be one of ${INTENTS.join(', ')}`);
106
+ return a.intent === undefined ? { id: a.id, label } : { id: a.id, label, intent: a.intent };
107
+ });
108
+ // Sess refuses editable quantities without a way to send the edit (signed rule, 2026-10-23).
109
+ if (editable && !out.some((a) => a.intent === 'request_change'))
110
+ refuse(`${editableAt}/editable`, 'needs an action with intent request_change in interaction.actions, such as "Request changes", so the person can send a changed quantity');
111
+ return out;
112
+ }
113
+ function bill(kind, input, adjust) {
114
+ if (input === null || typeof input !== 'object')
115
+ return refuse('/interaction', 'must be object');
116
+ const shape = SHAPES[kind];
117
+ const title = text(input.title ?? COMMERCE_DEFAULTS.titles[kind], '/interaction/title', LIMITS.title);
118
+ let description;
119
+ if (input.description !== undefined) {
120
+ if (typeof input.description !== 'string' || !input.description.isWellFormed())
121
+ refuse('/interaction/description', 'must be a well-formed string');
122
+ const length = [...input.description].length;
123
+ if (length > LIMITS.description)
124
+ tooLong('/interaction/description', LIMITS.description, length);
125
+ // A table drawn in the description reaches the person as pipes: the bill is the items card.
126
+ const table = lintText(input.description)[0];
127
+ if (table !== undefined)
128
+ refuse('/interaction/description', table.use === 'items'
129
+ ? 'contains a Markdown table, which the person would see as pipes; put prices in the rows'
130
+ : 'contains a Markdown table, which the person would see as pipes; put the rows in record');
131
+ description = input.description;
132
+ }
133
+ if (input.locale !== undefined &&
134
+ (typeof input.locale !== 'string' || input.locale.length > 35 || !LOCALE.test(input.locale)))
135
+ refuse('/interaction/locale', 'is not a locale Sess can format; use a BCP 47 tag such as en-CA, or leave it out');
136
+ const record = recordComponent(kind, input, `${COMPONENTS}/0`);
137
+ const at = `${COMPONENTS}/${record ? 1 : 0}`;
138
+ // The answer's name, when the person answers (a choice of rows or a quantity), is the builder's.
139
+ const wantsName = input.select !== undefined ||
140
+ (Array.isArray(input.rows) &&
141
+ input.rows.some((r) => r !== null && typeof r === 'object' && r.quantity !== undefined));
142
+ const items = buildItems({
143
+ ...input,
144
+ ...(input.name === undefined && wantsName ? { name: shape.name } : {}),
145
+ }, at);
146
+ adjust?.(items, at);
147
+ const editable = items.editable !== undefined;
148
+ const actions = checkActions(input.actions ?? [
149
+ ...(shape.decline ? [D.decline] : []),
150
+ ...(shape.change || editable ? [D.change] : []),
151
+ shape.accept,
152
+ ], editable, at);
153
+ return {
154
+ mode: 'interactive',
155
+ title,
156
+ ...(description === undefined ? {} : { description }),
157
+ ...(input.locale === undefined ? {} : { locale: input.locale }),
158
+ source: { kind: 'sess_surface', components: [...(record ? [record] : []), items] },
159
+ actions,
160
+ };
161
+ }
162
+ /**
163
+ * An invoice to approve: the items card with its totals, `Decline` and `Approve` (and
164
+ * `Request changes` when a row has an editable quantity). Returns an `interaction` for
165
+ * `sess.sessions.create({ interaction })`. Sess takes no payment: approval is the person's
166
+ * decision and its signed receipt; collecting the money stays with your payment processor.
167
+ */
168
+ export function invoice(input) {
169
+ return bill('invoice', input);
170
+ }
171
+ /** A receipt or order confirmation for the person to check, with one `Continue` button. */
172
+ export function receipt(input) {
173
+ return bill('receipt', input);
174
+ }
175
+ /** A quote or estimate to accept: `Decline` and `Accept`. Put its validity in `record`. */
176
+ export function quote(input) {
177
+ return bill('quote', input);
178
+ }
179
+ /**
180
+ * A refund to approve, stated in positive amounts: every row is zero or more and the total,
181
+ * labelled `Refund total`, is never negative. A deduction (such as a restocking fee) is a
182
+ * negative line. With `select: 'many'` the person chooses the rows to refund.
183
+ */
184
+ export function refund(input) {
185
+ if (input === null || typeof input !== 'object')
186
+ return refuse('/interaction', 'must be object');
187
+ if (input.payments !== undefined)
188
+ refuse('/interaction', 'is a refund, which has no payments; state what is refunded');
189
+ return bill('refund', {
190
+ ...input,
191
+ labels: { ...input.labels, total: input.labels?.total ?? COMMERCE_DEFAULTS.refundTotal },
192
+ }, (items, at) => {
193
+ for (const [i, row] of items.rows.entries())
194
+ if (row.amount !== null && row.amount < 0)
195
+ refuse(`${at}/rows/${i}/amount`, 'is negative; a refund states what is refunded as a positive amount (a deduction is a negative line)');
196
+ const total = items.totals?.find((t) => t.role === 'total');
197
+ if (total !== undefined && total.amount < 0)
198
+ refuse(`${at}/totals/${items.totals.indexOf(total)}/amount`, 'is a negative refund total; a refund total is zero or more');
199
+ });
200
+ }
201
+ /**
202
+ * A purchase order to approve. A row with a `quantity` lets the person change it; the order
203
+ * always offers `Request changes` (a changed quantity is sent only with it, and your agent replies
204
+ * with a new revision and updated amounts) beside `Decline` and `Approve`.
205
+ */
206
+ export function purchaseOrder(input) {
207
+ return bill('purchaseOrder', input);
208
+ }
@@ -0,0 +1,4 @@
1
+ /** Every ISO 4217 code Sess accepts and its minor-unit exponent (JPY 0, USD 2, BHD 3, CLF 4). */
2
+ export declare const CURRENCY_MINOR_UNITS: ReadonlyMap<string, 0 | 2 | 3 | 4>;
3
+ /** The minor-unit exponent of a currency Sess accepts, else undefined. */
4
+ export declare function minorUnits(currency: string): 0 | 2 | 3 | 4 | undefined;
@@ -0,0 +1,25 @@
1
+ // ISO 4217 minor units: the currencies an items component may state and the exponent of each
2
+ // one's minor unit. A copy of the Sess runtime's table (packages/core/src/currency.ts, transcribed
3
+ // by Sess from ISO 4217 List One, "Minor unit" column). Codes with no minor unit (XAU, XDR, XXX …)
4
+ // are not listed and are refused, as Sess refuses them. tests/unit/commerce-contract.test.ts pins
5
+ // this table to the runtime's, extracted at a recorded runtime commit.
6
+ const BY_EXPONENT = [
7
+ [0, 'BIF CLP DJF GNF ISK JPY KMF KRW PYG RWF UGX UYI VND VUV XAF XOF XPF'],
8
+ [
9
+ 2,
10
+ 'AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BMD BND BOB BOV BRL BSD BTN BWP BYN BZD ' +
11
+ 'CAD CDF CHE CHF CHW CNY COP COU CRC CUP CVE CZK DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS ' +
12
+ 'GIP GMD GTQ GYD HKD HNL HTG HUF IDR ILS INR IRR JMD KES KGS KHR KPW KYD KZT LAK LBP LKR LRD LSL ' +
13
+ 'MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD PAB PEN PGK ' +
14
+ 'PHP PKR PLN QAR RON RSD RUB SAR SBD SCR SDG SEK SGD SHP SLE SLL SOS SRD SSP STN SVC SYP SZL THB ' +
15
+ 'TJS TMT TOP TRY TTD TWD TZS UAH USD USN UYU UZS VED VES WST XCD XCG YER ZAR ZMW ZWG ZWL',
16
+ ],
17
+ [3, 'BHD IQD JOD KWD LYD OMR TND'],
18
+ [4, 'CLF UYW'],
19
+ ];
20
+ /** Every ISO 4217 code Sess accepts and its minor-unit exponent (JPY 0, USD 2, BHD 3, CLF 4). */
21
+ export const CURRENCY_MINOR_UNITS = new Map(BY_EXPONENT.flatMap(([exponent, codes]) => codes.split(' ').map((code) => [code, exponent])));
22
+ /** The minor-unit exponent of a currency Sess accepts, else undefined. */
23
+ export function minorUnits(currency) {
24
+ return CURRENCY_MINOR_UNITS.get(currency);
25
+ }
@@ -0,0 +1,119 @@
1
+ import type { ItemsComponent } from '../types.js';
2
+ /**
3
+ * The runtime's items limits (Unicode code points for text): rows 1–100, totals lines ≤ 8, a row
4
+ * name ≤ 80, a detail ≤ 160, a totals label ≤ 40, a caption ≤ 200, a quantity unit ≤ 16, every
5
+ * amount within ±10^15 minor units, a quantity within 0–1,000,000.
6
+ */
7
+ export declare const ITEMS_LIMITS: Readonly<{
8
+ rows: 100;
9
+ totals: 8;
10
+ name: 80;
11
+ detail: 160;
12
+ totalLabel: 40;
13
+ label: 200;
14
+ quantityUnit: 16;
15
+ amount: 1000000000000000;
16
+ quantity: 1000000;
17
+ }>;
18
+ /** An amount in a currency's minor unit (1250 is 12.50 USD, 1250 JPY, 1.250 BHD). */
19
+ export interface Money {
20
+ readonly amount: number;
21
+ readonly currency: string;
22
+ }
23
+ /** A row, totals or payment amount: minor units of the component's currency, or `money()`. */
24
+ export type Amount = number | Money;
25
+ /** A line of the bill. Put quantity and unit price in `detail`, not in `name`. */
26
+ export interface ItemRowInput {
27
+ /** What the line is, shown verbatim; at most 80. Example: `Design retainer, October` */
28
+ readonly name: string;
29
+ /** Optional second line: quantity or unit price; at most 160 with `reference`. Example: `3 × $150.00` */
30
+ readonly detail?: string;
31
+ /** Optional reference (SKU, booking or PO number): shown in the detail line, after it. */
32
+ readonly reference?: string;
33
+ /** Minor units (or `money()`), or null for a line with no amount, such as `Included`. */
34
+ readonly amount: Amount | null;
35
+ /**
36
+ * A quantity the person may change (an integer within `min`, default 0, and `max`, default
37
+ * 1,000,000). The amount stays as stated: a changed quantity comes back as a change request
38
+ * and your agent sends a new revision with new amounts.
39
+ */
40
+ readonly quantity?: {
41
+ readonly value: number;
42
+ readonly unit?: string;
43
+ readonly min?: number;
44
+ readonly max?: number;
45
+ };
46
+ }
47
+ /** A line between the subtotal and the total. Added to the total unless `included`. */
48
+ export interface ItemLineInput {
49
+ /** A word or two; at most 40. Examples: `GST 5%`, `Shipping`, `Early-payment discount` */
50
+ readonly label: string;
51
+ /** Minor units (or `money()`). A discount is negative. */
52
+ readonly amount: Amount;
53
+ readonly role: 'tax' | 'discount' | 'shipping' | 'fee' | 'tip' | 'adjustment' | 'other';
54
+ /** Already inside the row prices (such as VAT): shown, never added. */
55
+ readonly included?: boolean;
56
+ }
57
+ /** A payment already made, such as a deposit: a negative amount, counted once, in the amount due. */
58
+ export interface ItemPaymentInput {
59
+ /** A word or two; at most 40. Example: `Deposit paid` */
60
+ readonly label: string;
61
+ /** Minor units (or `money()`), negative. */
62
+ readonly amount: Amount;
63
+ }
64
+ export interface ItemsInput {
65
+ /** ISO 4217 code with known minor units, such as `CAD`, `JPY` or `BHD`: one per component. */
66
+ readonly currency: string;
67
+ /** 1–100 rows, in order. */
68
+ readonly rows: readonly ItemRowInput[];
69
+ /** Optional caption: what the list is; at most 200. Example: `Invoice 2041` */
70
+ readonly label?: string;
71
+ /** Tax, discount, shipping, fee, tip and other lines, shown between the subtotal and the total. */
72
+ readonly lines?: readonly ItemLineInput[];
73
+ /** Payments already made, shown after the total and followed by the amount due. */
74
+ readonly payments?: readonly ItemPaymentInput[];
75
+ /** The totals lines' labels. Defaults: `Subtotal`, `Total`, `Amount due`. */
76
+ readonly labels?: {
77
+ readonly subtotal?: string;
78
+ readonly total?: string;
79
+ readonly due?: string;
80
+ };
81
+ /** `false` states no totals (a list to choose from); then `lines` and `payments` are not allowed. */
82
+ readonly totals?: boolean;
83
+ /** The person may choose rows: `one` or `many`. Needs `name`. */
84
+ readonly select?: 'one' | 'many';
85
+ /** The answer's name (`^[a-z][a-z0-9_]{0,55}$`), with `select` or a row `quantity`. */
86
+ readonly name?: string;
87
+ }
88
+ /** Default totals labels (proposed copy; see CHANGELOG). */
89
+ export declare const ITEMS_DEFAULT_LABELS: Readonly<{
90
+ subtotal: "Subtotal";
91
+ total: "Total";
92
+ due: "Amount due";
93
+ }>;
94
+ /** Internal: a refused builder input, named by its JSON pointer; nothing was sent. */
95
+ export declare function refuse(field: string, problem: string): never;
96
+ /** Internal: a value over its limit, in Sess's own sentence (`field`, `limit` and `length` set). */
97
+ export declare function tooLong(field: string, limit: number, length: number): never;
98
+ /** Internal: a non-blank, well-formed string of at most `max` code points (never truncated). */
99
+ export declare function text(value: unknown, field: string, max: number): string;
100
+ /** Internal: the JSON pointer token of a key (RFC 6901). */
101
+ export declare const token: (key: string) => string;
102
+ /**
103
+ * An amount in a currency's minor unit, checked: a whole number within ±10^15 and an ISO 4217
104
+ * code Sess accepts. `money(1250, 'USD')` is $12.50; `money(1250, 'JPY')` is ¥1,250;
105
+ * `money(1250, 'BHD')` is 1.250 BHD. It never rounds or converts: `money(12.5, 'USD')` throws.
106
+ */
107
+ export declare function money(amount: number, currency: string): Money;
108
+ /** Internal: `items()` at a pointer (`at` is the component's pointer in the request). */
109
+ export declare function buildItems(input: ItemsInput, at: string): ItemsComponent;
110
+ /**
111
+ * Builds an items component: rows in one currency, and the subtotal, total and amount due computed
112
+ * exactly from them, so Sess's arithmetic check passes. A bill with lines (tax, discount,
113
+ * shipping …) gets `Subtotal`, the lines and `Total`; with none, `Total` only; with payments, the
114
+ * payments and `Amount due` after the total. Amounts are whole minor units (`money()` checks
115
+ * one). Over a limit it throws a `SessError` (`code` `INVALID_SCHEMA`, `outcome` `not_sent`) whose
116
+ * `field` is the value's JSON pointer within the component, such as `/rows/3/name`; nothing is
117
+ * ever truncated. With a row `quantity`, put it in a Surface with a `request_change` action.
118
+ */
119
+ export declare function items(input: ItemsInput): ItemsComponent;
@@ -0,0 +1,280 @@
1
+ // Commerce: money and the items builder. The runtime's `items` component carries amounts as
2
+ // whole numbers in a currency's minor unit and checks the stated subtotal, total and amount due
3
+ // exactly; this builder computes them so a bill it returns passes that check. It never rounds,
4
+ // converts or formats: what you state is what is sent. Limits reject, never truncate, with the
5
+ // pointer and sentences of Sess's 400 INVALID_SCHEMA. Pure: no network, clock or I/O.
6
+ import { SessError, lengthMessage } from '../errors.js';
7
+ import { minorUnits } from './currency.js';
8
+ /**
9
+ * The runtime's items limits (Unicode code points for text): rows 1–100, totals lines ≤ 8, a row
10
+ * name ≤ 80, a detail ≤ 160, a totals label ≤ 40, a caption ≤ 200, a quantity unit ≤ 16, every
11
+ * amount within ±10^15 minor units, a quantity within 0–1,000,000.
12
+ */
13
+ export const ITEMS_LIMITS = Object.freeze({
14
+ rows: 100,
15
+ totals: 8,
16
+ name: 80,
17
+ detail: 160,
18
+ totalLabel: 40,
19
+ label: 200,
20
+ quantityUnit: 16,
21
+ amount: 1_000_000_000_000_000,
22
+ quantity: 1_000_000,
23
+ });
24
+ /** Default totals labels (proposed copy; see CHANGELOG). */
25
+ export const ITEMS_DEFAULT_LABELS = Object.freeze({
26
+ subtotal: 'Subtotal',
27
+ total: 'Total',
28
+ due: 'Amount due',
29
+ });
30
+ const ADDITIVE_ROLES = [
31
+ 'tax',
32
+ 'discount',
33
+ 'shipping',
34
+ 'fee',
35
+ 'tip',
36
+ 'adjustment',
37
+ 'other',
38
+ ];
39
+ const ANSWER_NAME = /^[a-z][a-z0-9_]{0,55}$/;
40
+ const AMOUNT_MAX = BigInt(ITEMS_LIMITS.amount);
41
+ const codePoints = (value) => [...value].length;
42
+ /** Internal: a refused builder input, named by its JSON pointer; nothing was sent. */
43
+ export function refuse(field, problem) {
44
+ // Pointers and problems only: caller values never enter the message.
45
+ const subject = field === '' ? 'The items component' : field;
46
+ throw new SessError('configuration', `${subject} ${problem}.`, {
47
+ code: 'INVALID_SCHEMA',
48
+ outcome: 'not_sent',
49
+ ...(field === '' ? {} : { field }),
50
+ });
51
+ }
52
+ /** Internal: a value over its limit, in Sess's own sentence (`field`, `limit` and `length` set). */
53
+ export function tooLong(field, limit, length) {
54
+ throw new SessError('configuration', lengthMessage(field, limit, length), {
55
+ code: 'INVALID_SCHEMA',
56
+ outcome: 'not_sent',
57
+ field,
58
+ limit,
59
+ length,
60
+ });
61
+ }
62
+ /** Internal: a non-blank, well-formed string of at most `max` code points (never truncated). */
63
+ export function text(value, field, max) {
64
+ if (typeof value !== 'string')
65
+ return refuse(field, 'must be string');
66
+ if (!value.isWellFormed())
67
+ refuse(field, 'must be well-formed Unicode');
68
+ const length = codePoints(value);
69
+ if (length > max)
70
+ tooLong(field, max, length);
71
+ if (!/\S/.test(value))
72
+ refuse(field, 'must not be blank');
73
+ return value;
74
+ }
75
+ /** Internal: the JSON pointer token of a key (RFC 6901). */
76
+ export const token = (key) => key.replace(/~/g, '~0').replace(/\//g, '~1');
77
+ function checkCurrency(currency, field) {
78
+ if (typeof currency !== 'string' || minorUnits(currency) === undefined)
79
+ refuse(field, 'is not an ISO 4217 currency code with known minor units; use one such as USD, EUR or JPY');
80
+ return currency;
81
+ }
82
+ function wholeAmount(amount, field) {
83
+ if (typeof amount !== 'number' || !Number.isInteger(amount))
84
+ return refuse(field, 'must be integer');
85
+ if (amount > ITEMS_LIMITS.amount)
86
+ refuse(field, `must be <= ${ITEMS_LIMITS.amount}`);
87
+ if (amount < -ITEMS_LIMITS.amount)
88
+ refuse(field, `must be >= ${-ITEMS_LIMITS.amount}`);
89
+ return amount === 0 ? 0 : amount; // -0 is sent as 0
90
+ }
91
+ /**
92
+ * An amount in a currency's minor unit, checked: a whole number within ±10^15 and an ISO 4217
93
+ * code Sess accepts. `money(1250, 'USD')` is $12.50; `money(1250, 'JPY')` is ¥1,250;
94
+ * `money(1250, 'BHD')` is 1.250 BHD. It never rounds or converts: `money(12.5, 'USD')` throws.
95
+ */
96
+ export function money(amount, currency) {
97
+ if (typeof currency !== 'string' || minorUnits(currency) === undefined)
98
+ throw new SessError('configuration', 'money(): the currency is not an ISO 4217 code with known minor units; use one such as USD, EUR or JPY.', { code: 'INVALID_SCHEMA', outcome: 'not_sent' });
99
+ if (typeof amount !== 'number' || !Number.isSafeInteger(amount) || Math.abs(amount) > ITEMS_LIMITS.amount)
100
+ throw new SessError('configuration', `money(): the amount must be a whole number of the currency's smallest unit (cents for USD, yen for JPY, fils for BHD), within ±${ITEMS_LIMITS.amount}: 1250 for 12.50 USD. Sess never rounds.`, { code: 'INVALID_SCHEMA', outcome: 'not_sent' });
101
+ return Object.freeze({ amount: amount === 0 ? 0 : amount, currency });
102
+ }
103
+ /** A stated amount in the component's currency: a number, or `money()` in the same currency. */
104
+ function amountOf(value, currency, field) {
105
+ if (value !== null && typeof value === 'object') {
106
+ const m = value;
107
+ if (m.currency !== currency)
108
+ refuse(field, 'is in another currency; an items component has one currency, so send it as its own items component');
109
+ return wholeAmount(m.amount, field);
110
+ }
111
+ return wholeAmount(value, field);
112
+ }
113
+ function quantityOf(raw, field) {
114
+ if (raw === null || typeof raw !== 'object')
115
+ return refuse(field, 'must be object');
116
+ const whole = (v, at) => {
117
+ if (typeof v !== 'number' || !Number.isInteger(v))
118
+ return refuse(at, 'must be integer');
119
+ if (v < 0)
120
+ refuse(at, 'must be >= 0');
121
+ if (v > ITEMS_LIMITS.quantity)
122
+ refuse(at, `must be <= ${ITEMS_LIMITS.quantity}`);
123
+ return v;
124
+ };
125
+ const value = whole(raw.value, `${field}/value`);
126
+ const min = raw.min === undefined ? undefined : whole(raw.min, `${field}/min`);
127
+ const max = raw.max === undefined ? undefined : whole(raw.max, `${field}/max`);
128
+ if ((min ?? 0) > (max ?? ITEMS_LIMITS.quantity))
129
+ refuse(`${field}/min`, 'is more than max');
130
+ if (value < (min ?? 0) || value > (max ?? ITEMS_LIMITS.quantity))
131
+ refuse(`${field}/value`, 'is not within min and max');
132
+ const unit = raw.unit === undefined ? undefined : text(raw.unit, `${field}/unit`, ITEMS_LIMITS.quantityUnit);
133
+ return {
134
+ value,
135
+ ...(unit === undefined ? {} : { unit }),
136
+ ...(min === undefined ? {} : { min }),
137
+ ...(max === undefined ? {} : { max }),
138
+ };
139
+ }
140
+ /** The exact sum of minor-unit amounts (BigInt, so no order of 100 amounts loses a unit). */
141
+ function sum(field, amounts) {
142
+ const total = amounts.reduce((s, a) => s + BigInt(a), 0n);
143
+ if (total > AMOUNT_MAX)
144
+ refuse(field, `must be <= ${ITEMS_LIMITS.amount}`);
145
+ if (total < -AMOUNT_MAX)
146
+ refuse(field, `must be >= ${-ITEMS_LIMITS.amount}`);
147
+ return Number(total);
148
+ }
149
+ /** Internal: `items()` at a pointer (`at` is the component's pointer in the request). */
150
+ export function buildItems(input, at) {
151
+ if (input === null || typeof input !== 'object')
152
+ return refuse(at, 'must be object');
153
+ const currency = checkCurrency(input.currency, `${at}/currency`);
154
+ const label = input.label === undefined ? undefined : text(input.label, `${at}/label`, ITEMS_LIMITS.label);
155
+ const sourceRows = input.rows;
156
+ if (!Array.isArray(sourceRows) || sourceRows.length < 1)
157
+ return refuse(`${at}/rows`, 'needs at least one row');
158
+ if (sourceRows.length > ITEMS_LIMITS.rows)
159
+ tooLong(`${at}/rows`, ITEMS_LIMITS.rows, sourceRows.length);
160
+ const rows = sourceRows.map((r, i) => {
161
+ const p = `${at}/rows/${i}`;
162
+ if (r === null || typeof r !== 'object')
163
+ return refuse(p, 'must be object');
164
+ const name = text(r.name, `${p}/name`, ITEMS_LIMITS.name);
165
+ // A reference goes in the detail line under the plain name, after any detail, so it reads as one.
166
+ const detail = r.detail === undefined ? undefined : text(r.detail, `${p}/detail`, ITEMS_LIMITS.detail);
167
+ const reference = r.reference === undefined ? undefined : text(r.reference, `${p}/detail`, ITEMS_LIMITS.detail);
168
+ const joined = reference === undefined
169
+ ? detail
170
+ : text(detail === undefined ? reference : `${detail} · ${reference}`, `${p}/detail`, ITEMS_LIMITS.detail);
171
+ const quantity = r.quantity === undefined ? undefined : quantityOf(r.quantity, `${p}/quantity`);
172
+ const amount = r.amount === null ? null : amountOf(r.amount, currency, `${p}/amount`);
173
+ return {
174
+ name,
175
+ ...(joined === undefined ? {} : { detail: joined }),
176
+ ...(quantity === undefined ? {} : { quantity }),
177
+ amount,
178
+ };
179
+ });
180
+ const editable = rows.some((r) => r.quantity !== undefined);
181
+ const select = input.select;
182
+ if (select !== undefined && select !== 'one' && select !== 'many')
183
+ refuse(`${at}/select`, 'must be one or many');
184
+ const answered = select !== undefined || editable;
185
+ if (input.name !== undefined && !answered)
186
+ refuse(`${at}/name`, 'applies only with select or editable; remove it');
187
+ if (answered && input.name === undefined)
188
+ refuse(at, 'has select or editable but no name; add a name for the answer');
189
+ if (input.name !== undefined && (typeof input.name !== 'string' || !ANSWER_NAME.test(input.name)))
190
+ refuse(`${at}/name`, `must match pattern "${ANSWER_NAME.source}"`);
191
+ // Totals: the subtotal is the rows; the total adds every line not already included; payments are
192
+ // counted once, in the amount due. Computed exactly, as Sess checks them.
193
+ const lines = input.lines ?? [];
194
+ const payments = input.payments ?? [];
195
+ if (!Array.isArray(lines))
196
+ refuse(`${at}/lines`, 'must be array');
197
+ if (!Array.isArray(payments))
198
+ refuse(`${at}/payments`, 'must be array');
199
+ const totals = [];
200
+ if (input.totals === false) {
201
+ if (lines.length || payments.length)
202
+ refuse(`${at}/totals`, 'is false, so a bill without totals has no lines or payments; remove them');
203
+ }
204
+ else {
205
+ const labels = input.labels ?? {};
206
+ const labelOf = (key, index) => labels[key] === undefined
207
+ ? ITEMS_DEFAULT_LABELS[key]
208
+ : text(labels[key], `${at}/totals/${index}/label`, ITEMS_LIMITS.totalLabel);
209
+ const count = (lines.length ? 1 : 0) + lines.length + 1 + (payments.length ? payments.length + 1 : 0);
210
+ if (count > ITEMS_LIMITS.totals)
211
+ tooLong(`${at}/totals`, ITEMS_LIMITS.totals, count);
212
+ const subtotal = sum(`${at}/rows`, rows.map((r) => r.amount ?? 0));
213
+ if (lines.length)
214
+ totals.push({ label: labelOf('subtotal', 0), amount: subtotal, role: 'subtotal' });
215
+ for (const line of lines) {
216
+ const p = `${at}/totals/${totals.length}`;
217
+ if (line === null || typeof line !== 'object')
218
+ refuse(p, 'must be object');
219
+ const lineLabel = text(line.label, `${p}/label`, ITEMS_LIMITS.totalLabel);
220
+ if (!ADDITIVE_ROLES.includes(line.role))
221
+ refuse(`${p}/role`, `must be one of ${ADDITIVE_ROLES.join(', ')}`);
222
+ const amount = amountOf(line.amount, currency, `${p}/amount`);
223
+ if (line.role === 'discount' && amount > 0)
224
+ refuse(`${p}/amount`, 'is a discount, so it is negative; state it with a minus sign');
225
+ if (line.included !== undefined && typeof line.included !== 'boolean')
226
+ refuse(`${p}/included`, 'must be boolean');
227
+ totals.push({
228
+ label: lineLabel,
229
+ amount,
230
+ role: line.role,
231
+ ...(line.included === undefined ? {} : { included: line.included }),
232
+ });
233
+ }
234
+ const added = totals.filter((t) => t.role !== 'subtotal' && t.included !== true).map((t) => t.amount);
235
+ const total = sum(`${at}/totals`, [subtotal, ...added]);
236
+ totals.push({ label: labelOf('total', totals.length), amount: total, role: 'total' });
237
+ if (payments.length) {
238
+ const paid = [];
239
+ for (const payment of payments) {
240
+ const p = `${at}/totals/${totals.length}`;
241
+ if (payment === null || typeof payment !== 'object')
242
+ refuse(p, 'must be object');
243
+ const paymentLabel = text(payment.label, `${p}/label`, ITEMS_LIMITS.totalLabel);
244
+ const amount = amountOf(payment.amount, currency, `${p}/amount`);
245
+ if (amount > 0)
246
+ refuse(`${p}/amount`, 'is a payment, so it is negative; state it with a minus sign');
247
+ paid.push(amount);
248
+ totals.push({ label: paymentLabel, amount, role: 'paid' });
249
+ }
250
+ totals.push({
251
+ label: labelOf('due', totals.length),
252
+ amount: sum(`${at}/totals`, [total, ...paid]),
253
+ role: 'due',
254
+ });
255
+ }
256
+ }
257
+ // Canonical member order, as Sess stores the component.
258
+ return {
259
+ type: 'items',
260
+ ...(label === undefined ? {} : { label }),
261
+ currency,
262
+ ...(select === undefined ? {} : { select }),
263
+ ...(editable ? { editable: ['quantity'] } : {}),
264
+ ...(input.name === undefined ? {} : { name: input.name }),
265
+ rows,
266
+ ...(totals.length ? { totals } : {}),
267
+ };
268
+ }
269
+ /**
270
+ * Builds an items component: rows in one currency, and the subtotal, total and amount due computed
271
+ * exactly from them, so Sess's arithmetic check passes. A bill with lines (tax, discount,
272
+ * shipping …) gets `Subtotal`, the lines and `Total`; with none, `Total` only; with payments, the
273
+ * payments and `Amount due` after the total. Amounts are whole minor units (`money()` checks
274
+ * one). Over a limit it throws a `SessError` (`code` `INVALID_SCHEMA`, `outcome` `not_sent`) whose
275
+ * `field` is the value's JSON pointer within the component, such as `/rows/3/name`; nothing is
276
+ * ever truncated. With a row `quantity`, put it in a Surface with a `request_change` action.
277
+ */
278
+ export function items(input) {
279
+ return buildItems(input, '');
280
+ }
@@ -0,0 +1,16 @@
1
+ /** One pipe table found in a text. */
2
+ export interface TextLintFinding {
3
+ readonly rule: 'pipe-table';
4
+ /** The 1-based line where the table starts. */
5
+ readonly line: number;
6
+ /** What to send instead: `items` for amounts, `record` for other rows. */
7
+ readonly use: 'items' | 'record';
8
+ readonly message: string;
9
+ }
10
+ /**
11
+ * Finds Markdown pipe tables in a text: a header row with pipes followed by a delimiter row
12
+ * (`|---|---|`), or two or more consecutive rows drawn between pipes (`| a | b |`). Each finding
13
+ * says where the table starts and what to send instead: an items component for prices, or a
14
+ * record for other rows. Returns an empty list for ordinary text.
15
+ */
16
+ export declare function lintText(text: string): TextLintFinding[];