@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
@@ -0,0 +1,258 @@
1
+ // The `calendarEntry` declaration (stage 62 step 1, ADR 0891): an object whose records are events
2
+ // in its customer's calendar feed. Its manifest schema, the path walker the host's check shares,
3
+ // and the contract checks live here; the host's side (the feed's read, through the visibility seam
4
+ // as the customer) is packages/core/src/customers/calendar-feed.ts.
5
+ import { z } from "zod";
6
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+
8
+ /**
9
+ * Records of this object are events in their customer's private calendar feed (ADR 0891): a class
10
+ * booking, a ticket, an appointment. The host reads them as the customer, through the visibility
11
+ * seam, so the feed never shows a field the customer could not read.
12
+ *
13
+ * - `starts`, `ends`: a datetime path: a field of this object, or a relation of it and a field of
14
+ * what it names (`class.startsAt`), at most two relations deep.
15
+ * - `title`: a text path, the event's name (`classType.name`): the public name of what was booked.
16
+ * - `place` (optional): a text path, the event's place (`class.room.name`).
17
+ * - `live`: the states of the object's `states` in which the record shows. A record in any other
18
+ * state (cancelled, moved), or in the Trash, drops out on the next fetch.
19
+ *
20
+ * The object declares a `customer` (whose feed it is in, and, where it opens to guardians, a live
21
+ * guardian's too), and its customer's read list holds the states field and each path's first
22
+ * field. A field of `title` or `place` one relation or more away must be one that object makes
23
+ * `public` or `signedIn` (a class's own title may name another member: never in a bearer link). A
24
+ * field of `starts` or `ends` may also be, one relation away, what its `customerVia` from this
25
+ * object lists (a booking's class's times). A shipped pack's declaration only: a runtime extension
26
+ * declaring it fails the check.
27
+ */
28
+ export interface CalendarEntrySpec {
29
+ starts: string;
30
+ ends: string;
31
+ title: string;
32
+ place?: string;
33
+ live: readonly string[];
34
+ }
35
+
36
+ const path = z.string().min(1).max(122);
37
+
38
+ export const calendarEntryManifestSchema = z
39
+ .object({
40
+ starts: path,
41
+ ends: path,
42
+ title: path,
43
+ place: path.optional(),
44
+ live: z.array(z.string().min(1).max(100)).min(1).max(20),
45
+ })
46
+ .strict();
47
+ export type CalendarEntryManifest = z.infer<typeof calendarEntryManifestSchema>;
48
+
49
+ /** At most two relations, then the field: `class.room.name`. */
50
+ export const CALENDAR_PATH_MAX_SEGMENTS = 3;
51
+
52
+ /** What a path's last field may be, by key. */
53
+ export const CALENDAR_PATH_TYPES = {
54
+ starts: ["datetime"],
55
+ ends: ["datetime"],
56
+ title: ["text", "select"],
57
+ place: ["text", "select"],
58
+ } as const satisfies Record<"starts" | "ends" | "title" | "place", readonly string[]>;
59
+
60
+ /** The keys whose fields past the first must be public (shown text, never only a time). */
61
+ export const CALENDAR_PUBLIC_ONLY_KEYS: ReadonlySet<string> = new Set(["title", "place"]);
62
+ const PUBLIC_ONLY = CALENDAR_PUBLIC_ONLY_KEYS;
63
+
64
+ /** One field, as the walker needs it. */
65
+ export interface CalendarPathField {
66
+ type: string;
67
+ many: boolean;
68
+ /** A relation's target, as a registry name (`bookings.class`, `person`). */
69
+ to?: string | undefined;
70
+ }
71
+
72
+ /** One object a path passes through, as the walker needs it. */
73
+ export interface CalendarPathObject {
74
+ name: string;
75
+ /** Whether it declares a customer of its own (a path never passes through one). */
76
+ hasCustomer: boolean;
77
+ field(name: string): CalendarPathField | undefined;
78
+ /**
79
+ * The fields a customer reads of this object's records, reached from their own record of `from`
80
+ * through its relation `via` (`customerVia`, one relation away only), or as anyone signed in or
81
+ * the public may.
82
+ */
83
+ readable(from: string | null, via: string | null): ReadonlySet<string>;
84
+ }
85
+
86
+ export type CalendarPathResult =
87
+ | { ok: true; type: string; foreign: boolean }
88
+ | { ok: false; message: string; foreign: boolean }
89
+ /** The path reaches an object this checker leaves to another (the SDK: another extension's). */
90
+ | { ok: "deferred" };
91
+
92
+ /**
93
+ * Walks `path` from `origin`, the object declaring the entry, whose customer reads
94
+ * `originRead`. `lookup` answers an object by registry name: undefined to defer it (not this
95
+ * checker's), null when there is no such object. Pure.
96
+ */
97
+ export function walkCalendarPath(
98
+ origin: CalendarPathObject,
99
+ originRead: ReadonlySet<string>,
100
+ path: string,
101
+ lookup: (name: string) => CalendarPathObject | null | undefined,
102
+ /**
103
+ * Past the first field, only what the related object makes `public` or `signedIn` (a title or
104
+ * a place, ADR 0891): never a field the customer reads only through their own record, such as a
105
+ * class's own title, which may name another member. The feed is a bearer link.
106
+ */
107
+ publicOnly = false,
108
+ ): CalendarPathResult {
109
+ const segments = path.split(".");
110
+ if (segments.length > CALENDAR_PATH_MAX_SEGMENTS || segments.some((s) => s === "")) {
111
+ return {
112
+ ok: false,
113
+ message: `"${path}" must be a field, or at most two relations and a field`,
114
+ foreign: false,
115
+ };
116
+ }
117
+ let object = origin;
118
+ let readable = originRead;
119
+ let foreign = false;
120
+ for (const [i, segment] of segments.entries()) {
121
+ const field = object.field(segment);
122
+ if (!field) {
123
+ return { ok: false, message: `"${segment}" is not a field of ${object.name}`, foreign };
124
+ }
125
+ if (!readable.has(segment)) {
126
+ return {
127
+ ok: false,
128
+ message:
129
+ i === 0
130
+ ? `"${segment}" must be in ${object.name}'s customer.read: the feed shows only what the customer reads`
131
+ : publicOnly
132
+ ? `"${segment}" is not a public field of ${object.name}: a title or place shows only what ${object.name} makes public or signedIn`
133
+ : `"${segment}" is not a field a customer reads of ${object.name} (its public, signedIn or customerVia read)`,
134
+ foreign,
135
+ };
136
+ }
137
+ if (i === segments.length - 1) return { ok: true, type: field.type, foreign };
138
+ if (field.type !== "relation" || field.many || !field.to) {
139
+ return {
140
+ ok: false,
141
+ message: `"${segment}" must be a relation to one record to reach "${segments[i + 1]}"`,
142
+ foreign,
143
+ };
144
+ }
145
+ const next = lookup(field.to);
146
+ if (next === undefined) return { ok: "deferred" };
147
+ foreign ||= !field.to.startsWith(`${origin.name.split(".")[0]}.`);
148
+ if (next === null) return { ok: false, message: `${field.to} is not installed here`, foreign };
149
+ if (next.hasCustomer) {
150
+ return {
151
+ ok: false,
152
+ message: `${next.name} declares a customer of its own: a path cannot pass through it`,
153
+ foreign,
154
+ };
155
+ }
156
+ // Only one relation away does a customerVia from the declaring object count (the seam's
157
+ // `via` scope reaches what the customer's own records point to, no further), and never for a
158
+ // title or a place.
159
+ const via = i === 0 && !publicOnly;
160
+ readable = next.readable(via ? origin.name : null, via ? segment : null);
161
+ object = next;
162
+ }
163
+ return { ok: false, message: `"${path}" is empty`, foreign };
164
+ }
165
+
166
+ /** A manifest object as the walker sees it. */
167
+ export function manifestPathObject(
168
+ extensionId: string,
169
+ local: string,
170
+ object: ObjectManifest,
171
+ ): CalendarPathObject {
172
+ const name = `${extensionId}.${local}`;
173
+ return {
174
+ name,
175
+ hasCustomer: object.customer !== undefined,
176
+ field(fieldName) {
177
+ const field: FieldManifest | undefined = Object.hasOwn(object.fields, fieldName)
178
+ ? object.fields[fieldName]
179
+ : undefined;
180
+ return field ? { type: field.type, many: field.many === true, to: field.to } : undefined;
181
+ },
182
+ readable(from, via) {
183
+ const out = new Set<string>([
184
+ ...(object.public?.read ?? []),
185
+ ...(object.signedIn?.read ?? []),
186
+ ]);
187
+ const v = object.customerVia;
188
+ if (v && from !== null && v.from === from && v.field === via) {
189
+ for (const f of v.read) out.add(f);
190
+ }
191
+ return out;
192
+ },
193
+ };
194
+ }
195
+
196
+ /** Reports problems with `objects.<name>.calendarEntry` through `contract`. */
197
+ export function checkObjectCalendarEntry(
198
+ m: ExtensionManifest,
199
+ name: string,
200
+ object: ObjectManifest,
201
+ contract: (path: string, message: string) => void,
202
+ ): void {
203
+ const entry = object.calendarEntry;
204
+ if (!entry) return;
205
+ const at = `objects.${name}.calendarEntry`;
206
+ const customer = object.customer;
207
+ if (!customer) {
208
+ contract(at, `${name} must declare a customer: a calendar entry is in its customer's feed`);
209
+ return;
210
+ }
211
+ const read = new Set(customer.read);
212
+
213
+ // The states in which a record shows, which the customer reads.
214
+ const states = object.states;
215
+ if (!states) {
216
+ contract(`${at}.live`, `${name} must declare states: a record shows in some of them`);
217
+ } else {
218
+ const field = Object.hasOwn(object.fields, states.field) ? object.fields[states.field] : null;
219
+ const values = new Set((field?.options ?? []).map((o) => o.value));
220
+ for (const state of entry.live) {
221
+ if (!values.has(state)) contract(`${at}.live`, `"${state}" is not a state of ${name}`);
222
+ }
223
+ if (new Set(entry.live).size !== entry.live.length) {
224
+ contract(`${at}.live`, "List each state once");
225
+ }
226
+ if (!read.has(states.field)) {
227
+ contract(
228
+ `${at}.live`,
229
+ `"${states.field}" must be in ${name}'s customer.read: the feed reads the state as the customer`,
230
+ );
231
+ }
232
+ }
233
+
234
+ // Each path, as far as this extension's own objects go; the host checks another extension's.
235
+ const origin = manifestPathObject(m.id, name, object);
236
+ const lookup = (target: string) => {
237
+ const local = target.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
238
+ if (local === undefined) return undefined;
239
+ return Object.hasOwn(m.objects, local)
240
+ ? manifestPathObject(m.id, local, m.objects[local] as ObjectManifest)
241
+ : null;
242
+ };
243
+ for (const key of ["starts", "ends", "title", "place"] as const) {
244
+ const declared = entry[key];
245
+ if (declared === undefined) continue;
246
+ const result = walkCalendarPath(origin, read, declared, lookup, PUBLIC_ONLY.has(key));
247
+ if (result.ok === "deferred") continue;
248
+ if (!result.ok) contract(`${at}.${key}`, result.message);
249
+ else if (!(CALENDAR_PATH_TYPES[key] as readonly string[]).includes(result.type)) {
250
+ contract(
251
+ `${at}.${key}`,
252
+ `"${declared}" must end at a ${CALENDAR_PATH_TYPES[key].join(" or ")} field`,
253
+ );
254
+ }
255
+ }
256
+ if (entry.starts === entry.ends)
257
+ contract(`${at}.ends`, "An event's start and end are two fields");
258
+ }
package/src/capacity.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // is packages/core/src/capacity/.
5
5
  import { z } from "zod";
