@composable-os/sdk 0.0.0-stage → 0.1.0-beta.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 (81) hide show
  1. package/LICENSE +109 -0
  2. package/dist/allowance.d.ts +198 -0
  3. package/dist/allowance.js +374 -0
  4. package/dist/automation-check.d.ts +38 -0
  5. package/dist/automation-check.js +454 -0
  6. package/dist/automation.d.ts +767 -0
  7. package/dist/automation.js +303 -0
  8. package/dist/behaviour.d.ts +3 -0
  9. package/dist/behaviour.js +153 -0
  10. package/dist/capacity.d.ts +77 -0
  11. package/dist/capacity.js +127 -0
  12. package/dist/contract.d.ts +819 -0
  13. package/dist/contract.js +42 -0
  14. package/dist/document.d.ts +211 -0
  15. package/dist/document.js +726 -0
  16. package/dist/field-types.d.ts +11 -0
  17. package/dist/field-types.js +98 -0
  18. package/dist/formula/ast.d.ts +67 -0
  19. package/dist/formula/ast.js +22 -0
  20. package/dist/formula/compile.d.ts +37 -0
  21. package/dist/formula/compile.js +379 -0
  22. package/dist/formula/index.d.ts +3 -0
  23. package/dist/formula/index.js +4 -0
  24. package/dist/formula/parser.d.ts +13 -0
  25. package/dist/formula/parser.js +365 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.js +24 -0
  28. package/dist/manifest.d.ts +1596 -0
  29. package/dist/manifest.js +1420 -0
  30. package/dist/media.d.ts +41 -0
  31. package/dist/media.js +90 -0
  32. package/dist/permissions.d.ts +17 -0
  33. package/dist/permissions.js +44 -0
  34. package/dist/recurring.d.ts +114 -0
  35. package/dist/recurring.js +173 -0
  36. package/dist/renamed.d.ts +16 -0
  37. package/dist/renamed.js +59 -0
  38. package/dist/rich-text-fixture.d.ts +121 -0
  39. package/dist/rich-text-fixture.js +67 -0
  40. package/dist/rich-text.d.ts +48 -0
  41. package/dist/rich-text.js +184 -0
  42. package/dist/runtime.d.ts +95 -0
  43. package/dist/runtime.js +312 -0
  44. package/dist/sellable.d.ts +253 -0
  45. package/dist/sellable.js +593 -0
  46. package/dist/slug.d.ts +11 -0
  47. package/dist/slug.js +23 -0
  48. package/dist/states.d.ts +238 -0
  49. package/dist/states.js +315 -0
  50. package/dist/testing.d.ts +151 -0
  51. package/dist/testing.js +679 -0
  52. package/dist/unique.d.ts +20 -0
  53. package/dist/unique.js +58 -0
  54. package/package.json +34 -4
  55. package/src/allowance.ts +522 -0
  56. package/src/automation-check.ts +534 -0
  57. package/src/automation.ts +743 -0
  58. package/src/behaviour.ts +215 -0
  59. package/src/capacity.ts +201 -0
  60. package/src/contract.ts +884 -0
  61. package/src/document.ts +935 -0
  62. package/src/field-types.ts +111 -0
  63. package/src/formula/ast.ts +72 -0
  64. package/src/formula/compile.ts +454 -0
  65. package/src/formula/index.ts +4 -0
  66. package/src/formula/parser.ts +417 -0
  67. package/src/index.ts +36 -0
  68. package/src/manifest.ts +1709 -0
  69. package/src/media.ts +108 -0
  70. package/src/permissions.ts +60 -0
  71. package/src/recurring.ts +321 -0
  72. package/src/renamed.ts +63 -0
  73. package/src/rich-text-fixture.ts +68 -0
  74. package/src/rich-text.ts +221 -0
  75. package/src/runtime.ts +410 -0
  76. package/src/sellable.ts +888 -0
  77. package/src/slug.ts +25 -0
  78. package/src/states.ts +484 -0
  79. package/src/testing.ts +847 -0
  80. package/src/unique.ts +81 -0
  81. package/README.md +0 -3
