@composable-os/sdk 0.1.0-beta.10 → 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 (105) 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.d.ts +69 -0
  15. package/dist/capacity.js +63 -2
  16. package/dist/checklists.d.ts +41 -0
  17. package/dist/checklists.js +75 -0
  18. package/dist/contract.d.ts +527 -26
  19. package/dist/contract.js +21 -3
  20. package/dist/discount.d.ts +135 -0
  21. package/dist/discount.js +281 -0
  22. package/dist/document.d.ts +2 -1
  23. package/dist/document.js +2 -1
  24. package/dist/field-types.d.ts +1 -1
  25. package/dist/field-types.js +5 -0
  26. package/dist/formula/compile.d.ts +15 -0
  27. package/dist/formula/compile.js +9 -0
  28. package/dist/index.d.ts +17 -0
  29. package/dist/index.js +17 -0
  30. package/dist/intake.d.ts +134 -0
  31. package/dist/intake.js +239 -0
  32. package/dist/journey-signals.d.ts +89 -0
  33. package/dist/journey-signals.js +151 -0
  34. package/dist/manifest.d.ts +1060 -60
  35. package/dist/manifest.js +1111 -61
  36. package/dist/mine.d.ts +45 -0
  37. package/dist/mine.js +119 -0
  38. package/dist/occupies.d.ts +64 -0
  39. package/dist/occupies.js +122 -0
  40. package/dist/questions.d.ts +179 -0
  41. package/dist/questions.js +514 -0
  42. package/dist/recurring.d.ts +33 -4
  43. package/dist/recurring.js +50 -3
  44. package/dist/restricted-fields.d.ts +15 -0
  45. package/dist/restricted-fields.js +97 -0
  46. package/dist/rich-text.d.ts +22 -0
  47. package/dist/rich-text.js +91 -0
  48. package/dist/routine-mail.d.ts +400 -0
  49. package/dist/routine-mail.js +955 -0
  50. package/dist/runtime.d.ts +5 -11
  51. package/dist/runtime.js +21 -11
  52. package/dist/screens.d.ts +3 -0
  53. package/dist/screens.js +74 -0
  54. package/dist/sellable.d.ts +231 -2
  55. package/dist/sellable.js +342 -1
  56. package/dist/slug.d.ts +2 -0
  57. package/dist/slug.js +6 -2
  58. package/dist/staffed.d.ts +178 -0
  59. package/dist/staffed.js +287 -0
  60. package/dist/states.d.ts +74 -4
  61. package/dist/states.js +154 -58
  62. package/dist/stock.d.ts +129 -0
  63. package/dist/stock.js +205 -0
  64. package/dist/team.d.ts +28 -0
  65. package/dist/team.js +52 -0
  66. package/dist/testing.d.ts +22 -1
  67. package/dist/testing.js +47 -5
  68. package/dist/worked-on.d.ts +42 -0
  69. package/dist/worked-on.js +79 -0
  70. package/package.json +9 -1
  71. package/src/acknowledge.ts +100 -0
  72. package/src/agreements.ts +185 -0
  73. package/src/allowance.ts +98 -8
  74. package/src/automation-check.ts +120 -9
  75. package/src/automation.ts +78 -10
  76. package/src/behaviour.ts +26 -6
  77. package/src/calendar-entry.ts +258 -0
  78. package/src/capacity.ts +103 -2
  79. package/src/checklists.ts +118 -0
  80. package/src/contract.ts +514 -27
  81. package/src/discount.ts +408 -0
  82. package/src/document.ts +4 -2
  83. package/src/field-types.ts +5 -0
  84. package/src/formula/compile.ts +10 -0
  85. package/src/index.ts +17 -0
  86. package/src/intake.ts +380 -0
  87. package/src/journey-signals.ts +215 -0
  88. package/src/manifest.ts +1313 -66
  89. package/src/mine.ts +161 -0
  90. package/src/occupies.ts +192 -0
  91. package/src/questions.ts +681 -0
  92. package/src/recurring.ts +90 -9
  93. package/src/restricted-fields.ts +129 -0
  94. package/src/rich-text.ts +112 -0
  95. package/src/routine-mail.ts +1272 -0
  96. package/src/runtime.ts +25 -12
  97. package/src/screens.ts +91 -0
  98. package/src/sellable.ts +595 -1
  99. package/src/slug.ts +7 -2
  100. package/src/staffed.ts +474 -0
  101. package/src/states.ts +220 -64
  102. package/src/stock.ts +332 -0
  103. package/src/team.ts +83 -0
  104. package/src/testing.ts +70 -6
  105. package/src/worked-on.ts +134 -0
package/dist/contract.js CHANGED
@@ -22,16 +22,34 @@ export const GATEKEEPER_MODULES = [
22
22
  "fake",
23
23
  ];
24
24
  /** Host modules an extension can ask for (ADR 0025). There is no HTTP module. */
