@crubal/engine 0.0.0-stage → 0.4.0

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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +97 -2
  3. package/dist/bin/crubal.d.ts +2 -0
  4. package/dist/bin/crubal.js +103 -0
  5. package/dist/bin/crubal.js.map +1 -0
  6. package/dist/src/access.d.ts +149 -0
  7. package/dist/src/access.js +584 -0
  8. package/dist/src/access.js.map +1 -0
  9. package/dist/src/acts.d.ts +531 -0
  10. package/dist/src/acts.js +1466 -0
  11. package/dist/src/acts.js.map +1 -0
  12. package/dist/src/address.d.ts +29 -0
  13. package/dist/src/address.js +59 -0
  14. package/dist/src/address.js.map +1 -0
  15. package/dist/src/arrival.d.ts +55 -0
  16. package/dist/src/arrival.js +127 -0
  17. package/dist/src/arrival.js.map +1 -0
  18. package/dist/src/browser.d.ts +10 -0
  19. package/dist/src/browser.js +13 -0
  20. package/dist/src/browser.js.map +1 -0
  21. package/dist/src/bundle.d.ts +74 -0
  22. package/dist/src/bundle.js +1108 -0
  23. package/dist/src/bundle.js.map +1 -0
  24. package/dist/src/canonical.d.ts +6 -0
  25. package/dist/src/canonical.js +47 -0
  26. package/dist/src/canonical.js.map +1 -0
  27. package/dist/src/carriers.d.ts +7 -0
  28. package/dist/src/carriers.js +33 -0
  29. package/dist/src/carriers.js.map +1 -0
  30. package/dist/src/conditions.d.ts +28 -0
  31. package/dist/src/conditions.js +227 -0
  32. package/dist/src/conditions.js.map +1 -0
  33. package/dist/src/corpus.d.ts +8 -0
  34. package/dist/src/corpus.js +1207 -0
  35. package/dist/src/corpus.js.map +1 -0
  36. package/dist/src/defs.d.ts +174 -0
  37. package/dist/src/defs.js +690 -0
  38. package/dist/src/defs.js.map +1 -0
  39. package/dist/src/dictionary.d.ts +77 -0
  40. package/dist/src/dictionary.js +629 -0
  41. package/dist/src/dictionary.js.map +1 -0
  42. package/dist/src/exchange.d.ts +259 -0
  43. package/dist/src/exchange.js +1088 -0
  44. package/dist/src/exchange.js.map +1 -0
  45. package/dist/src/forms.d.ts +16 -0
  46. package/dist/src/forms.js +181 -0
  47. package/dist/src/forms.js.map +1 -0
  48. package/dist/src/index.d.ts +32 -0
  49. package/dist/src/index.js +34 -0
  50. package/dist/src/index.js.map +1 -0
  51. package/dist/src/lex.d.ts +21 -0
  52. package/dist/src/lex.js +142 -0
  53. package/dist/src/lex.js.map +1 -0
  54. package/dist/src/lifecycle.d.ts +92 -0
  55. package/dist/src/lifecycle.js +451 -0
  56. package/dist/src/lifecycle.js.map +1 -0
  57. package/dist/src/log.d.ts +91 -0
  58. package/dist/src/log.js +629 -0
  59. package/dist/src/log.js.map +1 -0
  60. package/dist/src/migrate.d.ts +129 -0
  61. package/dist/src/migrate.js +415 -0
  62. package/dist/src/migrate.js.map +1 -0
  63. package/dist/src/model.d.ts +81 -0
  64. package/dist/src/model.js +188 -0
  65. package/dist/src/model.js.map +1 -0
  66. package/dist/src/packages.d.ts +372 -0
  67. package/dist/src/packages.js +1158 -0
  68. package/dist/src/packages.js.map +1 -0
  69. package/dist/src/print-text.d.ts +7 -0
  70. package/dist/src/print-text.js +223 -0
  71. package/dist/src/print-text.js.map +1 -0
  72. package/dist/src/publish.d.ts +27 -0
  73. package/dist/src/publish.js +279 -0
  74. package/dist/src/publish.js.map +1 -0
  75. package/dist/src/read-text.d.ts +10 -0
  76. package/dist/src/read-text.js +400 -0
  77. package/dist/src/read-text.js.map +1 -0
  78. package/dist/src/records.d.ts +32 -0
  79. package/dist/src/records.js +104 -0
  80. package/dist/src/records.js.map +1 -0
  81. package/dist/src/review.d.ts +22 -0
  82. package/dist/src/review.js +198 -0
  83. package/dist/src/review.js.map +1 -0
  84. package/dist/src/rules.d.ts +101 -0
  85. package/dist/src/rules.js +670 -0
  86. package/dist/src/rules.js.map +1 -0
  87. package/dist/src/schedule.d.ts +24 -0
  88. package/dist/src/schedule.js +126 -0
  89. package/dist/src/schedule.js.map +1 -0
  90. package/dist/src/std-packages.d.ts +9 -0
  91. package/dist/src/std-packages.js +268 -0
  92. package/dist/src/std-packages.js.map +1 -0
  93. package/dist/src/store.d.ts +191 -0
  94. package/dist/src/store.js +671 -0
  95. package/dist/src/store.js.map +1 -0
  96. package/dist/src/surface.d.ts +47 -0
  97. package/dist/src/surface.js +92 -0
  98. package/dist/src/surface.js.map +1 -0
  99. package/dist/src/tree.d.ts +35 -0
  100. package/dist/src/tree.js +159 -0
  101. package/dist/src/tree.js.map +1 -0
  102. package/dist/src/units-table.d.ts +1 -0
  103. package/dist/src/units-table.js +200 -0
  104. package/dist/src/units-table.js.map +1 -0
  105. package/dist/src/units.d.ts +42 -0
  106. package/dist/src/units.js +98 -0
  107. package/dist/src/units.js.map +1 -0
  108. package/dist/src/versions.d.ts +10 -0
  109. package/dist/src/versions.js +27 -0
  110. package/dist/src/versions.js.map +1 -0
  111. package/dist/src/views.d.ts +372 -0
  112. package/dist/src/views.js +1170 -0
  113. package/dist/src/views.js.map +1 -0
  114. package/package.json +60 -4
