@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
@@ -2,7 +2,11 @@
2
2
  // declared automation, after the zod structure check. Every message names the problem and the fix
3
3
  // in terms a model can act on: the field that does not exist and the ones that do, the permission
4
4
  // to add, the step name that is repeated.
5
- import { durationMs, } from "./automation.js";
5
+ import { durationMs, MAX_MOMENT_MINUTES, } from "./automation.js";
6
+ import { checkFormula } from "./formula/compile.js";
7
+ // A function, read at call time: manifest.ts imports this file too.
8
+ import { objectFormulaEnvironment } from "./manifest.js";
9
+ import { resolveFieldPath } from "./states.js";
6
10
  /** Waits in one run (sleeps plus waitForEvent timeouts) add up to at most this. */
7
11
  export const MAX_TOTAL_WAIT_DAYS = 365;
8
12
  /** A waitForEvent without a timeout waits this long (ADR 0130). */
@@ -109,9 +113,21 @@ function fieldsOf(ctx, object) {
109
113
  const own = m.objects[object.slice(m.id.length + 1)];
110
114
  if (!own)
111
115
  return null;
116
+ // A formula whose value is a date or a time counts as one (ADR 0706): a date-relative trigger
117
+ // on it reads its rec_* column, as on any date field (a procedure's next review).
118
+ const env = objectFormulaEnvironment(own);
119
+ const typeOf = (name, f) => {
120
+ if (f.type !== "formula")
121
+ return f.type;
122
+ const compiled = checkFormula(f.expression ?? "", { fields: env }, name);
123
+ return compiled.ok &&
124
+ (compiled.formula.type === "date" || compiled.formula.type === "datetime")
125
+ ? compiled.formula.type
126
+ : f.type;
127
+ };
112
128
  return {
113
129
  ...RECORD_FIELDS,
114
- ...Object.fromEntries(Object.entries(own.fields).map(([name, f]) => [name, f.type])),
130
+ ...Object.fromEntries(Object.entries(own.fields).map(([name, f]) => [name, typeOf(name, f)])),
115
131
  };
116
132
  }
117
133
  const core = CORE_AUTOMATION_FIELDS[object] ?? BASE_AUTOMATION_FIELDS[object];
@@ -206,6 +222,55 @@ function filterFields(filter) {
206
222
  return [filter.field];
207
223
  }
208
224
  const isStageType = (match) => typeof match === "object" && match !== null && "stageType" in match;
225
+ /**
226
+ * A `dateRelative` trigger's minutes read per record (ADR 0570): `field` is a number field this
227
+ * extension declares on the trigger object or one relation away, `setting` one of its number
228
+ * settings, and each declares a `max` of at most a week, which bounds the records the host reads.
229
+ */
230
+ function checkMomentMinutes(ctx, object, minutes, path) {
231
+ const m = ctx.manifest;
232
+ const { contract } = ctx;
233
+ const capped = (max) => max !== undefined && max <= MAX_MOMENT_MINUTES;
234
+ if (minutes.field !== undefined) {
235
+ const own = object?.startsWith(`${m.id}.`) ? m.objects[object.slice(m.id.length + 1)] : null;
236
+ const field = own && minutes.field.split(".").length <= 2
237
+ ? resolveFieldPath(m, own, minutes.field)
238
+ : undefined;
239
+ if (!own) {
240
+ contract(`${path}.field`, "Minutes read from a field need a trigger object of this extension");
241
+ }
242
+ else if (field?.type !== "number") {
243
+ contract(`${path}.field`, `"${minutes.field}" must be a number field of ${object} or one relation away, declared by ${m.id}`);
244
+ }
245
+ else if (!capped(field.max)) {
246
+ contract(`${path}.field`, `"${minutes.field}" must declare a max of at most ${MAX_MOMENT_MINUTES}`);
247
+ }
248
+ }
249
+ if (minutes.setting !== undefined) {
250
+ const setting = Object.hasOwn(m.settings ?? {}, minutes.setting)
251
+ ? m.settings?.[minutes.setting]
252
+ : undefined;
253
+ if (setting?.type !== "number") {
254
+ contract(`${path}.setting`, `"${minutes.setting}" must be a number setting of ${m.id}`);
255
+ }
256
+ else if (!capped(setting.max)) {
257
+ contract(`${path}.setting`, `"${minutes.setting}" must declare a max of at most ${MAX_MOMENT_MINUTES}`);
258
+ }
259
+ }
260
+ }
261
+ /**
262
+ * True when `object` is of an extension in `onlyWith` that is not installed (no object of it is
263
+ * `known`): what an automation running only with it names of it is checked once it is (ADR 0812).
264
+ */
265
+ export function laterObject(onlyWith, known, object) {
266
+ const ext = object.split(".")[0];
267
+ if (!object.includes(".") || !onlyWith.includes(ext))
268
+ return false;
269
+ for (const name of known)
270
+ if (name.startsWith(`${ext}.`))
271
+ return false;
272
+ return true;
273
+ }
209
274
  /** Reports problems with `automations.<name>` through `ctx.contract`. */