@@ -0,0 +1,303 @@
1
+ // Automations (ADR 0028, ADR 0130, ADR 0131): `defineAutomation` declares a trigger, optional
2
+ // declarative conditions, the steps it takes (with their intents: what they read, write, notify
3
+ // and wait for) and a `run` handler shaped like a Cloudflare Workflow. The host renders the
4
+ // plain-English summary and step diagram from the declarations alone (no AI), evaluates the
5
+ // conditions before it starts a run, and runs `run` durably on Cloudflare Workflows: every
6
+ // `step.do` executes in a Dynamic Worker as actor `automation` under the extension principal.
7
+ //
8
+ // The declarations are the contract the diagram, the summary and the approval screen show, so the
9
+ // runtime holds `run` to them: every `step.do` / `step.sleep` / `step.waitForEvent` name must be a
10
+ // declared step of the matching kind. Effects a step did not declare are still gated at run time
11
+ // (and flagged in the run history), never silently allowed.
12
+ import { z } from "zod";
13
+ import { GATEKEEPER_MODULES, } from "./contract.js";
14
+ const UNIT_MS = {
15
+ second: 1_000,
16
+ minute: 60_000,
17
+ hour: 3_600_000,
18
+ day: 86_400_000,
19
+ week: 604_800_000,
20
+ };
21
+ /** Milliseconds in a duration. Throws on a malformed one. */
22
+ export function durationMs(duration) {
23
+ if (typeof duration === "number") {
24
+ if (!Number.isFinite(duration) || duration < 0)
25
+ throw new Error("Durations are >= 0 ms");
26
+ return duration;
27
+ }
28
+ const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/.exec(duration);
29
+ if (!match)
30
+ throw new Error(`"${duration}" is not a duration like "3 days" or "90 minutes"`);
31
+ return Math.round(Number(match[1]) * UNIT_MS[match[2]]);
32
+ }
33
+ // ---------------------------------------------------------------------------------------------
34
+ // Triggers
35
+ /** Record lifecycle events every core and extension object emits after commit. */
36
+ export const RECORD_EVENTS = ["created", "updated", "deleted", "restored"];
37
+ /**
38
+ * Sync events (stage 6, ADR 0112): what the built-in email and calendar sync records when it
39
+ * writes, updates or removes an activity. `meeting.scheduled` is a new meeting (the sync service
40
+ * records it as `meeting.created`; both names match it).
41
+ */
42
+ export const SYNC_EVENT_TYPES = [
43
+ "email.received",
44
+ "email.sent",
45
+ "email.deleted",
46
+ "meeting.scheduled",
47
+ "meeting.created",
48
+ "meeting.updated",
49
+ "meeting.cancelled",
50
+ ];
51
+ export const AUTOMATION_TRIGGER_TYPES = [
52
+ "record",
53
+ "fieldChanged",
54
+ "schedule",
55
+ "dateRelative",
56
+ "manual",
57
+ "approvalDecided",
58
+ "webhook",
59
+ "syncEvent",
60
+ ];
61
+ export function defineAutomation(automation) {
62
+ return automation;
63
+ }
64
+ // ---------------------------------------------------------------------------------------------
65
+ // Manifest form (JSON: no handler). Stored in core_automations.spec.
66
+ const scalar = z.union([z.string().max(500), z.number(), z.boolean(), z.null()]);
67
+ export const valueMatchSchema = z.union([
68
+ scalar,
69
+ z.object({ in: z.array(scalar).min(1).max(50) }).strict(),
70
+ z.object({ stageType: z.enum(["open", "won", "lost"]) }).strict(),
71
+ ]);
72
+ const objectName = z.string().min(1).max(80);
73
+ const fieldName = z.string().min(1).max(80);
74
+ export const automationTriggerSchema = z.discriminatedUnion("type", [
75
+ z
76
+ .object({
77
+ type: z.literal("record"),
78
+ object: objectName,
79
+ on: z.array(z.enum(RECORD_EVENTS)).min(1).max(4),
80
+ includeBulk: z.boolean().optional(),
81
+ })
82
+ .strict(),
83
+ z
84
+ .object({
85
+ type: z.literal("fieldChanged"),
86
+ object: objectName,
87
+ field: fieldName,
88
+ from: valueMatchSchema.optional(),
89
+ to: valueMatchSchema.optional(),
90
+ includeBulk: z.boolean().optional(),
91
+ })
92
+ .strict(),
93
+ z.object({ type: z.literal("schedule"), cron: z.string().min(9).max(100) }).strict(),
94
+ z
95
+ .object({
96
+ type: z.literal("dateRelative"),
97
+ object: objectName,
98
+ field: fieldName,
99
+ offsetDays: z.number().int().min(-365).max(365),
100
+ zoneField: fieldName.optional(),
101
+ })
102
+ .strict(),
103
+ z
104
+ .object({
105
+ type: z.literal("manual"),
106
+ object: objectName,
107
+ label: z.string().min(1).max(60),
108
+ bulk: z.boolean().optional(),
109
+ })
110
+ .strict(),
111
+ z
112
+ .object({
113
+ type: z.literal("approvalDecided"),
114
+ decision: z.enum(["approved", "rejected", "any"]).optional(),
115
+ operation: z.string().max(100).optional(),
116
+ object: objectName.optional(),
117
+ })
118
+ .strict(),
119
+ z
120
+ .object({
121
+ type: z.literal("webhook"),
122
+ endpoint: z
123
+ .string()
124
+ .min(1)
125
+ .max(64)
126
+ .regex(/^[a-z0-9][a-z0-9_-]*$/, "Endpoint ids are lowercase letters, digits, - and _"),
127
+ events: z.array(z.string().min(1).max(200)).min(1).max(50).optional(),
128
+ })
129
+ .strict(),
130
+ z
131
+ .object({
132
+ type: z.literal("syncEvent"),
133
+ event: z.enum(SYNC_EVENT_TYPES),
134
+ from: z.enum(["person", "organisation", "either"]).optional(),
135
+ })
136
+ .strict(),
137
+ ]);
138
+ export const automationConnectionSchema = z
139
+ .object({
140
+ id: z.string().min(1).max(40),
141
+ gatekeeper: z.enum(GATEKEEPER_MODULES),
142
+ purpose: z.string().min(1).max(200),
143
+ })
144
+ .strict();
145
+ export const durationSchema = z.union([
146
+ z.number().int().min(0),
147
+ z.string().regex(/^\s*\d+(?:\.\d+)?\s+(second|minute|hour|day|week)s?\s*$/),
148
+ ]);
149
+ export const recipientSchema = z.union([
150
+ z.literal("admins"),
151
+ z.literal("actor"),
152
+ z.object({ field: fieldName }).strict(),
153
+ z.object({ managerOf: fieldName }).strict(),
154
+ z.object({ userId: z.string().min(1).max(64) }).strict(),
155
+ ]);
156
+ const writeIntentSchema = z
157
+ .object({
158
+ object: objectName,
159
+ action: z.enum(["create", "update", "delete"]).optional(),
160
+ count: z.number().int().min(1).max(10_000).optional(),
161
+ titles: z.array(z.string().max(200)).max(50).optional(),
162
+ assignTo: recipientSchema.optional(),
163
+ linkedToTrigger: z.boolean().optional(),
164
+ })
165
+ .strict();
166
+ const notifyIntentSchema = z
167
+ .object({
168
+ to: recipientSchema,
169
+ message: z.string().min(1).max(500),
170
+ body: z.string().min(1).max(2000).optional(),
171
+ })
172
+ .strict();
173
+ const stepName = z.string().min(1).max(60);
174
+ const stepLabel = z.string().min(1).max(120).optional();
175
+ export const automationStepSchema = z.union([
176
+ z
177
+ .object({
178
+ name: stepName,
179
+ label: stepLabel,
180
+ kind: z.literal("do").optional(),
181
+ reads: z.array(objectName).max(50).optional(),
182
+ writes: z.array(writeIntentSchema).max(20).optional(),
183
+ notifies: z.array(notifyIntentSchema).max(20).optional(),
184
+ calls: z.array(z.string().max(100)).max(50).optional(),
185
+ })
186
+ .strict(),
187
+ z
188
+ .object({
189
+ name: stepName,
190
+ label: stepLabel,
191
+ kind: z.literal("sleep"),
192
+ duration: durationSchema,
193
+ })
194
+ .strict(),
195
+ z
196
+ .object({
197
+ name: stepName,
198
+ label: stepLabel,
199
+ kind: z.literal("waitForEvent"),
200
+ event: z.string().min(1).max(100),
201
+ timeout: durationSchema.optional(),
202
+ })
203
+ .strict(),
204
+ z
205
+ .object({
206
+ name: stepName,
207
+ label: z.string().min(1).max(120),
208
+ kind: z.literal("condition"),
209
+ clause: z.string().min(1).max(200).optional(),
210
+ })
211
+ .strict(),
212
+ ]);
213
+ const filterOpSchema = z.enum([
214
+ "eq",
215
+ "neq",
216
+ "lt",
217
+ "lte",
218
+ "gt",
219
+ "gte",
220
+ "between",
221
+ "in",
222
+ "not_in",
223
+ "contains",
224
+ "not_contains",
225
+ "starts_with",
226
+ "ends_with",
227
+ "is_null",
228
+ "is_not_null",
229
+ ]);
230
+ export const automationConditionSchema = z.lazy(() => z.union([
231
+ z.object({ field: fieldName, op: filterOpSchema, value: z.unknown().optional() }).strict(),
232
+ z.object({ and: z.array(automationConditionSchema).min(1).max(20) }).strict(),
233
+ z.object({ or: z.array(automationConditionSchema).min(1).max(20) }).strict(),
234
+ ]));
235
+ export const onRejectedSchema = z.union([
236
+ z.literal("stop"),
237
+ z.literal("continue"),
238
+ z.object({ notify: recipientSchema, message: z.string().max(500).optional() }).strict(),
239
+ ]);
240
+ export const automationRailsSchema = z
241
+ .object({
242
+ maxRunsPerMinute: z.number().int().min(1).max(600).optional(),
243
+ maxWritesPerHour: z.number().int().min(1).max(100_000).optional(),
244
+ debounceSeconds: z.number().int().min(0).max(3600).optional(),
245
+ })
246
+ .strict();
247
+ export const automationManifestSchema = z.object({
248
+ label: z.string().min(1).max(100),
249
+ description: z.string().min(1).max(2000),
250
+ trigger: automationTriggerSchema,
251
+ conditions: automationConditionSchema.optional(),
252
+ steps: z.array(automationStepSchema).min(1).max(50),
253
+ onRejected: onRejectedSchema.optional(),
254
+ rails: automationRailsSchema.optional(),
255
+ connections: z.array(automationConnectionSchema).max(10).optional(),
256
+ enabled: z.boolean().optional(),
257
+ });
258
+ /**
259
+ * Turns `ctx.notify(to, message)` into a `notification.send` input for `event`'s run: field and
260
+ * manager recipients point at the trigger record, `"actor"` is whoever started a manual run,
261
+ * `{record}` in the title and body becomes the trigger record's title, and the dedupe key
262
+ * (`<runId>:<key>`, key = `<step name>:<n>` with n counting notify calls within that step, so it is the same on every replay) makes a retried or replayed step send each
263
+ * notification once. Shared by the runtime and the testing harness.
264
+ */
265
+ export function notificationInput(event, to, message, key) {
266
+ const record = event.record;
267
+ const recipients = Array.isArray(to) ? to : [to];
268
+ const resolved = recipients.map((recipient) => {
269
+ if (recipient === "admins")
270
+ return { role: "admin" };
271
+ if (recipient === "actor") {
272
+ const userId = event.manual?.userId;
273
+ if (!userId)
274
+ throw new Error('"actor" recipients need a manual trigger (a person started it)');
275
+ return { userId };
276
+ }
277
+ if ("userId" in recipient)
278
+ return { userId: recipient.userId };
279
+ if (!record) {
280
+ throw new Error(`A ${event.trigger} run has no trigger record, so ${JSON.stringify(recipient)} cannot be resolved`);
281
+ }
282
+ const ref = { object: record.object, id: record.id };
283
+ return "field" in recipient
284
+ ? { field: recipient.field, record: ref }
285
+ : { managerOf: recipient.managerOf, record: ref };
286
+ });
287
+ const title = record?.title ?? "the record";
288
+ const fill = (text) => text.replaceAll("{record}", title);
289
+ const wanted = message.link ?? (record ? "record" : undefined);
290
+ const link = wanted === "run"
291
+ ? { kind: "automationRun", automationId: event.automation, runId: event.runId }
292
+ : wanted === "record" && record
293
+ ? { kind: "record", object: record.object, id: record.id }
294
+ : undefined;
295
+ return {
296
+ to: resolved,
297
+ type: "automation.message",
298
+ title: fill(message.title).slice(0, 200),
299
+ ...(message.body === undefined ? {} : { body: fill(message.body) }),
300
+ ...(link ? { link } : {}),
301
+ dedupeKey: `${event.runId}:${key}`.slice(0, 200),
302
+ };
303
+ }
@@ -0,0 +1,3 @@
1
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
2
+ /** Reports problems with `objects.<name>`'s behaviour keys through `contract`. */
3
+ export declare function checkObjectBehaviour(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
@@ -0,0 +1,153 @@
1
+ // Contract checks for an object's behaviour keys (ADR 0100): indexes, timeline links, the stage
2
+ // behaviour and seed records. Called by validateManifest for every declared object.
3
+ import { STAGE_TYPES } from "./contract.js";
4
+ const NUMERIC = ["number", "percent", "currency"];
5
+ const SEED_KEY_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
6
+ /** Reports problems with `objects.<name>`'s behaviour keys through `contract`. */
7
+ export function checkObjectBehaviour(m, name, object, contract) {
8
+ const path = `objects.${name}`;
9
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
10
+ const isSingle = (field) => field !== undefined && field.type !== "formula" && field.type !== "multiSelect" && !field.many;
11
+ const relationTo = (field) => field?.type === "relation" && !field.many ? field.to : undefined;
12
+ const ownObject = (target) => target?.startsWith(`${m.id}.`) ? m.objects[target.slice(m.id.length + 1)] : undefined;
13
+ (object.indexes ?? []).forEach((columns, i) => {
14
+ if (new Set(columns).size !== columns.length) {
15
+ contract(`${path}.indexes.${i}`, "An index lists each field once");
16
+ }
17
+ for (const column of columns) {
18
+ if (column === "createdAt" || column === "updatedAt")
19
+ continue;
20
+ if (!isSingle(fieldOf(column))) {
21
+ contract(`${path}.indexes.${i}`, `Index field "${column}" must be a single-valued, non-formula field of ${name}`);
22
+ }
23
+ }
24
+ });
25
+ (object.timelineLinks ?? []).forEach((local, i) => {
26
+ if (!relationTo(fieldOf(local))) {
27
+ contract(`${path}.timelineLinks.${i}`, `"${local}" must be a relation field (one record)`);
28
+ }
29
+ });
30
+ const stages = object.stages;
31
+ if (stages) {
32
+ const sp = `${path}.stages`;
33
+ const stageTarget = relationTo(fieldOf(stages.field));
34
+ const stageObject = ownObject(stageTarget);
35
+ if (!stageObject) {
36
+ contract(`${sp}.field`, `"${stages.field}" must be a relation field (one record) to another of this extension's objects`);
37
+ }
38
+ else {
39
+ if (fieldOf(stages.field)?.readOnly) {
40
+ contract(`${sp}.field`, "The stage field cannot be read-only");
41
+ }
42
+ const sf = (local) => Object.hasOwn(stageObject.fields, local) ? stageObject.fields[local] : undefined;
43
+ const type = sf(stages.stage.type);
44
+ const values = type?.options?.map((o) => o.value) ?? [];
45
+ if (type?.type !== "select" || !STAGE_TYPES.every((t) => values.includes(t))) {
46
+ contract(`${sp}.stage.type`, `"${stages.stage.type}" must be a select field of ${stageTarget} with options open, won and lost`);
47
+ }
48
+ const order = sf(stages.stage.order);
49
+ if (!order || !NUMERIC.includes(order.type)) {
50
+ contract(`${sp}.stage.order`, `"${stages.stage.order}" must be a number field of ${stageTarget}`);
51
+ }
52
+ if (stages.stage.requiredFields !== undefined) {
53
+ const required = sf(stages.stage.requiredFields);
54
+ if (required?.type !== "multiSelect") {
55
+ contract(`${sp}.stage.requiredFields`, `"${stages.stage.requiredFields}" must be a multiSelect field of ${stageTarget}`);
56
+ }
57
+ else {
58
+ for (const option of required.options ?? []) {
59
+ const target = fieldOf(option.value);
60
+ if (!target || target.type === "formula" || target.readOnly) {
61
+ contract(`${sp}.stage.requiredFields`, `Option "${option.value}" must name a writable field of ${name}`);
62
+ }
63
+ }
64
+ }
65
+ }
66
+ if (stages.stage.probability !== undefined) {
67
+ const probability = sf(stages.stage.probability);
68
+ if (!probability || !NUMERIC.includes(probability.type)) {
69
+ contract(`${sp}.stage.probability`, `"${stages.stage.probability}" must be a number or percent field of ${stageTarget}`);
70
+ }
71
+ }
72
+ const stageGroup = stages.stage.group ? relationTo(sf(stages.stage.group)) : undefined;
73
+ if (stages.stage.group !== undefined && !stageGroup) {
74
+ contract(`${sp}.stage.group`, `"${stages.stage.group}" must be a relation field (one record) of ${stageTarget}`);
75
+ }
76
+ if ((stages.group === undefined) !== (stages.stage.group === undefined)) {
77
+ contract(`${sp}.group`, "Declare both group and stage.group, or neither");
78
+ }
79
+ else if (stages.group !== undefined && relationTo(fieldOf(stages.group)) !== stageGroup) {
80
+ contract(`${sp}.group`, `"${stages.group}" must be a relation field to the same object as ${stageTarget}.${stages.stage.group}`);
81
+ }
82
+ }
83
+ if (stages.probability) {
84
+ const field = fieldOf(stages.probability.field);
85
+ if (!field || !NUMERIC.includes(field.type) || field.readOnly) {
86
+ contract(`${sp}.probability.field`, `"${stages.probability.field}" must be a writable number or percent field`);
87
+ }
88
+ const flag = fieldOf(stages.probability.overridden);
89
+ if (flag?.type !== "boolean" || flag.readOnly) {
90
+ contract(`${sp}.probability.overridden`, `"${stages.probability.overridden}" must be a writable boolean field`);
91
+ }
92
+ if (!stages.stage.probability) {
93
+ contract(`${sp}.stage.probability`, "probability needs the stage's default probability");
94
+ }
95
+ }
96
+ if (stages.closedDate !== undefined) {
97
+ const field = fieldOf(stages.closedDate);
98
+ if ((field?.type !== "date" && field?.type !== "datetime") || !field.readOnly) {
99
+ contract(`${sp}.closedDate`, `"${stages.closedDate}" must be a read-only date or datetime field`);
100
+ }
101
+ }
102
+ if (stages.status !== undefined) {
103
+ const field = fieldOf(stages.status);
104
+ const values = field?.options?.map((o) => o.value) ?? [];
105
+ if (field?.type !== "select" ||
106
+ !field.readOnly ||
107
+ !STAGE_TYPES.every((t) => values.includes(t))) {
108
+ contract(`${sp}.status`, `"${stages.status}" must be a read-only select field with options open, won and lost`);
109
+ }
110
+ }
111
+ if (stages.defaultGroupSetting !== undefined) {
112
+ const setting = m.settings?.[stages.defaultGroupSetting];
113
+ if (!stages.group) {
114
+ contract(`${sp}.defaultGroupSetting`, "defaultGroupSetting needs a group");
115
+ }
116
+ else if (setting?.type !== "text" && setting?.type !== "select") {
117
+ contract(`${sp}.defaultGroupSetting`, `"${stages.defaultGroupSetting}" must be a text or select setting of this extension`);
118
+ }
119
+ }
120
+ for (const [type, list] of Object.entries(stages.requiredByType ?? {})) {
121
+ for (const local of list ?? []) {
122
+ const field = fieldOf(local);
123
+ if (!field || field.type === "formula" || field.readOnly) {
124
+ contract(`${sp}.requiredByType.${type}`, `"${local}" must be a writable field of ${name}`);
125
+ }
126
+ }
127
+ }
128
+ }
129
+ for (const [key, values] of Object.entries(object.seed ?? {})) {
130
+ const kp = `${path}.seed.${key}`;
131
+ if (!SEED_KEY_RE.test(key))
132
+ contract(kp, "Seed keys must be camelCase");
133
+ for (const [local, value] of Object.entries(values)) {
134
+ const field = fieldOf(local);
135
+ if (!field || field.type === "formula" || field.readOnly) {
136
+ contract(`${kp}.${local}`, `"${local}" is not a writable field of ${name}`);
137
+ continue;
138
+ }
139
+ if (value && typeof value === "object" && !Array.isArray(value)) {
140
+ const ref = value.seed;
141
+ const target = ownObject(field.type === "relation" ? field.to : undefined);
142
+ if (typeof ref !== "string" || !target?.seed || !Object.hasOwn(target.seed, ref)) {
143
+ contract(`${kp}.${local}`, "A seed reference ({ seed: key }) must name a seed record of the relation's target");
144
+ }
145
+ }
146
+ }
147
+ for (const [local, field] of Object.entries(object.fields)) {
148
+ if (field.required && !(local in values)) {
149
+ contract(kp, `Seed record "${key}" needs required field "${local}"`);
150
+ }
151
+ }
152
+ }
153
+ }
@@ -0,0 +1,77 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * What customers and the public are told about a record's places (staff always see the real
5
+ * numbers): `exact`, the number left; `low`, available, "only N left" at or below `lowAt`, or sold
6
+ * out; `availability`, available or sold out.
7
+ */
8
+ export declare const CAPACITY_SHOW: readonly ["exact", "low", "availability"];
9
+ export type CapacityShow = (typeof CAPACITY_SHOW)[number];
10
+ /**
11
+ * The read-only values the host adds to every record of an object with a capacity: places held
12
+ * while someone pays, places taken, and places left (the record's and its pool's, whichever is
13
+ * fewer; null when unlimited). An object with a capacity cannot have fields of these names.
14
+ */
15
+ export declare const CAPACITY_VALUES: readonly ["held", "taken", "available"];
16
+ /**
17
+ * A limited number of places (ADR 0430). The host keeps a counter per record and refuses, in the
18
+ * database, any claim past the places: a hold while an order is unpaid, confirmed when it is paid.
19
+ * A hold has no clock of its own: it lasts as long as what it was taken for.
20
+ *
21
+ * - `places` is this object's number field holding how many places there are. Empty means
22
+ * unlimited. Staff edit it; lowering it below what is held and taken is refused with the
23
+ * numbers, for every actor, and nothing ever sells beyond it.
24
+ * - `pool` is a relation field (one record) to another of this extension's objects that itself
25
+ * declares a capacity, and no pool: a claim on this record also claims on that record, in the
26
+ * same batch (a ticket type's places within its event's). One level only.
27
+ * - `show` is what customers and the public are told (default `availability`); `lowAt` is the
28
+ * threshold for `low`.
29
+ * - `releaseOnRefund` (default true): a refunded order's places go back on sale.
30
+ */
31
+ export interface CapacitySpec {
32
+ places: string;
33
+ pool?: string;
34
+ show?: CapacityShow;
35
+ lowAt?: number;
36
+ releaseOnRefund?: boolean;
37
+ }
38
+ export declare const capacityManifestSchema: z.ZodObject<{
39
+ places: z.ZodString;
40
+ pool: z.ZodOptional<z.ZodString>;
41
+ show: z.ZodOptional<z.ZodEnum<{
42
+ exact: "exact";
43
+ low: "low";
44
+ availability: "availability";
45
+ }>>;
46
+ lowAt: z.ZodOptional<z.ZodNumber>;
47
+ releaseOnRefund: z.ZodOptional<z.ZodBoolean>;
48
+ }, z.core.$strict>;
49
+ export type CapacityManifest = z.infer<typeof capacityManifestSchema>;
50
+ /** Reports problems with `objects.<name>.capacity` through `contract`. */
51
+ export declare function checkObjectCapacity(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
52
+ /**
53
+ * A capacity claimant (stage 31, ADR 0501): a record whose own states hold and release a claim of
54
+ * one place on the record its relation `on` points to (a booking on its class), which declares a
55
+ * capacity. Entering a `held` state holds a place, entering a `confirmed` state takes one (from
56
+ * the hold, or claimed and taken at once), and leaving them gives it back, each in the batch of
57
+ * the write that makes the move, refused by the database past the places as an order's claim is.
58
+ * Moving between two `held` states, or two `confirmed` ones, changes nothing.
59
+ *
60
+ * - The object declares `states`; `held` and `confirmed` are its states, apart. No move goes from
61
+ * a confirmed state back to a held one.
62
+ * - While a record is in one of them, `on` cannot be changed: a move to another class is a new
63
+ * record. A record holding a place cannot be moved to Trash.
64
+ */
65
+ export interface ClaimsSpec {
66
+ on: string;
67
+ held?: readonly string[];
68
+ confirmed?: readonly string[];
69
+ }
70
+ export declare const claimsManifestSchema: z.ZodObject<{
71
+ on: z.ZodString;
72
+ held: z.ZodOptional<z.ZodArray<z.ZodString>>;
73
+ confirmed: z.ZodOptional<z.ZodArray<z.ZodString>>;
74
+ }, z.core.$strict>;
75
+ export type ClaimsManifest = z.infer<typeof claimsManifestSchema>;
76
+ /** Reports problems with `objects.<name>.claims` through `contract`. */
77
+ export declare function checkObjectClaims(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
@@ -0,0 +1,127 @@
1
+ // The `capacity` behaviour (stage 26, ADR 0430, ADR 0431): an object declares that its records
2
+ // have a limited number of places, and the host never gives out more than there are, for every
3
+ // actor. Its declaration, its manifest schema and its contract checks live here; the host's side
4
+ // is packages/core/src/capacity/.
5
+ import { z } from "zod";
6
+ /**
7
+ * What customers and the public are told about a record's places (staff always see the real
8
+ * numbers): `exact`, the number left; `low`, available, "only N left" at or below `lowAt`, or sold
9
+ * out; `availability`, available or sold out.
10
+ */
11
+ export const CAPACITY_SHOW = ["exact", "low", "availability"];
12
+ /**
13
+ * The read-only values the host adds to every record of an object with a capacity: places held
14
+ * while someone pays, places taken, and places left (the record's and its pool's, whichever is
15
+ * fewer; null when unlimited). An object with a capacity cannot have fields of these names.
16
+ */
17
+ export const CAPACITY_VALUES = ["held", "taken", "available"];
18
+ const fieldName = z.string().max(40);
19
+ export const capacityManifestSchema = z
20
+ .object({
21
+ places: fieldName,
22
+ pool: fieldName.optional(),
23
+ show: z.enum(CAPACITY_SHOW).optional(),
24
+ lowAt: z.number().int().min(1).max(1_000_000).optional(),
25
+ releaseOnRefund: z.boolean().optional(),
26
+ })
27
+ .strict();
28
+ /** Reports problems with `objects.<name>.capacity` through `contract`. */
29
+ export function checkObjectCapacity(m, name, object, contract) {
30
+ const capacity = object.capacity;
31
+ if (!capacity)
32
+ return;
33
+ const path = `objects.${name}.capacity`;
34
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
35
+ const places = fieldOf(capacity.places);
36
+ if (places?.type !== "number" || places.many) {
37
+ contract(`${path}.places`, `"${capacity.places}" must be a number field of ${name}`);
38
+ }
39
+ for (const reserved of CAPACITY_VALUES) {
40
+ if (Object.hasOwn(object.fields, reserved)) {
41
+ contract(`objects.${name}.fields.${reserved}`, `"${reserved}" is a value the host adds to an object with a capacity; rename the field`);
42
+ }
43
+ }
44
+ if (capacity.pool !== undefined) {
45
+ const pool = fieldOf(capacity.pool);
46
+ const target = pool?.type === "relation" && !pool.many ? pool.to : undefined;
47
+ const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
48
+ const targetObject = local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
49
+ if (!targetObject) {
50
+ contract(`${path}.pool`, `"${capacity.pool}" must be a relation field (one record) to another of this extension's objects`);
51
+ }
52
+ else if (local === name) {
53
+ contract(`${path}.pool`, "An object cannot be its own pool");
54
+ }
55
+ else if (!targetObject.capacity) {
56
+ contract(`${path}.pool`, `The pool's object ${target} must declare a capacity`);
57
+ }
58
+ else if (targetObject.capacity.pool !== undefined) {
59
+ contract(`${path}.pool`, `The pool's object ${target} has a pool of its own; capacity has one level of pool`);
60
+ }
61
+ }
62
+ if (capacity.lowAt !== undefined && capacity.show !== "low") {
63
+ contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
64
+ }
65
+ if (capacity.show === "low" && capacity.lowAt === undefined) {
66
+ contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
67
+ }
68
+ }
69
+ export const claimsManifestSchema = z
70
+ .object({
71
+ on: fieldName,
72
+ held: z.array(z.string().min(1).max(100)).max(20).optional(),
73
+ confirmed: z.array(z.string().min(1).max(100)).max(20).optional(),
74
+ })
75
+ .strict();
76
+ /** Reports problems with `objects.<name>.claims` through `contract`. */
77
+ export function checkObjectClaims(m, name, object, contract) {
78
+ const claims = object.claims;
79
+ if (!claims)
80
+ return;
81
+ const path = `objects.${name}.claims`;
82
+ const on = Object.hasOwn(object.fields, claims.on) ? object.fields[claims.on] : undefined;
83
+ const target = on?.type === "relation" && !on.many ? on.to : undefined;
84
+ const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
85
+ const targetObject = local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
86
+ if (!targetObject || local === name) {
87
+ contract(`${path}.on`, `"${claims.on}" must be a relation field (one record) to another of this extension's objects`);
88
+ }
89
+ else if (!targetObject.capacity) {
90
+ contract(`${path}.on`, `${target} must declare a capacity for its places to be claimed`);
91
+ }
92
+ const held = claims.held ?? [];
93
+ const confirmed = claims.confirmed ?? [];
94
+ if (!held.length && !confirmed.length) {
95
+ contract(path, "Name the states that hold a place (held) or take one (confirmed)");
96
+ }
97
+ const states = object.states;
98
+ if (!states) {
99
+ contract(path, `${name} must declare states: its states hold and release the claim`);
100
+ return;
101
+ }
102
+ const field = Object.hasOwn(object.fields, states.field)
103
+ ? object.fields[states.field]
104
+ : undefined;
105
+ const values = new Set((field?.options ?? []).map((o) => o.value));
106
+ for (const [key, list] of [
107
+ ["held", held],
108
+ ["confirmed", confirmed],
109
+ ]) {
110
+ if (new Set(list).size !== list.length)
111
+ contract(`${path}.${key}`, "List each state once");
112
+ for (const state of list) {
113
+ if (!values.has(state))
114
+ contract(`${path}.${key}`, `"${state}" is not a state of ${name}`);
115
+ }
116
+ }
117
+ const both = held.filter((state) => confirmed.includes(state));
118
+ if (both.length) {
119
+ contract(path, `"${both[0]}" cannot both hold and take a place`);
120
+ }
121
+ states.moves.forEach((move, i) => {
122
+ const from = typeof move.from === "string" ? [move.from] : move.from;
123
+ if (held.includes(move.to) && from.some((state) => confirmed.includes(state))) {
124
+ contract(`objects.${name}.states.moves.${i}`, `A move from a state that takes a place cannot go back to one that only holds it ("${move.to}")`);
125
+ }
126
+ });
127
+ }