@composable-os/sdk 0.1.0-beta.11 → 0.1.0-beta.13

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 (104) hide show
  1. package/dist/acknowledge.d.ts +38 -0
  2. package/dist/acknowledge.js +30 -0
  3. package/dist/agreements.d.ts +80 -0
  4. package/dist/agreements.js +109 -0
  5. package/dist/allowance.d.ts +47 -5
  6. package/dist/allowance.js +59 -4
  7. package/dist/automation-check.d.ts +6 -1
  8. package/dist/automation-check.js +93 -8
  9. package/dist/automation.d.ts +62 -4
  10. package/dist/automation.js +32 -9
  11. package/dist/behaviour.js +25 -6
  12. package/dist/calendar-entry.d.ts +97 -0
  13. package/dist/calendar-entry.js +180 -0
  14. package/dist/capacity.js +1 -2
  15. package/dist/checklists.d.ts +41 -0
  16. package/dist/checklists.js +75 -0
  17. package/dist/contract.d.ts +495 -26
  18. package/dist/contract.js +21 -3
  19. package/dist/discount.d.ts +135 -0
  20. package/dist/discount.js +281 -0
  21. package/dist/document.d.ts +2 -1
  22. package/dist/document.js +2 -1
  23. package/dist/field-types.d.ts +1 -1
  24. package/dist/field-types.js +5 -0
  25. package/dist/formula/compile.d.ts +15 -0
  26. package/dist/formula/compile.js +9 -0
  27. package/dist/index.d.ts +17 -0
  28. package/dist/index.js +17 -0
  29. package/dist/intake.d.ts +134 -0
  30. package/dist/intake.js +239 -0
  31. package/dist/journey-signals.d.ts +89 -0
  32. package/dist/journey-signals.js +151 -0
  33. package/dist/manifest.d.ts +944 -56
  34. package/dist/manifest.js +1036 -60
  35. package/dist/mine.d.ts +45 -0
  36. package/dist/mine.js +119 -0
  37. package/dist/occupies.d.ts +64 -0
  38. package/dist/occupies.js +122 -0
  39. package/dist/questions.d.ts +179 -0
  40. package/dist/questions.js +514 -0
  41. package/dist/recurring.d.ts +33 -4
  42. package/dist/recurring.js +50 -3
  43. package/dist/restricted-fields.d.ts +15 -0
  44. package/dist/restricted-fields.js +97 -0
  45. package/dist/rich-text.d.ts +22 -0
  46. package/dist/rich-text.js +91 -0
  47. package/dist/routine-mail.d.ts +400 -0
  48. package/dist/routine-mail.js +955 -0
  49. package/dist/runtime.d.ts +5 -11
  50. package/dist/runtime.js +21 -11
  51. package/dist/screens.d.ts +3 -0
  52. package/dist/screens.js +74 -0
  53. package/dist/sellable.d.ts +153 -2
  54. package/dist/sellable.js +188 -0
  55. package/dist/slug.d.ts +2 -0
  56. package/dist/slug.js +6 -2
  57. package/dist/staffed.d.ts +178 -0
  58. package/dist/staffed.js +287 -0
  59. package/dist/states.d.ts +17 -1
  60. package/dist/states.js +48 -20
  61. package/dist/stock.d.ts +129 -0
  62. package/dist/stock.js +205 -0
  63. package/dist/team.d.ts +28 -0
  64. package/dist/team.js +52 -0
  65. package/dist/testing.d.ts +22 -1
  66. package/dist/testing.js +47 -5
  67. package/dist/worked-on.d.ts +42 -0
  68. package/dist/worked-on.js +79 -0
  69. package/package.json +9 -1
  70. package/src/acknowledge.ts +100 -0
  71. package/src/agreements.ts +185 -0
  72. package/src/allowance.ts +98 -8
  73. package/src/automation-check.ts +120 -9
  74. package/src/automation.ts +78 -10
  75. package/src/behaviour.ts +26 -6
  76. package/src/calendar-entry.ts +258 -0
  77. package/src/capacity.ts +1 -2
  78. package/src/checklists.ts +118 -0
  79. package/src/contract.ts +489 -27
  80. package/src/discount.ts +408 -0
  81. package/src/document.ts +4 -2
  82. package/src/field-types.ts +5 -0
  83. package/src/formula/compile.ts +10 -0
  84. package/src/index.ts +17 -0
  85. package/src/intake.ts +380 -0
  86. package/src/journey-signals.ts +215 -0
  87. package/src/manifest.ts +1236 -65
  88. package/src/mine.ts +161 -0
  89. package/src/occupies.ts +192 -0
  90. package/src/questions.ts +681 -0
  91. package/src/recurring.ts +90 -9
  92. package/src/restricted-fields.ts +129 -0
  93. package/src/rich-text.ts +112 -0
  94. package/src/routine-mail.ts +1272 -0
  95. package/src/runtime.ts +25 -12
  96. package/src/screens.ts +91 -0
  97. package/src/sellable.ts +344 -0
  98. package/src/slug.ts +7 -2
  99. package/src/staffed.ts +474 -0
  100. package/src/states.ts +68 -26
  101. package/src/stock.ts +332 -0
  102. package/src/team.ts +83 -0
  103. package/src/testing.ts +70 -6
  104. package/src/worked-on.ts +134 -0