6
6
  import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+ import { moveOrigins, type WindowBound, windowBoundSchema, windowChecks } from "./states.ts";
7
8
 
8
9
  /**
9
10
  * What customers and the public are told about a record's places (staff always see the real
@@ -128,13 +129,56 @@ export interface ClaimsSpec {
128
129
  on: string;
129
130
  held?: readonly string[];
130
131
  confirmed?: readonly string[];
132
+ waitlist?: WaitlistSpec;
131
133
  }
132
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
+
133
176
  export const claimsManifestSchema = z
134
177
  .object({
135
178
  on: fieldName,
136
179
  held: z.array(z.string().min(1).max(100)).max(20).optional(),
137
180
  confirmed: z.array(z.string().min(1).max(100)).max(20).optional(),
181
+ waitlist: waitlistManifestSchema.optional(),
138
182
  })
139
183
  .strict();
140
184
  export type ClaimsManifest = z.infer<typeof claimsManifestSchema>;
@@ -190,12 +234,69 @@ export function checkObjectClaims(
190
234
  contract(path, `"${both[0]}" cannot both hold and take a place`);
191
235
  }
192
236
  states.moves.forEach((move, i) => {
193
- const from = typeof move.from === "string" ? [move.from] : move.from;
194
- if (held.includes(move.to) && from.some((state) => confirmed.includes(state))) {
237
+ if (held.includes(move.to) && moveOrigins(move).some((state) => confirmed.includes(state))) {
195
238
  contract(
196
239
  `objects.${name}.states.moves.${i}`,
197
240
  `A move from a state that takes a place cannot go back to one that only holds it ("${move.to}")`,
198
241
  );
199
242
  }
200
243
  });
244
+ const waitlist = claims.waitlist;
245
+ if (!waitlist) return;
246
+ // A waitlist (ADR 0520).
247
+ const wp = `${path}.waitlist`;
248
+ if (!values.has(waitlist.state)) {
249
+ contract(`${wp}.state`, `"${waitlist.state}" is not a state of ${name}`);
250
+ } else if (held.includes(waitlist.state) || confirmed.includes(waitlist.state)) {
251
+ contract(`${wp}.state`, `"${waitlist.state}" waits: it can neither hold nor take a place`);
252
+ } else if (states.moves.some((move) => move.final && move.to === waitlist.state)) {
253
+ contract(`${wp}.state`, `"${waitlist.state}" is final: nobody waits in it`);
254
+ } else if (
255
+ states.initial !== waitlist.state &&
256
+ !Object.hasOwn(states.create?.in ?? {}, waitlist.state)
257
+ ) {
258
+ contract(
259
+ `${wp}.state`,
260
+ `"${waitlist.state}" must be a state ${name} may be created in (states.create.in): a waiter joins by being made waiting`,
261
+ );
262
+ }
263
+ if (!confirmed.includes(waitlist.promote)) {
264
+ contract(`${wp}.promote`, `"${waitlist.promote}" must be one of claims.confirmed`);
265
+ }
266
+ const promotions = states.moves.filter(
267
+ (move) => move.to === waitlist.promote && moveOrigins(move).includes(waitlist.state),
268
+ );
269
+ if (!promotions.some((move) => move.by.includes("host"))) {
270
+ contract(
271
+ `${wp}.promote`,
272
+ `Declare a move from "${waitlist.state}" to "${waitlist.promote}" by the host: promotion is the host's`,
273
+ );
274
+ }
275
+ // A customer may move their own waiting record in, but only onto a free place: the host's
276
+ // promotion alone takes a place the waitlist holds, so nobody moves themselves ahead of it.
277
+ // Their move needs the create's window, so they cannot claim a place booking would refuse.
278
+ promotions.forEach((move) => {
279
+ if (move.by.includes("customer") && !move.window) {
280
+ contract(
281
+ `${wp}.promote`,
282
+ `A customer's move from "${waitlist.state}" to "${waitlist.promote}" needs a window (the create's): it books them`,
283
+ );
284
+ }
285
+ });
286
+ windowChecks(m, object, name, contract).checkBound(waitlist.until, `${wp}.until`);
287
+ for (const [key, type] of [
288
+ ["promotedAt", "datetime"],
289
+ ["passedOverAt", "datetime"],
290
+ ["passedOverReason", "text"],
291
+ ] as const) {
292
+ const local = waitlist[key];
293
+ if (local === undefined) continue;
294
+ const field = Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
295
+ if (field?.type !== type || field.many || !field.readOnly) {
296
+ contract(`${wp}.${key}`, `"${local}" must be a read-only ${type} field of ${name}`);
297
+ }
298
+ }
299
+ if (targetObject?.capacity?.pool !== undefined) {
300
+ contract(`${wp}`, `A waitlist is on places with no pool; ${target} has one`);
301
+ }
201
302
  }
@@ -0,0 +1,118 @@
1
+ // The `checklists` declaration (stage 45 step 4b, ADR 0650): a record its person ticks a checklist
2
+ // off on. Its manifest schema and contract checks live here; the host's side (the templates, the
3
+ // runs and their ticks, a completed run kept unchanged by the database, who reads how it went) is
4
+ // packages/core/src/checklists/.
5
+ import { z } from "zod";
6
+ import type { ExtensionManifest, FieldManifest, ObjectManifest } from "./manifest.ts";
7
+
8
+ /**
9
+ * A checklist a record's person ticks off (ADR 0650). A business writes a checklist once (its
10
+ * steps, in Settings → Checklists) and picks it on something that happens (a duty); each record
11
+ * that is live with one gets a **run** of it, made by the host a day before it opens, with the
12
+ * steps copied as they were then (a template changed later changes no run already made). Its
13
+ * person ticks it off from when it opens until it closes and a grace period after; someone who
14
+ * rosters may tick for them, with a reason, recorded as theirs for that person. A run marked done
15
+ * never changes, refused by the database for every writer; one not done by its close and grace is
16
+ * closed by the host as missed, and the rosterers are told. How a run went is read only by its
17
+ * person and by those who roster, never by other staff, any rec_* view or an AI.
18
+ *
19
+ * - `template`: the field naming the checklist, of type `checklist`: one of this object's, or
20
+ * `relation.field` through a relation (one record) to another of this extension's objects (a
21
+ * duty shift's `duty.checklist`).
22
+ * - `who`: the `user` field holding the staff account who ticks it (the shift's person).
23
+ * - `opens`, `closes`: datetime fields of this object, when it may be ticked (the shift's start and
24
+ * end).
25
+ * - `live`: the states of the object's `states` in which it applies. A record in any other state,
26
+ * or in the Trash, at its close is closed as cancelled, not missed.
27
+ *
28
+ * Only shipped packs and the org's own extensions declare it: who ticks what is a staff record.
29
+ */
30
+ export interface ChecklistsSpec {
31
+ template: string;
32
+ who: string;
33
+ opens: string;
34
+ closes: string;
35
+ live: readonly string[];
36
+ }
37
+
38
+ const fieldName = z.string().max(40);
39
+
40
+ export const checklistsManifestSchema = z
41
+ .object({
42
+ template: z.string().max(81),
43
+ who: fieldName,
44
+ opens: fieldName,
45
+ closes: fieldName,
46
+ live: z.array(z.string().min(1).max(100)).min(1).max(20),
47
+ })
48
+ .strict();
49
+ export type ChecklistsManifest = z.infer<typeof checklistsManifestSchema>;
50
+
51
+ /** Reports problems with `objects.<name>.checklists` through `contract`. */
52
+ export function checkObjectChecklists(
53
+ m: ExtensionManifest,
54
+ name: string,
55
+ object: ObjectManifest,
56
+ contract: (path: string, message: string) => void,
57
+ ): void {
58
+ const declared = object.checklists;
59
+ if (!declared) return;
60
+ const at = `objects.${name}.checklists`;
61
+ const own = (o: ObjectManifest, local: string): FieldManifest | undefined =>
62
+ Object.hasOwn(o.fields, local) ? o.fields[local] : undefined;
63
+ const single = (field: FieldManifest | undefined, types: readonly string[]) =>
64
+ field !== undefined && types.includes(field.type) && !field.many;
65
+
66
+ // The template: a checklist field of this object, or of what a relation of it names.
67
+ const [first, second, ...rest] = declared.template.split(".");
68
+ if (first === undefined || rest.length) {
69
+ contract(`${at}.template`, `"${declared.template}" must be a field, or relation.field`);
70
+ } else if (second === undefined) {
71
+ if (!single(own(object, first), ["checklist"])) {
72
+ contract(`${at}.template`, `"${first}" must be a checklist field of ${name}`);
73
+ }
74
+ } else {
75
+ const via = own(object, first);
76
+ const target = via?.type === "relation" && !via.many ? via.to : undefined;
77
+ const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
78
+ const holder = local && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
79
+ if (!holder || local === name) {
80
+ contract(
81
+ `${at}.template`,
82
+ `"${first}" must be a relation field (one record) to another of this extension's objects`,
83
+ );
84
+ } else if (!single(own(holder, second), ["checklist"])) {
85
+ contract(`${at}.template`, `"${second}" must be a checklist field of ${target as string}`);
86
+ }
87
+ }
88
+
89
+ // Who ticks it.
90
+ if (!single(own(object, declared.who), ["user"])) {
91
+ contract(`${at}.who`, `"${declared.who}" must be a user field of ${name}`);
92
+ }
93
+
94
+ // When it opens and closes.
95
+ for (const key of ["opens", "closes"] as const) {
96
+ if (!single(own(object, declared[key]), ["datetime"])) {
97
+ contract(`${at}.${key}`, `"${declared[key]}" must be a datetime field of ${name}`);
98
+ }
99
+ }
100
+ if (declared.opens === declared.closes) {
101
+ contract(`${at}.closes`, "A checklist opens and closes at two fields");
102
+ }
103
+
104
+ // The states in which it applies.
105
+ const states = object.states;
106
+ if (!states) {
107
+ contract(`${at}.live`, `${name} must declare states: a checklist applies in some of them`);
108
+ } else {
109
+ const field = own(object, states.field);
110
+ const values = new Set((field?.options ?? []).map((o) => o.value));
111
+ for (const state of declared.live) {
112
+ if (!values.has(state)) contract(`${at}.live`, `"${state}" is not a state of ${name}`);
113
+ }
114
+ if (new Set(declared.live).size !== declared.live.length) {
115
+ contract(`${at}.live`, "List each state once");
116
+ }
117
+ }
118
+ }