25
- export const HOST_MODULES = ["ops", "storage", "log", "ai", ...GATEKEEPER_MODULES];
25
+ export const HOST_MODULES = [
26
+ "ops",
27
+ "storage",
28
+ "log",
29
+ "ai",
30
+ // Routine mail (ADR 0590): a shipped pack's declared emails, in its automations only.
31
+ "routine-mail",
32
+ ...GATEKEEPER_MODULES,
33
+ ];
26
34
  /** Risk classes an extension tool may declare (schema and extension risks are host-only). */
27
35
  export const TOOL_RISKS = ["read", "write", "bulk-write", "destructive"];
28
36
  /** Stage types every stage object distinguishes. */
29
37
  export const STAGE_TYPES = ["open", "won", "lost"];
30
- /** Who may call a tool. `staff` when nothing is declared (ADR 0402). */
31
- export const TOOL_AUDIENCES = ["staff", "customer", "public"];
38
+ /**
39
+ * Who may call a tool. `staff` when nothing is declared (ADR 0402). `device` (ADR 0781): an
40
+ * enrolled device whose device role holds the tool's permission, on the desk origin only; a tool
41
+ * open to `device` is open to nobody else.
42
+ */
43
+ export const TOOL_AUDIENCES = ["staff", "customer", "public", "device"];
32
44
  export function defineTool(tool) {
33
45
  return tool;
34
46
  }
47
+ /** How a Today item's value is shown. Money is never a pack's: it is the host's (stage 52). */
48
+ export const TODAY_ITEM_FORMATS = ["count", "percent"];
49
+ /** What a Today item's value is compared with: the same time yesterday or a week ago, or nothing. */
50
+ export const TODAY_ITEM_COMPARES = ["yesterday", "lastWeek", "none"];
51
+ /** The parameters the host binds into a Today item's SQL: the local day `[from, to)` and now. */
52
+ export const TODAY_ITEM_PARAMS = ["today_from", "today_to", "now"];
35
53
  const EXTENSION = Symbol.for("ops.extension");
36
54
  /** The entry point of every extension: `export default defineExtension({ ... })`. */
