@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,955 @@
1
+ // Routine mail (ADR 0590): the fixed emails a shipped pack declares (a booking's confirmation,
2
+ // a class reminder), which the host sends without a person's approval. The declaration is the
3
+ // wording: a subject and a body with named slots, the record it is about, and what each slot
4
+ // holds. The host fills the slots itself from that record (and the records it points to), decides
5
+ // who it goes to, checks every value it puts in, and sends it; a pack names a kind, a record and
6
+ // a message, and may pass only a choice among declared words, a time, a count or a flag. Nothing
7
+ // a pack, an AI or a member types becomes free text, a link or an address in a routine email.
8
+ //
9
+ // Routine messages (ADR 0670, stage 30): a kind may also declare a text message's words and a push
10
+ // notification's (a title and one line), with the same slots and the same checks, and say whether
11
+ // a person may turn its email off (`essential`), what it is for (`purpose`), whether it may go
12
+ // during quiet hours (`urgent`), the moment after which a text or push is pointless (`until`) and
13
+ // the app screen a push opens (`open`). A kind that declares neither sends email only, as before.
14
+ //
15
+ // This module is the contract's part: the declaration's shape and checks, and the pure template
16
+ // rendering and value checks the host and the testing harness share.
17
+ import { z } from "zod";
18
+ /** The host module that sends routine mail, in an automation of a shipped pack only. */
19
+ export const ROUTINE_MAIL_MODULE = "routine-mail";
20
+ /** A kind may be about the host's own orders: the buyer's own address. */
21
+ export const ROUTINE_ABOUT_ORDER = "order";
22
+ /** What a routine email may read of an order (the host's own columns), by type. */
23
+ export const ROUTINE_ORDER_FIELDS = {
24
+ total: "number",
25
+ paid: "number",
26
+ balance: "number",
27
+ currency: "text",
28
+ balanceDueAt: "datetime",
29
+ state: "text",
30
+ };
31
+ /** The host fills this one: the name of the member a guardian's email is about. */
32
+ export const ROUTINE_MEMBER_SLOT = "member";
33
+ /** Most routine emails one recipient gets in a rolling day before the rest wait for a person. */
34
+ export const ROUTINE_DAILY_CAP = 20;
35
+ /** The channels a routine message goes on (ADR 0670). Email is every kind's. */
36
+ export const ROUTINE_CHANNELS = ["email", "text", "push"];
37
+ /**
38
+ * What a kind is for, as far as consent goes (stage 30): `account` (about something the person
39
+ * has or did) or `follow_up` (Reviews' ask, a welcome). Never `news_and_offers`: a routine kind is
40
+ * not promotional.
41
+ */
42
+ export const ROUTINE_PURPOSES = ["account", "follow_up"];
43
+ /**
44
+ * A personal link (ADR 0723): the route on the business's site a form-link slot opens, and the
45
+ * query parameter its token travels in. The client web app's form page serves it.
46
+ */
47
+ export const PERSONAL_LINK_PATH = "/form";
48
+ export const PERSONAL_LINK_PARAM = "t";
49
+ /** How long a personal link stays good unless the slot says (decision 4: a week). */
50
+ export const PERSONAL_LINK_DAYS = 7;
51
+ /** The longest a personal link may stay good. */
52
+ export const PERSONAL_LINK_MAX_DAYS = 30;
53
+ /** Most receipts (ADR 0724) one mailbox is sent in a rolling day: the fourth is not sent. */
54
+ export const RECEIPT_DAILY_CAP = 3;
55
+ /** The longest business name a text begins with: a longer one is cut to this (ADR 0670). */
56
+ export const TEXT_SENDER_MAX = 30;
57
+ /** What every text ends with, added by the host. */
58
+ export const TEXT_STOP_LINE = "Reply STOP to stop";
59
+ /** A text is at most two segments, the name and the stop line counted in. */
60
+ export const TEXT_MAX_SEGMENTS = 2;
61
+ /** A push's title and body, at most (it shows on a locked screen). */
62
+ export const PUSH_TITLE_MAX = 60;
63
+ export const PUSH_BODY_MAX = 140;
64
+ // ---------------------------------------------------------------------------------------------
65
+ // The manifest's shape
66
+ const NAME = /^[a-z][a-zA-Z0-9]{0,39}$/;
67
+ const name = z.string().regex(NAME, "camelCase letters and digits, starting lowercase");
68
+ const path = z
69
+ .string()
70
+ .regex(/^[a-z][a-zA-Z0-9]{0,39}(\.[a-z][a-zA-Z0-9]{0,39}){0,3}$/, "a field or a.relation.path");
71
+ const words = z.string().min(1).max(300);
72
+ const fieldSlotSchema = z
73
+ .object({
74
+ field: path,
75
+ format: z.enum(["text", "datetime", "time", "date", "money", "count"]).optional(),
76
+ zone: path.optional(),
77
+ currency: path.optional(),
78
+ year: z.boolean().optional(),
79
+ max: z.number().int().min(1).max(300).optional(),
80
+ optional: z.boolean().optional(),
81
+ private: z.boolean().optional(),
82
+ })
83
+ .strict();
84
+ const slotSchema = z.union([
85
+ fieldSlotSchema,
86
+ z
87
+ .object({
88
+ choice: z.record(name, words),
89
+ guardian: z.record(name, words).optional(),
90
+ })
91
+ .strict(),
92
+ z
93
+ .object({
94
+ at: z.literal(true),
95
+ zone: path.optional(),
96
+ year: z.boolean().optional(),
97
+ optional: z.boolean().optional(),
98
+ })
99
+ .strict(),
100
+ z.object({ count: z.object({ max: z.number().int().min(1).max(1000) }).strict() }).strict(),
101
+ z.object({ flag: z.literal(true) }).strict(),
102
+ z.object({ business: z.literal(true) }).strict(),
103
+ z
104
+ .object({
105
+ formLink: z
106
+ .object({
107
+ object: z.string().regex(/^[a-z][a-z0-9]{0,29}\.[a-z][a-zA-Z0-9]{0,49}$/),
108
+ setting: name,
109
+ days: z.number().int().min(1).max(PERSONAL_LINK_MAX_DAYS).optional(),
110
+ once: z.number().int().min(1).max(365).optional(),
111
+ })
112
+ .strict(),
113
+ })
114
+ .strict(),
115
+ z
116
+ .object({
117
+ link: name,
118
+ withId: z
119
+ .string()
120
+ .regex(/^[a-z][a-zA-Z0-9]{0,20}$/)
121
+ .optional(),
122
+ })
123
+ .strict(),
124
+ z
125
+ .object({
126
+ each: z
127
+ .object({
128
+ object: z.string().regex(/^[a-z][a-z0-9]{0,29}$/),
129
+ via: name,
130
+ where: z
131
+ .object({ field: name, in: z.array(z.string().max(100)).min(1).max(20) })
132
+ .strict()
133
+ .optional(),
134
+ distinct: path.optional(),
135
+ max: z.number().int().min(1).max(100),
136
+ line: z.string().min(1).max(500),
137
+ slots: z.record(name, fieldSlotSchema),
138
+ })
139
+ .strict(),
140
+ })
141
+ .strict(),
142
+ ]);
143
+ const calendarSchema = z
144
+ .object({
145
+ uid: name.optional(),
146
+ start: path,
147
+ end: path.optional(),
148
+ title: path,
149
+ location: path.optional(),
150
+ link: name.optional(),
151
+ cancelled: z.boolean().optional(),
152
+ update: z.boolean().optional(),
153
+ if: name.optional(),
154
+ })
155
+ .strict();
156
+ const pushSchema = z
157
+ .object({ title: z.string().min(1).max(200), body: z.string().min(1).max(400) })
158
+ .strict();
159
+ const textMessageSchema = z.string().min(1).max(600);
160
+ const messageSchema = z
161
+ .object({
162
+ subject: z.string().min(1).max(200),
163
+ text: z.string().min(1).max(4000),
164
+ textMessage: textMessageSchema.optional(),
165
+ push: pushSchema.optional(),
166
+ guardian: z
167
+ .object({
168
+ subject: z.string().min(1).max(200),
169
+ text: z.string().min(1).max(4000),
170
+ textMessage: textMessageSchema.optional(),
171
+ push: pushSchema.optional(),
172
+ })
173
+ .strict()
174
+ .optional(),
175
+ calendar: z.union([calendarSchema, z.array(calendarSchema).min(1).max(2)]).optional(),
176
+ })
177
+ .strict();
178
+ const routineMailKindSchema = z
179
+ .object({
180
+ label: z.string().min(1).max(80),
181
+ description: z.string().min(1).max(500),
182
+ about: z.string().regex(/^[a-z][a-z0-9]{0,29}$/),
183
+ on: z.boolean().optional(),
184
+ essential: z.boolean().optional(),
185
+ purpose: z.enum(ROUTINE_PURPOSES).optional(),
186
+ urgent: z.boolean().optional(),
187
+ until: path.optional(),
188
+ channels: z.array(z.enum(ROUTINE_CHANNELS)).min(1).max(3).optional(),
189
+ open: z.object({ screen: name }).strict().optional(),
190
+ receipt: z.boolean().optional(),
191
+ slots: z.record(name, slotSchema).default({}),
192
+ messages: z.record(name, messageSchema),
193
+ })
194
+ .strict();
195
+ export const routineMailManifestSchema = z.record(name, routineMailKindSchema);
196
+ /** The channels a kind may go on: email, and what it declares. */
197
+ export function channelsOf(kind) {
198
+ const declared = new Set(kind.channels ?? ["email"]);
199
+ return ROUTINE_CHANNELS.filter((c) => declared.has(c));
200
+ }
201
+ /** Whether a person may not turn the kind's email off (decision 9; follow-ups never are). */
202
+ export function essentialOf(kind) {
203
+ return kind.essential ?? (kind.purpose ?? "account") === "account";
204
+ }
205
+ /** A kind's messages' calendar events, as a list. */
206
+ export function calendarsOf(message) {
207
+ const c = message.calendar;
208
+ return c ? (Array.isArray(c) ? [...c] : [c]) : [];
209
+ }
210
+ /** Parses a template; `error` says what is wrong with it (the manifest check reports it). */
211
+ export function parseTemplate(template) {
212
+ const slots = new Set();
213
+ const bare = new Set();
214
+ const lines = [];
215
+ let error = null;
216
+ for (const line of template.split("\n")) {
217
+ const parts = [];
218
+ let optional = null;
219
+ let i = 0;
220
+ while (i < line.length) {
221
+ const ch = line[i];
222
+ if (ch === "[") {
223
+ if (optional)
224
+ error ??= "An optional part [...] cannot hold another";
225
+ optional = [];
226
+ i += 1;
227
+ }
228
+ else if (ch === "]") {
229
+ if (!optional)
230
+ error ??= "A ] with no [ before it";
231
+ else
232
+ parts.push({ optional });
233
+ optional = null;
234
+ i += 1;
235
+ }
236
+ else if (ch === "{") {
237
+ const end = line.indexOf("}", i);
238
+ const slot = end > i ? line.slice(i + 1, end) : "";
239
+ if (!NAME.test(slot)) {
240
+ error ??= `"{${slot}}" is not a slot name`;
241
+ i = end > i ? end + 1 : line.length;
242
+ continue;
243
+ }
244
+ slots.add(slot);
245
+ if (!optional)
246
+ bare.add(slot);
247
+ (optional ?? parts).push({ slot });
248
+ i = end + 1;
249
+ }
250
+ else if (ch === "}") {
251
+ error ??= "A } with no { before it";
252
+ i += 1;
253
+ }
254
+ else {
255
+ let j = i;
256
+ while (j < line.length && !"[]{}".includes(line[j]))
257
+ j += 1;
258
+ (optional ?? parts).push({ text: line.slice(i, j) });
259
+ i = j;
260
+ }
261
+ }
262
+ if (optional)
263
+ error ??= "An optional part [ is not closed on its line";
264
+ lines.push(parts);
265
+ }
266
+ const optionalOnly = new Set([...slots].filter((s) => !bare.has(s)));
267
+ return { lines, slots, optionalOnly, error };
268
+ }
269
+ /** The literal words of a template (what the pack wrote, not the slots). */
270
+ export function literalText(parsed) {
271
+ const out = [];
272
+ for (const line of parsed.lines) {
273
+ for (const part of line) {
274
+ const pieces = "optional" in part ? part.optional : [part];
275
+ for (const piece of pieces)
276
+ if ("text" in piece)
277
+ out.push(piece.text);
278
+ }
279
+ }
280
+ return out.join(" ");
281
+ }
282
+ /**
283
+ * Renders a template. A slot with no value (null or undefined) empties its optional part; outside
284
+ * one it is written as nothing (the host holds such a send for a person). A line that had words
285
+ * and is left with none is dropped.
286
+ */
287
+ export function renderTemplate(template, values) {
288
+ const parsed = typeof template === "string" ? parseTemplate(template) : template;
289
+ const piece = (p) => ("text" in p ? p.text : (values[p.slot] ?? ""));
290
+ const out = [];
291
+ for (const line of parsed.lines) {
292
+ if (!line.length) {
293
+ out.push("");
294
+ continue;
295
+ }
296
+ let text = "";
297
+ for (const part of line) {
298
+ if ("optional" in part) {
299
+ const missing = part.optional.some((p) => "slot" in p && (values[p.slot] === null || values[p.slot] === undefined));
300
+ if (!missing)
301
+ text += part.optional.map(piece).join("");
302
+ }
303
+ else {
304
+ text += piece(part);
305
+ }
306
+ }
307
+ if (text.trim())
308
+ out.push(text.replace(/ {2,}/g, " ").trimEnd());
309
+ }
310
+ return out.join("\n");
311
+ }
312
+ // ---------------------------------------------------------------------------------------------
313
+ // What a value may hold to be routine
314
+ // Control and format characters (bidirectional overrides, zero-width joiners) let a value hide
315
+ // or reorder what it shows.
316
+ const HIDDEN =
317
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching them is the point.
318
+ // biome-ignore lint/suspicious/noMisleadingCharacterClass: single code points, on purpose.
319
+ /[\u0000-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff9-\ufffb]/u;
320
+ /** Dots, and the characters that look like one. */
321
+ const DOT = "[.\\u2024\\u2027\\u00b7\\u2219\\u22c5\\u0701\\u3002\\uff0e\\uff61\\u0589\\u06d4\\ua4f8\\u2e33\\u2022\\u2e31]";
322
+ /** Top-level domains a reader would take for one (a dot before one makes `example.com`). */
323
+ const TLD = "(?:com|net|org|io|co|au|uk|nz|info|biz|xyz|app|dev|me|ly|gg|tv|online|site|shop|club|top|link|click|to|us|ca|de|fr|in|ru|cn|ai|be|fm|gl|cc|ws|vip|live|pro|store|tk|ml|ga|cf)";
324
+ /** A domain's letters, and the letters a reader takes for them (`c0m`). */
325
+ const TLD_LOOSE = `(?:${TLD}|c[o0]m|n[e3]t|[o0]rg)`;
326
+ // A link, an address, markup, or something a mail program (or a reader) turns into one:
327
+ // `example.com`, `example . com`, `gymhelp,com`, `gymhelp com`, `example(dot)com`, `dot xyz`,
328
+ // `bit ly slash`, `https colon slash slash`, `hxxp`, an IP address, a scheme.
329
+ const LINKISH = new RegExp([
330
+ ":\\/\\/",
331
+ `www\\s*${DOT}`,
332
+ "@",
333
+ "[<>[\\]{}\\\\]",
334
+ "xn--",
335
+ `[\\p{L}\\p{N}-]${DOT}${TLD_LOOSE}\\b`,
336
+ `[\\p{L}\\p{N}]\\s*(?:${DOT}|,)\\s*${TLD_LOOSE}\\b`,
337
+ `\\b[\\p{L}\\p{N}-]{3,}\\s+(?:com|net|org|xyz|c0m)\\b`,
338
+ "[([]\\s*(?:dot|\\.)\\s*[)\\]]",
339
+ `\\bdot\\s*${TLD_LOOSE}\\b`,
340
+ "\\bbit\\s*ly\\b",
341
+ "\\b(?:colon\\s*slash|slash\\s*slash)\\b",
342
+ "\\bhxxps?\\b",
343
+ "\\b\\d{1,3}(?:\\s*\\.\\s*\\d{1,3}){3}\\b",
344
+ "\\b(?:mailto|tel|sms|javascript|data|file|ftp|https?)\\s*:",
345
+ ].join("|"), "iu");
346
+ // A phone number (eight or more digits, spaced or not), or an instruction to call or text one;
347
+ // five or more numbers in words; a messaging app's name (a handle follows it).
348
+ const PHONE = new RegExp([
349
+ "(?:\\+|\\b)\\d(?:[\\s().-]*\\d){7,}",
350
+ "\\b(?:call|ring|text|sms|phone|whatsapp|tel)\\b\\D{0,20}\\d[\\d\\s().-]{2,}\\d",
351
+ "\\b(?:(?:zero|oh|one|two|three|four|five|six|seven|eight|nine|double|triple)\\b[\\s,.-]*){5,}",
352
+ "\\b(?:whats\\s*app|signal|telegram|wechat|viber|snapchat|kik|line\\s+id)\\b",
353
+ ].join("|"), "iu");
354
+ /**
355
+ * Why `value` cannot go into a routine email, or null when it can: one line of at most `max`
356
+ * characters, no hidden, blank-looking or direction-changing characters, nothing that is or
357
+ * becomes a link or an address (look-alike dots and spelled-out ones included), no markup, no
358
+ * phone number and nothing asking the reader to call or text one. A member's name, a class's
359
+ * title and a cancellation's reason are checked with it. A legitimate title with a phone number
360
+ * in it is held for a person: that is the intended outcome.
361
+ */
362
+ export function unroutineText(value, max) {
363
+ if (value.length > max)
364
+ return `longer than ${max} characters`;
365
+ if (HIDDEN.test(value))
366
+ return "a line break or hidden character";
367
+ if (LINKISH.test(value))
368
+ return "a link, an address or markup";
369
+ if (PHONE.test(value))
370
+ return "a phone number or a messaging handle";
371
+ return null;
372
+ }
373
+ /** Why the words a pack declares cannot be routine, or null (a link only through a link slot). */
374
+ export function unroutineWords(words) {
375
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching them is the point.
376
+ if (/[\u0000-\u0009\u000b-\u001f\u007f-\u009f​-‏‪-‮⁠-]/.test(words)) {
377
+ return "a hidden character";
378
+ }
379
+ if (/:\/\/|www\.|@|<|>|\\|xn--|[\p{L}\p{N}-]\.\p{L}{2,}/iu.test(words)) {
380
+ return "a link, an address or markup (links go in a link slot)";
381
+ }
382
+ return null;
383
+ }
384
+ // ---------------------------------------------------------------------------------------------
385
+ // How a value is written
386
+ /** A moment as a member reads it, in a zone (ADR 0460): "Monday 7 December at 06:00 (Europe/London time)". */
387
+ export function formatMoment(iso, zone, as, year = false) {
388
+ const at = new Date(iso);
389
+ if (Number.isNaN(at.getTime()))
390
+ return null;
391
+ const timeZone = zone || "UTC";
392
+ try {
393
+ const clock = {
394
+ hour: "2-digit",
395
+ minute: "2-digit",
396
+ hourCycle: "h23",
397
+ };
398
+ const day = {
399
+ weekday: "long",
400
+ day: "numeric",
401
+ month: "long",
402
+ ...(year ? { year: "numeric" } : {}),
403
+ };
404
+ const options = as === "time" ? clock : as === "date" ? day : { ...day, ...clock };
405
+ const local = new Intl.DateTimeFormat("en-GB", { timeZone, ...options }).format(at);
406
+ return as === "datetime" ? `${local} (${timeZone.replace(/_/g, " ")} time)` : local;
407
+ }
408
+ catch {
409
+ return null;
410
+ }
411
+ }
412
+ /** An amount in minor units: "12.50 AUD". */
413
+ export function formatMoney(minor, currency) {
414
+ if (!Number.isFinite(minor) || !/^[A-Za-z]{3}$/.test(currency))
415
+ return null;
416
+ return `${(minor / 100).toFixed(2)} ${currency.toUpperCase()}`;
417
+ }
418
+ // ---------------------------------------------------------------------------------------------
419
+ // Text messages: segments, and the words the host wraps around a kind's (ADR 0670)
420
+ // The GSM 03.38 alphabet a text is sent in when it can be; the extension table's characters take
421
+ // two units. Anything else sends the whole text in the longer encoding (UCS-2).
422
+ const GSM_BASIC = new Set("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà");
423
+ const GSM_EXTENDED = new Set("^{}\\[~]|€\f");
424
+ /** How a text is sent: its encoding, its length in that encoding's units, and its segments. */
425
+ export function textSegments(value) {
426
+ let units = 0;
427
+ let gsm = true;
428
+ for (const ch of value) {
429
+ if (GSM_BASIC.has(ch))
430
+ units += 1;
431
+ else if (GSM_EXTENDED.has(ch))
432
+ units += 2;
433
+ else {
434
+ gsm = false;
435
+ break;
436
+ }
437
+ }
438
+ if (gsm)
439
+ return { encoding: "gsm", units, segments: units <= 160 ? 1 : Math.ceil(units / 153) };
440
+ const length = value.length;
441
+ return { encoding: "ucs2", units: length, segments: length <= 70 ? 1 : Math.ceil(length / 67) };
442
+ }
443
+ /**
444
+ * A text in the plainest characters that say the same (a dash for an en dash, straight quotes,
445
+ * a space for a no-break space), so one typographic character does not double its cost.
446
+ */
447
+ export function textForm(value) {
448
+ return value
449
+ .replace(/[\u2013\u2014\u2212]/g, "-")
450
+ .replace(/[\u2018\u2019\u201b\u2032]/g, "'")
451
+ .replace(/[\u201c\u201d\u2033]/g, '"')
452
+ .replace(/\u2026/g, "...")
453
+ .replace(/[\u00a0\u2007\u202f]/g, " ");
454
+ }
455
+ /** A text as it is sent: the business's name first, the words, and the stop line last. */
456
+ export function wrapText(sender, words) {
457
+ const name = sender.trim().slice(0, TEXT_SENDER_MAX).trim();
458
+ return textForm(`${name}: ${words.trim()} ${TEXT_STOP_LINE}`);
459
+ }
460
+ /** The longest a moment written by `formatMoment` can be (the longest zone name counted). */
461
+ const LONGEST_ZONE = 32;
462
+ const MOMENT_MAX = {
463
+ // "Wednesday 30 September 2026 at 23:59 (America/Argentina/ComodRivadavia time)"
464
+ datetime: 9 + 1 + 2 + 1 + 9 + 4 + 5 + 2 + LONGEST_ZONE + 6,
465
+ time: 5,
466
+ date: 9 + 1 + 2 + 1 + 9,
467
+ };
468
+ const YEAR = 5;
469
+ /** The longest value a slot can be filled with (for the length checks), or null: not allowed. */
470
+ function slotMaxLength(slot, guardian) {
471
+ if ("field" in slot) {
472
+ const format = slot.format ?? "text";
473
+ if (format === "text")
474
+ return slot.max ?? 120;
475
+ if (format === "money")
476
+ return 16;
477
+ if (format === "count")
478
+ return 12;
479
+ return MOMENT_MAX[format] + (slot.year && format !== "time" ? YEAR : 0);
480
+ }
481
+ if ("choice" in slot) {
482
+ const words = Object.entries(slot.choice).map(([k, v]) => (guardian ? slot.guardian?.[k] : undefined) ?? v);
483
+ return Math.max(0, ...words.map((w) => w.length));
484
+ }
485
+ if ("at" in slot)
486
+ return MOMENT_MAX.datetime + (slot.year ? YEAR : 0);
487
+ if ("count" in slot)
488
+ return String(slot.count.max).length;
489
+ if ("flag" in slot)
490
+ return 0;
491
+ if ("business" in slot)
492
+ return TEXT_SENDER_MAX;
493
+ return null;
494
+ }
495
+ /** The kind's form-link slots, by name (at most one is allowed). */
496
+ export function formLinkSlotsOf(kind) {
497
+ const out = [];
498
+ for (const [slotName, slot] of Object.entries(kind.slots)) {
499
+ if ("formLink" in slot)
500
+ out.push([slotName, slot.formLink]);
501
+ }
502
+ return out;
503
+ }
504
+ /** The longest a member's name is written (`unroutineText`'s bound for it). */
505
+ const MEMBER_MAX = 80;
506
+ /** The longest link a text may carry: a longer one fails its row at the host (ADR 0670). */
507
+ export const TEXT_LINK_MAX = 120;
508
+ // ---------------------------------------------------------------------------------------------
509
+ // The manifest check
510
+ /** Field types a text slot may read: never an address, a link, a phone number or a user. */
511
+ const TEXT_FIELD_TYPES = new Set(["text", "longText", "select", "number", "timezone"]);
512
+ const TIME_FIELD_TYPES = new Set(["datetime", "date"]);
513
+ /**
514
+ * The type of the field at `path` from `object` (a local object name, or `order`), walking only
515
+ * relations to this extension's own objects; or why it cannot be read.
516
+ */
517
+ export function routinePathType(manifest, object, fieldPath) {
518
+ const segments = fieldPath.split(".");
519
+ if (object === ROUTINE_ABOUT_ORDER) {
520
+ const type = ROUTINE_ORDER_FIELDS[segments[0]];
521
+ if (segments.length !== 1 || !type) {
522
+ return {
523
+ problem: `an order's routine email reads ${Object.keys(ROUTINE_ORDER_FIELDS).join(", ")} only`,
524
+ };
525
+ }
526
+ return { type };
527
+ }
528
+ let current = manifest.objects[object];
529
+ for (const [i, segment] of segments.entries()) {
530
+ const field = current?.fields[segment];
531
+ if (!field)
532
+ return { problem: `${segments.slice(0, i + 1).join(".")} is not a field` };
533
+ if (i === segments.length - 1)
534
+ return { type: field.type, ...(field.to ? { to: field.to } : {}) };
535
+ const own = field.type === "relation" && field.to?.startsWith(`${manifest.id}.`);
536
+ if (!own) {
537
+ return {
538
+ problem: `${segments.slice(0, i + 1).join(".")} is not a relation to one of this extension's objects`,
539
+ };
540
+ }
541
+ current = manifest.objects[field.to.slice(manifest.id.length + 1)];
542
+ }
543
+ return { problem: "an empty path" };
544
+ }
545
+ /** Contract issues in an extension's routine mail. */
546
+ export function routineMailIssues(manifest) {
547
+ const issues = [];
548
+ const kinds = manifest.routineMail ?? {};
549
+ const contract = (path, message) => issues.push({ path, message });
550
+ const names = Object.keys(kinds);
551
+ if (names.length && !manifest.permissions.modules.includes(ROUTINE_MAIL_MODULE)) {
552
+ contract("permissions.modules", `Routine mail is sent through the "${ROUTINE_MAIL_MODULE}" module`);
553
+ }
554
+ if (names.length > 12)
555
+ contract("routineMail", "At most 12 kinds of routine mail");
556
+ for (const [kindName, kind] of Object.entries(kinds)) {
557
+ const base = `routineMail.${kindName}`;
558
+ const about = kind.about;
559
+ if (about !== ROUTINE_ABOUT_ORDER && !manifest.objects[about]) {
560
+ contract(`${base}.about`, `"${about}" is not an object of this extension, nor order`);
561
+ continue;
562
+ }
563
+ const checkField = (at, from, slot) => {
564
+ const found = routinePathType(manifest, from, slot.field);
565
+ if ("problem" in found)
566
+ return contract(`${at}.field`, found.problem);
567
+ const format = slot.format ?? "text";
568
+ const fits = format === "text"
569
+ ? TEXT_FIELD_TYPES.has(found.type)
570
+ : format === "money" || format === "count"
571
+ ? found.type === "number"
572
+ : TIME_FIELD_TYPES.has(found.type);
573
+ if (!fits)
574
+ contract(`${at}.format`, `A ${found.type} field cannot be written as ${format}`);
575
+ if (slot.zone) {
576
+ const zone = routinePathType(manifest, from, slot.zone);
577
+ if ("problem" in zone)
578
+ contract(`${at}.zone`, zone.problem);
579
+ else if (zone.type !== "timezone" && zone.type !== "text")
580
+ contract(`${at}.zone`, "zone must be a time zone field");
581
+ }
582
+ if (format === "money") {
583
+ const currency = slot.currency
584
+ ? routinePathType(manifest, from, slot.currency)
585
+ : { problem: "money needs currency" };
586
+ if ("problem" in currency)
587
+ contract(`${at}.currency`, currency.problem);
588
+ }
589
+ };
590
+ const slots = kind.slots;
591
+ for (const [slotName, slot] of Object.entries(slots)) {
592
+ const at = `${base}.slots.${slotName}`;
593
+ if (slotName === ROUTINE_MEMBER_SLOT)
594
+ contract(at, `"${slotName}" is filled by the host`);
595
+ if ("field" in slot)
596
+ checkField(at, about, slot);
597
+ else if ("choice" in slot) {
598
+ for (const [key, said] of Object.entries({ ...slot.choice, ...(slot.guardian ?? {}) })) {
599
+ const why = unroutineWords(said);
600
+ if (why)
601
+ contract(`${at}.choice.${key}`, `The words hold ${why}`);
602
+ }
603
+ for (const key of Object.keys(slot.guardian ?? {})) {
604
+ if (!(key in slot.choice))
605
+ contract(`${at}.guardian.${key}`, `"${key}" is not a choice`);
606
+ }
607
+ }
608
+ else if ("at" in slot) {
609
+ if (slot.zone) {
610
+ const zone = routinePathType(manifest, about, slot.zone);
611
+ if ("problem" in zone)
612
+ contract(`${at}.zone`, zone.problem);
613
+ }
614
+ }
615
+ else if ("formLink" in slot) {
616
+ const setting = manifest.settings[slot.formLink.setting];
617
+ if (setting?.type !== "text") {
618
+ contract(`${at}.formLink.setting`, `"${slot.formLink.setting}" is not a text setting of this extension`);
619
+ }
620
+ else if (setting.personApproves !== true) {
621
+ // Which form members are sent to is a person's to choose, never an AI's (ADR 0723).
622
+ contract(`${at}.formLink.setting`, `"${slot.formLink.setting}" must be a setting a person approves (personApproves)`);
623
+ }
624
+ if (about === ROUTINE_ABOUT_ORDER || !manifest.objects[about]?.customer) {
625
+ contract(`${at}.formLink`, "A personal link is for the record's own Person: the kind is about an object with a customer");
626
+ }
627
+ }
628
+ else if ("link" in slot) {
629
+ const setting = manifest.settings[slot.link];
630
+ if (setting?.type !== "text") {
631
+ contract(`${at}.link`, `"${slot.link}" is not a text setting of this extension`);
632
+ }
633
+ else if (setting.personApproves !== true) {
634
+ // The link every email carries: a person's to change, never an AI's (ADR 0590).
635
+ contract(`${at}.link`, `"${slot.link}" must be a setting a person approves (personApproves)`);
636
+ }
637
+ }
638
+ else if ("each" in slot) {
639
+ const each = slot.each;
640
+ const object = manifest.objects[each.object];
641
+ if (!object) {
642
+ contract(`${at}.each.object`, `"${each.object}" is not an object of this extension`);
643
+ continue;
644
+ }
645
+ const via = object.fields[each.via];
646
+ const target = about === ROUTINE_ABOUT_ORDER ? "order" : `${manifest.id}.${about}`;
647
+ if (!via || (via.type !== "text" && !(via.type === "relation" && via.to === target))) {
648
+ contract(`${at}.each.via`, `${each.object}.${each.via} must point to the ${about}`);
649
+ }
650
+ else if (via.readOnly !== true) {
651
+ // Which records are the lines is the host's (a grant's order): a caller re-pointing a
652
+ // ticket at another order must not put it in that buyer's email (ADR 0590).
653
+ contract(`${at}.each.via`, `${each.object}.${each.via} must be readOnly (set by the host)`);
654
+ }
655
+ if (each.where && !object.fields[each.where.field]) {
656
+ contract(`${at}.each.where`, `"${each.where.field}" is not a field of ${each.object}`);
657
+ }
658
+ if (each.where?.in.some((v) => v === "")) {
659
+ // An empty value is never checked (nothing shown): a line it picked would go unchecked.
660
+ contract(`${at}.each.where`, "where.in cannot hold an empty value");
661
+ }
662
+ if (each.distinct) {
663
+ const d = routinePathType(manifest, each.object, each.distinct);
664
+ if ("problem" in d)
665
+ contract(`${at}.each.distinct`, d.problem);
666
+ }
667
+ for (const [inner, innerSlot] of Object.entries(each.slots)) {
668
+ checkField(`${at}.each.slots.${inner}`, each.object, innerSlot);
669
+ }
670
+ const line = parseTemplate(each.line);
671
+ if (line.error)
672
+ contract(`${at}.each.line`, line.error);
673
+ if (each.line.includes("\n"))
674
+ contract(`${at}.each.line`, "One line");
675
+ const why = unroutineWords(literalText(line));
676
+ if (why)
677
+ contract(`${at}.each.line`, `The words hold ${why}`);
678
+ for (const used of line.slots) {
679
+ if (!(used in each.slots))
680
+ contract(`${at}.each.line`, `{${used}} is not one of its slots`);
681
+ else if (each.slots[used]?.optional && !line.optionalOnly.has(used)) {
682
+ contract(`${at}.each.line`, `{${used}} may be empty: put it in an optional part [...]`);
683
+ }
684
+ }
685
+ }
686
+ }
687
+ channelIssues(manifest, base, kind, contract);
688
+ personalLinkIssues(manifest, base, kind, contract);
689
+ const messages = Object.entries(kind.messages);
690
+ if (!messages.length || messages.length > 12) {
691
+ contract(`${base}.messages`, "A kind has 1 to 12 messages");
692
+ }
693
+ for (const [messageName, message] of messages) {
694
+ const at = `${base}.messages.${messageName}`;
695
+ const texts = [
696
+ [`${at}.subject`, message.subject, false],
697
+ [`${at}.text`, message.text, false],
698
+ ...(message.guardian
699
+ ? [
700
+ [`${at}.guardian.subject`, message.guardian.subject, true],
701
+ [`${at}.guardian.text`, message.guardian.text, true],
702
+ ]
703
+ : []),
704
+ ];
705
+ for (const [where, template, guardian] of texts) {
706
+ const parsed = parseTemplate(template);
707
+ if (parsed.error)
708
+ contract(where, parsed.error);
709
+ if (where.endsWith("subject") && template.includes("\n"))
710
+ contract(where, "One line");
711
+ const why = unroutineWords(literalText(parsed));
712
+ if (why)
713
+ contract(where, `The words hold ${why}`);
714
+ for (const used of parsed.slots) {
715
+ if (used === ROUTINE_MEMBER_SLOT) {
716
+ if (!guardian)
717
+ contract(where, `{${used}} is only for what a guardian is sent`);
718
+ continue;
719
+ }
720
+ const slot = slots[used];
721
+ if (!slot) {
722
+ contract(where, `{${used}} is not a slot of ${kindName}`);
723
+ continue;
724
+ }
725
+ if ("formLink" in slot) {
726
+ // The link is what the email is for: never in its subject, never in an optional part.
727
+ if (where.endsWith("subject"))
728
+ contract(where, `{${used}} is a link: not in a subject`);
729
+ else if (parsed.optionalOnly.has(used)) {
730
+ contract(where, `{${used}} is what the email is for: not in an optional part [...]`);
731
+ }
732
+ continue;
733
+ }
734
+ const mayBeEmpty = "link" in slot ||
735
+ "flag" in slot ||
736
+ (("field" in slot || "at" in slot) && slot.optional === true);
737
+ if (mayBeEmpty && !parsed.optionalOnly.has(used)) {
738
+ contract(where, `{${used}} may be empty: put it in an optional part [...]`);
739
+ }
740
+ }
741
+ }
742
+ for (const [i, event] of calendarsOf(message).entries()) {
743
+ const ev = `${at}.calendar.${i}`;
744
+ for (const key of ["start", "end", "title", "location"]) {
745
+ const p = event[key];
746
+ if (!p)
747
+ continue;
748
+ const found = routinePathType(manifest, about, p);
749
+ if ("problem" in found)
750
+ contract(`${ev}.${key}`, found.problem);
751
+ else if ((key === "start" || key === "end") && !TIME_FIELD_TYPES.has(found.type)) {
752
+ contract(`${ev}.${key}`, "must be a date or datetime field");
753
+ }
754
+ else if ((key === "title" || key === "location") && !TEXT_FIELD_TYPES.has(found.type)) {
755
+ contract(`${ev}.${key}`, `A ${found.type} field cannot be a calendar's ${key}`);
756
+ }
757
+ }
758
+ if (event.uid) {
759
+ const uid = routinePathType(manifest, about, event.uid);
760
+ if ("problem" in uid || uid.type !== "relation") {
761
+ contract(`${ev}.uid`, "uid must be a relation of the record");
762
+ }
763
+ }
764
+ if (event.link && !(event.link in slots && "link" in slots[event.link])) {
765
+ contract(`${ev}.link`, `"${event.link}" is not a link slot`);
766
+ }
767
+ if (event.if && !(event.if in slots && "flag" in slots[event.if])) {
768
+ contract(`${ev}.if`, `"${event.if}" is not a flag slot`);
769
+ }
770
+ }
771
+ }
772
+ }
773
+ return issues;
774
+ }
775
+ /**
776
+ * A personal link's kind and a receipt (ADRs 0723 and 0724). A kind with a form-link slot has one,
777
+ * goes by email only and is not a receipt. A receipt is about one of this extension's intake
778
+ * submissions, goes by email only, has no guardian's words (it goes to whoever sent it), is about
779
+ * something they did (purpose `account`), and shows only fields of the submission's form (a path
780
+ * through its `form` relation): never a list, a calendar or anything the sender typed.
781
+ */
782
+ function personalLinkIssues(manifest, base, kind, contract) {
783
+ const links = formLinkSlotsOf(kind);
784
+ const channels = kind.channels ?? ["email"];
785
+ if (links.length > 1)
786
+ contract(`${base}.slots`, "At most one form-link slot");
787
+ if ((links.length || kind.receipt) && channels.some((c) => c !== "email")) {
788
+ contract(`${base}.channels`, "A personal link and a receipt go by email only");
789
+ }
790
+ if (!kind.receipt)
791
+ return;
792
+ if (links.length)
793
+ contract(`${base}.receipt`, "A receipt carries no personal link");
794
+ const object = manifest.objects[kind.about];
795
+ const form = object?.intake?.role === "submission" ? object.intake.form : undefined;
796
+ if (!form) {
797
+ contract(`${base}.about`, "A receipt is about one of this extension's intake submissions");
798
+ }
799
+ if ((kind.purpose ?? "account") !== "account" || kind.essential === false) {
800
+ contract(`${base}.purpose`, "A receipt is about something the person did: purpose account");
801
+ }
802
+ for (const [slotName, slot] of Object.entries(kind.slots)) {
803
+ const at = `${base}.slots.${slotName}`;
804
+ if ("each" in slot)
805
+ contract(at, "A receipt shows no list");
806
+ if ("field" in slot && form && !slot.field.startsWith(`${form}.`)) {
807
+ contract(at, `A receipt shows only the form's own fields (${form}.<field>), never what the sender typed`);
808
+ }
809
+ }
810
+ for (const [messageName, message] of Object.entries(kind.messages)) {
811
+ const at = `${base}.messages.${messageName}`;
812
+ if (message.guardian)
813
+ contract(`${at}.guardian`, "A receipt goes to whoever sent it");
814
+ if (calendarsOf(message).length)
815
+ contract(`${at}.calendar`, "A receipt has no calendar file");
816
+ }
817
+ }
818
+ /**
819
+ * A kind's text and push words, and what it says of itself (ADR 0670): the words use only its
820
+ * slots and fit when every slot is at its longest (a text two segments with the business's name
821
+ * and the stop line counted in; a push's title 60 characters and its body 140); a push shows no
822
+ * private slot, no link and no list; `until` is a time of the record; a push names the screen it
823
+ * opens; a follow-up is never essential. A channel needs its words in every message, and words
824
+ * need their channel declared.
825
+ */
826
+ function channelIssues(manifest, base, kind, contract) {
827
+ const declared = kind.channels ?? ["email"];
828
+ if (new Set(declared).size !== declared.length)
829
+ contract(`${base}.channels`, "A channel twice");
830
+ if (!declared.includes("email")) {
831
+ contract(`${base}.channels`, "Every kind goes by email: list email first");
832
+ }
833
+ const channels = new Set(declared);
834
+ if ((kind.purpose ?? "account") === "follow_up" && kind.essential === true) {
835
+ contract(`${base}.essential`, "A follow-up is never essential: a person may always stop it");
836
+ }
837
+ if (kind.until) {
838
+ const found = routinePathType(manifest, kind.about, kind.until);
839
+ if ("problem" in found)
840
+ contract(`${base}.until`, found.problem);
841
+ else if (!TIME_FIELD_TYPES.has(found.type)) {
842
+ contract(`${base}.until`, "until must be a date or datetime field of the record");
843
+ }
844
+ }
845
+ if (kind.urgent && !kind.until) {
846
+ contract(`${base}.urgent`, "An urgent kind names its moment (until): it goes in quiet hours only when waiting would be too late");
847
+ }
848
+ if (channels.has("push") && !kind.open) {
849
+ contract(`${base}.open`, "A push opens a screen of the app: name it (open.screen)");
850
+ }
851
+ if (kind.open && !channels.has("push")) {
852
+ contract(`${base}.open`, "open is for a push: declare the push channel");
853
+ }
854
+ const slots = kind.slots;
855
+ // Private is the field's, not one slot's: a second slot reading a private field without saying
856
+ // so is private too (the review of PR #339).
857
+ const privateFields = new Set(Object.values(slots).flatMap((slot) => ("field" in slot && slot.private ? [slot.field] : [])));
858
+ const check = (at, template, guardian, channel, bound) => {
859
+ const parsed = parseTemplate(template);
860
+ if (parsed.error)
861
+ return contract(at, parsed.error);
862
+ if (template.includes("\n"))
863
+ contract(at, "One line");
864
+ const why = unroutineWords(literalText(parsed));
865
+ if (why)
866
+ contract(at, `The words hold ${why}`);
867
+ const longest = {};
868
+ for (const used of parsed.slots) {
869
+ if (used === ROUTINE_MEMBER_SLOT) {
870
+ if (!guardian)
871
+ contract(at, `{${used}} is only for what a guardian is sent`);
872
+ longest[used] = "a".repeat(MEMBER_MAX);
873
+ continue;
874
+ }
875
+ const slot = slots[used];
876
+ if (!slot) {
877
+ contract(at, `{${used}} is not a slot of the kind`);
878
+ continue;
879
+ }
880
+ if ("each" in slot) {
881
+ contract(at, `{${used}} is a list: a ${channel === "text" ? "text" : "push"} has no room for one`);
882
+ continue;
883
+ }
884
+ if ("formLink" in slot) {
885
+ contract(at, `{${used}} is a personal link: it goes by email only`);
886
+ continue;
887
+ }
888
+ if (channel === "push" && "link" in slot) {
889
+ contract(at, `{${used}} is a link: a push opens a screen of the app, never a web address`);
890
+ continue;
891
+ }
892
+ if (channel === "push" &&
893
+ "field" in slot &&
894
+ (slot.private || privateFields.has(slot.field))) {
895
+ contract(at, `{${used}} is private: a push shows on a locked screen`);
896
+ continue;
897
+ }
898
+ const mayBeEmpty = "link" in slot ||
899
+ "flag" in slot ||
900
+ (("field" in slot || "at" in slot) && slot.optional === true);
901
+ if (mayBeEmpty && !parsed.optionalOnly.has(used)) {
902
+ contract(at, `{${used}} may be empty: put it in an optional part [...]`);
903
+ }
904
+ const max = "link" in slot ? TEXT_LINK_MAX : slotMaxLength(slot, guardian);
905
+ longest[used] = "a".repeat(max ?? 0);
906
+ }
907
+ const filled = renderTemplate(parsed, longest);
908
+ if (channel === "text") {
909
+ const sent = wrapText("a".repeat(TEXT_SENDER_MAX), filled);
910
+ // The words decide the encoding: a value that forces the longer one fails its row (ADR 0670).
911
+ // Declared words decide it, a choice's words (and a guardian's) among them: one that forces
912
+ // the longer encoding forces it for the whole text (the review of PR #339).
913
+ const choices = [...parsed.slots].flatMap((used) => {
914
+ const slot = slots[used];
915
+ if (!slot || !("choice" in slot))
916
+ return [];
917
+ return [...Object.values(slot.choice), ...Object.values(slot.guardian ?? {})];
918
+ });
919
+ const literal = textSegments(wrapText("a", [literalText(parsed), ...choices].join(" ")));
920
+ const units = literal.encoding === "gsm" ? textSegments(sent).units : sent.length;
921
+ const limit = literal.encoding === "gsm" ? 153 * TEXT_MAX_SEGMENTS : 67 * TEXT_MAX_SEGMENTS;
922
+ if (units > limit) {
923
+ contract(at, `With every slot at its longest, the business's name and "${TEXT_STOP_LINE}" it is ${units} characters: a text is at most ${limit} (two segments). Use shorter slots (a time, a date, a lower max)`);
924
+ }
925
+ }
926
+ else if (bound !== null && filled.length > bound) {
927
+ contract(at, `With every slot at its longest it is ${filled.length} characters: at most ${bound}`);
928
+ }
929
+ };
930
+ for (const [messageName, message] of Object.entries(kind.messages)) {
931
+ const at = `${base}.messages.${messageName}`;
932
+ const versions = [[at, message, false]];
933
+ if (message.guardian)
934
+ versions.push([`${at}.guardian`, message.guardian, true]);
935
+ for (const [where, version, guardian] of versions) {
936
+ if (version.textMessage !== undefined) {
937
+ if (!channels.has("text"))
938
+ contract(`${where}.textMessage`, "Declare the text channel");
939
+ check(`${where}.textMessage`, version.textMessage, guardian, "text", null);
940
+ }
941
+ if (version.push) {
942
+ if (!channels.has("push"))
943
+ contract(`${where}.push`, "Declare the push channel");
944
+ check(`${where}.push.title`, version.push.title, guardian, "push", PUSH_TITLE_MAX);
945
+ check(`${where}.push.body`, version.push.body, guardian, "push", PUSH_BODY_MAX);
946
+ }
947
+ }
948
+ if (channels.has("text") && message.textMessage === undefined) {
949
+ contract(`${at}.textMessage`, "The kind goes by text: each message needs its text words");
950
+ }
951
+ if (channels.has("push") && !message.push) {
952
+ contract(`${at}.push`, "The kind goes by push: each message needs its push words");
953
+ }
954
+ }
955
+ }