package/dist/runtime.d.ts CHANGED
@@ -20,6 +20,10 @@ export interface RawHostModules {
20
20
  extract: HostFn;
21
21
  classify: HostFn;
22
22
  };
23
+ /** `codemode:routine-mail` (ADR 0590). */
24
+ "routine-mail"?: {
25
+ send: HostFn;
26
+ };
23
27
  /** `codemode:<gatekeeper>` modules, by gatekeeper name. */
24
28
  [gatekeeper: string]: Record<string, HostFn> | undefined;
25
29
  }
@@ -45,17 +49,7 @@ export type RunResponse = {
45
49
  };
46
50
  };
47
51
  /** What `codemode:ops`'s `call` returns. */
48
- export type OpsReply = {
49
- ok: true;
50
- value: unknown;
51
- } | {
52
- ok: false;
53
- error: {
54
- code: string;
55
- message: string;
56
- details?: unknown;
57
- };
58
- };
52
+ export type OpsReply = RunResponse;
59
53
  /** Thrown by `ctx.ops.call` when the operation fails; `code` is the pipeline's error code. */
60
54
  export declare class OpsCallError extends Error {
61
55
  readonly code: string;
package/dist/runtime.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // `ctx` built from those modules; a module the extension did not declare is absent, and using it
4
4
  // throws.
5
5
  import { durationMs, notificationInput, } from "./automation.js";
6
+ import { DEFAULT_WAIT_TIMEOUT, NOTIFY_OPERATION } from "./automation-check.js";
6
7
  import { toManifest } from "./manifest.js";
7
8
  /** Thrown by `ctx.ops.call` when the operation fails; `code` is the pipeline's error code. */
8
9
  export class OpsCallError extends Error {
@@ -15,6 +16,13 @@ export class OpsCallError extends Error {
15
16
  this.details = details;
16
17
  }
17
18
  }
19
+ // The host answers with an envelope so error codes survive the isolate boundary.
20
+ function unwrap(reply) {
21
+ const r = reply;
22
+ if (r.ok)
23
+ return r.value;
24
+ throw new OpsCallError(r.error.code, r.error.message, r.error.details);
25
+ }
18
26
  function missing(name) {
19
27
  throw new Error(`Host module "${name}" is not declared. Add "${name}" to permissions.modules in defineExtension.`);
20
28
  }
@@ -32,11 +40,7 @@ export function buildContext(extension, raw, pending = [], caller) {
32
40
  const ops = raw.ops
33
41
  ? {
34
42
  call: async (operation, input) => {
35
- // The host answers with an envelope so error codes survive the isolate boundary.
36
- const reply = (await raw.ops?.call(operation, input ?? {}));
37
- if (reply.ok)
38
- return reply.value;
39
- throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
43
+ return unwrap(await raw.ops?.call(operation, input ?? {}));
40
44
  },
41
45
  }
42
46
  : absent("ops");
@@ -67,6 +71,14 @@ export function buildContext(extension, raw, pending = [], caller) {
67
71
  classify: (text, labels) => raw.ai?.classify(text, labels),
68
72
  }
69
73
  : absent("ai");
74
+ const routine = raw["routine-mail"];
75
+ const routineMail = routine?.send
76
+ ? {
77
+ send: async (input) => {
78
+ return unwrap(await routine.send?.(input));
79
+ },
80
+ }
81
+ : absent("routine-mail");
70
82
  const gatekeeper = (name) => {
71
83
  const mod = raw[name];
72
84
  if (!mod?.call)
@@ -74,10 +86,7 @@ export function buildContext(extension, raw, pending = [], caller) {
74
86
  return {
75
87
  connections: () => mod.connections?.(),
76
88
  call: async (connectionId, resource, method, ...args) => {
77
- const reply = (await mod.call?.(connectionId, resource, method, args));
78
- if (reply.ok)
79
- return reply.value;
80
- throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
89
+ return unwrap(await mod.call?.(connectionId, resource, method, args));
81
90
  },
82
91
  types: (connectionId, resource) => mod.types?.(connectionId, resource),
83
92
  };
@@ -89,6 +98,7 @@ export function buildContext(extension, raw, pending = [], caller) {
89
98
  log,
90
99
  ai,
91
100
  gatekeeper: gatekeeper,
101
+ routineMail,
92
102
  ...(caller ? { caller: Object.freeze({ ...caller }) } : {}),
93
103
  };
94
104
  }
@@ -176,7 +186,7 @@ export function buildAutomationContext(extension, raw, event, pending = [], curr
176
186
  const n = (counts.get(step) ?? 0) + 1;
177
187
  counts.set(step, n);
178
188
  const input = notificationInput(event, to, message, `${step}:${n}`);
179
- const out = (await base.ops.call("notification.send", input));
189
+ const out = (await base.ops.call(NOTIFY_OPERATION, input));
180
190
  return { sent: typeof out?.sent === "number" ? out.sent : 0 };
181
191
  },
182
192
  };
@@ -280,7 +290,7 @@ export async function runAutomation(extension, request, raw) {
280
290
  const r = replayed(name, "waitForEvent");
281
291
  if (r)
282
292
  return r.value ?? null;
283
- const timeoutMs = durationMs(declaredWait.timeout ?? "7 days");
293
+ const timeoutMs = durationMs(declaredWait.timeout ?? DEFAULT_WAIT_TIMEOUT);
284
294
  if (test) {
285
295
  testSteps.push({ name, kind: "waitForEvent", skippedMs: timeoutMs });
286
296
  return null;
@@ -0,0 +1,3 @@
1
+ import type { ExtensionManifest } from "./manifest.ts";
2
+ /** The gate fingerprint of a manifest's screens, or null when it declares none. */
3
+ export declare function screenGateFingerprint(m: Partial<ExtensionManifest>): string | null;
@@ -0,0 +1,74 @@
1
+ /** JSON with object keys sorted, so the same manifest gives the same string. */
2
+ function canonical(value) {
3
+ if (Array.isArray(value))
4
+ return `[${value.map(canonical).join(",")}]`;
5
+ if (value && typeof value === "object") {
6
+ const entries = Object.entries(value)
7
+ .filter(([, v]) => v !== undefined)
8
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
9
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
10
+ }
11
+ return JSON.stringify(value ?? null);
12
+ }
13
+ const sorted = (list) => [...(list ?? [])].sort();
14
+ /** The gate fingerprint of a manifest's screens, or null when it declares none. */
15
+ export function screenGateFingerprint(m) {
16
+ const screens = m.screens ?? {};
17
+ if (!Object.keys(screens).length)
18
+ return null;
19
+ const toolNames = new Set(Object.values(screens).flatMap((s) => s.opens ?? []));
20
+ const tools = Object.fromEntries([...toolNames].sort().map((name) => {
21
+ const tool = m.tools?.[name];
22
+ return [
23
+ name,
24
+ tool
25
+ ? {
26
+ risk: tool.risk,
27
+ audiences: sorted(tool.audiences ?? ["staff"]),
28
+ permission: sorted(tool.permission === undefined
29
+ ? []
30
+ : typeof tool.permission === "string"
31
+ ? [tool.permission]
32
+ : tool.permission),
33
+ humanOnly: tool.humanOnly === true,
34
+ grantLiftsRoleLimits: tool.grantLiftsRoleLimits === true,
35
+ // ADR 0652: only when set, so a pack declaring neither keeps its fingerprint.
36
+ ...(tool.anyStaff ? { anyStaff: true } : {}),
37
+ ...(tool.corePermission ? { corePermission: tool.corePermission } : {}),
38
+ }
39
+ : null,
40
+ ];
41
+ }));
42
+ return canonical({
43
+ id: m.id,
44
+ screens: Object.fromEntries(Object.entries(screens).map(([key, s]) => [
45
+ key,
46
+ {
47
+ label: s.label,
48
+ block: s.block,
49
+ export: s.export,
50
+ nav: s.nav ? { group: s.nav.group, order: s.nav.order ?? null } : null,
51
+ opens: [...(s.opens ?? [])],
52
+ writes: [...(s.writes ?? [])],
53
+ record: s.record ? { object: s.record.object, as: s.record.as } : null,
54
+ },
55
+ ])),
56
+ tools,
57
+ restricted: sorted(m.restricted),
58
+ grantable: sorted(m.grantable),
59
+ roles: Object.fromEntries(Object.entries(m.roles ?? {})
60
+ .sort(([a], [b]) => (a < b ? -1 : 1))
61
+ .map(([name, r]) => [
62
+ name,
63
+ {
64
+ permissions: sorted(r.permissions),
65
+ read: sorted(r.read),
66
+ today: r.today ?? null,
67
+ // Left out when absent, so a role without it keeps its fingerprint (ADR 0889).
68
+ looksAfter: r.looksAfter,
69
+ // Left out when absent too (ADR 0755).
70
+ mine: r.mine,
71
+ },
72
+ ])),
73
+ });
74
+ }
@@ -105,7 +105,117 @@ export interface SellableSpec {
105
105
  * `grants`, `deposit`, `recurring`, `onePerPerson`, `maxPerOrder` or `saleWindow`.
106
106
  */
107
107
  moves?: MovesSpec;
108
+ /**
109
+ * What kind of sale this is in the finance reports, and when its money is earned (stage 52,
110
+ * ADR 0792), see FinanceSpec. Left out: category `other`, earned `at_sale`.
111
+ */
112
+ finance?: FinanceSpec;
113
+ /**
114
+ * The records are goods (stage 37, ADR 0682): things handed over or sent (a variant of an item
115
+ * in a shop), see GoodsSpec. An order with goods needs a delivery (`delivery`), and each goods
116
+ * line must be sold in the order's channel. Not with `deposit`, `recurring`, `moves` or
117
+ * `delivery`.
118
+ */
119
+ goods?: GoodsSpec;
120
+ /**
121
+ * The records are ways of getting goods to the buyer (stage 37, ADR 0682): a delivery option,
122
+ * see DeliverySpec. Never a line of `lines`: the buyer chooses one in `order.start`'s and
123
+ * `order.quote`'s `delivery`, and the host prices it (ADR 0685). Not with `goods`, `deposit`,
124
+ * `recurring`, `moves`, `onePerPerson` or `maxPerOrder` (one per order), nor beside `stock`.
125
+ */
126
+ delivery?: DeliverySpec;
127
+ }
128
+ /** Where goods are sold (stage 37 decision 3, ADR 0682): a select field holds one of these. */
129
+ export declare const SOLD_IN: readonly ["online", "in_person", "both"];
130
+ export type SoldIn = (typeof SOLD_IN)[number];
131
+ /** How a delivery option gets goods to the buyer (ADR 0682). */
132
+ export declare const DELIVERY_KINDS: readonly ["post", "collect", "here"];
133
+ export type DeliveryKind = (typeof DELIVERY_KINDS)[number];
134
+ /**
135
+ * Goods (ADR 0682). Every order with goods has a channel the host works out, never the caller's:
136
+ * a `post` or `collect` delivery is `online`, a `here` delivery ("take it now") is `in_person`.
137
+ *
138
+ * - `soldIn`: where a record is sold: a select field whose values are among `online`,
139
+ * `in_person` and `both`, of this object or through up to two relations (`item.whereSold`: a
140
+ * variant is sold where its item is). Left out or empty: both. A line not sold in the order's
141
+ * channel is refused (`rule: "not_sold_here"`), on every path.
142
+ */
143
+ export interface GoodsSpec {
144
+ soldIn?: string;
145
+ }
146
+ /**
147
+ * A delivery option (ADR 0682, priced by ADR 0685). A record is one way of getting an order's
148
+ * goods to the buyer; its object is sellable, so it has a price (which may be 0), a tax code and
149
+ * what a paid line grants (a shipment to pack, for `post` and `collect`; nothing is granted for a
150
+ * `here` record).
151
+ *
152
+ * - `kind`: a select field whose values are among `post` (an address is needed, in one of the
153
+ * option's countries), `collect` (at a place the record says; no address) and `here` (take it
154
+ * now, in person; no address).
155
+ * - `freeOver`: a currency or number field: when the goods on the order cost at least this
156
+ * (before the delivery), the delivery costs nothing. Empty: never free.
157
+ * - `countries`: a text field: the two-letter country codes (ISO 3166-1) a `post` record posts
158
+ * to, separated by commas or spaces; or `*`, everywhere no other post option of the object
159
+ * names. Empty: it posts nowhere yet.
160
+ * - `active`: a boolean field: a record with it off cannot be chosen.
161
+ */
162
+ export interface DeliverySpec {
163
+ kind: string;
164
+ freeOver?: string;
165
+ countries?: string;
166
+ active?: string;
167
+ }
168
+ /** How a sale's money is earned (ADR 0792), as the Unearned report reads it. */
169
+ export declare const EARNED: readonly ["at_sale", "over_period", "per_use", "at_date"];
170
+ export type Earned = (typeof EARNED)[number];
171
+ /**
172
+ * What kind of sale a sellable object is in the finance reports (stage 52, ADR 0792). It only
173
+ * labels the object's own sales: it prices nothing, grants nothing and moves no money. Which way
174
+ * the books treat a sale is the business's accountant's call; this says what the reports show.
175
+ *
176
+ * - `category`: the kind of sale its lines are counted under in Sales, Tax, Refunds and the book
177
+ * entries' `sales:<key>` and `refunds:<key>` headings. `key` is stable (lower case, digits and
178
+ * `_`); `label` is what the reports call it until an admin renames it. Two objects with the same
179
+ * key are one category, so this extension gives them one label.
180
+ * - `earned`: when the money is earned, for the Unearned report (cash is counted when it moved,
181
+ * whatever this says):
182
+ * - `at_sale`: when it is paid (a course, goods);
183
+ * - `over_period`: day by day over the order's period, from its start to its end (a plan's
184
+ * paid period); only on a plan (`recurring`);
185
+ * - `per_use`: as the uses of what a paid line grants are spent, the rest when it expires (a
186
+ * class pass); only when `grants` grants an object that holds uses (`allowance.holds`);
187
+ * - `at_date`: on the date in `at` (an event's start).
188
+ * - `at`: with `at_date`, a date or datetime field of this object, or `<relation>.<field>` through
189
+ * up to two relations (`event.startsAt`, `class.startsAt`).
190
+ *
191
+ * A line whose object issues stored value or a voucher (stage 34) is held for customers, not a
192
+ * sale, whatever it declares.
193
+ */
194
+ export interface FinanceSpec {
195
+ category?: {
196
+ key: string;
197
+ label: string;
198
+ };
199
+ earned?: Earned;
200
+ at?: string;
108
201
  }
202
+ /** What `sellable.finance` comes to when it, or a part of it, is left out (ADR 0792). */
203
+ export declare const FINANCE_DEFAULTS: {
204
+ readonly category: {
205
+ readonly key: "other";
206
+ readonly label: "Other";
207
+ };
208
+ readonly earned: "at_sale";
209
+ };
210
+ /** A sellable object's finance declaration with its defaults filled (ADR 0792). */
211
+ export declare function sellableFinance(finance: FinanceSpec | undefined): {
212
+ category: {
213
+ key: string;
214
+ label: string;
215
+ };
216
+ earned: Earned;
217
+ at?: string;
218
+ };
109
219
  /**
110
220
  * What an order does to the record it was started for (ADR 0560): a drop-in booking held while
111
221
  * its order is unpaid. The host makes every move, as the host, in the batch that moves the order.
@@ -189,7 +299,23 @@ export interface RecurringSpec {
189
299
  minDays?: string;
190
300
  maxDays?: string;
191
301
  };
302
+ /**
303
+ * A cooling-off period (stage 44 step 7, decision 11, ADR 0647): `setting` names a number setting
304
+ * of this extension holding whole days (0: off), which a person changes (`personApproves`),
305
+ * between 0 and `MAX_COOLING_OFF_DAYS`. A new member (a subscription started here without a
306
+ * continuation offer) may end their subscription within that many days of the provider-confirmed
307
+ * start, counted in the business's time zone to the end of the last day, for a full refund of
308
+ * what they paid; each refund waits for a person with `orders:refund` (ADR 0429). Once per
309
+ * holder. The days in force when a subscription started are kept with it: a setting shortened
310
+ * later never shortens that member's window. What any law requires is the business's to
311
+ * confirm; the platform only holds the number.
312
+ */
313
+ coolingOff?: {
314
+ setting: string;
315
+ };
192
316
  }
317
+ /** The longest cooling-off period the host keeps (days); a longer setting reads as this. */
318
+ export declare const MAX_COOLING_OFF_DAYS = 90;
193
319
  /** Where a field of what a subscription grants gets its value (see RecurringSpec.grants). */
194
320
  export type RecurringGrantSource = "item" | `item.${string}` | "subscription" | "subscription.holder" | "subscription.payer";
195
321
  /** The host's subscription states a grant follows (ADR 0485). */
@@ -242,14 +368,14 @@ export declare const sellableManifestSchema: z.ZodObject<{
242
368
  grants: z.ZodOptional<z.ZodObject<{
243
369
  object: z.ZodString;
244
370
  set: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodEnum<{
245
- item: "item";
371
+ code: "code";
246
372
  order: "order";
373
+ item: "item";
247
374
  "order.person": "order.person";
248
375
  "order.email": "order.email";
249
376
  line: "line";
250
377
  "line.title": "line.title";
251
378
  "line.unitPrice": "line.unitPrice";
252
- code: "code";
253
379
  }>, z.ZodString]>>;
254
380
  void: z.ZodString;
255
381
  valid: z.ZodOptional<z.ZodObject<{
@@ -297,6 +423,9 @@ export declare const sellableManifestSchema: z.ZodObject<{
297
423
  minDays: z.ZodOptional<z.ZodString>;
298
424
  maxDays: z.ZodOptional<z.ZodString>;
299
425
  }, z.core.$strict>>;
426
+ coolingOff: z.ZodOptional<z.ZodObject<{
427
+ setting: z.ZodString;
428
+ }, z.core.$strict>>;
300
429
  grants: z.ZodOptional<z.ZodObject<{
301
430
  object: z.ZodString;
302
431
  set: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodEnum<{
@@ -317,6 +446,28 @@ export declare const sellableManifestSchema: z.ZodObject<{
317
446
  }, z.core.$strict>;
318
447
  }, z.core.$strict>>;
319
448
  }, z.core.$strict>>;
449
+ finance: z.ZodOptional<z.ZodObject<{
450
+ category: z.ZodOptional<z.ZodObject<{
451
+ key: z.ZodString;
452
+ label: z.ZodString;
453
+ }, z.core.$strict>>;
454
+ earned: z.ZodOptional<z.ZodEnum<{
455
+ at_sale: "at_sale";
456
+ over_period: "over_period";
457
+ per_use: "per_use";
458
+ at_date: "at_date";
459
+ }>>;
460
+ at: z.ZodOptional<z.ZodString>;
461
+ }, z.core.$strict>>;
462
+ goods: z.ZodOptional<z.ZodObject<{
463
+ soldIn: z.ZodOptional<z.ZodString>;
464
+ }, z.core.$strict>>;
465
+ delivery: z.ZodOptional<z.ZodObject<{
466
+ kind: z.ZodString;
467
+ freeOver: z.ZodOptional<z.ZodString>;
468
+ countries: z.ZodOptional<z.ZodString>;
469
+ active: z.ZodOptional<z.ZodString>;
470
+ }, z.core.$strict>>;
320
471
  }, z.core.$strict>;
321
472
  export type SellableManifest = z.infer<typeof sellableManifestSchema>;
322
473
  /** Reports problems with `objects.<name>.sellable` through `contract`. */
package/dist/sellable.js CHANGED
@@ -6,6 +6,27 @@
6
6
  import { z } from "zod";
7
7
  import { customerWritable, spendsOnList } from "./allowance.js";
8
8
  import { moveOrigins, resolveFieldPath } from "./states.js";
9
+ /** Where goods are sold (stage 37 decision 3, ADR 0682): a select field holds one of these. */
10
+ export const SOLD_IN = ["online", "in_person", "both"];
11
+ /** How a delivery option gets goods to the buyer (ADR 0682). */
12
+ export const DELIVERY_KINDS = ["post", "collect", "here"];
13
+ /** How a sale's money is earned (ADR 0792), as the Unearned report reads it. */
14
+ export const EARNED = ["at_sale", "over_period", "per_use", "at_date"];
15
+ /** What `sellable.finance` comes to when it, or a part of it, is left out (ADR 0792). */
16
+ export const FINANCE_DEFAULTS = {
17
+ category: { key: "other", label: "Other" },
18
+ earned: "at_sale",
19
+ };
20
+ /** A sellable object's finance declaration with its defaults filled (ADR 0792). */
21
+ export function sellableFinance(finance) {
22
+ return {
23
+ category: finance?.category ?? FINANCE_DEFAULTS.category,
24
+ earned: finance?.earned ?? FINANCE_DEFAULTS.earned,
25
+ ...(finance?.at !== undefined ? { at: finance.at } : {}),
26
+ };
27
+ }
28
+ /** The longest cooling-off period the host keeps (days); a longer setting reads as this. */
29
+ export const MAX_COOLING_OFF_DAYS = 90;
9
30
  /** The host's subscription states a grant follows (ADR 0485). */
10
31
  export const SUBSCRIPTION_GRANT_STATES = [
11
32
  "trialing",
@@ -114,6 +135,7 @@ export const sellableManifestSchema = z
114
135
  .object({ minDays: fieldName.optional(), maxDays: fieldName.optional() })
115
136
  .strict()
116
137
  .optional(),
138
+ coolingOff: z.object({ setting: fieldName }).strict().optional(),
117
139
  grants: z
118
140
  .object({
119
141
  object: z.string().max(40),
@@ -136,6 +158,33 @@ export const sellableManifestSchema = z
136
158
  })
137
159
  .strict()
138
160
  .optional(),
161
+ finance: z
162
+ .object({
163
+ category: z
164
+ .object({
165
+ key: z.string().regex(/^[a-z][a-z0-9_]{0,39}$/, "Lower case letters, digits and _"),
166
+ label: z.string().min(1).max(60),
167
+ })
168
+ .strict()
169
+ .optional(),
170
+ earned: z.enum(EARNED).optional(),
171
+ at: z.string().max(130).optional(),
172
+ })
173
+ .strict()
174
+ .optional(),
175
+ goods: z
176
+ .object({ soldIn: z.string().max(130).optional() })
177
+ .strict()
178
+ .optional(),
179
+ delivery: z
180
+ .object({
181
+ kind: fieldName,
182
+ freeOver: fieldName.optional(),
183
+ countries: fieldName.optional(),
184
+ active: fieldName.optional(),
185
+ })
186
+ .strict()
187
+ .optional(),
139
188
  })
140
189
  .strict();
141
190
  const NUMERIC = new Set(["number", "currency"]);
@@ -192,6 +241,28 @@ export function checkObjectSellable(m, name, object, contract) {
192
241
  contract(`${path}.recurring.pause.${key}`, `"${days}" must be a number field of ${name}`);
193
242
  }
194
243
  }
244
+ const coolingOff = sellable.recurring.coolingOff;
245
+ if (coolingOff) {
246
+ const settings = m.settings ?? {};
247
+ const setting = Object.hasOwn(settings, coolingOff.setting)
248
+ ? settings[coolingOff.setting]
249
+ : undefined;
250
+ const at = `${path}.recurring.coolingOff.setting`;
251
+ if (setting?.type !== "number") {
252
+ contract(at, `"${coolingOff.setting}" must be a number setting of ${m.id}`);
253
+ }
254
+ else if (setting.personApproves !== true) {
255
+ // Refunds follow from it: a person's to change, never an AI's (decision 11).
256
+ contract(at, `"${coolingOff.setting}" must be a setting a person approves (personApproves): the cooling-off days are never an AI's to change`);
257
+ }
258
+ else if (setting.min === undefined ||
259
+ setting.min < 0 ||
260
+ setting.max === undefined ||
261
+ setting.max > MAX_COOLING_OFF_DAYS ||
262
+ (typeof setting.default === "number" && setting.default !== 0)) {
263
+ contract(at, `"${coolingOff.setting}" must be bounded from 0 to at most ${MAX_COOLING_OFF_DAYS} days, and off (0 or no default) until a person sets it`);
264
+ }
265
+ }
195
266
  if (sellable.onePerPerson !== undefined) {
196
267
  contract(`${path}.onePerPerson`, "A plan's trial is already one per person (ADR 0489); onePerPerson is for things bought once");
197
268
  }
@@ -221,6 +292,11 @@ export function checkObjectSellable(m, name, object, contract) {
221
292
  checkGrants(m, name, object, sellable.grants, `${path}.grants`, contract);
222
293
  if (sellable.moves)
223
294
  checkMoves(m, name, object, sellable.moves, `${path}.moves`, contract);
295
+ if (sellable.goods || sellable.delivery)
296
+ checkGoods(m, name, object, path, contract);
297
+ if (sellable.finance) {
298
+ checkFinance(m, name, object, sellable.finance, `${path}.finance`, contract);
299
+ }
224
300
  const place = sellable.tax?.place;
225
301
  if (place) {
226
302
  let holder = object;
@@ -254,6 +330,118 @@ export function checkObjectSellable(m, name, object, contract) {
254
330
  }
255
331
  }
256
332
  }
333
+ /** A select field's option values (empty when it is not a select field). */
334
+ function selectValues(field) {
335
+ if (!field || field.type !== "select" || field.many)
336
+ return null;
337
+ return (field.options ?? []).map((option) => typeof option === "string" ? option : option.value);
338
+ }
339
+ /**
340
+ * Checks `sellable.goods` and `sellable.delivery` (ADR 0682): where goods are sold is a select of
341
+ * `online`, `in_person` and `both`; a delivery option's kind a select of `post`, `collect` and
342
+ * `here`, with its other fields of the right types; and neither is bought by deposit, by
343
+ * subscription or by moving a record. A delivery is one per order and has no stock.
344
+ */
345
+ function checkGoods(m, name, object, path, contract) {
346
+ const sellable = object.sellable;
347
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
348
+ if (sellable.goods && sellable.delivery) {
349
+ contract(`${path}.delivery`, "A record is goods or a delivery option, not both");
350
+ }
351
+ const what = sellable.goods ? "goods" : "a delivery option";
352
+ for (const key of ["deposit", "recurring", "moves"]) {
353
+ if (sellable[key] !== undefined) {
354
+ contract(`${path}.${key}`, `${name} is ${what}, sold whole on an order: it has no ${key}`);
355
+ }
356
+ }
357
+ const soldIn = sellable.goods?.soldIn;
358
+ if (soldIn !== undefined) {
359
+ const values = selectValues(resolveFieldPath(m, object, soldIn));
360
+ if (!values || values.some((v) => !SOLD_IN.includes(v))) {
361
+ contract(`${path}.goods.soldIn`, `"${soldIn}" must be a select field (of ${name}, or through its relations) whose values are among ${SOLD_IN.join(", ")}`);
362
+ }
363
+ }
364
+ const delivery = sellable.delivery;
365
+ if (!delivery)
366
+ return;
367
+ for (const key of ["onePerPerson", "maxPerOrder"]) {
368
+ if (sellable[key] !== undefined) {
369
+ contract(`${path}.${key}`, `A delivery option is one per order: it has no ${key}`);
370
+ }
371
+ }
372
+ if (object.stock) {
373
+ contract(`objects.${name}.stock`, "A delivery option is not counted on a shelf: no stock");
374
+ }
375
+ const kinds = selectValues(fieldOf(delivery.kind));
376
+ if (!kinds?.length || kinds.some((v) => !DELIVERY_KINDS.includes(v))) {
377
+ contract(`${path}.delivery.kind`, `"${delivery.kind}" must be a select field of ${name} whose values are among ${DELIVERY_KINDS.join(", ")}`);
378
+ }
379
+ if (delivery.freeOver !== undefined) {
380
+ const field = fieldOf(delivery.freeOver);
381
+ if (!field || !NUMERIC.has(field.type) || field.many) {
382
+ contract(`${path}.delivery.freeOver`, `"${delivery.freeOver}" must be a currency or number field of ${name}`);
383
+ }
384
+ }
385
+ if (delivery.countries !== undefined) {
386
+ const field = fieldOf(delivery.countries);
387
+ if (!field || !TEXT.has(field.type) || field.many) {
388
+ contract(`${path}.delivery.countries`, `"${delivery.countries}" must be a text field of ${name}`);
389
+ }
390
+ }
391
+ if (delivery.active !== undefined) {
392
+ const field = fieldOf(delivery.active);
393
+ if (!field || field.type !== "boolean" || field.many) {
394
+ contract(`${path}.delivery.active`, `"${delivery.active}" must be a boolean field of ${name}`);
395
+ }
396
+ }
397
+ }
398
+ /**
399
+ * Checks `sellable.finance` (ADR 0792): each way of earning names what the host reads to work it
400
+ * out, and one category key has one label across this extension.
401
+ */
402
+ function checkFinance(m, name, object, finance, path, contract) {
403
+ const sellable = object.sellable;
404
+ const earned = finance.earned ?? FINANCE_DEFAULTS.earned;
405
+ if (earned === "at_date") {
406
+ if (finance.at === undefined) {
407
+ contract(`${path}.at`, "at_date names its date: at, a date or datetime field");
408
+ }
409
+ else {
410
+ const at = resolveFieldPath(m, object, finance.at);
411
+ if (!at || at.many || !DATES.has(at.type)) {
412
+ contract(`${path}.at`, `"${finance.at}" must be a date or datetime field of ${name}, or <relation>.<field> through up to two relations, every field on the way declared by this extension`);
413
+ }
414
+ }
415
+ }
416
+ else if (finance.at !== undefined) {
417
+ contract(`${path}.at`, "at is the date of at_date: declare earned: at_date, or remove at");
418
+ }
419
+ if (earned === "over_period" && !sellable.recurring) {
420
+ contract(`${path}.earned`, "over_period is earned over a paid period: only a plan (recurring) has one");
421
+ }
422
+ if (earned === "per_use") {
423
+ const grants = sellable.grants;
424
+ const local = grants?.object.startsWith(`${m.id}.`)
425
+ ? grants.object.slice(m.id.length + 1)
426
+ : grants?.object;
427
+ const granted = local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
428
+ if (!granted?.allowance || !("holds" in granted.allowance)) {
429
+ contract(`${path}.earned`, "per_use is earned as uses are spent: grants must grant an object that holds uses (allowance.holds)");
430
+ }
431
+ }
432
+ const category = finance.category;
433
+ if (category) {
434
+ for (const [other, o] of Object.entries(m.objects)) {
435
+ if (other === name)
436
+ continue;
437
+ const theirs = o.sellable?.finance?.category;
438
+ if (theirs?.key === category.key && theirs.label !== category.label) {
439
+ contract(`${path}.category.label`, `${other} names category "${category.key}" "${theirs.label}": one category has one label`);
440
+ break;
441
+ }
442
+ }
443
+ }
444
+ }
257
445
  /**
258
446
  * Checks `sellable.moves` (ADR 0560): each of these is a way the order's batch could otherwise fail
259
447
  * (a payment the host could not apply), or a record someone could hold with no order.
package/dist/slug.d.ts CHANGED
@@ -9,3 +9,5 @@ export declare const SLUG_FROM_TITLE_MAX = 80;
9
9
  * a hyphen, at most SLUG_FROM_TITLE_MAX characters. Empty when nothing is left.
10
10
  */
11
11
  export declare function slugify(title: string): string;
12
+ /** Text as words of lowercase letters and digits joined by hyphens, accents dropped, at most `max`. */
13
+ export declare function hyphenate(text: string, max: number): string;
package/dist/slug.js CHANGED
@@ -13,11 +13,15 @@ export const SLUG_FROM_TITLE_MAX = 80;
13
13
  * a hyphen, at most SLUG_FROM_TITLE_MAX characters. Empty when nothing is left.
14
14
  */
15
15
  export function slugify(title) {
16
- const plain = title
16
+ return hyphenate(title, SLUG_FROM_TITLE_MAX);
17
+ }
18
+ /** Text as words of lowercase letters and digits joined by hyphens, accents dropped, at most `max`. */
19
+ export function hyphenate(text, max) {
20
+ const plain = text
17
21
  .normalize("NFKD")
18
22
  .replace(/[̀-ͯ]/g, "")
19
23
  .toLowerCase()
20
24
  .replace(/[^a-z0-9]+/g, "-")
21
25
  .replace(/^-+|-+$/g, "");
22
- return plain.slice(0, SLUG_FROM_TITLE_MAX).replace(/-+$/g, "");
26
+ return plain.slice(0, max).replace(/-+$/g, "");
23
27
  }