@composable-os/sdk 0.0.0-stage → 0.1.0-beta.11

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 +146 -0
  11. package/dist/capacity.js +189 -0
  12. package/dist/contract.d.ts +851 -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 +1708 -0
  29. package/dist/manifest.js +1494 -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 +331 -0
  45. package/dist/sellable.js +746 -0
  46. package/dist/slug.d.ts +11 -0
  47. package/dist/slug.js +23 -0
  48. package/dist/states.d.ts +292 -0
  49. package/dist/states.js +383 -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 +303 -0
  60. package/src/contract.ts +909 -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 +1785 -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 +1138 -0
  77. package/src/slug.ts +25 -0
  78. package/src/states.ts +598 -0
  79. package/src/testing.ts +847 -0
  80. package/src/unique.ts +81 -0
  81. package/README.md +0 -3
@@ -0,0 +1,215 @@
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.ts";
4
+ import type { FieldTypeName } from "./field-types.ts";
5
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
6
+
7
+ const NUMERIC: readonly FieldTypeName[] = ["number", "percent", "currency"];
8
+ const SEED_KEY_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
9
+
10
+ /** Reports problems with `objects.<name>`'s behaviour keys through `contract`. */
11
+ export function checkObjectBehaviour(
12
+ m: ExtensionManifest,
13
+ name: string,
14
+ object: ObjectManifest,
15
+ contract: (path: string, message: string) => void,
16
+ ): void {
17
+ const path = `objects.${name}`;
18
+ const fieldOf = (local: string): FieldManifest | undefined =>
19
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
20
+ const isSingle = (field: FieldManifest | undefined) =>
21
+ field !== undefined && field.type !== "formula" && field.type !== "multiSelect" && !field.many;
22
+ const relationTo = (field: FieldManifest | undefined) =>
23
+ field?.type === "relation" && !field.many ? field.to : undefined;
24
+ const ownObject = (target: string | undefined) =>
25
+ target?.startsWith(`${m.id}.`) ? m.objects[target.slice(m.id.length + 1)] : undefined;
26
+
27
+ (object.indexes ?? []).forEach((columns, i) => {
28
+ if (new Set(columns).size !== columns.length) {
29
+ contract(`${path}.indexes.${i}`, "An index lists each field once");
30
+ }
31
+ for (const column of columns) {
32
+ if (column === "createdAt" || column === "updatedAt") continue;
33
+ if (!isSingle(fieldOf(column))) {
34
+ contract(
35
+ `${path}.indexes.${i}`,
36
+ `Index field "${column}" must be a single-valued, non-formula field of ${name}`,
37
+ );
38
+ }
39
+ }
40
+ });
41
+
42
+ (object.timelineLinks ?? []).forEach((local, i) => {
43
+ if (!relationTo(fieldOf(local))) {
44
+ contract(`${path}.timelineLinks.${i}`, `"${local}" must be a relation field (one record)`);
45
+ }
46
+ });
47
+
48
+ const stages = object.stages;
49
+ if (stages) {
50
+ const sp = `${path}.stages`;
51
+ const stageTarget = relationTo(fieldOf(stages.field));
52
+ const stageObject = ownObject(stageTarget);
53
+ if (!stageObject) {
54
+ contract(
55
+ `${sp}.field`,
56
+ `"${stages.field}" must be a relation field (one record) to another of this extension's objects`,
57
+ );
58
+ } else {
59
+ if (fieldOf(stages.field)?.readOnly) {
60
+ contract(`${sp}.field`, "The stage field cannot be read-only");
61
+ }
62
+ const sf = (local: string): FieldManifest | undefined =>
63
+ Object.hasOwn(stageObject.fields, local) ? stageObject.fields[local] : undefined;
64
+ const type = sf(stages.stage.type);
65
+ const values = type?.options?.map((o) => o.value) ?? [];
66
+ if (type?.type !== "select" || !STAGE_TYPES.every((t) => values.includes(t))) {
67
+ contract(
68
+ `${sp}.stage.type`,
69
+ `"${stages.stage.type}" must be a select field of ${stageTarget} with options open, won and lost`,
70
+ );
71
+ }
72
+ const order = sf(stages.stage.order);
73
+ if (!order || !NUMERIC.includes(order.type)) {
74
+ contract(
75
+ `${sp}.stage.order`,
76
+ `"${stages.stage.order}" must be a number field of ${stageTarget}`,
77
+ );
78
+ }
79
+ if (stages.stage.requiredFields !== undefined) {
80
+ const required = sf(stages.stage.requiredFields);
81
+ if (required?.type !== "multiSelect") {
82
+ contract(
83
+ `${sp}.stage.requiredFields`,
84
+ `"${stages.stage.requiredFields}" must be a multiSelect field of ${stageTarget}`,
85
+ );
86
+ } else {
87
+ for (const option of required.options ?? []) {
88
+ const target = fieldOf(option.value);
89
+ if (!target || target.type === "formula" || target.readOnly) {
90
+ contract(
91
+ `${sp}.stage.requiredFields`,
92
+ `Option "${option.value}" must name a writable field of ${name}`,
93
+ );
94
+ }
95
+ }
96
+ }
97
+ }
98
+ if (stages.stage.probability !== undefined) {
99
+ const probability = sf(stages.stage.probability);
100
+ if (!probability || !NUMERIC.includes(probability.type)) {
101
+ contract(
102
+ `${sp}.stage.probability`,
103
+ `"${stages.stage.probability}" must be a number or percent field of ${stageTarget}`,
104
+ );
105
+ }
106
+ }
107
+ const stageGroup = stages.stage.group ? relationTo(sf(stages.stage.group)) : undefined;
108
+ if (stages.stage.group !== undefined && !stageGroup) {
109
+ contract(
110
+ `${sp}.stage.group`,
111
+ `"${stages.stage.group}" must be a relation field (one record) of ${stageTarget}`,
112
+ );
113
+ }
114
+ if ((stages.group === undefined) !== (stages.stage.group === undefined)) {
115
+ contract(`${sp}.group`, "Declare both group and stage.group, or neither");
116
+ } else if (stages.group !== undefined && relationTo(fieldOf(stages.group)) !== stageGroup) {
117
+ contract(
118
+ `${sp}.group`,
119
+ `"${stages.group}" must be a relation field to the same object as ${stageTarget}.${stages.stage.group}`,
120
+ );
121
+ }
122
+ }
123
+ if (stages.probability) {
124
+ const field = fieldOf(stages.probability.field);
125
+ if (!field || !NUMERIC.includes(field.type) || field.readOnly) {
126
+ contract(
127
+ `${sp}.probability.field`,
128
+ `"${stages.probability.field}" must be a writable number or percent field`,
129
+ );
130
+ }
131
+ const flag = fieldOf(stages.probability.overridden);
132
+ if (flag?.type !== "boolean" || flag.readOnly) {
133
+ contract(
134
+ `${sp}.probability.overridden`,
135
+ `"${stages.probability.overridden}" must be a writable boolean field`,
136
+ );
137
+ }
138
+ if (!stages.stage.probability) {
139
+ contract(`${sp}.stage.probability`, "probability needs the stage's default probability");
140
+ }
141
+ }
142
+ if (stages.closedDate !== undefined) {
143
+ const field = fieldOf(stages.closedDate);
144
+ if ((field?.type !== "date" && field?.type !== "datetime") || !field.readOnly) {
145
+ contract(
146
+ `${sp}.closedDate`,
147
+ `"${stages.closedDate}" must be a read-only date or datetime field`,
148
+ );
149
+ }
150
+ }
151
+ if (stages.status !== undefined) {
152
+ const field = fieldOf(stages.status);
153
+ const values = field?.options?.map((o) => o.value) ?? [];
154
+ if (
155
+ field?.type !== "select" ||
156
+ !field.readOnly ||
157
+ !STAGE_TYPES.every((t) => values.includes(t))
158
+ ) {
159
+ contract(
160
+ `${sp}.status`,
161
+ `"${stages.status}" must be a read-only select field with options open, won and lost`,
162
+ );
163
+ }
164
+ }
165
+ if (stages.defaultGroupSetting !== undefined) {
166
+ const setting = m.settings?.[stages.defaultGroupSetting];
167
+ if (!stages.group) {
168
+ contract(`${sp}.defaultGroupSetting`, "defaultGroupSetting needs a group");
169
+ } else if (setting?.type !== "text" && setting?.type !== "select") {
170
+ contract(
171
+ `${sp}.defaultGroupSetting`,
172
+ `"${stages.defaultGroupSetting}" must be a text or select setting of this extension`,
173
+ );
174
+ }
175
+ }
176
+ for (const [type, list] of Object.entries(stages.requiredByType ?? {})) {
177
+ for (const local of list ?? []) {
178
+ const field = fieldOf(local);
179
+ if (!field || field.type === "formula" || field.readOnly) {
180
+ contract(
181
+ `${sp}.requiredByType.${type}`,
182
+ `"${local}" must be a writable field of ${name}`,
183
+ );
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ for (const [key, values] of Object.entries(object.seed ?? {})) {
190
+ const kp = `${path}.seed.${key}`;
191
+ if (!SEED_KEY_RE.test(key)) contract(kp, "Seed keys must be camelCase");
192
+ for (const [local, value] of Object.entries(values)) {
193
+ const field = fieldOf(local);
194
+ if (!field || field.type === "formula" || field.readOnly) {
195
+ contract(`${kp}.${local}`, `"${local}" is not a writable field of ${name}`);
196
+ continue;
197
+ }
198
+ if (value && typeof value === "object" && !Array.isArray(value)) {
199
+ const ref = (value as { seed?: unknown }).seed;
200
+ const target = ownObject(field.type === "relation" ? field.to : undefined);
201
+ if (typeof ref !== "string" || !target?.seed || !Object.hasOwn(target.seed, ref)) {
202
+ contract(
203
+ `${kp}.${local}`,
204
+ "A seed reference ({ seed: key }) must name a seed record of the relation's target",
205
+ );
206
+ }
207
+ }
208
+ }
209
+ for (const [local, field] of Object.entries(object.fields)) {
210
+ if (field.required && !(local in values)) {
211
+ contract(kp, `Seed record "${key}" needs required field "${local}"`);
212
+ }
213
+ }
214
+ }
215
+ }
@@ -0,0 +1,303 @@
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
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+ import { moveOrigins, type WindowBound, windowBoundSchema, windowChecks } from "./states.ts";
8
+
9
+ /**
10
+ * What customers and the public are told about a record's places (staff always see the real
11
+ * numbers): `exact`, the number left; `low`, available, "only N left" at or below `lowAt`, or sold
12
+ * out; `availability`, available or sold out.
13
+ */
14
+ export const CAPACITY_SHOW = ["exact", "low", "availability"] as const;
15
+ export type CapacityShow = (typeof CAPACITY_SHOW)[number];
16
+
17
+ /**
18
+ * The read-only values the host adds to every record of an object with a capacity: places held
19
+ * while someone pays, places taken, and places left (the record's and its pool's, whichever is
20
+ * fewer; null when unlimited). An object with a capacity cannot have fields of these names.
21
+ */
22
+ export const CAPACITY_VALUES = ["held", "taken", "available"] as const;
23
+
24
+ /**
25
+ * A limited number of places (ADR 0430). The host keeps a counter per record and refuses, in the
26
+ * database, any claim past the places: a hold while an order is unpaid, confirmed when it is paid.
27
+ * A hold has no clock of its own: it lasts as long as what it was taken for.
28
+ *
29
+ * - `places` is this object's number field holding how many places there are. Empty means
30
+ * unlimited. Staff edit it; lowering it below what is held and taken is refused with the
31
+ * numbers, for every actor, and nothing ever sells beyond it.
32
+ * - `pool` is a relation field (one record) to another of this extension's objects that itself
33
+ * declares a capacity, and no pool: a claim on this record also claims on that record, in the
34
+ * same batch (a ticket type's places within its event's). One level only.
35
+ * - `show` is what customers and the public are told (default `availability`); `lowAt` is the
36
+ * threshold for `low`.
37
+ * - `releaseOnRefund` (default true): a refunded order's places go back on sale.
38
+ */
39
+ export interface CapacitySpec {
40
+ places: string;
41
+ pool?: string;
42
+ show?: CapacityShow;
43
+ lowAt?: number;
44
+ releaseOnRefund?: boolean;
45
+ }
46
+
47
+ const fieldName = z.string().max(40);
48
+
49
+ export const capacityManifestSchema = z
50
+ .object({
51
+ places: fieldName,
52
+ pool: fieldName.optional(),
53
+ show: z.enum(CAPACITY_SHOW).optional(),
54
+ lowAt: z.number().int().min(1).max(1_000_000).optional(),
55
+ releaseOnRefund: z.boolean().optional(),
56
+ })
57
+ .strict();
58
+ export type CapacityManifest = z.infer<typeof capacityManifestSchema>;
59
+
60
+ /** Reports problems with `objects.<name>.capacity` through `contract`. */
61
+ export function checkObjectCapacity(
62
+ m: ExtensionManifest,
63
+ name: string,
64
+ object: ObjectManifest,
65
+ contract: (path: string, message: string) => void,
66
+ ): void {
67
+ const capacity = object.capacity;
68
+ if (!capacity) return;
69
+ const path = `objects.${name}.capacity`;
70
+ const fieldOf = (local: string): FieldManifest | undefined =>
71
+ Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
72
+
73
+ const places = fieldOf(capacity.places);
74
+ if (places?.type !== "number" || places.many) {
75
+ contract(`${path}.places`, `"${capacity.places}" must be a number field of ${name}`);
76
+ }
77
+ for (const reserved of CAPACITY_VALUES) {
78
+ if (Object.hasOwn(object.fields, reserved)) {
79
+ contract(
80
+ `objects.${name}.fields.${reserved}`,
81
+ `"${reserved}" is a value the host adds to an object with a capacity; rename the field`,
82
+ );
83
+ }
84
+ }
85
+ if (capacity.pool !== undefined) {
86
+ const pool = fieldOf(capacity.pool);
87
+ const target = pool?.type === "relation" && !pool.many ? pool.to : undefined;
88
+ const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
89
+ const targetObject =
90
+ local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
91
+ if (!targetObject) {
92
+ contract(
93
+ `${path}.pool`,
94
+ `"${capacity.pool}" must be a relation field (one record) to another of this extension's objects`,
95
+ );
96
+ } else if (local === name) {
97
+ contract(`${path}.pool`, "An object cannot be its own pool");
98
+ } else if (!targetObject.capacity) {
99
+ contract(`${path}.pool`, `The pool's object ${target} must declare a capacity`);
100
+ } else if (targetObject.capacity.pool !== undefined) {
101
+ contract(
102
+ `${path}.pool`,
103
+ `The pool's object ${target} has a pool of its own; capacity has one level of pool`,
104
+ );
105
+ }
106
+ }
107
+ if (capacity.lowAt !== undefined && capacity.show !== "low") {
108
+ contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
109
+ }
110
+ if (capacity.show === "low" && capacity.lowAt === undefined) {
111
+ contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
112
+ }
113
+ }
114
+
115
+ /**
116
+ * A capacity claimant (stage 31, ADR 0501): a record whose own states hold and release a claim of
117
+ * one place on the record its relation `on` points to (a booking on its class), which declares a
118
+ * capacity. Entering a `held` state holds a place, entering a `confirmed` state takes one (from
119
+ * the hold, or claimed and taken at once), and leaving them gives it back, each in the batch of
120
+ * the write that makes the move, refused by the database past the places as an order's claim is.
121
+ * Moving between two `held` states, or two `confirmed` ones, changes nothing.
122
+ *
123
+ * - The object declares `states`; `held` and `confirmed` are its states, apart. No move goes from
124
+ * a confirmed state back to a held one.
125
+ * - While a record is in one of them, `on` cannot be changed: a move to another class is a new
126
+ * record. A record holding a place cannot be moved to Trash.
127
+ */
128
+ export interface ClaimsSpec {
129
+ on: string;
130
+ held?: readonly string[];
131
+ confirmed?: readonly string[];
132
+ waitlist?: WaitlistSpec;
133
+ }
134
+
135
+ /**
136
+ * A waitlist on the claimed record's places (stage 31, ADR 0520). A record in `state` waits: it
137
+ * holds no place and spends nothing. It may be made only while the record it claims on is full
138
+ * and before `until`. Until then, a place given back while anyone waits is handed to the waitlist
139
+ * in the same statements that give it back, as a hold of its own that nobody booking directly
140
+ * can take. The host then promotes the first waiter (by when the record was made) from a current
141
+ * read: the move from `state` into `promote` takes the waitlist's hold, and whatever that move
142
+ * spends is spent then. A waiter who cannot be moved in (their spend is refused) is passed over
143
+ * and stays waiting; a hold nobody can take is given back to everyone. From `until`, nobody is
144
+ * promoted and a place given back goes to whoever claims first.
145
+ *
146
+ * - `state` is a state of the object that neither holds nor takes a place, and is not final.
147
+ * - `promote` is one of `confirmed`; a move from `state` to it must be declared for the host.
148
+ * Declared for a customer too (with a window), it lets a waiter take a free place themselves:
149
+ * only the host's promotion takes a place the waitlist holds, so nobody jumps the queue.
150
+ * - `until` is a moment, named as a window's end is (`{ at: "class.startsAt", minutesBefore:
151
+ * { field: "class.classType.promotionMinutes", setting: "promotionMinutes" } }`).
152
+ * - `promotedAt`, `passedOverAt` (read-only datetimes) and `passedOverReason` (read-only text)
153
+ * are what the host writes when it promotes a waiter or passes one over, for messages.
154
+ * - The claimed object has no pool.
155
+ */
156
+ export interface WaitlistSpec {
157
+ state: string;
158
+ promote: string;
159
+ until: string | WindowBound;
160
+ promotedAt?: string;
161
+ passedOverAt?: string;
162
+ passedOverReason?: string;
163
+ }
164
+
165
+ export const waitlistManifestSchema = z
166
+ .object({
167
+ state: z.string().min(1).max(100),
168
+ promote: z.string().min(1).max(100),
169
+ until: windowBoundSchema,
170
+ promotedAt: fieldName.optional(),
171
+ passedOverAt: fieldName.optional(),
172
+ passedOverReason: fieldName.optional(),
173
+ })
174
+ .strict();
175
+
176
+ export const claimsManifestSchema = z
177
+ .object({
178
+ on: fieldName,
179
+ held: z.array(z.string().min(1).max(100)).max(20).optional(),
180
+ confirmed: z.array(z.string().min(1).max(100)).max(20).optional(),
181
+ waitlist: waitlistManifestSchema.optional(),
182
+ })
183
+ .strict();
184
+ export type ClaimsManifest = z.infer<typeof claimsManifestSchema>;
185
+
186
+ /** Reports problems with `objects.<name>.claims` through `contract`. */
187
+ export function checkObjectClaims(
188
+ m: ExtensionManifest,
189
+ name: string,
190
+ object: ObjectManifest,
191
+ contract: (path: string, message: string) => void,
192
+ ): void {
193
+ const claims = object.claims;
194
+ if (!claims) return;
195
+ const path = `objects.${name}.claims`;
196
+ const on = Object.hasOwn(object.fields, claims.on) ? object.fields[claims.on] : undefined;
197
+ const target = on?.type === "relation" && !on.many ? on.to : undefined;
198
+ const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
199
+ const targetObject =
200
+ local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
201
+ if (!targetObject || local === name) {
202
+ contract(
203
+ `${path}.on`,
204
+ `"${claims.on}" must be a relation field (one record) to another of this extension's objects`,
205
+ );
206
+ } else if (!targetObject.capacity) {
207
+ contract(`${path}.on`, `${target} must declare a capacity for its places to be claimed`);
208
+ }
209
+ const held = claims.held ?? [];
210
+ const confirmed = claims.confirmed ?? [];
211
+ if (!held.length && !confirmed.length) {
212
+ contract(path, "Name the states that hold a place (held) or take one (confirmed)");
213
+ }
214
+ const states = object.states;
215
+ if (!states) {
216
+ contract(path, `${name} must declare states: its states hold and release the claim`);
217
+ return;
218
+ }
219
+ const field = Object.hasOwn(object.fields, states.field)
220
+ ? object.fields[states.field]
221
+ : undefined;
222
+ const values = new Set((field?.options ?? []).map((o) => o.value));
223
+ for (const [key, list] of [
224
+ ["held", held],
225
+ ["confirmed", confirmed],
226
+ ] as const) {
227
+ if (new Set(list).size !== list.length) contract(`${path}.${key}`, "List each state once");
228
+ for (const state of list) {
229
+ if (!values.has(state)) contract(`${path}.${key}`, `"${state}" is not a state of ${name}`);
230
+ }
231
+ }
232
+ const both = held.filter((state) => confirmed.includes(state));
233
+ if (both.length) {
234
+ contract(path, `"${both[0]}" cannot both hold and take a place`);
235
+ }
236
+ states.moves.forEach((move, i) => {
237
+ const from = typeof move.from === "string" ? [move.from] : move.from;
238
+ if (held.includes(move.to) && from.some((state) => confirmed.includes(state))) {
239
+ contract(
240
+ `objects.${name}.states.moves.${i}`,
241
+ `A move from a state that takes a place cannot go back to one that only holds it ("${move.to}")`,
242
+ );
243
+ }
244
+ });
245
+ const waitlist = claims.waitlist;
246
+ if (!waitlist) return;
247
+ // A waitlist (ADR 0520).
248
+ const wp = `${path}.waitlist`;
249
+ if (!values.has(waitlist.state)) {
250
+ contract(`${wp}.state`, `"${waitlist.state}" is not a state of ${name}`);
251
+ } else if (held.includes(waitlist.state) || confirmed.includes(waitlist.state)) {
252
+ contract(`${wp}.state`, `"${waitlist.state}" waits: it can neither hold nor take a place`);
253
+ } else if (states.moves.some((move) => move.final && move.to === waitlist.state)) {
254
+ contract(`${wp}.state`, `"${waitlist.state}" is final: nobody waits in it`);
255
+ } else if (
256
+ states.initial !== waitlist.state &&
257
+ !Object.hasOwn(states.create?.in ?? {}, waitlist.state)
258
+ ) {
259
+ contract(
260
+ `${wp}.state`,
261
+ `"${waitlist.state}" must be a state ${name} may be created in (states.create.in): a waiter joins by being made waiting`,
262
+ );
263
+ }
264
+ if (!confirmed.includes(waitlist.promote)) {
265
+ contract(`${wp}.promote`, `"${waitlist.promote}" must be one of claims.confirmed`);
266
+ }
267
+ const promotions = states.moves.filter(
268
+ (move) => move.to === waitlist.promote && moveOrigins(move).includes(waitlist.state),
269
+ );
270
+ if (!promotions.some((move) => move.by.includes("host"))) {
271
+ contract(
272
+ `${wp}.promote`,
273
+ `Declare a move from "${waitlist.state}" to "${waitlist.promote}" by the host: promotion is the host's`,
274
+ );
275
+ }
276
+ // A customer may move their own waiting record in, but only onto a free place: the host's
277
+ // promotion alone takes a place the waitlist holds, so nobody moves themselves ahead of it.
278
+ // Their move needs the create's window, so they cannot claim a place booking would refuse.
279
+ promotions.forEach((move) => {
280
+ if (move.by.includes("customer") && !move.window) {
281
+ contract(
282
+ `${wp}.promote`,
283
+ `A customer's move from "${waitlist.state}" to "${waitlist.promote}" needs a window (the create's): it books them`,
284
+ );
285
+ }
286
+ });
287
+ windowChecks(m, object, name, contract).checkBound(waitlist.until, `${wp}.until`);
288
+ for (const [key, type] of [
289
+ ["promotedAt", "datetime"],
290
+ ["passedOverAt", "datetime"],
291
+ ["passedOverReason", "text"],
292
+ ] as const) {
293
+ const local = waitlist[key];
294
+ if (local === undefined) continue;
295
+ const field = Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
296
+ if (field?.type !== type || field.many || !field.readOnly) {
297
+ contract(`${wp}.${key}`, `"${local}" must be a read-only ${type} field of ${name}`);
298
+ }
299
+ }
300
+ if (targetObject?.capacity?.pool !== undefined) {
301
+ contract(`${wp}`, `A waitlist is on places with no pool; ${target} has one`);
302
+ }
303
+ }