37
55
  export function defineExtension(extension) {
@@ -0,0 +1,135 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * What a discount takes off: `percent` of each line it applies to (rounded down per line);
5
+ * `amount`, money off the order, spread over the lines it applies to in proportion; `price`, a set
6
+ * price for one of each line it applies to (a member's $15 drop-in), never above the line's own.
7
+ */
8
+ export declare const DISCOUNT_KINDS: readonly ["percent", "amount", "price"];
9
+ export type DiscountKind = (typeof DISCOUNT_KINDS)[number];
10
+ /**
11
+ * Who a discount is for. `anyone` includes a guest. Every other value needs a buyer who proved who
12
+ * they are (a signed-in customer, or staff buying for a Person): a guest never qualifies, the same
13
+ * answer for every address. `members`: the Person holds a live subscription (to one of `plans`
14
+ * when it names any). `new_customers`: no paid order and no subscription for any Person sharing a
15
+ * folded address with them (ADR 0692). `organisation`: the Person is currently at one of
16
+ * `organisations`. `tag`: the Person has the tag named in `tag`.
17
+ */
18
+ export declare const DISCOUNT_WHO: readonly ["anyone", "signed_in", "members", "new_customers", "organisation", "tag"];
19
+ export type DiscountWho = (typeof DISCOUNT_WHO)[number];
20
+ /**
21
+ * A promo code as the host keeps and compares it (ADR 0940): Unicode-normalised (NFKC), with no
22
+ * white space and no invisible characters (zero-width spaces, soft hyphens: Unicode's default
23
+ * ignorables), in upper case, so `été 26`, `ÉTÉ26` and `Été26` are one code, and non-ASCII letters
24
+ * match however they are typed. The host stores a code word folded when a record is written, and
25
+ * folds what a buyer types the same way before it looks the word up by its index. One function,
26
+ * here, for both.
27
+ */
28
+ export declare function foldCode(word: string): string;
29
+ /** The least length of a code word, in characters after folding (ADR 0940): no `SALE`, no `A1`. */
30
+ export declare const CODE_MIN_LENGTH = 6;
31
+ /** The longest code word (and the longest a buyer may type). */
32
+ export declare const CODE_MAX_LENGTH = 64;
33
+ /**
34
+ * The letters a generated code is made of: 32, with no 0, 1, I or O, so nothing is misread and
35
+ * each character is 5 bits exactly (no bias from the random bytes).
36
+ */
37
+ export declare const CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
38
+ /**
39
+ * `count` random single-use codes (ADR 0940), each `length` characters of CODE_ALPHABET from
40
+ * `crypto.getRandomValues`: 16 by default, 80 bits, which no rate of guessing reaches. Already
41
+ * folded. For a pack's tool that makes a batch of codes; a person still approves writing them
42
+ * (ADR 0693).
43
+ */
44
+ export declare function randomCodes(count: number, length?: number): string[];
45
+ /**
46
+ * Codes kept as records of another object of this extension (a promo code belongs to a
47
+ * discount): `discount` is that object's relation field (one record) to this object, `word` its
48
+ * text field holding what the buyer types (compared without case), `uses` an optional number field
49
+ * of the most orders one code may be used on (1: a single-use code), and `active` an optional
50
+ * boolean field that, off, voids the code.
51
+ */
52
+ export interface DiscountCodesSpec {
53
+ object: string;
54
+ discount: string;
55
+ word: string;
56
+ uses?: string;
57
+ active?: string;
58
+ }
59
+ /**
60
+ * Records that are discounts (ADR 0693). Every name is a field of this object.
61
+ *
62
+ * - `kind`: a select field whose options are among `percent`, `amount` and `price`; `percent` the
63
+ * number field of the percentage (0 to 100), `amount` the currency or number field of the amount
64
+ * off or the set price, in the currency's major unit.
65
+ * - `live`: the states (of this object's `states`) in which the discount applies. Entering one is
66
+ * a person's act: every move into a live state is by `["host"]` with the tools a person makes it
67
+ * through, or by staff writing a state field declared `personApproves`, and nothing is created
68
+ * live but by the host, so an assistant's request waits for a person. The host also holds any
69
+ * change to a live discount by anyone but a person for a person's approval.
70
+ * - How it applies: `automatic`, a boolean field (on: it applies by itself to whoever qualifies);
71
+ * `code`, a text field of one shared word; `codes`, codes kept as records of another object. At
72
+ * least one.
73
+ * - `who`: a select field whose options are among DISCOUNT_WHO (left out: anyone); `plans` a
74
+ * relation field to plans (`members`), `organisations` one to organisations, `tag` a text field.
75
+ * - On what: `objects`, a multi-select (or select) field whose option values are the objects it
76
+ * applies to (`bookings.booking`), and `records`, relation fields naming records it applies to.
77
+ * With neither, every line but a delivery. A line it applies to is any of either.
78
+ * - When: `from` and `until`, date or datetime fields (a date from the start of its day through
79
+ * its end, UTC).
80
+ * - Limits: `totalUses` (orders across everyone), `perPerson` (orders per Person, folded
81
+ * addresses counting as one), number fields; `minSpend`, a currency or number field of the least
82
+ * the lines it applies to must cost. A use is held from the order's start, used when it is paid,
83
+ * given back when it expires or is cancelled unpaid; a refund keeps it used.
84
+ *
85
+ * Not on an object that is sellable, has stock or a capacity: a discount is not bought.
86
+ */
87
+ export interface DiscountSpec {
88
+ kind: string;
89
+ percent?: string;
90
+ amount?: string;
91
+ live: readonly string[];
92
+ automatic?: string;
93
+ code?: string;
94
+ codes?: DiscountCodesSpec;
95
+ who?: string;
96
+ plans?: string;
97
+ organisations?: string;
98
+ tag?: string;
99
+ objects?: string;
100
+ records?: readonly string[];
101
+ from?: string;
102
+ until?: string;
103
+ totalUses?: string;
104
+ perPerson?: string;
105
+ minSpend?: string;
106
+ }
107
+ export declare const discountManifestSchema: z.ZodObject<{
108
+ kind: z.ZodString;
109
+ percent: z.ZodOptional<z.ZodString>;
110
+ amount: z.ZodOptional<z.ZodString>;
111
+ live: z.ZodArray<z.ZodString>;
112
+ automatic: z.ZodOptional<z.ZodString>;
113
+ code: z.ZodOptional<z.ZodString>;
114
+ codes: z.ZodOptional<z.ZodObject<{
115
+ object: z.ZodString;
116
+ discount: z.ZodString;
117
+ word: z.ZodString;
118
+ uses: z.ZodOptional<z.ZodString>;
119
+ active: z.ZodOptional<z.ZodString>;
120
+ }, z.core.$strict>>;
121
+ who: z.ZodOptional<z.ZodString>;
122
+ plans: z.ZodOptional<z.ZodString>;
123
+ organisations: z.ZodOptional<z.ZodString>;
124
+ tag: z.ZodOptional<z.ZodString>;
125
+ objects: z.ZodOptional<z.ZodString>;
126
+ records: z.ZodOptional<z.ZodArray<z.ZodString>>;
127
+ from: z.ZodOptional<z.ZodString>;
128
+ until: z.ZodOptional<z.ZodString>;
129
+ totalUses: z.ZodOptional<z.ZodString>;
130
+ perPerson: z.ZodOptional<z.ZodString>;
131
+ minSpend: z.ZodOptional<z.ZodString>;
132
+ }, z.core.$strict>;
133
+ export type DiscountManifest = z.infer<typeof discountManifestSchema>;
134
+ /** Reports problems with `objects.<name>.discount` through `contract`. */
135
+ export declare function checkObjectDiscount(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
@@ -0,0 +1,281 @@
1
+ // The `discount` behaviour (stage 34 step 4, ADR 0693): an object declares that its records are
2
+ // discounts (money off an order), and names the fields that say what is off, on what, for whom,
3
+ // when and how often. The host reads the record when it prices an order and enforces every rule:
4
+ // a code a buyer types, a member's price that applies by itself, one deal per order (the better
5
+ // for the buyer), and limits the database keeps under orders started at once. No caller sends an
6
+ // amount: a caller sends at most a code. Its declaration, its manifest schema and its contract
7
+ // checks live here; the host's side is packages/core/src/discounts/.
8
+ import { z } from "zod";
9
+ import { moveOrigins } from "./states.js";
10
+ /**
11
+ * What a discount takes off: `percent` of each line it applies to (rounded down per line);
12
+ * `amount`, money off the order, spread over the lines it applies to in proportion; `price`, a set
13
+ * price for one of each line it applies to (a member's $15 drop-in), never above the line's own.
14
+ */
15
+ export const DISCOUNT_KINDS = ["percent", "amount", "price"];
16
+ /**
17
+ * Who a discount is for. `anyone` includes a guest. Every other value needs a buyer who proved who
18
+ * they are (a signed-in customer, or staff buying for a Person): a guest never qualifies, the same
19
+ * answer for every address. `members`: the Person holds a live subscription (to one of `plans`
20
+ * when it names any). `new_customers`: no paid order and no subscription for any Person sharing a
21
+ * folded address with them (ADR 0692). `organisation`: the Person is currently at one of
22
+ * `organisations`. `tag`: the Person has the tag named in `tag`.
23
+ */
24
+ export const DISCOUNT_WHO = [
25
+ "anyone",
26
+ "signed_in",
27
+ "members",
28
+ "new_customers",
29
+ "organisation",
30
+ "tag",
31
+ ];
32
+ /**
33
+ * A promo code as the host keeps and compares it (ADR 0940): Unicode-normalised (NFKC), with no
34
+ * white space and no invisible characters (zero-width spaces, soft hyphens: Unicode's default
35
+ * ignorables), in upper case, so `été 26`, `ÉTÉ26` and `Été26` are one code, and non-ASCII letters
36
+ * match however they are typed. The host stores a code word folded when a record is written, and
37
+ * folds what a buyer types the same way before it looks the word up by its index. One function,
38
+ * here, for both.
39
+ */
40
+ export function foldCode(word) {
41
+ return word
42
+ .normalize("NFKC")
43
+ .replace(/[\s\p{Default_Ignorable_Code_Point}]+/gu, "")
44
+ .toUpperCase()
45
+ .normalize("NFKC");
46
+ }
47
+ /** The least length of a code word, in characters after folding (ADR 0940): no `SALE`, no `A1`. */
48
+ export const CODE_MIN_LENGTH = 6;
49
+ /** The longest code word (and the longest a buyer may type). */
50
+ export const CODE_MAX_LENGTH = 64;
51
+ /**
52
+ * The letters a generated code is made of: 32, with no 0, 1, I or O, so nothing is misread and
53
+ * each character is 5 bits exactly (no bias from the random bytes).
54
+ */
55
+ export const CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
56
+ /**
57
+ * `count` random single-use codes (ADR 0940), each `length` characters of CODE_ALPHABET from
58
+ * `crypto.getRandomValues`: 16 by default, 80 bits, which no rate of guessing reaches. Already
59
+ * folded. For a pack's tool that makes a batch of codes; a person still approves writing them
60
+ * (ADR 0693).
61
+ */
62
+ export function randomCodes(count, length = 16) {
63
+ if (!Number.isInteger(count) || count < 1 || count > 10_000) {
64
+ throw new Error("randomCodes makes 1 to 10,000 codes");
65
+ }
66
+ if (!Number.isInteger(length) || length < 12 || length > CODE_MAX_LENGTH) {
67
+ throw new Error(`A generated code is 12 to ${CODE_MAX_LENGTH} characters (60 bits or more)`);
68
+ }
69
+ // The Web Crypto global of every runtime the SDK runs in (Workers, browsers, Node 20+); the SDK
70
+ // is typed without DOM or Workers types, so it is named here.
71
+ const { crypto } = globalThis;
72
+ const codes = new Set();
73
+ while (codes.size < count) {
74
+ const bytes = crypto.getRandomValues(new Uint8Array(length));
75
+ codes.add(Array.from(bytes, (b) => CODE_ALPHABET[b & 31]).join(""));
76
+ }
77
+ return [...codes];
78
+ }
79
+ const fieldName = z.string().max(40);
80
+ export const discountManifestSchema = z
81
+ .object({
82
+ kind: fieldName,
83
+ percent: fieldName.optional(),
84
+ amount: fieldName.optional(),
85
+ live: z.array(z.string().min(1).max(100)).min(1).max(10),
86
+ automatic: fieldName.optional(),
87
+ code: fieldName.optional(),
88
+ codes: z
89
+ .object({
90
+ object: fieldName,
91
+ discount: fieldName,
92
+ word: fieldName,
93
+ uses: fieldName.optional(),
94
+ active: fieldName.optional(),
95
+ })
96
+ .strict()
97
+ .optional(),
98
+ who: fieldName.optional(),
99
+ plans: fieldName.optional(),
100
+ organisations: fieldName.optional(),
101
+ tag: fieldName.optional(),
102
+ objects: fieldName.optional(),
103
+ records: z.array(fieldName).min(1).max(5).optional(),
104
+ from: fieldName.optional(),
105
+ until: fieldName.optional(),
106
+ totalUses: fieldName.optional(),
107
+ perPerson: fieldName.optional(),
108
+ minSpend: fieldName.optional(),
109
+ })
110
+ .strict();
111
+ const NUMBER = ["number", "percent"];
112
+ const MONEY = ["currency", "number"];
113
+ const WHEN = ["date", "datetime"];
114
+ /** Reports problems with `objects.<name>.discount` through `contract`. */
115
+ export function checkObjectDiscount(m, name, object, contract) {
116
+ const discount = object.discount;
117
+ if (!discount)
118
+ return;
119
+ const path = `objects.${name}.discount`;
120
+ const fieldOf = (owner, local) => Object.hasOwn(owner.fields, local) ? owner.fields[local] : undefined;
121
+ const single = (field, types) => field !== undefined && types.includes(field.type) && !field.many;
122
+ const need = (key, local, types, words) => {
123
+ if (local === undefined)
124
+ return;
125
+ if (!single(fieldOf(object, local), types)) {
126
+ contract(`${path}.${key}`, `"${local}" must be ${words} field of ${name}`);
127
+ }
128
+ };
129
+ /** The option values of a select field of this object, or null when it is not one. */
130
+ const optionsOf = (local, multi) => {
131
+ const field = fieldOf(object, local);
132
+ const ok = field?.type === "select" || (multi && field?.type === "multiSelect");
133
+ return ok ? (field?.options ?? []).map((o) => o.value) : null;
134
+ };
135
+ // What is off.
136
+ const kinds = optionsOf(discount.kind, false);
137
+ if (!kinds) {
138
+ contract(`${path}.kind`, `"${discount.kind}" must be a select field of ${name}`);
139
+ }
140
+ else {
141
+ for (const value of kinds) {
142
+ if (!DISCOUNT_KINDS.includes(value)) {
143
+ contract(`${path}.kind`, `"${value}" is not a kind of discount: the options of ${discount.kind} are among ${DISCOUNT_KINDS.join(", ")}`);
144
+ }
145
+ }
146
+ if (kinds.includes("percent") && discount.percent === undefined) {
147
+ contract(`${path}.percent`, "A percentage discount needs percent: the field of its percentage");
148
+ }
149
+ if ((kinds.includes("amount") || kinds.includes("price")) && discount.amount === undefined) {
150
+ contract(`${path}.amount`, "An amount or a set price needs amount: the field of the money");
151
+ }
152
+ }
153
+ need("percent", discount.percent, NUMBER, "a number or percent");
154
+ need("amount", discount.amount, MONEY, "a currency or number");
155
+ // How it applies.
156
+ if (discount.automatic === undefined &&
157
+ discount.code === undefined &&
158
+ discount.codes === undefined) {
159
+ contract(path, "Say how the discount applies: automatic (a boolean field), code (a text field) or codes (records of another object)");
160
+ }
161
+ need("automatic", discount.automatic, ["boolean"], "a boolean");
162
+ need("code", discount.code, ["text"], "a text");
163
+ if (discount.codes) {
164
+ const codes = discount.codes;
165
+ const cp = `${path}.codes`;
166
+ const owner = Object.hasOwn(m.objects, codes.object) ? m.objects[codes.object] : undefined;
167
+ if (!owner || codes.object === name) {
168
+ contract(`${cp}.object`, `"${codes.object}" must be another object of this extension`);
169
+ }
170
+ else {
171
+ const relation = fieldOf(owner, codes.discount);
172
+ if (relation?.type !== "relation" || relation.many || relation.to !== `${m.id}.${name}`) {
173
+ contract(`${cp}.discount`, `"${codes.discount}" must be a relation field (one record) of ${codes.object} to ${m.id}.${name}`);
174
+ }
175
+ if (!single(fieldOf(owner, codes.word), ["text"])) {
176
+ contract(`${cp}.word`, `"${codes.word}" must be a text field of ${codes.object}`);
177
+ }
178
+ if (codes.uses !== undefined && !single(fieldOf(owner, codes.uses), ["number"])) {
179
+ contract(`${cp}.uses`, `"${codes.uses}" must be a number field of ${codes.object}`);
180
+ }
181
+ if (codes.active !== undefined && !single(fieldOf(owner, codes.active), ["boolean"])) {
182
+ contract(`${cp}.active`, `"${codes.active}" must be a boolean field of ${codes.object}`);
183
+ }
184
+ if (owner.sellable || owner.discount) {
185
+ contract(`${cp}.object`, `${codes.object} holds codes: it is not sold and not a discount`);
186
+ }
187
+ }
188
+ }
189
+ // For whom.
190
+ if (discount.who !== undefined) {
191
+ const who = optionsOf(discount.who, false);
192
+ if (!who) {
193
+ contract(`${path}.who`, `"${discount.who}" must be a select field of ${name}`);
194
+ }
195
+ else {
196
+ for (const value of who) {
197
+ if (!DISCOUNT_WHO.includes(value)) {
198
+ contract(`${path}.who`, `"${value}" is not who a discount is for: the options of ${discount.who} are among ${DISCOUNT_WHO.join(", ")}`);
199
+ }
200
+ }
201
+ if (who.includes("tag") && discount.tag === undefined) {
202
+ contract(`${path}.tag`, "A discount for a tag needs tag: the text field naming it");
203
+ }
204
+ if (who.includes("organisation") && discount.organisations === undefined) {
205
+ contract(`${path}.organisations`, "A discount for an organisation needs organisations: the relation field naming them");
206
+ }
207
+ }
208
+ }
209
+ const relation = (local) => local === undefined ? undefined : fieldOf(object, local);
210
+ if (discount.plans !== undefined) {
211
+ const field = relation(discount.plans);
212
+ if (field?.type !== "relation") {
213
+ contract(`${path}.plans`, `"${discount.plans}" must be a relation field to a plan`);
214
+ }
215
+ }
216
+ if (discount.organisations !== undefined) {
217
+ const field = relation(discount.organisations);
218
+ if (field?.type !== "relation" || field.to !== "organisation") {
219
+ contract(`${path}.organisations`, `"${discount.organisations}" must be a relation field to organisation`);
220
+ }
221
+ }
222
+ need("tag", discount.tag, ["text"], "a text");
223
+ // On what.
224
+ if (discount.objects !== undefined && !optionsOf(discount.objects, true)) {
225
+ contract(`${path}.objects`, `"${discount.objects}" must be a multi-select or select field of ${name} whose option values are objects`);
226
+ }
227
+ for (const [i, local] of (discount.records ?? []).entries()) {
228
+ if (relation(local)?.type !== "relation") {
229
+ contract(`${path}.records.${i}`, `"${local}" must be a relation field of ${name}`);
230
+ }
231
+ }
232
+ // When, and how often.
233
+ need("from", discount.from, WHEN, "a date or datetime");
234
+ need("until", discount.until, WHEN, "a date or datetime");
235
+ need("totalUses", discount.totalUses, ["number"], "a number");
236
+ need("perPerson", discount.perPerson, ["number"], "a number");
237
+ need("minSpend", discount.minSpend, MONEY, "a currency or number");
238
+ for (const key of ["sellable", "stock", "capacity"]) {
239
+ if (object[key] !== undefined) {
240
+ contract(`objects.${name}.${key}`, `A discount is not bought or counted: it has no ${key}`);
241
+ }
242
+ }
243
+ // Live states, entered only by a person (an AI's request waits), as stock moves are (ADR 0681).
244
+ const states = object.states;
245
+ if (!states) {
246
+ contract(`${path}.live`, `${name} must declare states: live names the states it applies in`);
247
+ return;
248
+ }
249
+ const stateField = fieldOf(object, states.field);
250
+ const values = new Set((stateField?.options ?? []).map((o) => o.value));
251
+ for (const live of discount.live) {
252
+ if (!values.has(live))
253
+ contract(`${path}.live`, `"${live}" is not a state of ${name}`);
254
+ }
255
+ const liveSet = new Set(discount.live);
256
+ if (liveSet.has(states.initial)) {
257
+ contract(`${path}.live`, `"${states.initial}" is where a new discount starts: a discount is made in another state and moved live by a person`);
258
+ }
259
+ // A person moves it live: through a tool a person makes the move with (a shipped pack, whose
260
+ // tools declare a permission), or by staff writing a state field a person approves (any
261
+ // extension: anyone else's write of it waits for a person, ADR 0507). Never a customer.
262
+ const personField = stateField?.personApproves === true;
263
+ states.moves.forEach((move, i) => {
264
+ if (!liveSet.has(move.to))
265
+ return;
266
+ // A move between two live states (active to paused and back) changes nothing a buyer gets.
267
+ if (moveOrigins(move).every((from) => liveSet.has(from)))
268
+ return;
269
+ const byTool = move.by.every((mover) => mover === "host");
270
+ const byPerson = personField && move.by.every((mover) => mover !== "customer");
271
+ if (!byTool && !byPerson) {
272
+ contract(`objects.${name}.states.moves.${i}.by`, `Entering "${move.to}" makes a discount apply: declare it by ["host"] with the tools a person makes it through (states.moves.<n>.tools), or by ["staff"] with a state field a person approves (fields.${states.field}.personApproves)`);
273
+ }
274
+ });
275
+ for (const live of discount.live) {
276
+ const created = states.create?.in?.[live];
277
+ if (created?.some((mover) => mover !== "host")) {
278
+ contract(`objects.${name}.states.create.in.${live}`, `Creating a discount in "${live}" makes it apply: only the host may; create it in another state and move it through a tool`);
279
+ }
280
+ }
281
+ }
@@ -1,3 +1,4 @@
1
+ import { type MediaKind } from "./media.ts";
1
2
  /** The most a document may be, in bytes of its JSON, whatever a field declares. */
2
3
  export declare const DOCUMENT_MAX_BYTES = 524288;
3
4
  /** A field that declares no `maxBytes`. */
@@ -51,7 +52,7 @@ export type DocumentHolders = true | {
51
52
  unless?: string;
52
53
  };
53
54
  /** The kinds of media item (stage 42, ADR 0475). */
54
- export type DocumentMediaKind = "image" | "video" | "file";
55
+ export type DocumentMediaKind = MediaKind;
55
56
  export interface DocumentArrayNode extends NodeBase {
56
57
  type: "array";
57
58
  of: DocumentNode;
package/dist/document.js CHANGED
@@ -28,6 +28,7 @@
28
28
  // removed, from what an outsider reads unless they hold access to the record (the seam's one
29
29
  // question, visibility/access.ts) or its `unless` key is true (a lesson marked as a free
30
30
  // preview). A `ref` to `media` may name the kind of item it takes (`media: "video"`).
31
+ import { MEDIA_KINDS } from "./media.js";
31
32
  /** The most a document may be, in bytes of its JSON, whatever a field declares. */
32
33
  export const DOCUMENT_MAX_BYTES = 524_288;
33
34
  /** A field that declares no `maxBytes`. */
@@ -241,7 +242,7 @@ export function checkDocumentSchema(schema, knownObjects) {
241
242
  if (value.media !== undefined) {
242
243
  if (value.to !== "media")
243
244
  add(`${path}.media`, "media is for a ref to media");
244
- else if (!["image", "video", "file"].includes(String(value.media))) {
245
+ else if (!MEDIA_KINDS.includes(String(value.media))) {
245
246
  add(`${path}.media`, "media is image, video or file");
246
247
  }
247
248
  }
@@ -1,5 +1,5 @@
1
1
  import type { FormulaType } from "./formula/ast.ts";
2
- export declare const FIELD_TYPES: readonly ["text", "longText", "number", "currency", "percent", "date", "datetime", "boolean", "select", "multiSelect", "relation", "user", "email", "phone", "url", "formula", "document", "timezone", "richText", "slug", "image", "video"];
2
+ export declare const FIELD_TYPES: readonly ["text", "longText", "number", "currency", "percent", "date", "datetime", "boolean", "select", "multiSelect", "relation", "user", "email", "phone", "url", "formula", "document", "timezone", "richText", "slug", "image", "video", "checklist"];
3
3
  export type FieldTypeName = (typeof FIELD_TYPES)[number];
4
4
  /** What a formula sees when it reads a field of this type (null: not readable from formulas). */
5
5
  export declare function formulaTypeOf(type: FieldTypeName, many?: boolean): Exclude<FormulaType, "null"> | null;
@@ -30,6 +30,9 @@ export const FIELD_TYPES = [
30
30
  // A video from the media library, held in Cloudflare Stream, played only with a token the host
31
31
  // signs (stage 42, ADR 0475).
32
32
  "video",
33
+ // One of the business's checklist templates, by id (stage 45 step 4b, ADR 0650): an active one
34
+ // is checked on write. Named by an object's `checklists` declaration.
35
+ "checklist",
33
36
  ];
34
37
  /** What a formula sees when it reads a field of this type (null: not readable from formulas). */
35
38
  export function formulaTypeOf(type, many = false) {
@@ -43,6 +46,7 @@ export function formulaTypeOf(type, many = false) {
43
46
  case "url":
44
47
  case "timezone":
45
48
  case "slug":
49
+ case "checklist":
46
50
  return "text";
47
51
  case "relation":
48
52
  return many ? null : "text";
@@ -92,6 +96,7 @@ export const LOSSLESS_TYPE_CHANGES = {
92
96
  slug: ["text", "longText"],
93
97
  image: [],
94
98
  video: [],
99
+ checklist: [],
95
100
  };
96
101
  export function isLosslessChange(from, to) {
97
102
  return from === to || LOSSLESS_TYPE_CHANGES[from].includes(to);
@@ -8,6 +8,21 @@ export type FormulaFieldRef = {
8
8
  | {
9
9
  expression: string;
10
10
  };
11
+ /**
12
+ * The host's read-only published values a formula of a publishable object's own fields may read
13
+ * (ADR 0706): when the current version went live, and its number. Columns of the object's rec_*
14
+ * view, empty while it is not published.
15
+ */
16
+ export declare const PUBLISHED_FORMULA_FIELDS: {
17
+ readonly publishedAt: {
18
+ readonly type: "datetime";
19
+ readonly sql: "\"_pub_at\"";
20
+ };
21
+ readonly publishedVersion: {
22
+ readonly type: "number";
23
+ readonly sql: "\"_pub_version\"";
24
+ };
25
+ };
11
26
  export interface FormulaEnvironment {
12
27
  /** Fields of the same record, by name. Names are case-sensitive. */
13
28
  fields: Record<string, FormulaFieldRef>;
@@ -7,6 +7,15 @@
7
7
  // source is spliced into SQL verbatim.
8
8
  import { FormulaError, formulaError, } from "./ast.js";
9
9
  import { parseFormula } from "./parser.js";
10
+ /**
11
+ * The host's read-only published values a formula of a publishable object's own fields may read
12
+ * (ADR 0706): when the current version went live, and its number. Columns of the object's rec_*
13
+ * view, empty while it is not published.
14
+ */
15
+ export const PUBLISHED_FORMULA_FIELDS = {
16
+ publishedAt: { type: "datetime", sql: '"_pub_at"' },
17
+ publishedVersion: { type: "number", sql: '"_pub_version"' },
18
+ };
10
19
  const DATE_UNITS = ["day", "week", "month", "year"];
11
20
  /** Function signatures, for error messages and the README. */
12
21
  export const FORMULA_FUNCTIONS = {
package/dist/index.d.ts CHANGED
@@ -1,20 +1,37 @@
1
1
  export { z } from "zod";
2
+ export * from "./acknowledge.ts";
3
+ export * from "./agreements.ts";
2
4
  export * from "./allowance.ts";
3
5
  export * from "./automation.ts";
4
6
  export * from "./automation-check.ts";
7
+ export * from "./calendar-entry.ts";
5
8
  export * from "./capacity.ts";
9
+ export * from "./checklists.ts";
6
10
  export * from "./contract.ts";
11
+ export * from "./discount.ts";
7
12
  export * from "./document.ts";
8
13
  export * from "./field-types.ts";
14
+ export * from "./intake.ts";
15
+ export * from "./journey-signals.ts";
9
16
  export * from "./manifest.ts";
10
17
  export * from "./media.ts";
18
+ export * from "./mine.ts";
19
+ export * from "./occupies.ts";
11
20
  export * from "./permissions.ts";
21
+ export * from "./questions.ts";
12
22
  export * from "./recurring.ts";
13
23
  export * from "./renamed.ts";
24
+ export * from "./restricted-fields.ts";
14
25
  export * from "./rich-text.ts";
15
26
  export * from "./rich-text-fixture.ts";
27
+ export * from "./routine-mail.ts";
16
28
  export { type AutomationRunValue, AutomationStepError, buildAutomationContext, buildContext, OpsCallError, type OpsReply, type RawHostModules, type RunRequest, type RunResponse, runAutomation, runExtension, } from "./runtime.ts";
29
+ export * from "./screens.ts";
17
30
  export * from "./sellable.ts";
18
31
  export * from "./slug.ts";
32
+ export * from "./staffed.ts";
19
33
  export * from "./states.ts";
34
+ export * from "./stock.ts";
35
+ export * from "./team.ts";
20
36
  export * from "./unique.ts";
37
+ export * from "./worked-on.ts";
package/dist/index.js CHANGED
@@ -3,22 +3,39 @@
3
3
  // import { defineExtension, defineTool, z } from "@composable-os/sdk";
4
4
  // export default defineExtension({ id: "example", version: "1.0.0", contractVersion: 1, ... });
5
5
  export { z } from "zod";
6
+ export * from "./acknowledge.js";
7
+ export * from "./agreements.js";
6
8
  export * from "./allowance.js";
7
9
  export * from "./automation.js";
8
10
  export * from "./automation-check.js";
11
+ export * from "./calendar-entry.js";
9
12
  export * from "./capacity.js";
13
+ export * from "./checklists.js";
10
14
  export * from "./contract.js";
15
+ export * from "./discount.js";
11
16
  export * from "./document.js";
12
17
  export * from "./field-types.js";
18
+ export * from "./intake.js";
19
+ export * from "./journey-signals.js";
13
20
  export * from "./manifest.js";
14
21
  export * from "./media.js";
22
+ export * from "./mine.js";
23
+ export * from "./occupies.js";
15
24
  export * from "./permissions.js";
25
+ export * from "./questions.js";
16
26
  export * from "./recurring.js";
17
27
  export * from "./renamed.js";
28
+ export * from "./restricted-fields.js";
18
29
  export * from "./rich-text.js";
19
30
  export * from "./rich-text-fixture.js";
31
+ export * from "./routine-mail.js";
20
32
  export { AutomationStepError, buildAutomationContext, buildContext, OpsCallError, runAutomation, runExtension, } from "./runtime.js";
33
+ export * from "./screens.js";
21
34
  export * from "./sellable.js";
22
35
  export * from "./slug.js";
36
+ export * from "./staffed.js";
23
37
  export * from "./states.js";
38
+ export * from "./stock.js";
39
+ export * from "./team.js";
24
40
  export * from "./unique.js";
41
+ export * from "./worked-on.js";