210
275
  export function checkAutomation(ctx, name, automation) {
211
276
  const m = ctx.manifest;
@@ -216,6 +281,9 @@ export function checkAutomation(ctx, name, automation) {
216
281
  const canWrite = (object) => own(object) || perms.write.includes(object);
217
282
  const canRead = (object) => canWrite(object) || perms.read.includes(object);
218
283
  const trigger = automation.trigger;
284
+ // An object of an extension the automation runs only with (ADR 0812) is unknown while that
285
+ // extension is not installed: it is checked when it is, and the automation waits until then.
286
+ const known = (object) => ctx.known.has(object) || laterObject(automation.onlyWith ?? [], ctx.known, object);
219
287
  const object = triggerObject(trigger);
220
288
  const base = object !== null && Object.hasOwn(BASE_AUTOMATION_FIELDS, object);
221
289
  const fields = object && (ctx.known.has(object) || base) ? fieldsOf(ctx, object) : null;
@@ -225,11 +293,22 @@ export function checkAutomation(ctx, name, automation) {
225
293
  if (!NAME_RE.test(name)) {
226
294
  contract(path, `Automation name "${name}" must be camelCase letters and digits, e.g. wonDeal`);
227
295
  }
296
+ // 0. The extensions it runs only with: never itself, each once, none it already requires.
297
+ (automation.onlyWith ?? []).forEach((id, i) => {
298
+ const at = `${path}.onlyWith.${i}`;
299
+ if (id === m.id)
300
+ contract(at, "An automation of an extension always runs with it");
301
+ else if ((automation.onlyWith ?? []).indexOf(id) !== i)
302
+ contract(at, `"${id}" is listed twice`);
303
+ else if (m.requires?.includes(id)) {
304
+ contract(at, `The extension requires ${id}, so it is always installed: remove it here`);
305
+ }
306
+ });
228
307
  // 1. The trigger.
229
308
  if (base && !perms.operations.includes(`${object}.get`)) {
230
309
  contract(`${path}.trigger.object`, `An automation started by ${object} reads it: add "${object}.get" to permissions.operations`);
231
310
  }
232
- if (object !== null && !ctx.known.has(object) && !base) {
311
+ if (object !== null && !known(object) && !base) {
233
312
  contract(`${path}.trigger.object`, `Unknown object "${object}". Use a core object (person, organisation, task, activity) or ` +
234
313
  "<extension>.<object>");
235
314
  }
@@ -279,19 +358,25 @@ export function checkAutomation(ctx, name, automation) {
279
358
  for (const issue of cronIssues(trigger.cron))
280
359
  contract(`${path}.trigger.cron`, issue);
281
360
  break;
282
- case "dateRelative":
283
- requireField(`${path}.trigger.field`, trigger.field, ["date", "datetime"]);
361
+ case "dateRelative": {
362
+ const minutes = trigger.minutesBefore ?? trigger.minutesAfter;
363
+ // A moment some minutes from a field is an instant: the field is a datetime (ADR 0570).
364
+ requireField(`${path}.trigger.field`, trigger.field, minutes === undefined ? ["date", "datetime"] : ["datetime"]);
284
365
  if (trigger.zoneField !== undefined) {
285
366
  requireField(`${path}.trigger.zoneField`, trigger.zoneField, ["timezone"]);
286
367
  }
368
+ if (minutes !== undefined && typeof minutes === "object") {
369
+ checkMomentMinutes(ctx, object, minutes, `${path}.trigger.${trigger.minutesBefore !== undefined ? "minutesBefore" : "minutesAfter"}`);
370
+ }
287
371
  break;
372
+ }
288
373
  case "manual":
289
374
  break;
290
375
  case "approvalDecided":
291
376
  if (trigger.operation !== undefined && !OPERATION_RE.test(trigger.operation)) {
292
377
  contract(`${path}.trigger.operation`, `"${trigger.operation}" is not an operation name, e.g. record.update`);
293
378
  }
294
- if (trigger.object !== undefined && !ctx.known.has(trigger.object)) {
379
+ if (trigger.object !== undefined && !known(trigger.object)) {
295
380
  contract(`${path}.trigger.object`, `Unknown object "${trigger.object}"`);
296
381
  }
297
382
  break;
@@ -396,7 +481,7 @@ export function checkAutomation(ctx, name, automation) {
396
481
  break;
397
482
  default: {
398
483
  for (const read of step.reads ?? []) {
399
- if (!ctx.known.has(read)) {
484
+ if (!known(read)) {
400
485
  contract(`${at}.reads`, `Unknown object "${read}"`);
401
486
  }
402
487
  else if (!canRead(read)) {
@@ -405,7 +490,7 @@ export function checkAutomation(ctx, name, automation) {
405
490
  }
406
491
  (step.writes ?? []).forEach((write, j) => {
407
492
  const wat = `${at}.writes.${j}`;
408
- if (!ctx.known.has(write.object)) {
493
+ if (!known(write.object)) {
409
494
  contract(`${wat}.object`, `Unknown object "${write.object}"`);
410
495
  }
411
496
  else if (!canWrite(write.object)) {
@@ -60,11 +60,22 @@ export type AutomationTrigger = {
60
60
  * of `object`; 0 is the day itself. Evaluated once a day, in the automation timezone; or,
61
61
  * with `zoneField`, in each record's own time zone (ADR 0460): the day of the date and
62
62
  * "today" are both that zone's, and the run starts in the first hour of that local day.
63
+ *
64
+ * Or, instead of `offsetDays`, `minutesBefore` or `minutesAfter` a datetime field (ADR
65
+ * 0570): the run starts within about a minute of that moment, once per record and value of
66
+ * the field (a record whose time changes is due again at its new time). The minutes may be a
67
+ * number, or read per record (a number field of the record or one relation away, else the
68
+ * extension's number setting), as a window's are (ADR 0505). A moment missed by more than
69
+ * 15 minutes (a record made after it) is not run.
63
70
  */
64
71
  type: "dateRelative";
65
72
  object: string;
66
73
  field: string;
67
- offsetDays: number;
74
+ offsetDays?: number;
75
+ /** Minutes before the datetime field (ADR 0570); not with `offsetDays` or `minutesAfter`. */
76
+ minutesBefore?: MomentMinutes;
77
+ /** Minutes after the datetime field (ADR 0570); not with `offsetDays` or `minutesBefore`. */
78
+ minutesAfter?: MomentMinutes;
68
79
  /** A `timezone` field of `object`: count days in the zone each record names. */
69
80
  zoneField?: string;
70
81
  } | {
@@ -110,6 +121,18 @@ export type AutomationTrigger = {
110
121
  */
111
122
  from?: "person" | "organisation" | "either";
112
123
  };
124
+ /**
125
+ * A `dateRelative` trigger's minutes (ADR 0570): a number (0 to 10,080, a week), or a number read
126
+ * per record: `field`, a number field of the trigger object or one relation away that this
127
+ * extension declares (`classType.reminderMinutes`), and when it is empty `setting`, this
128
+ * extension's number setting. The field and the setting declare a `max` of at most 10,080.
129
+ */
130
+ export type MomentMinutes = number | {
131
+ field?: string;
132
+ setting?: string;
133
+ };
134
+ /** The most minutes a `dateRelative` trigger's moment may be from its field (a week). */
135
+ export declare const MAX_MOMENT_MINUTES = 10080;
113
136
  export type AutomationTriggerType = AutomationTrigger["type"];
114
137
  export declare const AUTOMATION_TRIGGER_TYPES: readonly ["record", "fieldChanged", "schedule", "dateRelative", "manual", "approvalDecided", "webhook", "syncEvent"];
115
138
  /**
@@ -206,7 +229,10 @@ export type OnRejected = "stop" | "continue" | {
206
229
  };
207
230
  /** Per-automation limits, within the host's maxima (Settings shows both). */
208
231
  export interface AutomationRails {
209
- /** Default 60. Above it the automation auto-pauses and admins are notified. */
232
+ /**
233
+ * Default 60. Runs above it wait their turn and start on the next minutes' ticks, never dropped
234
+ * (ADR 0573); only a backlog of thousands (a runaway) pauses the automation.
235
+ */
210
236
  maxRunsPerMinute?: number;
211
237
  /** Default 500 writes an hour across all its runs. */
212
238
  maxWritesPerHour?: number;
@@ -218,6 +244,11 @@ export interface AutomationEvent {
218
244
  /** `<extension>.<automation>` */
219
245
  automation: string;
220
246
  runId: string;
247
+ /**
248
+ * A retry's first run: the run its chain of retries began with (ADR 0574). Key a send by it
249
+ * (`originalRunId ?? runId`) so a retried run never sends again what an earlier one sent.
250
+ */
251
+ originalRunId?: string;
221
252
  trigger: AutomationTriggerType;
222
253
  /** The trigger record (record, fieldChanged, dateRelative, manual), as read when the run started. */
223
254
  record?: {
@@ -318,6 +349,16 @@ export interface AutomationSpec<T extends AutomationTrigger = AutomationTrigger>
318
349
  * first install reads it; after that, on or off is the person's choice.
319
350
  */
320
351
  enabled?: boolean;
352
+ /**
353
+ * Other extensions, by id, this automation runs only with (ADR 0812): the extension installs
354
+ * without them, and the automation is listed as waiting and starts no run until every one is
355
+ * installed and on. Its trigger, steps and permissions may name their objects; those are
356
+ * checked at this extension's next install or upgrade while they are installed (`cos ext check`
357
+ * installs them from the directories beside it first), and listed as broken if one does not
358
+ * exist. Use it for one automation that needs another pack; `requires` makes the whole
359
+ * extension need it.
360
+ */
361
+ onlyWith?: readonly string[];
321
362
  run(event: AutomationEvent, step: AutomationStepApi, ctx: AutomationContext): Promise<unknown>;
322
363
  }
323
364
  export declare function defineAutomation<const T extends AutomationTrigger>(automation: AutomationSpec<T>): AutomationSpec<T>;
@@ -370,7 +411,15 @@ export declare const automationTriggerSchema: z.ZodDiscriminatedUnion<[z.ZodObje
370
411
  type: z.ZodLiteral<"dateRelative">;
371
412
  object: z.ZodString;
372
413
  field: z.ZodString;
373
- offsetDays: z.ZodNumber;
414
+ offsetDays: z.ZodOptional<z.ZodNumber>;
415
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodObject<{
416
+ field: z.ZodOptional<z.ZodString>;
417
+ setting: z.ZodOptional<z.ZodString>;
418
+ }, z.core.$strict>]>>;
419
+ minutesAfter: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodObject<{
420
+ field: z.ZodOptional<z.ZodString>;
421
+ setting: z.ZodOptional<z.ZodString>;
422
+ }, z.core.$strict>]>>;
374
423
  zoneField: z.ZodOptional<z.ZodString>;
375
424
  }, z.core.$strict>, z.ZodObject<{
376
425
  type: z.ZodLiteral<"manual">;
@@ -543,7 +592,15 @@ export declare const automationManifestSchema: z.ZodObject<{
543
592
  type: z.ZodLiteral<"dateRelative">;
544
593
  object: z.ZodString;
545
594
  field: z.ZodString;
546
- offsetDays: z.ZodNumber;
595
+ offsetDays: z.ZodOptional<z.ZodNumber>;
596
+ minutesBefore: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodObject<{
597
+ field: z.ZodOptional<z.ZodString>;
598
+ setting: z.ZodOptional<z.ZodString>;
599
+ }, z.core.$strict>]>>;
600
+ minutesAfter: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodObject<{
601
+ field: z.ZodOptional<z.ZodString>;
602
+ setting: z.ZodOptional<z.ZodString>;
603
+ }, z.core.$strict>]>>;
547
604
  zoneField: z.ZodOptional<z.ZodString>;
548
605
  }, z.core.$strict>, z.ZodObject<{
549
606
  type: z.ZodLiteral<"manual">;
@@ -666,6 +723,7 @@ export declare const automationManifestSchema: z.ZodObject<{
666
723
  purpose: z.ZodString;
667
724
  }, z.core.$strict>>>;
668
725
  enabled: z.ZodOptional<z.ZodBoolean>;
726
+ onlyWith: z.ZodOptional<z.ZodArray<z.ZodString>>;
669
727
  }, z.core.$strip>;
670
728
  export type AutomationManifest = z.infer<typeof automationManifestSchema>;
671
729
  export interface AutomationJournalEntry {
@@ -10,7 +10,7 @@
10
10
  // declared step of the matching kind. Effects a step did not declare are still gated at run time
11
11
  // (and flagged in the run history), never silently allowed.
12
12
  import { z } from "zod";
13
- import { GATEKEEPER_MODULES, } from "./contract.js";
13
+ import { GATEKEEPER_MODULES, STAGE_TYPES, } from "./contract.js";
14
14
  const UNIT_MS = {
15
15
  second: 1_000,
16
16
  minute: 60_000,
@@ -18,6 +18,7 @@ const UNIT_MS = {
18
18
  day: 86_400_000,
19
19
  week: 604_800_000,
20
20
  };
21
+ const DURATION_RE = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/;
21
22
  /** Milliseconds in a duration. Throws on a malformed one. */
22
23
  export function durationMs(duration) {
23
24
  if (typeof duration === "number") {
@@ -25,7 +26,7 @@ export function durationMs(duration) {
25
26
  throw new Error("Durations are >= 0 ms");
26
27
  return duration;
27
28
  }
28
- const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/.exec(duration);
29
+ const match = DURATION_RE.exec(duration);
29
30
  if (!match)
30
31
  throw new Error(`"${duration}" is not a duration like "3 days" or "90 minutes"`);
31
32
  return Math.round(Number(match[1]) * UNIT_MS[match[2]]);
@@ -48,6 +49,8 @@ export const SYNC_EVENT_TYPES = [
48
49
  "meeting.updated",
49
50
  "meeting.cancelled",
50
51
  ];
52
+ /** The most minutes a `dateRelative` trigger's moment may be from its field (a week). */
53
+ export const MAX_MOMENT_MINUTES = 10_080;
51
54
  export const AUTOMATION_TRIGGER_TYPES = [
52
55
  "record",
53
56
  "fieldChanged",
@@ -67,10 +70,22 @@ const scalar = z.union([z.string().max(500), z.number(), z.boolean(), z.null()])
67
70
  export const valueMatchSchema = z.union([
68
71
  scalar,
69
72
  z.object({ in: z.array(scalar).min(1).max(50) }).strict(),
70
- z.object({ stageType: z.enum(["open", "won", "lost"]) }).strict(),
73
+ z.object({ stageType: z.enum(STAGE_TYPES) }).strict(),
71
74
  ]);
72
75
  const objectName = z.string().min(1).max(80);
73
76
  const fieldName = z.string().min(1).max(80);
77
+ const momentMinutesSchema = z.union([
78
+ z.number().int().min(0).max(MAX_MOMENT_MINUTES),
79
+ z
80
+ .object({
81
+ field: z.string().min(1).max(200).optional(),
82
+ setting: z.string().min(1).max(80).optional(),
83
+ })
84
+ .strict()
85
+ .refine((m) => m.field !== undefined || m.setting !== undefined, {
86
+ message: "name a field, a setting or both",
87
+ }),
88
+ ]);
74
89
  export const automationTriggerSchema = z.discriminatedUnion("type", [
75
90
  z
76
91
  .object({
@@ -96,10 +111,16 @@ export const automationTriggerSchema = z.discriminatedUnion("type", [
96
111
  type: z.literal("dateRelative"),
97
112
  object: objectName,
98
113
  field: fieldName,
99
- offsetDays: z.number().int().min(-365).max(365),
114
+ offsetDays: z.number().int().min(-365).max(365).optional(),
115
+ minutesBefore: momentMinutesSchema.optional(),
116
+ minutesAfter: momentMinutesSchema.optional(),
100
117
  zoneField: fieldName.optional(),
101
118
  })
102
- .strict(),
119
+ .strict()
120
+ .refine((t) => [t.offsetDays, t.minutesBefore, t.minutesAfter].filter((v) => v !== undefined).length === 1, { message: "give exactly one of offsetDays, minutesBefore and minutesAfter" })
121
+ .refine((t) => t.zoneField === undefined || t.offsetDays !== undefined, {
122
+ message: "zoneField counts days: use it with offsetDays only",
123
+ }),
103
124
  z
104
125
  .object({
105
126
  type: z.literal("manual"),
@@ -142,10 +163,7 @@ export const automationConnectionSchema = z
142
163
  purpose: z.string().min(1).max(200),
143
164
  })
144
165
  .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
- ]);
166
+ export const durationSchema = z.union([z.number().int().min(0), z.string().regex(DURATION_RE)]);
149
167
  export const recipientSchema = z.union([
150
168
  z.literal("admins"),
151
169
  z.literal("actor"),
@@ -254,6 +272,11 @@ export const automationManifestSchema = z.object({
254
272
  rails: automationRailsSchema.optional(),
255
273
  connections: z.array(automationConnectionSchema).max(10).optional(),
256
274
  enabled: z.boolean().optional(),
275
+ onlyWith: z
276
+ .array(z.string().regex(/^[a-z][a-z0-9]*$/))
277
+ .min(1)
278
+ .max(5)
279
+ .optional(),
257
280
  });
258
281
  /**
259
282
  * Turns `ctx.notify(to, message)` into a `notification.send` input for `event`'s run: field and
package/dist/behaviour.js CHANGED
@@ -30,6 +30,19 @@ export function checkObjectBehaviour(m, name, object, contract) {
30
30
  const stages = object.stages;
31
31
  if (stages) {
32
32
  const sp = `${path}.stages`;
33
+ // Fields the stage behaviour keeps itself: requiring one either always holds or, for a
34
+ // closed date on an open stage, never can (the behaviour clears it first). A status or closed
35
+ // date that is not read-only is reported as such below, once.
36
+ const kept = new Set([
37
+ ...[stages.status, stages.closedDate].filter((f) => f && fieldOf(f)?.readOnly),
38
+ stages.probability?.field,
39
+ stages.probability?.overridden,
40
+ ].filter((f) => f !== undefined));
41
+ const requirable = (local) => {
42
+ const field = fieldOf(local);
43
+ return field !== undefined && field.type !== "formula" && local !== stages.field;
44
+ };
45
+ const keptMessage = (local) => `"${local}" is kept by the stage behaviour itself and cannot be required`;
33
46
  const stageTarget = relationTo(fieldOf(stages.field));
34
47
  const stageObject = ownObject(stageTarget);
35
48
  if (!stageObject) {
@@ -55,10 +68,14 @@ export function checkObjectBehaviour(m, name, object, contract) {
55
68
  contract(`${sp}.stage.requiredFields`, `"${stages.stage.requiredFields}" must be a multiSelect field of ${stageTarget}`);
56
69
  }
57
70
  else {
71
+ // A read-only field may be required (ADR 0750): a fact the host sets, such as the
72
+ // time a quote was accepted, which then gates the stage for every actor.
58
73
  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}`);
74
+ if (!requirable(option.value)) {
75
+ contract(`${sp}.stage.requiredFields`, `Option "${option.value}" must name a field of ${name} other than a formula or the stage field`);
76
+ }
77
+ else if (kept.has(option.value)) {
78
+ contract(`${sp}.stage.requiredFields`, `Option ${keptMessage(option.value)}`);
62
79
  }
63
80
  }
64
81
  }
@@ -119,9 +136,11 @@ export function checkObjectBehaviour(m, name, object, contract) {
119
136
  }
120
137
  for (const [type, list] of Object.entries(stages.requiredByType ?? {})) {
121
138
  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}`);
139
+ if (!requirable(local)) {
140
+ contract(`${sp}.requiredByType.${type}`, `"${local}" must be a field of ${name} other than a formula or the stage field`);
141
+ }
142
+ else if (kept.has(local)) {
143
+ contract(`${sp}.requiredByType.${type}`, keptMessage(local));
125
144
  }
126
145
  }
127
146
  }
@@ -0,0 +1,97 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * Records of this object are events in their customer's private calendar feed (ADR 0891): a class
5
+ * booking, a ticket, an appointment. The host reads them as the customer, through the visibility
6
+ * seam, so the feed never shows a field the customer could not read.
7
+ *
8
+ * - `starts`, `ends`: a datetime path: a field of this object, or a relation of it and a field of
9
+ * what it names (`class.startsAt`), at most two relations deep.
10
+ * - `title`: a text path, the event's name (`classType.name`): the public name of what was booked.
11
+ * - `place` (optional): a text path, the event's place (`class.room.name`).
12
+ * - `live`: the states of the object's `states` in which the record shows. A record in any other
13
+ * state (cancelled, moved), or in the Trash, drops out on the next fetch.
14
+ *
15
+ * The object declares a `customer` (whose feed it is in, and, where it opens to guardians, a live
16
+ * guardian's too), and its customer's read list holds the states field and each path's first
17
+ * field. A field of `title` or `place` one relation or more away must be one that object makes
18
+ * `public` or `signedIn` (a class's own title may name another member: never in a bearer link). A
19
+ * field of `starts` or `ends` may also be, one relation away, what its `customerVia` from this
20
+ * object lists (a booking's class's times). A shipped pack's declaration only: a runtime extension
21
+ * declaring it fails the check.
22
+ */
23
+ export interface CalendarEntrySpec {
24
+ starts: string;
25
+ ends: string;
26
+ title: string;
27
+ place?: string;
28
+ live: readonly string[];
29
+ }
30
+ export declare const calendarEntryManifestSchema: z.ZodObject<{
31
+ starts: z.ZodString;
32
+ ends: z.ZodString;
33
+ title: z.ZodString;
34
+ place: z.ZodOptional<z.ZodString>;
35
+ live: z.ZodArray<z.ZodString>;
36
+ }, z.core.$strict>;
37
+ export type CalendarEntryManifest = z.infer<typeof calendarEntryManifestSchema>;
38
+ /** At most two relations, then the field: `class.room.name`. */
39
+ export declare const CALENDAR_PATH_MAX_SEGMENTS = 3;
40
+ /** What a path's last field may be, by key. */
41
+ export declare const CALENDAR_PATH_TYPES: {
42
+ readonly starts: readonly ["datetime"];
43
+ readonly ends: readonly ["datetime"];
44
+ readonly title: readonly ["text", "select"];
45
+ readonly place: readonly ["text", "select"];
46
+ };
47
+ /** The keys whose fields past the first must be public (shown text, never only a time). */
48
+ export declare const CALENDAR_PUBLIC_ONLY_KEYS: ReadonlySet<string>;
49
+ /** One field, as the walker needs it. */
50
+ export interface CalendarPathField {
51
+ type: string;
52
+ many: boolean;
53
+ /** A relation's target, as a registry name (`bookings.class`, `person`). */
54
+ to?: string | undefined;
55
+ }
56
+ /** One object a path passes through, as the walker needs it. */
57
+ export interface CalendarPathObject {
58
+ name: string;
59
+ /** Whether it declares a customer of its own (a path never passes through one). */
60
+ hasCustomer: boolean;
61
+ field(name: string): CalendarPathField | undefined;
62
+ /**
63
+ * The fields a customer reads of this object's records, reached from their own record of `from`
64
+ * through its relation `via` (`customerVia`, one relation away only), or as anyone signed in or
65
+ * the public may.
66
+ */
67
+ readable(from: string | null, via: string | null): ReadonlySet<string>;
68
+ }
69
+ export type CalendarPathResult = {
70
+ ok: true;
71
+ type: string;
72
+ foreign: boolean;
73
+ } | {
74
+ ok: false;
75
+ message: string;
76
+ foreign: boolean;
77
+ }
78
+ /** The path reaches an object this checker leaves to another (the SDK: another extension's). */
79
+ | {
80
+ ok: "deferred";
81
+ };
82
+ /**
83
+ * Walks `path` from `origin`, the object declaring the entry, whose customer reads
84
+ * `originRead`. `lookup` answers an object by registry name: undefined to defer it (not this
85
+ * checker's), null when there is no such object. Pure.
86
+ */
87
+ export declare function walkCalendarPath(origin: CalendarPathObject, originRead: ReadonlySet<string>, path: string, lookup: (name: string) => CalendarPathObject | null | undefined,
88
+ /**
89
+ * Past the first field, only what the related object makes `public` or `signedIn` (a title or
90
+ * a place, ADR 0891): never a field the customer reads only through their own record, such as a
91
+ * class's own title, which may name another member. The feed is a bearer link.
92
+ */
93
+ publicOnly?: boolean): CalendarPathResult;
94
+ /** A manifest object as the walker sees it. */
95
+ export declare function manifestPathObject(extensionId: string, local: string, object: ObjectManifest): CalendarPathObject;
96
+ /** Reports problems with `objects.<name>.calendarEntry` through `contract`. */
97
+ export declare function checkObjectCalendarEntry(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;