@@ -0,0 +1,1158 @@
1
+ // packages.ts: package files (spec chapter 11). A file may hold several packages, each starting at a
2
+ // `package:` line. The checks here are 11.1's prefixes, 11.3's trust entries and 11.4's rule that an
3
+ // extending package may add to what it extends but never change it.
4
+ import { emptyDictionary, readDefinitions, unquote } from "./defs.js";
5
+ import { LANGUAGE } from "./read-text.js";
6
+ import { readContracts } from "./store.js";
7
+ import { readAccess } from "./access.js";
8
+ import { readViews } from "./views.js";
9
+ import { CrubalError, readTree } from "./tree.js";
10
+ import { checkActList, readAct, readWhen, termsOf } from "./acts.js";
11
+ /** Revision 57: an owner is one lower-case word that belongs to the surface drawing it. */
12
+ const ownerWord = (v, line) => {
13
+ if (!/^[a-z][a-z0-9-]*$/.test(v))
14
+ throw new CrubalError(`owner is one lower-case word, a surface's name for whom the thing belongs to: ${v}`, line);
15
+ return v;
16
+ };
17
+ /** The eight hue words a mark may name (11.1, revision 13); an app maps each to its own colors. */
18
+ export const HUES = ["amber", "blue", "violet", "slate", "teal", "plum", "coral", "olive"];
19
+ export const isHue = (v) => typeof v === "string" && HUES.includes(v);
20
+ /** Revision 51: an ask's words with each `{record.<facet>}` said as the record touched holds it: a number or a
21
+ * word as written, money and a quantity by their amount, nothing where it is not set. Pure. */
22
+ export function askWords(words, record) {
23
+ return words.replace(/\{record\.([\w:]+)\}/g, (_all, facet) => {
24
+ const v = record.values[facet.split("::").pop()];
25
+ if (typeof v === "string" || typeof v === "number")
26
+ return String(v);
27
+ if (v && typeof v === "object" && !Array.isArray(v))
28
+ return typeof v.$money === "string" ? v.$money : typeof v.$qty === "string" ? v.$qty : "";
29
+ return "";
30
+ });
31
+ }
32
+ /** The press a case runs without asking, by its answer or the one given; undefined asks. Pure. */
33
+ export function casePress(c, answer = c.answer) {
34
+ return answer === "yes" ? c.yes : answer === "no" ? c.no : undefined;
35
+ }
36
+ /**
37
+ * The stamps of a flow's stops, derived from its lanes: never declared, never published. `facetOf` resolves
38
+ * a filter's name to its facet's key (the views' filters); a stop whose pick names no filter stamps nothing.
39
+ * A lane stop whose done is `viewed` or absent (an end stop) stamps nothing; a block stop after the last
40
+ * lane stamps nothing. A step stop (revision 34) stamps its mark (`mark: true`; the value is the writer's: now on
41
+ * a date, yes on a yes-no, nothing on a link, which the act sets), and a block before one stamps nothing. Pure.
42
+ */
43
+ export function flowStamps(f, lanes, facetOf) {
44
+ const out = [];
45
+ const laneOf = (n) => lanes.find((x) => x.name === n);
46
+ const nextPick = (i) => {
47
+ for (let j = i + 1; j < f.stops.length; j++) {
48
+ const l = laneOf(f.stops[j]?.name ?? "");
49
+ if (l)
50
+ return l.step ? undefined : l.pick;
51
+ }
52
+ return undefined;
53
+ };
54
+ f.stops.forEach((st, i) => {
55
+ const l = laneOf(st.name);
56
+ const pk = l ? (l.done && l.done !== "viewed" ? l.done : undefined) : nextPick(i);
57
+ const facet = pk ? facetOf(pk.filter) : undefined;
58
+ if (pk && facet)
59
+ out.push({ stop: st.name, at: i, facet, value: pk.value, ...(l?.step ? { mark: true } : {}) });
60
+ });
61
+ return out;
62
+ }
63
+ /**
64
+ * The joins of a flow's lane stops, in order, derived from its lanes: never declared, never published. A record
65
+ * passes from one stop to the next where the first's `done` is a state and is the second's `pick`, filter and
66
+ * value, or where the second is a step lane that waits `after` the first's step. A block between two lanes
67
+ * leaves their join as it is. Where nothing passes, the two stand together by what the flow holds (its
68
+ * context) or by their order alone, which is the app's to say. Pure.
69
+ */
70
+ export function flowJoins(f, lanes) {
71
+ const out = [];
72
+ let prev;
73
+ f.stops.forEach((st, at) => {
74
+ const l = lanes.find((x) => x.name === st.name);
75
+ if (!l)
76
+ return;
77
+ if (prev) {
78
+ const state = !!prev.done && prev.done !== "viewed" && !!l.pick && prev.done.filter === l.pick.filter && prev.done.value === l.pick.value;
79
+ const step = !!prev.step && !!l.step && (l.after ?? []).includes(prev.step);
80
+ out.push({ from: prev.name, to: l.name, at, passes: state || step });
81
+ }
82
+ prev = l;
83
+ });
84
+ return out;
85
+ }
86
+ const ORIGINS = new Set(["observed", "declared", "derived", "reported"]);
87
+ const AUDIENCES = new Set(["public", "member", "staff", "owner"]);
88
+ const splitList = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
89
+ /** Split at commas outside parentheses: `controller, curator(ship, returns)` → two pieces. */
90
+ function splitServes(value) {
91
+ const parts = [];
92
+ let depth = 0;
93
+ let cur = "";
94
+ for (const ch of value) {
95
+ if (ch === "(")
96
+ depth++;
97
+ if (ch === ")")
98
+ depth--;
99
+ if (ch === "," && depth === 0) {
100
+ parts.push(cur);
101
+ cur = "";
102
+ }
103
+ else
104
+ cur += ch;
105
+ }
106
+ parts.push(cur);
107
+ return parts.map((s) => s.trim()).filter(Boolean);
108
+ }
109
+ /** Read one `utility:` block. */
110
+ function readUtility(node) {
111
+ const [name = "", version = ""] = node.value.split(/\s+\//).map((s) => s.trim());
112
+ if (!/^[a-z][\w-]*$/.test(name))
113
+ throw new CrubalError(`a utility is "utility: <name> /<version>", the name a lower-case word: ${node.value}`, node.line);
114
+ const u = { name, version, serves: [], needs: [], setup: [], acts: [], line: node.line };
115
+ for (const c of node.children) {
116
+ if (!c.key)
117
+ continue;
118
+ if (c.key === "label")
119
+ u.label = unquote(c.value.trim());
120
+ else if (c.key === "describe")
121
+ u.describe = unquote(c.value.trim());
122
+ else if (c.key === "group") {
123
+ const g = unquote(c.value.trim());
124
+ if (!g)
125
+ throw new CrubalError("group names the group the utility stands in: a word", c.line);
126
+ u.group = g;
127
+ }
128
+ else if (c.key === "owner")
129
+ u.owner = ownerWord(c.value.trim(), c.line);
130
+ else if (c.key === "serves") {
131
+ for (const p of splitServes(c.value)) {
132
+ const m = p.match(/^([A-Za-z][\w-]*)(?:\((.*)\))?$/);
133
+ if (!m)
134
+ throw new CrubalError(`serves: ${p} is not a name, or a name with items in parentheses`, c.line);
135
+ u.serves.push({ as: m[1], ...(m[2] !== undefined ? { items: splitList(m[2]) } : {}), line: c.line });
136
+ }
137
+ }
138
+ else if (c.key === "needs") {
139
+ for (const n of splitList(c.value)) {
140
+ const [nm = "", ver] = n.split(/\s+\//).map((s) => s.trim());
141
+ if (!/^([a-z0-9.-]+\/[a-z][\w-]*|[a-z][\w-]*)$/.test(nm))
142
+ throw new CrubalError(`needs: ${nm} is not a package identity (domain/name) or a utility name`, c.line);
143
+ u.needs.push({ name: nm, ...(ver ? { version: ver } : {}), line: c.line });
144
+ }
145
+ }
146
+ else if (c.key === "setup") {
147
+ for (const s of splitList(c.value)) {
148
+ const m = s.match(/^(connection|setting)\s+(\S+)$/);
149
+ if (!m)
150
+ throw new CrubalError(`setup: ${s} is not "connection <name>" or "setting <facet>"`, c.line);
151
+ u.setup.push(m[1] === "connection" ? { connection: m[2], line: c.line } : { setting: m[2], line: c.line });
152
+ }
153
+ }
154
+ else if (c.key === "acts") {
155
+ for (const a of splitList(c.value)) {
156
+ if (!/^[a-z][\w-]*$/.test(a))
157
+ throw new CrubalError(`acts: ${a} is not a lower-case word`, c.line);
158
+ u.acts.push({ name: a, line: c.line });
159
+ }
160
+ }
161
+ else if (c.key === "mark") {
162
+ const m = c.value.trim().match(/^([a-z][\w-]*)\s+([a-z]+)$/);
163
+ if (!m)
164
+ throw new CrubalError(`mark: is "<glyph> <hue>", the glyph a lower-case word and the hue one of ${HUES.join(", ")}: ${c.value.trim()}`, c.line);
165
+ if (!isHue(m[2]))
166
+ throw new CrubalError(`mark: ${m[2]} is not a hue; the eight are ${HUES.join(", ")}`, c.line);
167
+ u.mark = { glyph: m[1], hue: m[2], line: c.line };
168
+ }
169
+ else
170
+ throw new CrubalError(`a utility has label, describe, group, owner, serves, needs, setup, acts and mark, not ${c.key}`, c.line);
171
+ }
172
+ return u;
173
+ }
174
+ /** Read one `group:` block (revision 57). */
175
+ function readGroup(node) {
176
+ const name = unquote(node.value.trim());
177
+ if (!name)
178
+ throw new CrubalError("a group is \"group: <word>\", the word utilities name it by", node.line);
179
+ const g = { name, line: node.line };
180
+ for (const c of node.children) {
181
+ if (!c.key)
182
+ continue;
183
+ const v = c.value.trim();
184
+ if (c.key === "label")
185
+ g.label = unquote(v);
186
+ else if (c.key === "owner")
187
+ g.owner = ownerWord(v, c.line);
188
+ else if (c.key === "order") {
189
+ if (!/^\d+$/.test(v))
190
+ throw new CrubalError(`order is a whole number, the group's place among the groups: ${v}`, c.line);
191
+ g.order = Number(v);
192
+ }
193
+ else
194
+ throw new CrubalError(`a group has label, owner and order, not ${c.key}`, c.line);
195
+ }
196
+ return g;
197
+ }
198
+ /** `Word -> target`, or `Word as glyph -> target` (revision 33): a press's word, its glyph and where it lands. */
199
+ function readPress(value, line, what) {
200
+ const at = value.lastIndexOf(" -> ");
201
+ if (at < 0)
202
+ throw new CrubalError(`${what} is "Word -> target" or "Word as glyph -> target": ${value}`, line);
203
+ let head = value.slice(0, at).trim();
204
+ const to = value.slice(at + 4).trim();
205
+ let glyph;
206
+ const as = head.match(/^(.*\S)\s+as\s+([a-z][a-z0-9-]*)$/);
207
+ if (as) {
208
+ head = as[1].trim();
209
+ glyph = as[2];
210
+ }
211
+ const word = unquote(head);
212
+ if (!word || !to)
213
+ throw new CrubalError(`${what} is "Word -> target" or "Word as glyph -> target": ${value}`, line);
214
+ return { word, to, ...(glyph ? { glyph } : {}), line };
215
+ }
216
+ /** `filter = value`: a view's filter pick. */
217
+ function readPick(value, line, what) {
218
+ const m = value.match(/^([\w:-]+)\s*=\s*(.+)$/);
219
+ if (!m)
220
+ throw new CrubalError(`${what} is "filter = value": ${value}`, line);
221
+ return { filter: m[1], value: unquote(m[2].trim()), line };
222
+ }
223
+ /** Read one `lane:` block (12.10). */
224
+ function readLane(node) {
225
+ const [name = "", version = ""] = node.value.split(/\s+\//).map((s) => s.trim());
226
+ if (!/^[a-z][\w-]*$/.test(name))
227
+ throw new CrubalError(`a lane is "lane: <name> /<version>", the name a lower-case word: ${node.value}`, node.line);
228
+ const s = { name, version, band: "rarely", house: 8, serves: [], home: { chips: [], line: node.line }, line: node.line };
229
+ const said = new Set();
230
+ for (const c of node.children) {
231
+ if (!c.key)
232
+ continue;
233
+ const v = c.value.trim();
234
+ if (c.key === "label")
235
+ s.label = unquote(v);
236
+ else if (c.key === "describe")
237
+ s.describe = unquote(v);
238
+ else if (c.key === "about")
239
+ s.about = unquote(v);
240
+ else if (c.key === "sort") {
241
+ if (!/^[a-z][a-z0-9-]*$/.test(v))
242
+ throw new CrubalError(`sort is one lower-case word, a surface's name for the sort of row: ${v}`, c.line);
243
+ s.sort = v;
244
+ }
245
+ else if (c.key === "owner")
246
+ s.owner = ownerWord(v, c.line);
247
+ else if (c.key === "utility")
248
+ s.utility = v;
249
+ else if (c.key === "view")
250
+ s.view = v;
251
+ else if (c.key === "serve")
252
+ s.serve = v;
253
+ else if (c.key === "pick") {
254
+ s.pick = readPick(v, c.line, "pick");
255
+ said.add("pick");
256
+ }
257
+ else if (c.key === "done") {
258
+ s.done = v === "viewed" ? "viewed" : readPick(v, c.line, "done");
259
+ said.add("done");
260
+ }
261
+ else if (c.key === "step") {
262
+ if (!/^[\w:-]+$/.test(v))
263
+ throw new CrubalError(`step names one of the view's marked filters: ${v}`, c.line);
264
+ s.step = v;
265
+ }
266
+ else if (c.key === "until") {
267
+ s.until = splitList(v);
268
+ for (const u of s.until)
269
+ if (!/^[\w:-]+$/.test(u))
270
+ throw new CrubalError(`until names the view's marked filters: ${u}`, c.line);
271
+ if (!s.until.length)
272
+ throw new CrubalError("until names the view's marked filters", c.line);
273
+ }
274
+ else if (c.key === "group") {
275
+ if (!/^[\w:-]+$/.test(v))
276
+ throw new CrubalError(`group names one of the view's filters: ${v}`, c.line);
277
+ s.group = v;
278
+ }
279
+ else if (c.key === "band") {
280
+ if (v !== "daily" && v !== "weekly" && v !== "rarely")
281
+ throw new CrubalError(`band is daily, weekly or rarely, not ${v}`, c.line);
282
+ s.band = v;
283
+ }
284
+ else if (c.key === "house") {
285
+ if (!/^\d+$/.test(v))
286
+ throw new CrubalError(`house is a whole number, governance first: ${v}`, c.line);
287
+ s.house = Number(v);
288
+ }
289
+ else if (c.key === "serves") {
290
+ for (const p of splitServes(v)) {
291
+ const m = p.match(/^([A-Za-z][\w-]*)(?:\((.*)\))?$/);
292
+ if (!m)
293
+ throw new CrubalError(`serves: ${p} is not a name, or a name with items in parentheses`, c.line);
294
+ s.serves.push({ as: m[1], ...(m[2] !== undefined ? { items: splitList(m[2]) } : {}), line: c.line });
295
+ }
296
+ }
297
+ else if (c.key === "home") {
298
+ s.home.line = c.line;
299
+ for (const h of c.children) {
300
+ if (!h.key)
301
+ continue;
302
+ const hv = h.value.trim();
303
+ if (h.key === "figure") {
304
+ const m = hv.match(/^(count|sum|state)(?:\s+(\S+))?$/);
305
+ if (!m)
306
+ throw new CrubalError(`figure is count, "sum <slot>" or "state <slot>", not ${hv}`, h.line);
307
+ if (m[1] === "count")
308
+ s.home.figure = { of: "count" };
309
+ else {
310
+ if (!m[2])
311
+ throw new CrubalError(`figure ${m[1]} names a slot`, h.line);
312
+ s.home.figure = { of: m[1], slot: m[2] };
313
+ }
314
+ }
315
+ else if (h.key === "word") {
316
+ const m = hv.match(/^one\s+("(?:[^"\\]|\\.)*")\s+many\s+("(?:[^"\\]|\\.)*")$/);
317
+ s.home.word = m ? { one: unquote(m[1]), many: unquote(m[2]) } : { word: unquote(hv) };
318
+ }
319
+ else if (h.key === "press")
320
+ s.home.press = readPress(hv, h.line, "home's press");
321
+ else if (h.key === "chips")
322
+ s.home.chips = splitList(hv);
323
+ else
324
+ throw new CrubalError(`a lane's home has figure, word, press and chips, not ${h.key}`, h.line);
325
+ }
326
+ }
327
+ else if (c.key === "card") {
328
+ const card = { name: [], sub: [], lines: [], quick: [], opens: "page", line: c.line };
329
+ for (const k of c.children) {
330
+ if (!k.key)
331
+ continue;
332
+ const kv = k.value.trim();
333
+ if (k.key === "name")
334
+ card.name = splitList(kv);
335
+ else if (k.key === "sub")
336
+ card.sub = splitList(kv);
337
+ else if (k.key === "lines")
338
+ card.lines = splitList(kv);
339
+ else if (k.key === "state")
340
+ card.state = kv;
341
+ else if (k.key === "moment")
342
+ card.moment = kv;
343
+ else if (k.key === "figure")
344
+ card.figure = kv;
345
+ else if (k.key === "primary")
346
+ card.primary = readPress(kv, k.line, "primary");
347
+ else if (k.key === "quiet")
348
+ card.quiet = readPress(kv, k.line, "quiet");
349
+ else if (k.key === "quick")
350
+ card.quick.push(readPress(kv, k.line, "quick"));
351
+ else if (k.key === "opens") {
352
+ if (kv !== "page")
353
+ throw new CrubalError(`opens: ${kv}: a card opens its page; a nest is not in this language version`, k.line);
354
+ }
355
+ else if (k.key === "face") {
356
+ if (!/^[a-z][a-z0-9-]*$/.test(kv))
357
+ throw new CrubalError(`face is one lower-case word, a surface's name for the card: ${kv}`, k.line);
358
+ card.face = kv;
359
+ }
360
+ else
361
+ throw new CrubalError(`a lane's card has name, sub, lines, state, moment, figure, primary, quiet, quick, opens and face, not ${k.key}`, k.line);
362
+ }
363
+ if (!card.name.length)
364
+ throw new CrubalError(`the lane ${name}'s card names nothing`, c.line);
365
+ s.card = card;
366
+ }
367
+ else if (c.key === "after") {
368
+ s.after = splitList(v);
369
+ for (const u of s.after)
370
+ if (!/^[\w:-]+$/.test(u))
371
+ throw new CrubalError(`after names the view's marked filters: ${u}`, c.line);
372
+ if (!s.after.length)
373
+ throw new CrubalError("after names the view's marked filters", c.line);
374
+ }
375
+ else
376
+ throw new CrubalError(`a lane has label, describe, about, sort, owner, utility, view, serve, pick, done, step, until, after, group, band, house, serves, home and card, not ${c.key}`, c.line);
377
+ }
378
+ if (!s.view && !s.serve)
379
+ throw new CrubalError(`the lane ${name} names no view and no serve`, node.line);
380
+ if (s.view && s.serve)
381
+ throw new CrubalError(`the lane ${name} names both a view and a serve`, node.line);
382
+ // A step lane (revision 34): the step in place of pick and done, which hold its two buckets from here on.
383
+ if (s.step && (said.has("pick") || said.has("done")))
384
+ throw new CrubalError(`the lane ${name} names a step, so it names no pick and no done`, node.line);
385
+ if (s.until && !s.step)
386
+ throw new CrubalError(`the lane ${name} names an until, so it needs a step`, node.line);
387
+ if (s.after && !s.step)
388
+ throw new CrubalError(`the lane ${name} names an after, so it needs a step`, node.line);
389
+ for (const a of s.after ?? []) {
390
+ if (a === s.step)
391
+ throw new CrubalError(`the lane ${name}'s after names its own step, ${a}`, node.line);
392
+ if (s.until?.includes(a))
393
+ throw new CrubalError(`the lane ${name} names ${a} as an after and an until: nothing would wait there`, node.line);
394
+ }
395
+ if (s.step) {
396
+ s.pick = { filter: s.step, value: "open", line: node.line };
397
+ s.done = { filter: s.step, value: "done", line: node.line };
398
+ }
399
+ if (s.serve && (s.pick || s.done || s.card))
400
+ throw new CrubalError(`the lane ${name} is a utility's own (serve): no pick, done or card`, node.line);
401
+ // A list (12.10, revision 17): a lane without a pick holds every record its view serves and has no history.
402
+ if (s.view && !s.pick && s.done)
403
+ throw new CrubalError(`the lane ${name} is a list (no pick), so it has no done`, node.line);
404
+ return s;
405
+ }
406
+ /** Read one `flow:` block (12.11). */
407
+ function readFlow(node) {
408
+ const [name = "", version = ""] = node.value.split(/\s+\//).map((s) => s.trim());
409
+ if (!/^[a-z][\w-]*$/.test(name))
410
+ throw new CrubalError(`a flow is "flow: <name> /<version>", the name a lower-case word: ${node.value}`, node.line);
411
+ const f = { name, version, follow: "queue", serves: [], context: [], stops: [], line: node.line };
412
+ for (const c of node.children) {
413
+ if (!c.key)
414
+ continue;
415
+ const v = c.value.trim();
416
+ if (c.key === "label")
417
+ f.label = unquote(v);
418
+ else if (c.key === "utility")
419
+ f.utility = v;
420
+ else if (c.key === "follow") {
421
+ if (v !== "queue" && v !== "card")
422
+ throw new CrubalError(`follow is queue or card, not ${v}`, c.line);
423
+ f.follow = v;
424
+ }
425
+ else if (c.key === "serves") {
426
+ for (const part of splitServes(v)) {
427
+ const m = part.match(/^([A-Za-z][\w-]*)(?:\((.*)\))?$/);
428
+ if (!m)
429
+ throw new CrubalError(`serves: ${part} is not a name, or a name with items in parentheses`, c.line);
430
+ f.serves.push({ as: m[1], ...(m[2] !== undefined ? { items: splitList(m[2]) } : {}), line: c.line });
431
+ }
432
+ }
433
+ else if (c.key === "context") {
434
+ f.context = splitList(v);
435
+ for (const k of f.context)
436
+ if (!/^[a-z][\w-]*$/.test(k))
437
+ throw new CrubalError(`context names kinds, lower-case words: ${k}`, c.line);
438
+ }
439
+ else if (c.key === "replaces") {
440
+ if (!/^[a-z][\w-]*$/.test(v))
441
+ throw new CrubalError(`replaces names a flow, a lower-case word: ${v}`, c.line);
442
+ f.replaces = v;
443
+ }
444
+ else if (c.key === "closed") {
445
+ const m = v.match(/^([a-z][\w-]*)\s+to\s+([a-z][\w-]*)\s+over\s+([a-z][\w-]*)(?:\s+cancel\s+([a-z][\w-]*))?$/);
446
+ if (!m)
447
+ throw new CrubalError(`closed is "<start stop> to <finish stop> over <rest stop>", with "cancel <act>" after it or not: ${v}`, c.line);
448
+ f.closed = { start: m[1], finish: m[2], rest: m[3], ...(m[4] ? { cancel: m[4] } : {}), line: c.line };
449
+ }
450
+ else if (c.key === "done")
451
+ f.done = /^[\w:-]+$/.test(v) ? { filter: v, value: "done", line: c.line, mark: true } : readPick(v, c.line, "done");
452
+ else if (c.key === "stops") {
453
+ for (const st of c.children) {
454
+ const text = st.text.trim();
455
+ if (!text)
456
+ continue;
457
+ const m = text.match(/^([a-z][\w-]*)(?:\s+->\s+([a-z][\w-]*)|\s+of\s+([a-z][\w-]*)(?:\s+with\s+(.+))?)?$/);
458
+ if (!m)
459
+ throw new CrubalError(`a stop is "<lane> -> <act>", "<lane>", or "<form> of <level>" (with "<facet> = <value>, …" after it, or not), not ${text}`, st.line);
460
+ // Revision 36: `with`, the values a block's form opens with, set and locked.
461
+ const locks = (m[4] ?? "").split(",").map((s) => s.trim()).filter(Boolean).map((pair) => {
462
+ const w = pair.match(/^([a-z][\w:-]*)\s*=\s*(\S(?:.*\S)?)$/);
463
+ if (!w)
464
+ throw new CrubalError(`a stop's with is "<facet> = <value>", not ${pair}`, st.line);
465
+ return { facet: w[1], value: w[2] };
466
+ });
467
+ if (m[4] !== undefined && !locks.length)
468
+ throw new CrubalError(`the stop ${m[1]} says with and names no value`, st.line);
469
+ if (new Set(locks.map((l) => l.facet)).size !== locks.length)
470
+ throw new CrubalError(`the stop ${m[1]} locks a facet twice`, st.line);
471
+ const cased = readStopCases(st, m[1], !!m[2]);
472
+ f.stops.push({ name: m[1], ...(m[2] ? { act: m[2] } : {}), ...(m[3] ? { of: m[3] } : {}), ...(locks.length ? { with: locks } : {}), ...cased, line: st.line });
473
+ }
474
+ }
475
+ else
476
+ throw new CrubalError(`a flow has label, utility, follow, serves, context, replaces, closed, stops and done, not ${c.key}`, c.line);
477
+ }
478
+ if (!f.stops.length)
479
+ throw new CrubalError(`the flow ${name} has no stops`, node.line);
480
+ return f;
481
+ }
482
+ /** A case's press: `<Word>` alone, or `<Word> -> <act>[ on found], …`, an act of the flow's utility or `<utility>.<act>`. */
483
+ function readCasePress(text, line, flag) {
484
+ const m = text.match(/^([^>]*?\S)(?:\s+->\s+(.+))?$/);
485
+ if (!m || /->/.test(m[1]))
486
+ throw new CrubalError(`a case's press is "<word>" or "<word> -> <act>, …", not ${text}`, line);
487
+ const runs = (m[2] ?? "").split(",").map((x) => x.trim()).filter(Boolean).map((r) => {
488
+ const a = r.match(/^(?:([a-z][\w-]*)\.)?([a-z][\w-]*)(\s+on\s+found)?$/);
489
+ if (!a)
490
+ throw new CrubalError(`a case's press runs "<act>" or "<utility>.<act>" (a flag's may end "on found"), not ${r}`, line);
491
+ if (a[3] && !flag)
492
+ throw new CrubalError(`only a flag's press runs an act on found: ${r}`, line);
493
+ return { act: a[2], ...(a[1] ? { utility: a[1] } : {}), ...(a[3] ? { onFound: true } : {}) };
494
+ });
495
+ if (m[2] !== undefined && !runs.length)
496
+ throw new CrubalError(`the press ${m[1]} names no act after its arrow`, line);
497
+ return { word: m[1], runs };
498
+ }
499
+ /** The lines beneath a stop (revision 41): `already: ignore`, `stranger: <answer>`, `flag <name>: <answer> when any <lane> where <facet> = record`, each case with its presses beneath. */
500
+ function readStopCases(st, stop, link) {
501
+ const out = {};
502
+ for (const c of st.children) {
503
+ const text = c.text.trim();
504
+ if (!text)
505
+ continue;
506
+ if (!link)
507
+ throw new CrubalError(`the stop ${stop} names no act, so it has no cases: a case is a link's ("<lane> -> <act>")`, c.line);
508
+ const al = text.match(/^already:\s*(\S+)$/);
509
+ if (al) {
510
+ if (al[1] !== "ignore" && al[1] !== "stamp")
511
+ throw new CrubalError(`already is ignore or stamp, not ${al[1]}`, c.line);
512
+ if (al[1] === "ignore")
513
+ out.already = "ignore";
514
+ continue;
515
+ }
516
+ // Revision 48: `asks <name>: [<utility>.]<act> when <when> [open <value>] ["words"]` and `offers: <act>[, …]`.
517
+ const ak = text.match(/^asks\s+([a-z][\w-]*):\s*(?:([a-z][\w-]*)\.)?([a-z][\w-]*)\s+when\s+(.+?)(?:\s+open\s+([^\s"]+))?(?:\s+"([^"]+)")?$/);
518
+ if (ak) {
519
+ if (out.asks?.some((x) => x.name === ak[1]))
520
+ throw new CrubalError(`the stop ${stop} asks ${ak[1]} twice`, c.line);
521
+ (out.asks ??= []).push({ name: ak[1], ...(ak[2] ? { utility: ak[2] } : {}), act: ak[3], when: readWhen(ak[4], c.line), ...(ak[5] ? { open: ak[5] } : {}), ...(ak[6] ? { words: ak[6] } : {}), line: c.line });
522
+ continue;
523
+ }
524
+ const of = text.match(/^offers:\s*(.+)$/);
525
+ if (of) {
526
+ if (out.offers)
527
+ throw new CrubalError(`the stop ${stop} says offers twice`, c.line);
528
+ out.offers = of[1].split(",").map((x) => x.trim()).filter(Boolean).map((x) => {
529
+ const o = x.match(/^(?:([a-z][\w-]*)\.)?([a-z][\w-]*)$/);
530
+ if (!o)
531
+ throw new CrubalError(`offers names acts, "<act>" or "<utility>.<act>": ${x}`, c.line);
532
+ return { ...(o[1] ? { utility: o[1] } : {}), act: o[2] };
533
+ });
534
+ if (!out.offers.length)
535
+ throw new CrubalError(`the stop ${stop} offers nothing`, c.line);
536
+ continue;
537
+ }
538
+ const m = text.match(/^(?:(stranger)|flag\s+([a-z][\w-]*)):\s*(\S+)(?:\s+when\s+any\s+([a-z][\w-]*)\s+where\s+([a-z][\w:-]*)\s*=\s*record)?$/);
539
+ if (!m)
540
+ throw new CrubalError(`beneath a stop stands "already: ignore", "stranger: <answer>" or "flag <name>: <answer> when any <lane> where <facet> = record", not ${text}`, c.line);
541
+ const answer = m[3];
542
+ if (answer !== "ask" && answer !== "yes" && answer !== "no")
543
+ throw new CrubalError(`a case's answer is ask, yes or no, not ${answer}`, c.line);
544
+ const flag = !m[1];
545
+ if (flag && !m[4])
546
+ throw new CrubalError(`the flag ${m[2]} says no when: "when any <lane> where <facet> = record"`, c.line);
547
+ if (!flag && m[4])
548
+ throw new CrubalError("a stranger has no when: it is a record the lane does not hold", c.line);
549
+ let yes;
550
+ let no;
551
+ const or = [];
552
+ for (const pr of c.children) {
553
+ const t = pr.text.trim();
554
+ if (!t)
555
+ continue;
556
+ const k = t.match(/^(yes|no|or):\s*(.+)$/);
557
+ if (!k)
558
+ throw new CrubalError(`a case's lines are "yes: <press>", "no: <press>" and "or: <press>", not ${t}`, pr.line);
559
+ const press = readCasePress(k[2], pr.line, flag);
560
+ if (k[1] === "yes") {
561
+ if (yes)
562
+ throw new CrubalError("a case has one yes", pr.line);
563
+ yes = press;
564
+ }
565
+ else if (k[1] === "no") {
566
+ if (no)
567
+ throw new CrubalError("a case has one no", pr.line);
568
+ no = press;
569
+ }
570
+ else
571
+ or.push(press);
572
+ }
573
+ const what = flag ? `the flag ${m[2]}` : "the stranger";
574
+ if (!yes || !no)
575
+ throw new CrubalError(`${what} at ${stop} needs a yes and a no: every question has three answers (ask, yes, no)`, c.line);
576
+ const words = [yes, no, ...or].map((x) => x.word);
577
+ if (new Set(words).size !== words.length)
578
+ throw new CrubalError(`${what} at ${stop} offers one word twice`, c.line);
579
+ const made = { kind: flag ? "flag" : "stranger", ...(flag ? { name: m[2], when: { lane: m[4], facet: m[5] } } : {}), answer, yes, no, or, line: c.line };
580
+ out.cases ??= [];
581
+ if (!flag && out.cases.some((x) => x.kind === "stranger"))
582
+ throw new CrubalError(`the stop ${stop} has one stranger`, c.line);
583
+ if (flag && out.cases.some((x) => x.name === made.name))
584
+ throw new CrubalError(`the stop ${stop} names the flag ${made.name} twice`, c.line);
585
+ out.cases.push(made);
586
+ }
587
+ return out;
588
+ }
589
+ /** Split a file into its packages, keeping line numbers true. */
590
+ export function readPackages(source) {
591
+ const lines = source.split(/\r?\n/);
592
+ const starts = lines.flatMap((l, i) => (/^package: /.test(l) ? [i] : []));
593
+ return starts.map((start, n) => {
594
+ const end = starts[n + 1] ?? lines.length;
595
+ const text = lines.map((l, i) => (i >= start && i < end ? l : "")).join("\n");
596
+ const [head, ...rest] = readTree(text);
597
+ if (!head)
598
+ throw new CrubalError("an empty package", start + 1);
599
+ const [name = "", version = ""] = head.value.split(/\s+\//).map((s) => s.trim());
600
+ const info = { name, version, owner: "", line: head.line, crubal: LANGUAGE, crubalLine: head.line, extends: [], prefixes: new Map(), trust: [], dict: emptyDictionary(), contracts: [], header: {}, terms: {}, utilities: [], groups: [], lanes: [], flows: [], acts: [] };
601
+ for (const c of head.children) {
602
+ if (c.key === "owner")
603
+ info.owner = c.value;
604
+ if (c.key === "crubal") {
605
+ info.crubal = Number(c.value);
606
+ info.crubalLine = c.line;
607
+ }
608
+ if (c.key === "extends") {
609
+ for (const e of c.value.split(",")) {
610
+ const [en = "", ev = ""] = e.trim().split(/\s+\//);
611
+ info.extends.push({ name: en.trim(), version: ev.trim(), line: c.line });
612
+ }
613
+ }
614
+ if (c.key === "prefixes")
615
+ for (const p of c.children)
616
+ if (p.key)
617
+ info.prefixes.set(p.key, { target: p.value, line: p.line });
618
+ if (c.key === "terms")
619
+ for (const t of c.children)
620
+ if (t.key)
621
+ info.terms[t.key] = t.value.trim();
622
+ if (c.key && !["owner", "crubal", "extends", "prefixes", "terms"].includes(c.key))
623
+ info.header[c.key] = c.value.trim();
624
+ }
625
+ for (const node of rest) {
626
+ if (node.key === "trust")
627
+ for (const t of node.children)
628
+ info.trust.push({ entry: t.text.trim(), line: t.line });
629
+ if (node.key === "utility") {
630
+ const u = readUtility(node);
631
+ if (info.utilities.some((x) => x.name === u.name))
632
+ throw new CrubalError(`the utility ${u.name} twice in one package`, node.line);
633
+ info.utilities.push(u);
634
+ }
635
+ if (node.key === "group") {
636
+ const g = readGroup(node);
637
+ if (info.groups.some((x) => x.name === g.name))
638
+ throw new CrubalError(`the group ${g.name} twice in one package`, node.line);
639
+ info.groups.push(g);
640
+ }
641
+ if (node.key === "lane") {
642
+ const s = readLane(node);
643
+ if (info.lanes.some((x) => x.name === s.name))
644
+ throw new CrubalError(`the lane ${s.name} twice in one package`, node.line);
645
+ info.lanes.push(s);
646
+ }
647
+ if (node.key === "flow") {
648
+ const f = readFlow(node);
649
+ if (info.flows.some((x) => x.name === f.name))
650
+ throw new CrubalError(`the flow ${f.name} twice in one package`, node.line);
651
+ info.flows.push(f);
652
+ }
653
+ if (node.key === "act") {
654
+ const a = readAct(node);
655
+ if (info.acts.some((x) => x.name === a.name))
656
+ throw new CrubalError(`the act ${a.name} twice in one package`, node.line);
657
+ info.acts.push(a);
658
+ }
659
+ }
660
+ // Definitions are everything after the header block.
661
+ const headerEnd = Math.max(start, ...head.children.flatMap(function deep(c) { return [c.line - 1, ...c.children.flatMap(deep)]; }));
662
+ const defs = text.split("\n").map((l, i) => (i > headerEnd ? l : "")).join("\n");
663
+ readDefinitions(defs, info.dict);
664
+ info.contracts = readContracts(defs).map((c) => c.name);
665
+ return info;
666
+ });
667
+ }
668
+ function sameDefinition(base, mine) {
669
+ if (base.type !== mine.type)
670
+ return "type";
671
+ if (base.pick !== mine.pick)
672
+ return "pick";
673
+ if ((base.unit ?? "") !== (mine.unit ?? ""))
674
+ return "unit";
675
+ const baseValues = (base.values ?? []).map((v) => v.value);
676
+ const mineValues = (mine.values ?? []).map((v) => v.value);
677
+ if (mine.values && baseValues.some((v) => !mineValues.includes(v)))
678
+ return "values";
679
+ return null;
680
+ }
681
+ /** Check every package in a file (11.1, 11.3, 11.4). Throws the first problem. */
682
+ export function checkPackages(source) {
683
+ // 11.2: a kind's vary step names a level of its kind and facets of this package (a key of another package
684
+ // carries its prefix and is checked where that package is resolved).
685
+ {
686
+ const d = readDefinitions(source);
687
+ for (const [level, keys] of d.vary) {
688
+ if (!d.levels.has(level))
689
+ throw new CrubalError(`vary names ${level}, which isn't a level`, d.varyLines.get(level));
690
+ for (const k of keys)
691
+ if (!k.includes(":") && !d.facets.has(k))
692
+ throw new CrubalError(`vary at ${level} names ${k}, which isn't a facet`, d.varyLines.get(level));
693
+ }
694
+ // Revision 35: a level's quantity is a number facet of this package.
695
+ for (const k of d.kinds.values())
696
+ for (const [level, facet] of Object.entries(k.shares ?? {})) {
697
+ const f = d.facets.get(facet);
698
+ if (!f && !facet.includes(":"))
699
+ throw new CrubalError(`shares at ${level} names ${facet}, which isn't a facet`, k.sharesLine);
700
+ if (f && f.type !== "number")
701
+ throw new CrubalError(`shares at ${level} names ${facet}, which isn't a number`, k.sharesLine);
702
+ }
703
+ }
704
+ const pkgs = readPackages(source);
705
+ const byName = new Map(pkgs.map((p) => [p.name, p]));
706
+ for (const p of pkgs) {
707
+ // Language versions (11.8): never above this reader's, and never extending a package above one's own.
708
+ if (!Number.isInteger(p.crubal) || p.crubal < 1)
709
+ throw new CrubalError(`${p.name}: the language version is a whole number`, p.crubalLine);
710
+ if (p.crubal > LANGUAGE)
711
+ throw new CrubalError(`${p.name} is written in CRUBAL ${p.crubal}; this reader knows ${LANGUAGE}`, p.crubalLine);
712
+ for (const e of p.extends) {
713
+ const base = byName.get(e.name);
714
+ if (base && base.crubal > p.crubal)
715
+ throw new CrubalError(`${p.name} (CRUBAL ${p.crubal}) extends ${e.name}, written in CRUBAL ${base.crubal}, which it couldn't read`, e.line);
716
+ }
717
+ for (const [prefix, { target, line }] of p.prefixes) {
718
+ if (prefix === "crubal")
719
+ throw new CrubalError("the prefix crubal is reserved for the core", line);
720
+ if (prefix === p.name && target !== `${p.owner}/${p.name}`)
721
+ throw new CrubalError(`${p.name} can't map its own name to something else`, line);
722
+ }
723
+ for (const { entry, line } of p.trust) {
724
+ if (entry === "person" || ORIGINS.has(entry))
725
+ continue;
726
+ const bare = entry.startsWith(`${p.name}:`) ? entry.slice(p.name.length + 1) : entry;
727
+ if (p.contracts.includes(bare))
728
+ continue;
729
+ if (!entry.includes(":") && entry.includes("."))
730
+ continue; // a party's domain
731
+ throw new CrubalError(`${entry} is not a contract of this package`, line);
732
+ }
733
+ for (const f of p.dict.facets.values()) {
734
+ const m = f.key.match(/^([a-z][a-z0-9-]*):(.+)$/);
735
+ if (!m || m[1] === "crubal")
736
+ continue;
737
+ const base = byName.get(m[1]);
738
+ if (!base || !p.extends.some((e) => e.name === base.name))
739
+ continue;
740
+ const original = base.dict.facets.get(m[2]);
741
+ if (!original)
742
+ continue;
743
+ const changed = sameDefinition(original, f);
744
+ if (changed)
745
+ throw new CrubalError(`${p.name} changes ${f.key}'s ${changed}; an extending package may only add to it`, f.line);
746
+ }
747
+ }
748
+ checkUtilities(source, pkgs);
749
+ checkLanes(source, pkgs);
750
+ checkFlows(source, pkgs);
751
+ checkActs(source, pkgs);
752
+ checkFormUtilities(source, pkgs);
753
+ return pkgs;
754
+ }
755
+ const AUDIENCE_RANK = { public: 0, member: 1, staff: 2, owner: 3 };
756
+ /**
757
+ * Lane blocks (12.10): a lane names its own package's view, the view's filters for its picks with
758
+ * real values of their facets, slots of the view's shapes for its card, its utility's acts for its presses,
759
+ * and serves nothing wider than its view shows. File-local, as the utility checks are.
760
+ */
761
+ function checkLanes(source, pkgs) {
762
+ if (!pkgs.some((p) => p.lanes.length))
763
+ return;
764
+ const { perms } = readAccess(source);
765
+ const dict = readDefinitions(source);
766
+ const views = readViews(source);
767
+ const known = (n) => perms.presets.has(n) || perms.relations.has(n) || AUDIENCES.has(n);
768
+ const item = (n) => perms.presets.has(n) || perms.menu.has(n) || perms.relations.has(n);
769
+ for (const p of pkgs) {
770
+ for (const s of p.lanes) {
771
+ const where = `the lane ${s.name}`;
772
+ const utility = s.utility ? p.utilities.find((u) => u.name === s.utility) : undefined;
773
+ if (s.utility && !utility)
774
+ throw new CrubalError(`${where} names the utility ${s.utility}, which this package doesn't declare`, s.line);
775
+ const acts = new Set((utility?.acts ?? []).map((a) => a.name));
776
+ for (const sv of s.serves) {
777
+ if (!known(sv.as))
778
+ throw new CrubalError(`${where} serves ${sv.as}, which isn't a preset, relation or audience here`, sv.line);
779
+ for (const i of sv.items ?? [])
780
+ if (!item(i))
781
+ throw new CrubalError(`${where} serves ${sv.as}(${i}): ${i} isn't a preset, menu item or relation`, sv.line);
782
+ }
783
+ const press = (pr, what) => {
784
+ if (!pr)
785
+ return;
786
+ if (pr.to === "page" || pr.to.startsWith("/"))
787
+ return;
788
+ if (!acts.has(pr.to))
789
+ throw new CrubalError(`${where}'s ${what} ${pr.word} -> ${pr.to}: ${pr.to} isn't an act of ${s.utility ?? "its utility"}`, pr.line);
790
+ };
791
+ press(s.home.press, "press");
792
+ if (s.serve) {
793
+ if (!/^[a-z][\w-]*$/.test(s.serve))
794
+ throw new CrubalError(`${where}'s serve is a lower-case word: ${s.serve}`, s.line);
795
+ if (s.group)
796
+ throw new CrubalError(`${where} groups by ${s.group}, but a lane the app serves has no view to group by`, s.line);
797
+ continue;
798
+ }
799
+ const view = views.views.get(s.view);
800
+ if (!view)
801
+ throw new CrubalError(`${where} names the view ${s.view}, which this package doesn't declare`, s.line);
802
+ // Revision 32: the group is one of the view's filters, whose buckets the row's cards stand in.
803
+ if (s.group && !view.filters.includes(s.group))
804
+ throw new CrubalError(`${where} groups by ${s.group}, which isn't a filter of ${view.name}`, s.line);
805
+ // Serves nothing wider than the view shows (12.4): an audience named must rank at or above the view's.
806
+ for (const sv of s.serves) {
807
+ const rank = AUDIENCE_RANK[sv.as];
808
+ if (rank !== undefined && rank < (AUDIENCE_RANK[view.show] ?? 0))
809
+ throw new CrubalError(`${where} serves ${sv.as}, wider than ${view.name} shows (${view.show})`, sv.line);
810
+ }
811
+ const pick = (pk, what) => {
812
+ if (!pk)
813
+ return;
814
+ if (!view.filters.includes(pk.filter))
815
+ throw new CrubalError(`${where}'s ${what} names ${pk.filter}, which isn't a filter of ${view.name}`, pk.line);
816
+ const f = views.filters.get(pk.filter);
817
+ const facet = f ? dict.facets.get(f.facet) : undefined;
818
+ if (facet?.values && !facet.values.some((x) => x.value === pk.value))
819
+ throw new CrubalError(`${where}'s ${what}: ${pk.value} is not a value of ${facet.key}`, pk.line);
820
+ };
821
+ if (s.step) {
822
+ // Revision 34: the step and every until is a marked filter of the lane's view; revision 38: every after too.
823
+ for (const [m, what] of [[s.step, "step"], ...(s.until ?? []).map((u) => [u, "until"]), ...(s.after ?? []).map((u) => [u, "after"])]) {
824
+ if (!view.filters.includes(m))
825
+ throw new CrubalError(`${where}'s ${what} names ${m}, which isn't a filter of ${view.name}`, s.line);
826
+ if (!views.filters.get(m)?.marked)
827
+ throw new CrubalError(`${where}'s ${what} names ${m}, which isn't a marked filter (buckets: marked)`, s.line);
828
+ }
829
+ }
830
+ else {
831
+ pick(s.pick, "pick");
832
+ if (s.done && s.done !== "viewed")
833
+ pick(s.done, "done");
834
+ }
835
+ for (const ch of s.home.chips)
836
+ if (!view.filters.includes(ch))
837
+ throw new CrubalError(`${where}'s chips name ${ch}, which isn't a filter of ${view.name}`, s.home.line);
838
+ const slots = new Set(["id"]);
839
+ for (const sh of view.shapes)
840
+ for (const sl of views.shapes.get(sh)?.slots ?? [])
841
+ slots.add(sl.to);
842
+ const slot = (k, what, line) => {
843
+ if (k !== undefined && !slots.has(k))
844
+ throw new CrubalError(`${where}'s ${what} names ${k}, which isn't a slot of ${view.name}'s shape`, line);
845
+ };
846
+ if (s.home.figure && s.home.figure.of !== "count")
847
+ slot(s.home.figure.slot, "figure", s.home.line);
848
+ const card = s.card;
849
+ if (card) {
850
+ for (const k of [...card.name, ...card.sub, ...card.lines])
851
+ slot(k, "card", card.line);
852
+ slot(card.state, "state", card.line);
853
+ slot(card.moment, "moment", card.line);
854
+ slot(card.figure, "figure", card.line);
855
+ press(card.primary, "primary");
856
+ press(card.quiet, "quiet");
857
+ for (const q of card.quick)
858
+ press(q, "quick");
859
+ }
860
+ }
861
+ }
862
+ }
863
+ /**
864
+ * Utility blocks (11.1): what a utility `serves` is a preset, a relation or an audience the file declares,
865
+ * and the items in parentheses are presets, menu items or relations; a `setting` in `setup` is a facet the
866
+ * file defines. Packages the file doesn't hold are named by prefix and checked where they are resolved.
867
+ */
868
+ function checkUtilities(source, pkgs) {
869
+ if (!pkgs.some((p) => p.utilities.length))
870
+ return;
871
+ const { perms } = readAccess(source);
872
+ const dict = readDefinitions(source);
873
+ const known = (n) => perms.presets.has(n) || perms.relations.has(n) || AUDIENCES.has(n);
874
+ const item = (n) => perms.presets.has(n) || perms.menu.has(n) || perms.relations.has(n);
875
+ for (const p of pkgs) {
876
+ for (const u of p.utilities) {
877
+ for (const s of u.serves) {
878
+ if (!known(s.as))
879
+ throw new CrubalError(`${u.name} serves ${s.as}, which isn't a preset, relation or audience here`, s.line);
880
+ for (const i of s.items ?? [])
881
+ if (!item(i))
882
+ throw new CrubalError(`${u.name} serves ${s.as}(${i}): ${i} isn't a preset, menu item or relation here`, s.line);
883
+ }
884
+ for (const s of u.setup)
885
+ if ("setting" in s && !s.setting.includes(":") && !dict.facets.has(s.setting))
886
+ throw new CrubalError(`${u.name} needs the setting ${s.setting}, which isn't a facet here`, s.line);
887
+ if (u.needs.some((n) => n.name === u.name))
888
+ throw new CrubalError(`${u.name} needs itself`, u.line);
889
+ }
890
+ }
891
+ }
892
+ /**
893
+ * Flow blocks (12.11): a flow names its own package's utility and serves what that package knows; each
894
+ * stop is a lane of the package (with an act of the utility when one is named) or a form contract of the
895
+ * package (with a level of the package's kinds when `of` is named); its done pick is a declared filter
896
+ * with a real value. Revision 23: a package that extends others may walk their lanes and forms and name
897
+ * their utility, presets and filters (a place's own package carrying the flow it drew from a preset): what
898
+ * the file-local check cannot see it leaves to `checkFlowsInForce`, over the packages in force together.
899
+ */
900
+ function checkFlowList(flows, env) {
901
+ const { perms, dict, strict } = env;
902
+ const known = (n) => perms.presets.has(n) || perms.relations.has(n) || AUDIENCES.has(n);
903
+ const item = (n) => perms.presets.has(n) || perms.menu.has(n) || perms.relations.has(n);
904
+ const laneNames = new Set(env.lanes.map((l) => l.name));
905
+ const { here } = env;
906
+ const lacks = here === "in force here" ? "isn't in force here" : "this package doesn't declare";
907
+ for (const f of flows) {
908
+ const where = `the flow ${f.name}`;
909
+ const utility = f.utility ? env.utilities.find((u) => u.name === f.utility) : undefined;
910
+ if (f.utility && !utility && strict)
911
+ throw new CrubalError(`${where} names the utility ${f.utility}, which ${lacks}`, f.line);
912
+ const acts = utility ? new Set(utility.acts.map((a) => a.name)) : f.utility ? undefined : new Set();
913
+ for (const sv of f.serves) {
914
+ if (!known(sv.as) && strict)
915
+ throw new CrubalError(`${where} serves ${sv.as}, which isn't a preset, relation or audience here`, sv.line);
916
+ for (const i of sv.items ?? [])
917
+ if (!item(i) && strict)
918
+ throw new CrubalError(`${where} serves ${sv.as}(${i}): ${i} isn't a preset, menu item or relation`, sv.line);
919
+ }
920
+ // Revision 23: the context is kinds (or levels) in force; a flow never replaces itself.
921
+ for (const k of f.context)
922
+ if (!dict.kinds.has(k) && !dict.levels.has(k) && strict)
923
+ throw new CrubalError(`${where}'s context names ${k}, which isn't a kind or level ${here}`, f.line);
924
+ if (f.replaces === f.name)
925
+ throw new CrubalError(`${where} replaces itself`, f.line);
926
+ // Revision 42: a closed set names three of the flow's own lane stops, each with an act but the rest's (which
927
+ // may have none), the start before the finish; its cancel is an act of the flow's utility.
928
+ if (f.closed) {
929
+ const cl = f.closed;
930
+ const at = (n) => f.stops.findIndex((x) => x.name === n && x.of === undefined);
931
+ for (const [word, n] of [["starts at", cl.start], ["finishes at", cl.finish], ["is over", cl.rest]])
932
+ if (at(n) < 0)
933
+ throw new CrubalError(`${where} is closed and ${word} ${n}, which isn't a lane stop of it`, cl.line);
934
+ if (new Set([cl.start, cl.finish, cl.rest]).size < 3)
935
+ throw new CrubalError(`${where} is closed: its start, its finish and its rest are three stops`, cl.line);
936
+ if (at(cl.start) > at(cl.finish))
937
+ throw new CrubalError(`${where} is closed and finishes at ${cl.finish} before it starts at ${cl.start}`, cl.line);
938
+ for (const n of [cl.start, cl.finish])
939
+ if (f.stops[at(n)]?.act === undefined)
940
+ throw new CrubalError(`${where} is closed and its stop ${n} names no act: a start and a finish are each a stamp`, cl.line);
941
+ if (cl.cancel && acts && !acts.has(cl.cancel))
942
+ throw new CrubalError(`${where} is closed and cancels by ${cl.cancel}, which isn't an act of ${f.utility ?? "its utility"}`, cl.line);
943
+ }
944
+ let deferred = false;
945
+ for (const st of f.stops) {
946
+ const isLane = laneNames.has(st.name);
947
+ const isForm = env.forms.has(st.name);
948
+ if (!isLane && !isForm && !strict) {
949
+ deferred = true;
950
+ continue;
951
+ }
952
+ if (st.act !== undefined && !isLane)
953
+ throw new CrubalError(`${where}'s stop ${st.name} -> ${st.act}: ${st.name} isn't a lane ${here}`, st.line);
954
+ if (st.of !== undefined && !isForm)
955
+ throw new CrubalError(`${where}'s stop ${st.name} of ${st.of}: ${st.name} isn't a form ${here}`, st.line);
956
+ if (!isLane && !isForm)
957
+ throw new CrubalError(`${where}'s stop ${st.name} is neither a lane nor a form ${here}`, st.line);
958
+ if (st.act !== undefined && acts && !acts.has(st.act))
959
+ throw new CrubalError(`${where}'s stop ${st.name} -> ${st.act}: ${st.act} isn't an act of ${f.utility ?? "its utility"}`, st.line);
960
+ if (st.of !== undefined && !dict.levels.has(st.of) && !dict.kinds.has(st.of) && strict)
961
+ throw new CrubalError(`${where}'s stop ${st.name} of ${st.of}: ${st.of} isn't a level or kind ${here}`, st.line);
962
+ for (const w of st.with ?? []) {
963
+ const facet = dict.facets.get(w.facet.split("::").pop());
964
+ if (!facet && strict)
965
+ throw new CrubalError(`${where}'s stop ${st.name} locks ${w.facet}, which isn't a facet ${here}`, st.line);
966
+ }
967
+ // Revision 48: an ask's and an offer's act is the flow's utility's or a named one's; an ask's when reads
968
+ // the record touched alone.
969
+ for (const q of [...(st.asks ?? []).map((x) => ({ ...x, what: `asks ${x.name}` })), ...(st.offers ?? []).map((x) => ({ ...x, what: "offers", line: st.line, when: undefined }))]) {
970
+ const what = `${where}'s stop ${st.name} ${q.what}`;
971
+ const u = q.utility ? env.utilities.find((x) => x.name === q.utility) : utility;
972
+ if (q.utility && !u && strict)
973
+ throw new CrubalError(`${what}: the utility ${q.utility} ${lacks}`, q.line);
974
+ if (u && !u.acts.some((x) => x.name === q.act))
975
+ throw new CrubalError(`${what}: ${q.act} isn't among ${u.name}'s acts`, q.line);
976
+ for (const t of termsOf(q.when)) {
977
+ if ("count" in t)
978
+ throw new CrubalError(`${what}: a link's when reads the record touched, not a count`, q.line);
979
+ if (!("ref" in t))
980
+ continue;
981
+ if (!("record" in t.ref) || !t.ref.record)
982
+ throw new CrubalError(`${what}: a link's when reads record.<facet>, the record touched`, q.line);
983
+ if (!dict.facets.get(t.ref.record.split("::").pop()) && strict)
984
+ throw new CrubalError(`${what}: ${t.ref.record} isn't a facet ${here}`, q.line);
985
+ }
986
+ // Revision 51: an ask's words may say a value of the record touched, `{record.<facet>}`.
987
+ for (const m of ("words" in q && typeof q.words === "string" ? q.words : "").matchAll(/\{([^}]*)\}/g)) {
988
+ const f = m[1].match(/^record\.([\w:]+)$/);
989
+ if (!f)
990
+ throw new CrubalError(`${what}: its words say {record.<facet>}, a value of the record touched, not {${m[1]}}`, q.line);
991
+ if (!dict.facets.get(f[1].split("::").pop()) && strict)
992
+ throw new CrubalError(`${what}: ${f[1]} isn't a facet ${here}`, q.line);
993
+ }
994
+ }
995
+ // Revision 41: a case's flag names a lane and a link facet to the stop's records; its presses name acts of
996
+ // the flow's utility, or another utility's by its name. What this file cannot see waits for the check in force.
997
+ for (const cs of st.cases ?? []) {
998
+ const what = `${where}'s stop ${st.name}, ${cs.kind === "flag" ? `the flag ${cs.name}` : "the stranger"}`;
999
+ if (cs.when) {
1000
+ if (!laneNames.has(cs.when.lane) && strict)
1001
+ throw new CrubalError(`${what}: ${cs.when.lane} isn't a lane ${here}`, cs.line);
1002
+ const facet = dict.facets.get(cs.when.facet.split("::").pop());
1003
+ if (!facet && strict)
1004
+ throw new CrubalError(`${what}: ${cs.when.facet} isn't a facet ${here}`, cs.line);
1005
+ if (facet && facet.type !== "link")
1006
+ throw new CrubalError(`${what}: ${cs.when.facet} isn't a link, so no record is reached by it`, cs.line);
1007
+ }
1008
+ for (const pr of [cs.yes, cs.no, ...cs.or])
1009
+ for (const r of pr.runs) {
1010
+ const u = r.utility ? env.utilities.find((x) => x.name === r.utility) : utility;
1011
+ if (r.utility && !u) {
1012
+ if (strict)
1013
+ throw new CrubalError(`${what}: the press ${pr.word} names the utility ${r.utility}, which ${lacks}`, cs.line);
1014
+ continue;
1015
+ }
1016
+ if (u && !u.acts.some((a) => a.name === r.act))
1017
+ throw new CrubalError(`${what}: the press ${pr.word} runs ${r.act}, which isn't an act of ${u.name}`, cs.line);
1018
+ }
1019
+ }
1020
+ }
1021
+ if (f.done) {
1022
+ const flt = env.filters.get(f.done.filter);
1023
+ if (!flt && strict)
1024
+ throw new CrubalError(`${where}'s done names ${f.done.filter}, which isn't a filter ${here}`, f.done.line);
1025
+ const facet = flt ? dict.facets.get(flt.facet) : undefined;
1026
+ if (f.done.mark) {
1027
+ if (flt && !flt.marked)
1028
+ throw new CrubalError(`${where}'s done names ${f.done.filter}, which isn't a marked filter (buckets: marked)`, f.done.line);
1029
+ }
1030
+ else if (facet?.values && !facet.values.some((x) => x.value === f.done?.value))
1031
+ throw new CrubalError(`${where}'s done: ${f.done.value} is not a value of ${facet.key}`, f.done.line);
1032
+ }
1033
+ // The chain (12.11, revision 22; revision 40: read, not required): a list lane is a stop only with
1034
+ // an act (revision 37), and the
1035
+ // flow's done is its last lane's (its pick when that lane holds what is finished). A block between two
1036
+ // lanes leaves the chain as it is. A chain with a stop the file-local check could not see waits for the
1037
+ // check in force.
1038
+ if (deferred)
1039
+ continue;
1040
+ const show = (pk) => `${pk.filter} = ${pk.value}`;
1041
+ const same = (a, b) => a.filter === b.filter && a.value === b.value;
1042
+ let prev;
1043
+ let last;
1044
+ for (const st of f.stops) {
1045
+ const l = env.lanes.find((x) => x.name === st.name);
1046
+ if (!l)
1047
+ continue;
1048
+ last = l;
1049
+ // A step stop (revision 34) chains with nothing: it may stand anywhere, and the state stops chain across it.
1050
+ if (l.step)
1051
+ continue;
1052
+ // A list stop (revision 37): a list holds no state, so it is a stop only where the stop names the act that is
1053
+ // its work; like a step stop it chains with nothing, and it stamps nothing.
1054
+ if (!l.pick) {
1055
+ if (!st.act)
1056
+ throw new CrubalError(`${where}'s stop ${l.name} is a list: it holds no state, so it is a stop only with an act (${l.name} -> <act>)`, st.line);
1057
+ continue;
1058
+ }
1059
+ // Revision 40: how two links join is read, never refused (flowJoins): a record passes where the first's
1060
+ // done is the second's pick; where it is not, the two stand together by what the flow holds, or by their
1061
+ // order alone.
1062
+ prev = l;
1063
+ }
1064
+ if (f.done && prev && last === prev) {
1065
+ const end = prev.done && prev.done !== "viewed" ? prev.done : prev.pick;
1066
+ if (end && !same(f.done, end))
1067
+ throw new CrubalError(`${where}'s done is ${show(f.done)}, but its last lane ${prev.name} leaves a record at ${show(end)}`, f.done.line);
1068
+ }
1069
+ }
1070
+ }
1071
+ /** The file-local flow checks: strict for a package that extends nothing, deferring what it cannot see otherwise. */
1072
+ function checkFlows(source, pkgs) {
1073
+ if (!pkgs.some((p) => p.flows.length))
1074
+ return;
1075
+ const { perms } = readAccess(source);
1076
+ const dict = readDefinitions(source);
1077
+ const views = readViews(source);
1078
+ const forms = new Set(readContracts(source).filter((c) => c.kind === "form").map((c) => c.name));
1079
+ for (const p of pkgs)
1080
+ checkFlowList(p.flows, { lanes: p.lanes, forms, utilities: p.utilities, filters: views.filters, dict, perms, strict: p.extends.length === 0, here: "of this package" });
1081
+ }
1082
+ /**
1083
+ * The flow checks over the packages in force together (11.4, revision 23): everything a file-local check
1084
+ * deferred because the package extends others, refused as the publish would have; run where the
1085
+ * permissions are checked in force (at install, and on a trial definition).
1086
+ */
1087
+ export function checkFlowsInForce(p) {
1088
+ if (!p.info.flows.length)
1089
+ return;
1090
+ checkFlowList(p.info.flows, { lanes: p.info.lanes, forms: new Set(p.contracts.filter((c) => c.kind === "form").map((c) => c.name)), utilities: p.info.utilities, filters: p.views.filters, dict: p.dict, perms: p.perms, strict: true, here: "in force here" });
1091
+ }
1092
+ /**
1093
+ * A form's utility and act (7.7, revision 16): a form names a utility its package declares, an act that
1094
+ * utility provides, and no two forms name one act of a utility. File-local, as the lane checks are.
1095
+ */
1096
+ function checkFormUtilities(source, pkgs) {
1097
+ const forms = readContracts(source).filter((c) => c.kind === "form" && c.parts.utility !== undefined);
1098
+ if (!forms.length)
1099
+ return;
1100
+ const utilities = new Map(pkgs.flatMap((p) => p.utilities).map((u) => [u.name, u]));
1101
+ const taken = new Map();
1102
+ for (const c of forms) {
1103
+ const name = c.parts.utility;
1104
+ const u = utilities.get(name);
1105
+ if (!u)
1106
+ throw new CrubalError(`the form ${c.name} names the utility ${name}, which this package doesn't declare`, c.partLines.utility ?? c.line);
1107
+ const act = c.parts.act;
1108
+ if (act === undefined)
1109
+ continue;
1110
+ if (!u.acts.some((a) => a.name === act))
1111
+ throw new CrubalError(`the form ${c.name} names the act ${act}, which ${name} doesn't provide`, c.partLines.act ?? c.line);
1112
+ const key = `${name}/${act}`;
1113
+ const was = taken.get(key);
1114
+ if (was)
1115
+ throw new CrubalError(`the forms ${was} and ${c.name} both name the act ${act} of ${name}: one form per act`, c.partLines.act ?? c.line);
1116
+ taken.set(key, c.name);
1117
+ }
1118
+ }
1119
+ /** The file-local act checks (15): strict for a package that extends nothing, deferring what it cannot see otherwise. */
1120
+ function checkActs(source, pkgs) {
1121
+ if (!pkgs.some((p) => p.acts.length))
1122
+ return;
1123
+ const dict = readDefinitions(source);
1124
+ for (const p of pkgs)
1125
+ checkActList(p.acts, {
1126
+ utilities: p.utilities,
1127
+ levels: new Set(dict.levels.keys()),
1128
+ kinds: new Set(dict.kinds.keys()),
1129
+ facets: new Set(dict.facets.keys()),
1130
+ facetOf: (k) => dict.facets.get(k),
1131
+ aspects: aspectsOf(dict),
1132
+ shares: sharesOf(dict),
1133
+ strict: p.extends.length === 0,
1134
+ here: "of this package",
1135
+ });
1136
+ }
1137
+ /** The act checks over the packages in force together (11.4): what a file-local check deferred. */
1138
+ export function checkActsInForce(p) {
1139
+ if (!p.info.acts.length)
1140
+ return;
1141
+ checkActList(p.info.acts, {
1142
+ utilities: p.info.utilities,
1143
+ levels: new Set(p.dict.levels.keys()),
1144
+ kinds: new Set(p.dict.kinds.keys()),
1145
+ facets: new Set(p.dict.facets.keys()),
1146
+ facetOf: (k) => p.dict.facets.get(k),
1147
+ aspects: aspectsOf(p.dict),
1148
+ shares: sharesOf(p.dict),
1149
+ inertTelling: true,
1150
+ strict: true,
1151
+ here: "in force here",
1152
+ });
1153
+ }
1154
+ /** Every aspect the kinds declare under `follow:` (11.2, revision 31), which an act's `tells:` may name. */
1155
+ /** Level → the facet that is its quantity, over every kind's `shares:` (11.2, revision 35). */
1156
+ export const sharesOf = (dict) => new Map([...dict.kinds.values()].flatMap((k) => Object.entries(k.shares ?? {})));
1157
+ const aspectsOf = (dict) => new Set([...dict.kinds.values()].flatMap((k) => Object.values(k.follow ?? {}).flat()));
1158
+ //# sourceMappingURL=packages.js.map