@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.
- package/LICENSE +202 -0
- package/README.md +97 -2
- package/dist/bin/crubal.d.ts +2 -0
- package/dist/bin/crubal.js +103 -0
- package/dist/bin/crubal.js.map +1 -0
- package/dist/src/access.d.ts +149 -0
- package/dist/src/access.js +584 -0
- package/dist/src/access.js.map +1 -0
- package/dist/src/acts.d.ts +531 -0
- package/dist/src/acts.js +1466 -0
- package/dist/src/acts.js.map +1 -0
- package/dist/src/address.d.ts +29 -0
- package/dist/src/address.js +59 -0
- package/dist/src/address.js.map +1 -0
- package/dist/src/arrival.d.ts +55 -0
- package/dist/src/arrival.js +127 -0
- package/dist/src/arrival.js.map +1 -0
- package/dist/src/browser.d.ts +10 -0
- package/dist/src/browser.js +13 -0
- package/dist/src/browser.js.map +1 -0
- package/dist/src/bundle.d.ts +74 -0
- package/dist/src/bundle.js +1108 -0
- package/dist/src/bundle.js.map +1 -0
- package/dist/src/canonical.d.ts +6 -0
- package/dist/src/canonical.js +47 -0
- package/dist/src/canonical.js.map +1 -0
- package/dist/src/carriers.d.ts +7 -0
- package/dist/src/carriers.js +33 -0
- package/dist/src/carriers.js.map +1 -0
- package/dist/src/conditions.d.ts +28 -0
- package/dist/src/conditions.js +227 -0
- package/dist/src/conditions.js.map +1 -0
- package/dist/src/corpus.d.ts +8 -0
- package/dist/src/corpus.js +1207 -0
- package/dist/src/corpus.js.map +1 -0
- package/dist/src/defs.d.ts +174 -0
- package/dist/src/defs.js +690 -0
- package/dist/src/defs.js.map +1 -0
- package/dist/src/dictionary.d.ts +77 -0
- package/dist/src/dictionary.js +629 -0
- package/dist/src/dictionary.js.map +1 -0
- package/dist/src/exchange.d.ts +259 -0
- package/dist/src/exchange.js +1088 -0
- package/dist/src/exchange.js.map +1 -0
- package/dist/src/forms.d.ts +16 -0
- package/dist/src/forms.js +181 -0
- package/dist/src/forms.js.map +1 -0
- package/dist/src/index.d.ts +32 -0
- package/dist/src/index.js +34 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/lex.d.ts +21 -0
- package/dist/src/lex.js +142 -0
- package/dist/src/lex.js.map +1 -0
- package/dist/src/lifecycle.d.ts +92 -0
- package/dist/src/lifecycle.js +451 -0
- package/dist/src/lifecycle.js.map +1 -0
- package/dist/src/log.d.ts +91 -0
- package/dist/src/log.js +629 -0
- package/dist/src/log.js.map +1 -0
- package/dist/src/migrate.d.ts +129 -0
- package/dist/src/migrate.js +415 -0
- package/dist/src/migrate.js.map +1 -0
- package/dist/src/model.d.ts +81 -0
- package/dist/src/model.js +188 -0
- package/dist/src/model.js.map +1 -0
- package/dist/src/packages.d.ts +372 -0
- package/dist/src/packages.js +1158 -0
- package/dist/src/packages.js.map +1 -0
- package/dist/src/print-text.d.ts +7 -0
- package/dist/src/print-text.js +223 -0
- package/dist/src/print-text.js.map +1 -0
- package/dist/src/publish.d.ts +27 -0
- package/dist/src/publish.js +279 -0
- package/dist/src/publish.js.map +1 -0
- package/dist/src/read-text.d.ts +10 -0
- package/dist/src/read-text.js +400 -0
- package/dist/src/read-text.js.map +1 -0
- package/dist/src/records.d.ts +32 -0
- package/dist/src/records.js +104 -0
- package/dist/src/records.js.map +1 -0
- package/dist/src/review.d.ts +22 -0
- package/dist/src/review.js +198 -0
- package/dist/src/review.js.map +1 -0
- package/dist/src/rules.d.ts +101 -0
- package/dist/src/rules.js +670 -0
- package/dist/src/rules.js.map +1 -0
- package/dist/src/schedule.d.ts +24 -0
- package/dist/src/schedule.js +126 -0
- package/dist/src/schedule.js.map +1 -0
- package/dist/src/std-packages.d.ts +9 -0
- package/dist/src/std-packages.js +268 -0
- package/dist/src/std-packages.js.map +1 -0
- package/dist/src/store.d.ts +191 -0
- package/dist/src/store.js +671 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/surface.d.ts +47 -0
- package/dist/src/surface.js +92 -0
- package/dist/src/surface.js.map +1 -0
- package/dist/src/tree.d.ts +35 -0
- package/dist/src/tree.js +159 -0
- package/dist/src/tree.js.map +1 -0
- package/dist/src/units-table.d.ts +1 -0
- package/dist/src/units-table.js +200 -0
- package/dist/src/units-table.js.map +1 -0
- package/dist/src/units.d.ts +42 -0
- package/dist/src/units.js +98 -0
- package/dist/src/units.js.map +1 -0
- package/dist/src/versions.d.ts +10 -0
- package/dist/src/versions.js +27 -0
- package/dist/src/versions.js.map +1 -0
- package/dist/src/views.d.ts +372 -0
- package/dist/src/views.js +1170 -0
- package/dist/src/views.js.map +1 -0
- package/package.json +60 -4
|
@@ -0,0 +1,1170 @@
|
|
|
1
|
+
// views.ts: the Views level (spec chapter 12). Shapes map facets into display slots like a send
|
|
2
|
+
// contract's writes; views select records, curate, order and page them; filters are sub-indexes whose
|
|
3
|
+
// counts follow the other picks; audiences and show rules decide visibility, and roles narrow an audience;
|
|
4
|
+
// a view's read set decides which projection rows go stale.
|
|
5
|
+
import { serialize } from "./canonical.js";
|
|
6
|
+
import { evaluate, parseCondition } from "./conditions.js";
|
|
7
|
+
import { facetOf, leafOf, linkStep, rowStep } from "./address.js";
|
|
8
|
+
export { facetOf, leafOf } from "./address.js";
|
|
9
|
+
import { splitTop } from "./lex.js";
|
|
10
|
+
import { MemoryRecords } from "./records.js";
|
|
11
|
+
import { Engine } from "./rules.js";
|
|
12
|
+
import { CrubalError, readTree } from "./tree.js";
|
|
13
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
14
|
+
const unq = (s) => (s.trim().startsWith('"') ? JSON.parse(s.trim()) : s.trim());
|
|
15
|
+
export const AUDIENCES = ["public", "member", "staff", "owner"];
|
|
16
|
+
const rankOf = (a) => {
|
|
17
|
+
const i = AUDIENCES.indexOf(a);
|
|
18
|
+
return i < 0 ? AUDIENCES.length : i;
|
|
19
|
+
};
|
|
20
|
+
/** The brand slots a print's field may draw from the place that prints it (12.12). */
|
|
21
|
+
export const PRINT_PLACE_SLOTS = ["name", "mark", "primary", "accent", "words"];
|
|
22
|
+
export const PERIODS = ["day", "week", "month", "quarter", "year"];
|
|
23
|
+
/** The two buckets of a filter over a mark (12.3, revision 34): no real value, and one. */
|
|
24
|
+
export const MARK_OPEN = "open";
|
|
25
|
+
export const MARK_DONE = "done";
|
|
26
|
+
/**
|
|
27
|
+
* The period a date or moment falls in, named: a day `2026-10-21`, a week `2026-W43` (ISO, Monday first), a
|
|
28
|
+
* month `2026-10`, a quarter `2026-Q4`, a year `2026`; undefined for a value with no date in it.
|
|
29
|
+
*/
|
|
30
|
+
export function periodOf(value, period) {
|
|
31
|
+
const m = value.match(/^(\d{4})-(\d{2})-(\d{2})/) ?? value.match(/^(\d{4})-(\d{2})$/) ?? value.match(/^(\d{4})$/);
|
|
32
|
+
if (!m)
|
|
33
|
+
return undefined;
|
|
34
|
+
const y = Number(m[1]);
|
|
35
|
+
const mo = m[2] !== undefined ? Number(m[2]) : undefined;
|
|
36
|
+
const d = m[3] !== undefined ? Number(m[3]) : undefined;
|
|
37
|
+
if (period === "year")
|
|
38
|
+
return String(y);
|
|
39
|
+
if (mo === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (period === "month")
|
|
42
|
+
return `${y}-${String(mo).padStart(2, "0")}`;
|
|
43
|
+
if (period === "quarter")
|
|
44
|
+
return `${y}-Q${Math.floor((mo - 1) / 3) + 1}`;
|
|
45
|
+
if (d === undefined)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (period === "day")
|
|
48
|
+
return `${y}-${String(mo).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
|
|
49
|
+
// ISO week: the week with the year's first Thursday is week 1.
|
|
50
|
+
const date = new Date(Date.UTC(y, mo - 1, d));
|
|
51
|
+
const dow = date.getUTCDay() || 7;
|
|
52
|
+
date.setUTCDate(date.getUTCDate() + 4 - dow);
|
|
53
|
+
const jan1 = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
|
|
54
|
+
const week = Math.ceil(((date.getTime() - jan1.getTime()) / 86_400_000 + 1) / 7);
|
|
55
|
+
return `${date.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
|
56
|
+
}
|
|
57
|
+
/** The member maps of a view set, for merging one set onto another. */
|
|
58
|
+
export const VIEW_SET_KEYS = ["shapes", "displays", "prints", "filters", "views", "roles", "shown", "shownFor"];
|
|
59
|
+
/** An empty view set. */
|
|
60
|
+
export const emptyViewSet = () => ({ shapes: new Map(), displays: new Map(), prints: new Map(), filters: new Map(), views: new Map(), roles: new Map(), shown: new Map(), shownFor: new Map() });
|
|
61
|
+
/** The words of an element line, a quoted literal kept whole. */
|
|
62
|
+
const printTokens = (text) => text.match(/"(?:[^"\\]|\\.)*"|\S+/g) ?? [];
|
|
63
|
+
/** A fraction of the art, 0 to 1, as an element writes it. */
|
|
64
|
+
const fraction = (tok, what, line) => {
|
|
65
|
+
const n = Number(tok);
|
|
66
|
+
if (tok === undefined || !Number.isFinite(n) || n < 0 || n > 1)
|
|
67
|
+
throw new CrubalError(`${what} is a fraction of the art, 0 to 1, not ${tok ?? "nothing"}`, line);
|
|
68
|
+
return n;
|
|
69
|
+
};
|
|
70
|
+
const printBox = (t, at, what, line) => ({ x: fraction(t[at], `${what}'s x`, line), y: fraction(t[at + 1], `${what}'s y`, line), w: fraction(t[at + 2], `${what}'s width`, line), h: fraction(t[at + 3], `${what}'s height`, line) });
|
|
71
|
+
/** One element line of a print (12.12). */
|
|
72
|
+
function readPrintElement(text, line) {
|
|
73
|
+
const t = printTokens(text);
|
|
74
|
+
const type = t[0];
|
|
75
|
+
const rest = (from) => {
|
|
76
|
+
// The options after the positional words: `anchor middle`, `clip x y w h`, `text`, `rotate cw`.
|
|
77
|
+
const out = new Map();
|
|
78
|
+
let i = from;
|
|
79
|
+
while (i < t.length) {
|
|
80
|
+
const k = t[i];
|
|
81
|
+
const n = k === "clip" ? 4 : k === "text" ? 0 : 1;
|
|
82
|
+
out.set(k, t.slice(i + 1, i + 1 + n));
|
|
83
|
+
i += 1 + n;
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
};
|
|
87
|
+
const one = (o, k, allowed) => {
|
|
88
|
+
const v = o.get(k)?.[0];
|
|
89
|
+
if (v !== undefined && !allowed.includes(v))
|
|
90
|
+
throw new CrubalError(`${k} is one of ${allowed.join(", ")}, not ${v}`, line);
|
|
91
|
+
return v;
|
|
92
|
+
};
|
|
93
|
+
if (type === "rect") {
|
|
94
|
+
const o = rest(5);
|
|
95
|
+
const fill = one(o, "fill", ["white", "black", "none"]) ?? "white";
|
|
96
|
+
const stroke = o.has("stroke") ? Number(o.get("stroke")?.[0]) : undefined;
|
|
97
|
+
if (stroke !== undefined && !(Number.isFinite(stroke) && stroke > 0))
|
|
98
|
+
throw new CrubalError(`a rect's stroke is a width in dots, not ${o.get("stroke")?.[0]}`, line);
|
|
99
|
+
return { type, box: printBox(t, 1, "the rect", line), fill: fill, ...(stroke !== undefined ? { stroke } : {}), line };
|
|
100
|
+
}
|
|
101
|
+
if (type === "barcode" || type === "qr") {
|
|
102
|
+
const field = t[5];
|
|
103
|
+
if (!field || field.startsWith('"'))
|
|
104
|
+
throw new CrubalError(`a ${type} is "${type} x y w h <field>"`, line);
|
|
105
|
+
const o = rest(6);
|
|
106
|
+
if (type === "barcode") {
|
|
107
|
+
const rotate = one(o, "rotate", ["cw", "ccw"]);
|
|
108
|
+
return { type, box: printBox(t, 1, "the barcode", line), field, ...(rotate ? { rotate: rotate } : {}), ...(o.has("text") ? { text: true } : {}), line };
|
|
109
|
+
}
|
|
110
|
+
const gravity = one(o, "gravity", ["bottom-right", "top-left"]);
|
|
111
|
+
return { type, box: printBox(t, 1, "the qr", line), field, ...(gravity ? { gravity: gravity } : {}), line };
|
|
112
|
+
}
|
|
113
|
+
if (type === "image") {
|
|
114
|
+
const field = t[5];
|
|
115
|
+
if (!field || field.startsWith('"'))
|
|
116
|
+
throw new CrubalError(`an image is "image x y w h <field>"`, line);
|
|
117
|
+
if (t.length > 6)
|
|
118
|
+
throw new CrubalError(`an image takes no options after its field: ${t.slice(6).join(" ")}`, line);
|
|
119
|
+
return { type, box: printBox(t, 1, "the image", line), field, line };
|
|
120
|
+
}
|
|
121
|
+
if (type === "text") {
|
|
122
|
+
const src = t[4];
|
|
123
|
+
if (!src)
|
|
124
|
+
throw new CrubalError(`a text is "text x y size <field or \"words\">"`, line);
|
|
125
|
+
const source = src.startsWith('"') ? { literal: JSON.parse(src) } : { field: src };
|
|
126
|
+
const o = rest(5);
|
|
127
|
+
const anchor = one(o, "anchor", ["start", "middle", "end"]);
|
|
128
|
+
const weight = one(o, "weight", ["bold"]);
|
|
129
|
+
const rotate = one(o, "rotate", ["cw", "ccw", "180"]);
|
|
130
|
+
const clipT = o.get("clip");
|
|
131
|
+
const clip = clipT ? printBox(clipT, 0, "the text's clip", line) : undefined;
|
|
132
|
+
const linesT = o.get("lines")?.[0];
|
|
133
|
+
const lines = linesT === undefined ? undefined : Number(linesT);
|
|
134
|
+
if (lines !== undefined && !(Number.isInteger(lines) && lines >= 2 && lines <= 9))
|
|
135
|
+
throw new CrubalError(`lines is a count from 2 to 9, not ${linesT}`, line);
|
|
136
|
+
return { type, x: fraction(t[1], "the text's x", line), y: fraction(t[2], "the text's y", line), size: fraction(t[3], "the text's size", line), source, ...(anchor ? { anchor: anchor } : {}), ...(weight ? { weight: "bold" } : {}), ...(clip ? { clip } : {}), ...(rotate ? { rotate: rotate } : {}), ...(lines !== undefined ? { lines } : {}), line };
|
|
137
|
+
}
|
|
138
|
+
throw new CrubalError(`an element is a rect, a barcode, a qr, a text or an image, not ${type ?? "nothing"}`, line);
|
|
139
|
+
}
|
|
140
|
+
/** The field names a print's text draws: its field, or the `{field}` places of its literal. */
|
|
141
|
+
export const printSourceFields = (s) => ("field" in s ? [s.field] : [...s.literal.matchAll(/\{(\w+)\}/g)].map((m) => m[1]));
|
|
142
|
+
/** Read shapes, displays, filters, views (with a body), roles and `shown to` rules. */
|
|
143
|
+
export function readViews(source) {
|
|
144
|
+
const set = emptyViewSet();
|
|
145
|
+
for (const n of readTree(source)) {
|
|
146
|
+
if (n.kind !== "pair" || !n.key)
|
|
147
|
+
continue;
|
|
148
|
+
const name = n.value.trim();
|
|
149
|
+
const get = (k) => n.children.find((c) => c.key === k);
|
|
150
|
+
if (n.key === "shape") {
|
|
151
|
+
const slots = (get("slots")?.children ?? []).map((l) => {
|
|
152
|
+
const at = l.text.lastIndexOf(" -> ");
|
|
153
|
+
if (at < 0)
|
|
154
|
+
throw new CrubalError(`a slot is "from -> slot": ${l.text}`, l.line);
|
|
155
|
+
let from = l.text.slice(0, at).trim();
|
|
156
|
+
const required = from.startsWith("!");
|
|
157
|
+
if (required)
|
|
158
|
+
from = from.slice(1);
|
|
159
|
+
return { from, to: l.text.slice(at + 4).trim(), required, line: l.line };
|
|
160
|
+
});
|
|
161
|
+
set.shapes.set(name, { name, slots, line: n.line });
|
|
162
|
+
}
|
|
163
|
+
else if (n.key === "display") {
|
|
164
|
+
// A display (12.9): `layout:` names the family; `slots:` lines read `shapeSlot -> displaySlot`; `tokens:`
|
|
165
|
+
// lines are `name: value` words for the app; `label:` and `describe:` are its words on a screen.
|
|
166
|
+
const layout = get("layout")?.value.trim();
|
|
167
|
+
if (!layout)
|
|
168
|
+
throw new CrubalError(`the display ${name} names no layout`, n.line);
|
|
169
|
+
const slots = (get("slots")?.children ?? []).map((l) => {
|
|
170
|
+
const at = l.text.lastIndexOf(" -> ");
|
|
171
|
+
if (at < 0)
|
|
172
|
+
throw new CrubalError(`a display slot is "shapeSlot -> displaySlot": ${l.text}`, l.line);
|
|
173
|
+
const from = l.text.slice(0, at).trim();
|
|
174
|
+
const to = l.text.slice(at + 4).trim();
|
|
175
|
+
if (!from || !to)
|
|
176
|
+
throw new CrubalError(`a display slot is "shapeSlot -> displaySlot": ${l.text}`, l.line);
|
|
177
|
+
return { from, to, line: l.line };
|
|
178
|
+
});
|
|
179
|
+
const tokens = new Map();
|
|
180
|
+
for (const t of get("tokens")?.children ?? []) {
|
|
181
|
+
if (t.kind !== "pair" || !t.key)
|
|
182
|
+
throw new CrubalError(`a display token is "name: value": ${t.text}`, t.line);
|
|
183
|
+
tokens.set(t.key, t.value.trim());
|
|
184
|
+
}
|
|
185
|
+
set.displays.set(name, { name, ...(get("label") ? { label: get("label")?.value.trim() } : {}), ...(get("describe") ? { describe: get("describe")?.value.trim() } : {}), layout, slots, tokens, line: n.line });
|
|
186
|
+
}
|
|
187
|
+
else if (n.key === "print") {
|
|
188
|
+
// A print (12.12): `for:` the class or kind it prints; `inches:` its intrinsic stock; `fields:` lines read
|
|
189
|
+
// `slot -> facet` (or `id`, or a brand slot `place:name`); `elements:` lines are its art; `label:` and
|
|
190
|
+
// `describe:` its words.
|
|
191
|
+
const forWhat = get("for")?.value.trim();
|
|
192
|
+
if (!forWhat)
|
|
193
|
+
throw new CrubalError(`the print ${name} says no for: the class or kind it prints`, n.line);
|
|
194
|
+
const inchesT = (get("inches")?.value ?? "").trim().split(/\s+/).filter(Boolean);
|
|
195
|
+
const [w, h] = inchesT.map(Number);
|
|
196
|
+
if (inchesT.length !== 2 || !(Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0))
|
|
197
|
+
throw new CrubalError(`the print ${name} names its inches as "width height", two numbers above zero`, get("inches")?.line ?? n.line);
|
|
198
|
+
const stretchT = get("stretch")?.value.trim();
|
|
199
|
+
if (stretchT && stretchT !== "yes" && stretchT !== "no")
|
|
200
|
+
throw new CrubalError(`stretch is yes or no, not ${stretchT}`, get("stretch")?.line ?? n.line);
|
|
201
|
+
const fields = (get("fields")?.children ?? []).map((l) => {
|
|
202
|
+
const at = l.text.lastIndexOf(" -> ");
|
|
203
|
+
if (at < 0)
|
|
204
|
+
throw new CrubalError(`a print field is "slot -> facet": ${l.text}`, l.line);
|
|
205
|
+
const slot = l.text.slice(0, at).trim();
|
|
206
|
+
const from = l.text.slice(at + 4).trim();
|
|
207
|
+
if (!slot || !from || !/^\w+$/.test(slot))
|
|
208
|
+
throw new CrubalError(`a print field is "slot -> facet": ${l.text}`, l.line);
|
|
209
|
+
return { slot, from, line: l.line };
|
|
210
|
+
});
|
|
211
|
+
const elements = (get("elements")?.children ?? []).map((l) => readPrintElement(l.text, l.line));
|
|
212
|
+
if (!elements.length)
|
|
213
|
+
throw new CrubalError(`the print ${name} draws nothing: it needs elements`, n.line);
|
|
214
|
+
set.prints.set(name, { name, ...(get("label") ? { label: get("label")?.value.trim() } : {}), ...(get("describe") ? { describe: get("describe")?.value.trim() } : {}), for: forWhat, inches: { w: w, h: h }, stretch: stretchT === "yes", fields, elements, line: n.line });
|
|
215
|
+
}
|
|
216
|
+
else if (n.key === "filter") {
|
|
217
|
+
const b = get("buckets");
|
|
218
|
+
// `buckets: by month`: the buckets are the periods the facet's dates fall in (12.3).
|
|
219
|
+
const by = b && !b.children.length ? b.value.trim().match(/^by\s+(\w+)$/) : null;
|
|
220
|
+
if (b && by && !PERIODS.includes(by[1]))
|
|
221
|
+
throw new CrubalError(`buckets by ${by[1]}: a period is day, week, month, quarter or year`, b.line);
|
|
222
|
+
const period = by ? by[1] : undefined;
|
|
223
|
+
// `buckets: marked` (revision 34): the facet is a step's mark; the records that lack it, and those that hold it.
|
|
224
|
+
const marked = !!b && !b.children.length && b.value.trim() === "marked";
|
|
225
|
+
const buckets = period ? undefined : marked ? [{ name: MARK_OPEN, marked: "open" }, { name: MARK_DONE, marked: "done" }] : b?.children.map((c) => {
|
|
226
|
+
// A bucket line is `name: values`; the name may be quoted, with spaces ("Like new": NM, VG).
|
|
227
|
+
const m = c.text.match(/^("(?:[^"\\]|\\.)*"|[^:]+):\s+(.*)$/);
|
|
228
|
+
if (!m)
|
|
229
|
+
throw new CrubalError(`a bucket is "name: values": ${c.text}`, c.line);
|
|
230
|
+
const label = unq(m[1]);
|
|
231
|
+
const rest = m[2].trim();
|
|
232
|
+
const range = rest.match(/^(-?[\d.]+)\.\.(-?[\d.]+)$/);
|
|
233
|
+
return range ? { name: label, range: [Number(range[1]), Number(range[2])] } : { name: label, values: splitTop(rest, ",", c.line).map(unq) };
|
|
234
|
+
});
|
|
235
|
+
set.filters.set(name, {
|
|
236
|
+
name,
|
|
237
|
+
facet: get("facet")?.value ?? name,
|
|
238
|
+
...(buckets ? { buckets } : {}),
|
|
239
|
+
...(period ? { period } : {}),
|
|
240
|
+
...(marked ? { marked: true } : {}),
|
|
241
|
+
sums: (get("sum")?.value ?? "").split(",").map((s) => s.trim()).filter(Boolean),
|
|
242
|
+
dependent: (get("dependent")?.value ?? "").split(",").map((s) => s.trim()).filter(Boolean),
|
|
243
|
+
line: n.line,
|
|
244
|
+
bucketLines: b?.children.map((c) => c.line) ?? [],
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
else if (n.key === "view" && n.children.length) {
|
|
248
|
+
const sel = get("select");
|
|
249
|
+
const s = (k) => sel?.children.find((c) => c.key === k)?.value;
|
|
250
|
+
const list = (k) => (get(k)?.value ?? "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
251
|
+
set.views.set(name, {
|
|
252
|
+
name,
|
|
253
|
+
line: n.line,
|
|
254
|
+
...(s("level") ? { level: s("level") } : {}),
|
|
255
|
+
wears: (s("wears") ?? "").split(",").map((x) => x.trim()).filter(Boolean),
|
|
256
|
+
...(s("when") ? { when: s("when") } : {}),
|
|
257
|
+
...(s("list") ? { list: s("list") } : {}),
|
|
258
|
+
...(get("of") ? { of: get("of")?.value } : {}),
|
|
259
|
+
pin: list("pin"),
|
|
260
|
+
hide: list("hide"),
|
|
261
|
+
order: list("order").map((o) => {
|
|
262
|
+
const [key = "", dir] = o.split(/\s+/);
|
|
263
|
+
return { key, dir: dir === "after" ? "after" : "before" };
|
|
264
|
+
}),
|
|
265
|
+
page: Number(get("page")?.value ?? 24),
|
|
266
|
+
shapes: list("shape"),
|
|
267
|
+
filters: list("filters"),
|
|
268
|
+
index: list("index"),
|
|
269
|
+
indexLine: get("index")?.line ?? n.line,
|
|
270
|
+
show: get("show")?.value ?? "public",
|
|
271
|
+
fresh: get("fresh")?.value ?? "write",
|
|
272
|
+
...(get("partition") ? { partition: get("partition")?.value.trim() } : {}),
|
|
273
|
+
...(get("version") ? { version: get("version")?.value.trim() } : {}),
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
else if (n.key === "role") {
|
|
277
|
+
const see = get("may")?.children.find((c) => c.key === "see");
|
|
278
|
+
set.roles.set(name, {
|
|
279
|
+
name,
|
|
280
|
+
audience: get("audience")?.value ?? "member",
|
|
281
|
+
see: (see?.value ?? "").split(",").map((x) => x.trim()).filter(Boolean),
|
|
282
|
+
seeLine: see?.line ?? n.line,
|
|
283
|
+
line: n.line,
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
else if (n.key === "rule") {
|
|
287
|
+
const then = get("then")?.value ?? "";
|
|
288
|
+
const m = then.match(/^(\S+) shown to (\S+)$/);
|
|
289
|
+
if (m) {
|
|
290
|
+
const scope = get("for")?.value.trim() ?? "everywhere";
|
|
291
|
+
if (scope === "everywhere")
|
|
292
|
+
set.shown.set(m[1], m[2]);
|
|
293
|
+
else
|
|
294
|
+
set.shownFor.set(m[1], [...(set.shownFor.get(m[1]) ?? []), { for: scope, audience: m[2] }]);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return set;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The lowest audience that may see a facet (12.4): a show rule whose `for` covers the record decides for it,
|
|
302
|
+
* a class over a kind or level, else the rule for everywhere; no rule, the public.
|
|
303
|
+
*/
|
|
304
|
+
export function shownAudience(set, facet, record, dict) {
|
|
305
|
+
const key = facet.replace(/^\w+::/, "");
|
|
306
|
+
if (record) {
|
|
307
|
+
const scoped = set.shownFor.get(key) ?? [];
|
|
308
|
+
// A record wears its kind's base class without saying so (chapter 5).
|
|
309
|
+
const base = dict?.kinds.get(record.kind)?.base;
|
|
310
|
+
const byClass = scoped.find((s) => (record.wears ?? []).includes(s.for) || s.for === base);
|
|
311
|
+
if (byClass)
|
|
312
|
+
return byClass.audience;
|
|
313
|
+
const byKind = scoped.find((s) => s.for === record.kind || s.for === record.level);
|
|
314
|
+
if (byKind)
|
|
315
|
+
return byKind.audience;
|
|
316
|
+
}
|
|
317
|
+
return set.shown.get(key);
|
|
318
|
+
}
|
|
319
|
+
/** Can an audience see a facet, of this record when one is given? */
|
|
320
|
+
export function visibleTo(set, facet, audience, record, dict) {
|
|
321
|
+
const min = shownAudience(set, facet, record, dict);
|
|
322
|
+
return !min || rankOf(audience) >= rankOf(min);
|
|
323
|
+
}
|
|
324
|
+
/** The keys a slot's source reads. */
|
|
325
|
+
function slotKeys(from) {
|
|
326
|
+
if (from.startsWith('"'))
|
|
327
|
+
return [...JSON.parse(from).matchAll(/\{([^{}]+)\}/g)].flatMap((m) => m[1].split("??").map((k) => k.trim().replace(/\?$/, "")));
|
|
328
|
+
const agg = from.match(/^(?:count|least|most|sum|best|worst|join) of (\S+)$/);
|
|
329
|
+
return [agg ? agg[1] : from];
|
|
330
|
+
}
|
|
331
|
+
// ─── Publish checks (12.8) ───────────────────────────────────────────────────
|
|
332
|
+
export function checkViews(set, dict) {
|
|
333
|
+
const defined = (k) => facetOf(k, dict) !== undefined;
|
|
334
|
+
for (const f of set.filters.values()) {
|
|
335
|
+
if (!defined(f.facet))
|
|
336
|
+
throw new CrubalError(`the filter ${f.name} reads ${f.facet}, which isn't a facet`, f.line);
|
|
337
|
+
const facet = facetOf(f.facet, dict);
|
|
338
|
+
const seen = new Map();
|
|
339
|
+
f.buckets?.forEach((b, i) => {
|
|
340
|
+
for (const v of b.values ?? []) {
|
|
341
|
+
if (facet?.values && !facet.values.some((x) => x.value === v))
|
|
342
|
+
throw new CrubalError(`${v} is not a value of ${facet.key}`, f.bucketLines[i]);
|
|
343
|
+
const other = seen.get(v);
|
|
344
|
+
if (other)
|
|
345
|
+
throw new CrubalError(`${v} is in both ${other} and ${b.name}`, f.bucketLines[i]);
|
|
346
|
+
seen.set(v, b.name);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
for (const s of set.shapes.values()) {
|
|
351
|
+
for (const sl of s.slots) {
|
|
352
|
+
// A page shape's slot may hold another view (12.1), run with the page's record as its context.
|
|
353
|
+
if (sl.from.startsWith("view:")) {
|
|
354
|
+
if (!set.views.has(sl.from.slice(5)))
|
|
355
|
+
throw new CrubalError(`the slot ${sl.to} holds the view ${sl.from.slice(5)}, which doesn't exist`, sl.line);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
for (const k of slotKeys(sl.from))
|
|
359
|
+
if (!sl.from.startsWith('"') || k)
|
|
360
|
+
if (!defined(k) && k !== "id")
|
|
361
|
+
throw new CrubalError(`the slot ${sl.to} reads ${k}, which isn't a facet`, sl.line);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
for (const f of set.filters.values())
|
|
365
|
+
for (const d of f.dependent)
|
|
366
|
+
if (!defined(d))
|
|
367
|
+
throw new CrubalError(`the filter ${f.name} depends on ${d}, which isn't a facet`, f.line);
|
|
368
|
+
// A print (12.12) prints a class or kind the dictionary has; its fields read facets, `id` or the brand's
|
|
369
|
+
// slots; every field an element names is declared.
|
|
370
|
+
for (const p of set.prints.values()) {
|
|
371
|
+
if (!dict.classes.has(p.for) && !dict.kinds.has(p.for))
|
|
372
|
+
throw new CrubalError(`the print ${p.name} is for ${p.for}, which is neither a class nor a kind`, p.line);
|
|
373
|
+
const slots = new Set(["id"]);
|
|
374
|
+
for (const f of p.fields) {
|
|
375
|
+
if (slots.has(f.slot) && f.slot !== "id")
|
|
376
|
+
throw new CrubalError(`the print ${p.name} names the field ${f.slot} twice`, f.line);
|
|
377
|
+
const place = f.from.match(/^place:(\w+)$/);
|
|
378
|
+
if (place) {
|
|
379
|
+
if (!PRINT_PLACE_SLOTS.includes(place[1]))
|
|
380
|
+
throw new CrubalError(`a brand slot is one of ${PRINT_PLACE_SLOTS.map((x) => `place:${x}`).join(", ")}, not ${f.from}`, f.line);
|
|
381
|
+
}
|
|
382
|
+
else if (f.from !== "id" && !defined(f.from))
|
|
383
|
+
throw new CrubalError(`the field ${f.slot} reads ${f.from}, which isn't a facet`, f.line);
|
|
384
|
+
slots.add(f.slot);
|
|
385
|
+
}
|
|
386
|
+
for (const e of p.elements) {
|
|
387
|
+
const wanted = e.type === "text" ? printSourceFields(e.source) : e.type === "rect" ? [] : [e.field];
|
|
388
|
+
for (const k of wanted)
|
|
389
|
+
if (!slots.has(k))
|
|
390
|
+
throw new CrubalError(`the print ${p.name} draws ${k}, which is none of its fields`, e.line);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// A display (12.9) fills its slots from a shape's slots; two of its lines may not fill one display slot.
|
|
394
|
+
for (const d of set.displays.values()) {
|
|
395
|
+
const filled = new Set();
|
|
396
|
+
for (const sl of d.slots) {
|
|
397
|
+
if (filled.has(sl.to))
|
|
398
|
+
throw new CrubalError(`the display ${d.name} fills the slot ${sl.to} twice`, sl.line);
|
|
399
|
+
filled.add(sl.to);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
for (const v of set.views.values()) {
|
|
403
|
+
for (const s of v.shapes)
|
|
404
|
+
if (!CORE_SHAPES.includes(s) && !set.shapes.has(s))
|
|
405
|
+
throw new CrubalError(`${v.name} names the shape ${s}, which doesn't exist`, v.line);
|
|
406
|
+
// A list is the whole selection (12.2): a level, classes, a condition or curation would contradict it.
|
|
407
|
+
if (v.list && (v.level || v.wears.length || v.when || v.pin.length || v.hide.length || v.order.length))
|
|
408
|
+
throw new CrubalError(`${v.name} selects a list, so it takes no level, wears, when, pin, hide or order`, v.line);
|
|
409
|
+
for (const f of v.filters)
|
|
410
|
+
if (!set.filters.has(f))
|
|
411
|
+
throw new CrubalError(`${v.name} names the filter ${f}, which doesn't exist`, v.line);
|
|
412
|
+
for (const i of v.index)
|
|
413
|
+
if (!v.filters.includes(i))
|
|
414
|
+
throw new CrubalError(`${v.name} indexes ${i}, which isn't one of its filters`, v.indexLine);
|
|
415
|
+
for (const c of v.wears)
|
|
416
|
+
if (!dict.classes.has(c))
|
|
417
|
+
throw new CrubalError(`${v.name} selects by ${c}, which isn't a class`, v.line);
|
|
418
|
+
// A `linked <facet>` partition (12.2, 14.10) names a link facet: the row carries whom the record links to.
|
|
419
|
+
const linked = v.partition?.match(/^linked (\S+)$/);
|
|
420
|
+
if (linked) {
|
|
421
|
+
const f = facetOf(linked[1], dict);
|
|
422
|
+
if (!f)
|
|
423
|
+
throw new CrubalError(`${v.name} is partitioned by ${linked[1]}, which isn't a facet`, v.line);
|
|
424
|
+
if (f.type !== "link")
|
|
425
|
+
throw new CrubalError(`${v.name} is partitioned by ${linked[1]}, which isn't a link`, v.line);
|
|
426
|
+
}
|
|
427
|
+
else if (v.partition && !/^(none|owned|administered|controlled|relation \S+)$/.test(v.partition))
|
|
428
|
+
throw new CrubalError(`${v.name} has the partition ${v.partition}; a partition is administered, controlled, owned, relation <name>, linked <facet> or none`, v.line);
|
|
429
|
+
if (v.show === "public") {
|
|
430
|
+
const reads = [
|
|
431
|
+
...v.shapes.flatMap((s) => (set.shapes.get(s)?.slots ?? []).flatMap((sl) => slotKeys(sl.from))),
|
|
432
|
+
...v.filters.map((f) => set.filters.get(f)?.facet ?? f),
|
|
433
|
+
];
|
|
434
|
+
const hidden = reads.find((k) => !visibleTo(set, leafOf(k, dict), "public"));
|
|
435
|
+
if (hidden)
|
|
436
|
+
throw new CrubalError(`the public view ${v.name} reads ${hidden}, which show rules hide from public`, v.line);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
for (const r of set.roles.values()) {
|
|
440
|
+
for (const k of r.see) {
|
|
441
|
+
if (!defined(k))
|
|
442
|
+
throw new CrubalError(`${r.name} grants see: ${k}, which isn't a facet`, r.seeLine);
|
|
443
|
+
if (!visibleTo(set, k, r.audience))
|
|
444
|
+
throw new CrubalError(`${r.name} grants see: ${k}, which the ${r.audience} audience can't see`, r.seeLine);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/** The shapes the core defines (12.1, 12.5): the portable one, and structured data for the public. */
|
|
449
|
+
export const CORE_SHAPES = ["crubal:portable", "crubal:jsonld"];
|
|
450
|
+
/** A view's partition: what it declares, else `controlled` above member and `none` otherwise (12.2). */
|
|
451
|
+
export function partitionOf(v) {
|
|
452
|
+
return v.partition ?? (rankOf(v.show) > rankOf("member") ? "controlled" : "none");
|
|
453
|
+
}
|
|
454
|
+
function plainText(v) {
|
|
455
|
+
if (typeof v === "string")
|
|
456
|
+
return v;
|
|
457
|
+
if (isObj(v) && "$link" in v)
|
|
458
|
+
return `&${v.$link}`;
|
|
459
|
+
if (isObj(v) && "$value" in v)
|
|
460
|
+
return plainText(v.$value);
|
|
461
|
+
return serialize(v);
|
|
462
|
+
}
|
|
463
|
+
function label(key) {
|
|
464
|
+
const words = key.replace(/^.*:/, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
|
|
465
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
466
|
+
}
|
|
467
|
+
export class Views {
|
|
468
|
+
dict;
|
|
469
|
+
set;
|
|
470
|
+
records = new MemoryRecords();
|
|
471
|
+
engine;
|
|
472
|
+
/** Over a record set of the caller's (a store's working set), or an empty memory set to `put` into. */
|
|
473
|
+
constructor(dict, set, records) {
|
|
474
|
+
this.dict = dict;
|
|
475
|
+
this.set = set;
|
|
476
|
+
if (records)
|
|
477
|
+
this.records = records;
|
|
478
|
+
this.engine = new Engine(dict, []);
|
|
479
|
+
}
|
|
480
|
+
put(r) {
|
|
481
|
+
this.records.set(r.id, r);
|
|
482
|
+
}
|
|
483
|
+
effective(r) {
|
|
484
|
+
const up = r.of ? this.records.get(r.of) : undefined;
|
|
485
|
+
return { ...(up ? this.effective(up) : {}), ...r.values };
|
|
486
|
+
}
|
|
487
|
+
/** The classes a record wears, those of the records above it included (5.5). */
|
|
488
|
+
wearsOf(r) {
|
|
489
|
+
const up = r.of ? this.records.get(r.of) : undefined;
|
|
490
|
+
return [...(up ? this.wearsOf(up) : []), ...(r.wears ?? [])];
|
|
491
|
+
}
|
|
492
|
+
below(r, level) {
|
|
493
|
+
return this.records.childrenOf(r.id, "of", level);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* The records a link facet points at: shared parts, read through (1.6). A link into a vocabulary (`wd`,
|
|
497
|
+
* `gpc`) or to a url points at no record here and reads nothing.
|
|
498
|
+
*/
|
|
499
|
+
linked(r, link) {
|
|
500
|
+
const f = this.dict.facets.get(link);
|
|
501
|
+
// A link to a kind, a class, or (revision 34, erratum) a level of a kind: `lineUnit&unit` names a level of item.
|
|
502
|
+
if (!f || f.type !== "link" || !f.to || !(this.dict.kinds.has(f.to) || this.dict.classes.has(f.to) || this.dict.levels.has(f.to)))
|
|
503
|
+
return [];
|
|
504
|
+
const v = this.effective(r)[link];
|
|
505
|
+
const items = v === undefined ? [] : Array.isArray(v) ? v : [v];
|
|
506
|
+
return items.flatMap((x) => {
|
|
507
|
+
const id = isObj(x) && "$link" in x ? String(x.$link) : typeof x === "string" ? x : "";
|
|
508
|
+
const t = id ? this.records.get(id) : undefined;
|
|
509
|
+
return t && t.status?.state !== "archived" ? [t] : [];
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
/** The rows of a compound on a record, as objects. */
|
|
513
|
+
rowsOf(r, compound) {
|
|
514
|
+
const v = this.effective(r)[compound];
|
|
515
|
+
return (v === undefined ? [] : Array.isArray(v) ? v : [v]).filter(isObj);
|
|
516
|
+
}
|
|
517
|
+
/** The values an address reads, as a list: own values, or a lower level's (`unit::price`). */
|
|
518
|
+
valuesAt(r, address) {
|
|
519
|
+
// A step through a link facet reads the linked records (shared parts, 1.6), each by the rest of the address.
|
|
520
|
+
const ls = linkStep(address, this.dict);
|
|
521
|
+
if (ls)
|
|
522
|
+
return this.linked(r, ls.link).flatMap((t) => this.valuesAt(t, ls.rest));
|
|
523
|
+
// A step into a compound's rows reads the child on every row (1.10 with the wildcard).
|
|
524
|
+
const rs = rowStep(address, this.dict);
|
|
525
|
+
if (rs)
|
|
526
|
+
return this.rowsOf(r, rs.compound).flatMap((row) => { const c = rs.child ? row[rs.child] : row; return c === undefined ? [] : Array.isArray(c) ? c : [c]; });
|
|
527
|
+
const m = address.match(/^(\w+)::(.+)$/);
|
|
528
|
+
// A level prefix reads the records below at that level, or the record itself when it sits there
|
|
529
|
+
// (a standing-alone lower record answers for its own level, 1.7).
|
|
530
|
+
if (m && r.level === m[1])
|
|
531
|
+
return this.valuesAt(r, m[2]);
|
|
532
|
+
if (m)
|
|
533
|
+
return this.below(r, m[1]).flatMap((u) => this.valuesAt(u, m[2]));
|
|
534
|
+
const v = this.effective(r)[address];
|
|
535
|
+
return v === undefined ? [] : Array.isArray(v) ? v : [v];
|
|
536
|
+
}
|
|
537
|
+
/** Is a value fit for this audience's eyes? New, unknown and held values never reach the public. */
|
|
538
|
+
fit(key, v, audience) {
|
|
539
|
+
if (audience !== "public")
|
|
540
|
+
return true;
|
|
541
|
+
if (isObj(v) && "$empty" in v)
|
|
542
|
+
return v.$empty === "n/a";
|
|
543
|
+
const f = facetOf(key, this.dict);
|
|
544
|
+
if (f?.type === "choice" && typeof v === "string")
|
|
545
|
+
return (f.values ?? []).some((x) => x.value === v);
|
|
546
|
+
return true;
|
|
547
|
+
}
|
|
548
|
+
canSee(address, audience, caller, record) {
|
|
549
|
+
const key = leafOf(address, this.dict);
|
|
550
|
+
if (!visibleTo(this.set, key, audience, record, this.dict))
|
|
551
|
+
return false;
|
|
552
|
+
if (!caller || rankOf(audience) <= rankOf("member"))
|
|
553
|
+
return true;
|
|
554
|
+
// Above member, a person sees what members see plus what their roles grant (default deny).
|
|
555
|
+
if (visibleTo(this.set, key, "member", record, this.dict))
|
|
556
|
+
return true;
|
|
557
|
+
const held = caller.values.roles;
|
|
558
|
+
const names = (Array.isArray(held) ? held : held ? [held] : []).map((x) => (isObj(x) && "$link" in x ? String(x.$link) : String(x)));
|
|
559
|
+
return names.some((n) => {
|
|
560
|
+
const role = this.set.roles.get(n);
|
|
561
|
+
return role && role.see.includes(key) && rankOf(role.audience) <= rankOf(audience);
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
slot(r, s, audience, caller) {
|
|
565
|
+
const keys = slotKeys(s.from);
|
|
566
|
+
if (!keys.every((k) => this.canSee(k, audience, caller, r)))
|
|
567
|
+
return undefined;
|
|
568
|
+
if (s.from.startsWith('"'))
|
|
569
|
+
return this.engine.template(s.from, this.effective(r));
|
|
570
|
+
const agg = s.from.match(/^(count|least|most|sum|best|worst|join) of (\S+)$/);
|
|
571
|
+
if (agg) {
|
|
572
|
+
const items = this.valuesAt(r, agg[2]).filter((v) => !(isObj(v) && "$empty" in v));
|
|
573
|
+
if (agg[1] === "count")
|
|
574
|
+
return String(items.length);
|
|
575
|
+
if (!items.length)
|
|
576
|
+
return undefined;
|
|
577
|
+
const amount = (v) => Number(isObj(v) ? (v.$money ?? v.$qty ?? NaN) : v);
|
|
578
|
+
const sorted = [...items].sort((a, b) => amount(a) - amount(b));
|
|
579
|
+
if (agg[1] === "least")
|
|
580
|
+
return sorted[0];
|
|
581
|
+
if (agg[1] === "most")
|
|
582
|
+
return sorted.at(-1);
|
|
583
|
+
return items;
|
|
584
|
+
}
|
|
585
|
+
const f = facetOf(s.from, this.dict);
|
|
586
|
+
const through = s.from.includes("::") || linkStep(s.from, this.dict) !== null || rowStep(s.from, this.dict) !== null;
|
|
587
|
+
const v = through ? this.valuesAt(r, s.from) : this.effective(r)[s.from];
|
|
588
|
+
if (v === undefined || (Array.isArray(v) && !v.length))
|
|
589
|
+
return undefined;
|
|
590
|
+
if (Array.isArray(v)) {
|
|
591
|
+
const kept = v.filter((x) => this.fit(s.from, x, audience));
|
|
592
|
+
return kept.length ? (f?.many || through ? kept : kept[0]) : undefined;
|
|
593
|
+
}
|
|
594
|
+
return this.fit(s.from, v, audience) ? v : undefined;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* What a condition reads of a record (6.3): the envelope under `crubal:`, and bare `id` and `status`
|
|
598
|
+
* too unless a facet of that name holds a value, which then wins.
|
|
599
|
+
*/
|
|
600
|
+
conditionValues(r) {
|
|
601
|
+
const status = r.status?.state ?? "active";
|
|
602
|
+
const own = this.effective(r);
|
|
603
|
+
const out = { id: r.id, status, "crubal:id": r.id, "crubal:status": status, ...own };
|
|
604
|
+
// A compound's rows, addressed `X[*].child`, as lists of the child's values.
|
|
605
|
+
const rowKeys = (vals, prefix) => {
|
|
606
|
+
const added = {};
|
|
607
|
+
for (const [key, v] of Object.entries(vals)) {
|
|
608
|
+
if (this.dict.facets.get(key)?.type !== "compound")
|
|
609
|
+
continue;
|
|
610
|
+
for (const row of (Array.isArray(v) ? v : [v]).filter(isObj))
|
|
611
|
+
for (const [child, cv] of Object.entries(row))
|
|
612
|
+
(added[`${prefix}${key}[*].${child}`] ??= []).push(...(Array.isArray(cv) ? cv : [cv]));
|
|
613
|
+
}
|
|
614
|
+
return added;
|
|
615
|
+
};
|
|
616
|
+
Object.assign(out, rowKeys(own, ""));
|
|
617
|
+
// The linked records' values, addressed through the link (`works[*].genre`, `works.genre`), so a
|
|
618
|
+
// condition reads a shared part as it reads a level below (1.6); their compounds' rows likewise.
|
|
619
|
+
for (const key of Object.keys(own)) {
|
|
620
|
+
if (this.dict.facets.get(key)?.type !== "link")
|
|
621
|
+
continue;
|
|
622
|
+
const targets = this.linked(r, key);
|
|
623
|
+
if (!targets.length)
|
|
624
|
+
continue;
|
|
625
|
+
const merged = {};
|
|
626
|
+
for (const t of targets) {
|
|
627
|
+
const tv = this.effective(t);
|
|
628
|
+
for (const [k, v] of Object.entries(tv))
|
|
629
|
+
(merged[k] ??= []).push(...(Array.isArray(v) ? v : [v]));
|
|
630
|
+
for (const [k, v] of Object.entries(rowKeys(tv, "")))
|
|
631
|
+
(merged[k] ??= []).push(...v);
|
|
632
|
+
}
|
|
633
|
+
for (const [k, list] of Object.entries(merged)) {
|
|
634
|
+
out[`${key}[*].${k}`] = list;
|
|
635
|
+
out[`${key}.${k}`] = list.length === 1 ? list[0] : list;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return out;
|
|
639
|
+
}
|
|
640
|
+
/** The values of the view's order keys as text, and the pin position: what an index orders rows by (12.7). */
|
|
641
|
+
sortOf(v, r) {
|
|
642
|
+
const sort = v.order.map((o) => this.orderText(r, o.key));
|
|
643
|
+
const at = v.pin.indexOf(r.id);
|
|
644
|
+
return at >= 0 ? { sort, pin: at + 1 } : { sort };
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* An order key's text on a record: the record's own value, or (revision 34, erratum) the first value an address
|
|
648
|
+
* reads, so a view may sort by what a link reaches (`pickUnit.filedSlot`: the walking order).
|
|
649
|
+
*/
|
|
650
|
+
orderText(r, key) {
|
|
651
|
+
const own = this.effective(r)[key];
|
|
652
|
+
if (own !== undefined)
|
|
653
|
+
return plainText(own);
|
|
654
|
+
if (!/[.:[]/.test(key))
|
|
655
|
+
return "";
|
|
656
|
+
const v = this.valuesAt(r, key)[0];
|
|
657
|
+
return v === undefined ? "" : plainText(v);
|
|
658
|
+
}
|
|
659
|
+
/** The buckets a record falls into, per filter of the view (12.6): what an index counts from. */
|
|
660
|
+
bucketsFor(v, r) {
|
|
661
|
+
const out = {};
|
|
662
|
+
for (const fname of v.filters) {
|
|
663
|
+
const f = this.set.filters.get(fname);
|
|
664
|
+
if (!f)
|
|
665
|
+
continue;
|
|
666
|
+
const names = this.bucketsOf(f, r).filter((b) => this.inBucket(r, f, b)).map((b) => b.name);
|
|
667
|
+
if (names.length)
|
|
668
|
+
out[fname] = names;
|
|
669
|
+
// A dependent facet (12.3): its values, one bucket each, so an index can count them inside this filter's.
|
|
670
|
+
for (const dep of f.dependent) {
|
|
671
|
+
const vals = this.valuesAt(r, dep).filter((x) => this.fit(dep, x, "public")).map(plainText);
|
|
672
|
+
if (vals.length)
|
|
673
|
+
out[dep] = [...new Set(vals)];
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return out;
|
|
677
|
+
}
|
|
678
|
+
/** Dependent counts (12.3) over records already narrowed by the other filters. */
|
|
679
|
+
nestedCounts(v, pool) {
|
|
680
|
+
const out = {};
|
|
681
|
+
for (const fname of v.filters) {
|
|
682
|
+
const f = this.set.filters.get(fname);
|
|
683
|
+
if (!f?.dependent.length)
|
|
684
|
+
continue;
|
|
685
|
+
const rows = pool(fname);
|
|
686
|
+
const per = {};
|
|
687
|
+
for (const b of this.bucketsOf(f)) {
|
|
688
|
+
const inB = rows.filter((r) => this.inBucket(r, f, b));
|
|
689
|
+
const byDep = {};
|
|
690
|
+
for (const dep of f.dependent) {
|
|
691
|
+
const tally = {};
|
|
692
|
+
for (const r of inB)
|
|
693
|
+
for (const val of new Set(this.valuesAt(r, dep).map(plainText)))
|
|
694
|
+
tally[val] = (tally[val] ?? 0) + 1;
|
|
695
|
+
byDep[dep] = tally;
|
|
696
|
+
}
|
|
697
|
+
per[b.name] = byDep;
|
|
698
|
+
}
|
|
699
|
+
out[fname] = per;
|
|
700
|
+
}
|
|
701
|
+
return out;
|
|
702
|
+
}
|
|
703
|
+
/** Does a view select this record (its own tests, before curation and the shape's required slots)? */
|
|
704
|
+
selects(v, r, opts) {
|
|
705
|
+
if (v.level && r.level !== v.level)
|
|
706
|
+
return false;
|
|
707
|
+
// An archived record is left out unless the view selects on status explicitly (1.12).
|
|
708
|
+
if (r.status?.state === "archived" && !(v.when && /\bstatus\b/.test(v.when)))
|
|
709
|
+
return false;
|
|
710
|
+
if (v.wears.some((w) => !this.wearsOf(r).includes(w)))
|
|
711
|
+
return false;
|
|
712
|
+
if (v.hide.includes(r.id))
|
|
713
|
+
return false;
|
|
714
|
+
const vals = this.conditionValues(r);
|
|
715
|
+
if (v.when && evaluate(parseCondition(v.when), vals) !== true)
|
|
716
|
+
return false;
|
|
717
|
+
if (v.of) {
|
|
718
|
+
const ctx = opts.context;
|
|
719
|
+
if (!ctx)
|
|
720
|
+
return false;
|
|
721
|
+
const cvals = this.conditionValues(ctx);
|
|
722
|
+
const cond = v.of.replace(/context\.(\w+)/g, (_, k) => JSON.stringify(cvals[k] === undefined ? "" : plainText(cvals[k])));
|
|
723
|
+
if (evaluate(parseCondition(cond), vals) !== true)
|
|
724
|
+
return false;
|
|
725
|
+
}
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
/** The records a list holds, in its order (12.2): the links in its `crubal:items`. */
|
|
729
|
+
listed(v) {
|
|
730
|
+
const list = v.list ? this.records.get(v.list) : undefined;
|
|
731
|
+
const items = list?.values["crubal:items"];
|
|
732
|
+
const ids = (Array.isArray(items) ? items : items === undefined ? [] : [items]).map((x) => (isObj(x) && "$link" in x ? String(x.$link) : String(x)));
|
|
733
|
+
return ids.flatMap((id) => this.records.get(id) ?? []).filter((r) => r.status?.state !== "archived");
|
|
734
|
+
}
|
|
735
|
+
inBucket(r, f, b) {
|
|
736
|
+
// A mark's two buckets (12.3, revision 34): the one place an empty value is bucketed.
|
|
737
|
+
if (b.marked)
|
|
738
|
+
return this.valuesAt(r, f.facet).some((v) => plainText(v) !== "") === (b.marked === "done");
|
|
739
|
+
return this.valuesAt(r, f.facet).some((v) => {
|
|
740
|
+
const t = plainText(v);
|
|
741
|
+
if (b.period)
|
|
742
|
+
return periodOf(t, b.period) === b.name;
|
|
743
|
+
if (b.values)
|
|
744
|
+
return b.values.includes(t);
|
|
745
|
+
if (b.range)
|
|
746
|
+
return Number.parseFloat(t) >= b.range[0] && Number.parseFloat(t) <= b.range[1];
|
|
747
|
+
return false;
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* A filter's buckets: the ones it declares, else one per value of the facet's list. A facet with no list (a
|
|
752
|
+
* link into a vocabulary, a number, a text) buckets by the values the records carry, each its own bucket
|
|
753
|
+
* named by the value (12.3): given a record, its values; given none, nothing is known in advance.
|
|
754
|
+
*/
|
|
755
|
+
bucketsOf(f, r) {
|
|
756
|
+
if (f.buckets)
|
|
757
|
+
return f.buckets;
|
|
758
|
+
if (f.period) {
|
|
759
|
+
// The periods the record's dates fall in, each its own bucket (12.3 `by`).
|
|
760
|
+
if (!r)
|
|
761
|
+
return [];
|
|
762
|
+
const period = f.period;
|
|
763
|
+
const names = new Set();
|
|
764
|
+
for (const v of this.valuesAt(r, f.facet)) {
|
|
765
|
+
const name = periodOf(plainText(v), period);
|
|
766
|
+
if (name)
|
|
767
|
+
names.add(name);
|
|
768
|
+
}
|
|
769
|
+
return [...names].map((name) => ({ name, period }));
|
|
770
|
+
}
|
|
771
|
+
const facet = facetOf(f.facet, this.dict);
|
|
772
|
+
if (facet?.values?.length)
|
|
773
|
+
return facet.values.map((v) => ({ name: v.value, values: [v.value] }));
|
|
774
|
+
if (!r)
|
|
775
|
+
return [];
|
|
776
|
+
return [...new Set(this.valuesAt(r, f.facet).map(plainText).filter(Boolean))].map((t) => ({ name: t, values: [t] }));
|
|
777
|
+
}
|
|
778
|
+
/** Does the filter bucket by the values records carry, with no list known in advance (12.3): a period, or a facet with no list? */
|
|
779
|
+
unlisted(f) {
|
|
780
|
+
return !f.buckets && (!!f.period || !facetOf(f.facet, this.dict)?.values?.length);
|
|
781
|
+
}
|
|
782
|
+
/** A facet's numeric value on a record, summed over its values: money by its amount, a number as it is. */
|
|
783
|
+
numberOf(r, facet) {
|
|
784
|
+
let total = 0;
|
|
785
|
+
for (const v of this.valuesAt(r, facet)) {
|
|
786
|
+
const n = isObj(v) && typeof v.$money === "string" ? Number(v.$money) : isObj(v) && "$qty" in v ? Number(v.$qty) : typeof v === "number" ? v : typeof v === "string" ? Number(v) : Number.NaN;
|
|
787
|
+
if (Number.isFinite(n))
|
|
788
|
+
total += n;
|
|
789
|
+
}
|
|
790
|
+
return total;
|
|
791
|
+
}
|
|
792
|
+
/** The records a view selects, curated and ordered, before filters and paging. */
|
|
793
|
+
select(v, opts = {}) {
|
|
794
|
+
const audience = opts.audience ?? v.show;
|
|
795
|
+
const shape = this.set.shapes.get(v.shapes[0] ?? "");
|
|
796
|
+
const fills = (r) => (shape?.slots ?? []).every((s) => !s.required || this.slot(r, s, audience, opts.caller) !== undefined);
|
|
797
|
+
if (v.list) {
|
|
798
|
+
// A hand-made list (12.2): its records in its order, whatever their levels; no curation applies.
|
|
799
|
+
const listed = this.listed(v).filter(fills);
|
|
800
|
+
return opts.only ? listed.filter((r) => opts.only.includes(r.id)) : listed;
|
|
801
|
+
}
|
|
802
|
+
const pool = opts.only ? opts.only.flatMap((id) => this.records.get(id) ?? []) : v.level ? this.records.atLevel(v.level) : this.records.all();
|
|
803
|
+
let rows = pool.filter((r) => this.selects(v, r, opts));
|
|
804
|
+
// A record whose required slot is empty is dropped from the view.
|
|
805
|
+
rows = rows.filter(fills);
|
|
806
|
+
const cmp = (a, b) => {
|
|
807
|
+
for (const o of v.order) {
|
|
808
|
+
const x = this.orderText(a, o.key);
|
|
809
|
+
const y = this.orderText(b, o.key);
|
|
810
|
+
if (x !== y)
|
|
811
|
+
return (x < y ? -1 : 1) * (o.dir === "after" ? -1 : 1);
|
|
812
|
+
}
|
|
813
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
814
|
+
};
|
|
815
|
+
const pinned = v.pin.map((id) => rows.find((r) => r.id === id)).filter((r) => !!r);
|
|
816
|
+
return [...pinned, ...rows.filter((r) => !v.pin.includes(r.id)).sort(cmp)];
|
|
817
|
+
}
|
|
818
|
+
/** The roles whose `see` a slot needs above member (12.6 role marks): none when members may see it. */
|
|
819
|
+
marksFor(s, audience) {
|
|
820
|
+
if (rankOf(audience) <= rankOf("member"))
|
|
821
|
+
return [];
|
|
822
|
+
const keys = slotKeys(s.from);
|
|
823
|
+
if (keys.every((k) => visibleTo(this.set, k, "member")))
|
|
824
|
+
return [];
|
|
825
|
+
return [...this.set.roles.values()].filter((r) => rankOf(r.audience) <= rankOf(audience) && keys.every((k) => visibleTo(this.set, k, "member") || r.see.includes(k.replace(/^\w+::/, "")))).map((r) => r.name).sort();
|
|
826
|
+
}
|
|
827
|
+
/** A view's projection for an audience (or a caller), with filter counts and a page. */
|
|
828
|
+
project(name, opts = {}) {
|
|
829
|
+
const v = this.set.views.get(name);
|
|
830
|
+
if (!v)
|
|
831
|
+
throw new Error(`no view ${name}`);
|
|
832
|
+
// A caller's audience is read off their edges (14.4) when access is at hand; a stated value otherwise.
|
|
833
|
+
const audience = opts.caller ? (opts.access ? opts.access.audienceOf(opts.caller.id) : String(opts.caller.values.audience ?? "member")) : (opts.audience ?? v.show);
|
|
834
|
+
const partition = partitionOf(v);
|
|
835
|
+
let all = this.select(v, { ...opts, audience });
|
|
836
|
+
// A partitioned view serves a caller only the rows their edges match (12.6, 14.10).
|
|
837
|
+
if (partition !== "none" && opts.access && opts.caller)
|
|
838
|
+
all = all.filter((r) => opts.access.standsIn(opts.caller.id, r.id, partition));
|
|
839
|
+
const picks = opts.picks ?? {};
|
|
840
|
+
const passes = (r, except) => Object.entries(picks).every(([fname, chosen]) => {
|
|
841
|
+
if (fname === except)
|
|
842
|
+
return true;
|
|
843
|
+
const f = this.set.filters.get(fname);
|
|
844
|
+
return !f || this.bucketsOf(f, r).some((b) => chosen.includes(b.name) && this.inBucket(r, f, b));
|
|
845
|
+
});
|
|
846
|
+
const counts = {};
|
|
847
|
+
const sums = {};
|
|
848
|
+
if (!opts.all) {
|
|
849
|
+
for (const fname of v.filters) {
|
|
850
|
+
const f = this.set.filters.get(fname);
|
|
851
|
+
if (!f)
|
|
852
|
+
continue;
|
|
853
|
+
const pool = all.filter((r) => passes(r, fname));
|
|
854
|
+
const totals = {};
|
|
855
|
+
const add = (bucket, r) => {
|
|
856
|
+
if (!f.sums.length)
|
|
857
|
+
return;
|
|
858
|
+
const t = (totals[bucket] ??= {});
|
|
859
|
+
for (const facet of f.sums)
|
|
860
|
+
t[facet] = Math.round(((t[facet] ?? 0) + this.numberOf(r, facet)) * 1e6) / 1e6;
|
|
861
|
+
};
|
|
862
|
+
if (this.unlisted(f)) {
|
|
863
|
+
// One bucket per value (or period) the records carry: a tally over the pool (12.3).
|
|
864
|
+
const tally = {};
|
|
865
|
+
for (const r of pool)
|
|
866
|
+
for (const b of this.bucketsOf(f, r)) {
|
|
867
|
+
tally[b.name] = (tally[b.name] ?? 0) + 1;
|
|
868
|
+
add(b.name, r);
|
|
869
|
+
}
|
|
870
|
+
counts[fname] = tally;
|
|
871
|
+
}
|
|
872
|
+
else {
|
|
873
|
+
const by = {};
|
|
874
|
+
for (const b of this.bucketsOf(f)) {
|
|
875
|
+
const inB = pool.filter((r) => this.inBucket(r, f, b));
|
|
876
|
+
by[b.name] = inB.length;
|
|
877
|
+
for (const r of inB)
|
|
878
|
+
add(b.name, r);
|
|
879
|
+
}
|
|
880
|
+
counts[fname] = by;
|
|
881
|
+
}
|
|
882
|
+
if (f.sums.length)
|
|
883
|
+
sums[fname] = totals;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
const nested = opts.all ? {} : this.nestedCounts(v, (fname) => all.filter((r) => passes(r, fname)));
|
|
887
|
+
const chosen = all.filter((r) => passes(r));
|
|
888
|
+
const pages = opts.all ? 1 : Math.max(1, Math.ceil(chosen.length / v.page));
|
|
889
|
+
const page = opts.all ? 1 : (opts.page ?? 1);
|
|
890
|
+
const onPage = opts.all ? chosen : chosen.slice((page - 1) * v.page, page * v.page);
|
|
891
|
+
const pickList = Object.entries(picks).filter(([, c]) => c.length);
|
|
892
|
+
const indexable = page === 1 && (pickList.length === 0 || (pickList.length === 1 && v.index.includes(pickList[0]?.[0]) && pickList[0]?.[1].length === 1));
|
|
893
|
+
const [shapeName = "", ...more] = v.shapes;
|
|
894
|
+
const rows = onPage.map((r) => {
|
|
895
|
+
const row = this.shaped(r, shapeName, audience, opts);
|
|
896
|
+
// Further shapes (12.1) share the selection: their output rides under `shapes`, served on request.
|
|
897
|
+
const shapes = {};
|
|
898
|
+
for (const s of more) {
|
|
899
|
+
const out = this.shaped(r, s, audience, opts);
|
|
900
|
+
delete out.record;
|
|
901
|
+
if (Object.keys(out).length)
|
|
902
|
+
shapes[s] = s === "crubal:jsonld" ? out.jsonld : s === "crubal:portable" ? out.values : out;
|
|
903
|
+
}
|
|
904
|
+
if (Object.keys(shapes).length)
|
|
905
|
+
row.shapes = shapes;
|
|
906
|
+
// A partitioned view's row carries its record's ancestors, so an index can match edges to it.
|
|
907
|
+
if (partition !== "none" && opts.access)
|
|
908
|
+
row.ancestors = opts.access.ancestors(r.id);
|
|
909
|
+
// A linked partition's row carries whom the record's link facet names (12.2), so an index can bound by it.
|
|
910
|
+
const linked = partition.match(/^linked (\S+)$/);
|
|
911
|
+
if (linked && opts.access) {
|
|
912
|
+
const t = r.values[linked[1]];
|
|
913
|
+
if (isObj(t) && typeof t.$link === "string")
|
|
914
|
+
row.linked = t.$link;
|
|
915
|
+
}
|
|
916
|
+
return row;
|
|
917
|
+
});
|
|
918
|
+
return { rows, records: onPage.map((r) => r.id), counts, ...(Object.keys(sums).length ? { sums } : {}), ...(Object.keys(nested).length ? { nested } : {}), pages, indexable };
|
|
919
|
+
}
|
|
920
|
+
/** One record in one shape: a core shape's object, or the shape's slots with their role marks. */
|
|
921
|
+
shaped(r, shapeName, audience, opts) {
|
|
922
|
+
if (shapeName === "crubal:portable")
|
|
923
|
+
return { record: r.id, values: this.portable(r, audience, opts.caller) };
|
|
924
|
+
if (shapeName === "crubal:jsonld") {
|
|
925
|
+
const ld = this.jsonld(r, audience);
|
|
926
|
+
return ld ? { record: r.id, jsonld: ld } : { record: r.id };
|
|
927
|
+
}
|
|
928
|
+
const row = { record: r.id };
|
|
929
|
+
const marks = {};
|
|
930
|
+
for (const s of this.set.shapes.get(shapeName)?.slots ?? []) {
|
|
931
|
+
// A slot holding a view (12.1): that view's rows, with this record as their context.
|
|
932
|
+
if (s.from.startsWith("view:")) {
|
|
933
|
+
const inner = this.nestedRows(s.from.slice(5), r, audience, opts);
|
|
934
|
+
if (inner.length)
|
|
935
|
+
row[s.to] = inner;
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
const val = this.slot(r, s, audience, opts.caller);
|
|
939
|
+
if (val !== undefined)
|
|
940
|
+
row[s.to] = val;
|
|
941
|
+
const m = opts.caller ? [] : this.marksFor(s, audience);
|
|
942
|
+
if (val !== undefined && m.length)
|
|
943
|
+
marks[s.to] = m.length === 1 ? m[0] : m;
|
|
944
|
+
}
|
|
945
|
+
if (Object.keys(marks).length)
|
|
946
|
+
row.marks = marks;
|
|
947
|
+
return row;
|
|
948
|
+
}
|
|
949
|
+
/** A nested view's rows for a page record (12.1, 12.2 `of`): every page, in the view's order. */
|
|
950
|
+
nestedRows(name, context, audience, opts) {
|
|
951
|
+
return this.project(name, { audience, context, all: true, ...(opts.caller ? { caller: opts.caller } : {}), ...(opts.access ? { access: opts.access } : {}) }).rows;
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Structured data (12.5): schema.org JSON-LD for the public from the kind's type per level (11.2) and
|
|
955
|
+
* each facet's `same-as` in the schema prefix; nothing for any other audience.
|
|
956
|
+
*/
|
|
957
|
+
jsonld(r, audience = "public") {
|
|
958
|
+
if (audience !== "public")
|
|
959
|
+
return undefined;
|
|
960
|
+
const out = { "@context": "https://schema.org/" };
|
|
961
|
+
const kind = this.dict.kinds.get(this.dict.levels.get(r.level) ?? "");
|
|
962
|
+
const type = typeof kind?.schema === "string" ? kind.schema : kind?.schema?.[r.level];
|
|
963
|
+
if (type)
|
|
964
|
+
out["@type"] = type.replace(/^schema:/, "");
|
|
965
|
+
for (const [key, v] of Object.entries(this.effective(r))) {
|
|
966
|
+
if (!this.canSee(key, "public", undefined, r))
|
|
967
|
+
continue;
|
|
968
|
+
const f = this.dict.facets.get(key);
|
|
969
|
+
const same = f?.sameAs.find((s) => s.startsWith("schema:"));
|
|
970
|
+
if (!same)
|
|
971
|
+
continue;
|
|
972
|
+
const vals = (Array.isArray(v) ? v : [v]).filter((x) => this.fit(key, x, "public") && !(isObj(x) && "$empty" in x));
|
|
973
|
+
if (!vals.length)
|
|
974
|
+
continue;
|
|
975
|
+
const prop = same.slice(7);
|
|
976
|
+
const plain = vals.map((x) => {
|
|
977
|
+
if (isObj(x) && "$money" in x)
|
|
978
|
+
return { price: String(x.$money), priceCurrency: String(x.currency) };
|
|
979
|
+
if (isObj(x) && "$qty" in x)
|
|
980
|
+
return `${x.$qty} ${x.unit}`;
|
|
981
|
+
if (isObj(x) && "$link" in x)
|
|
982
|
+
return { "@id": String(x.$link) };
|
|
983
|
+
if (isObj(x) && "$image" in x)
|
|
984
|
+
return String(x.$image);
|
|
985
|
+
if (isObj(x) && "$color" in x)
|
|
986
|
+
return String(x.$color);
|
|
987
|
+
return plainText(x);
|
|
988
|
+
});
|
|
989
|
+
out[prop] = plain.length === 1 ? plain[0] : plain;
|
|
990
|
+
}
|
|
991
|
+
return out;
|
|
992
|
+
}
|
|
993
|
+
streams = new Map();
|
|
994
|
+
/** A view's version, as its stream names it. */
|
|
995
|
+
versionOf(name) {
|
|
996
|
+
return this.set.views.get(name)?.version ?? "";
|
|
997
|
+
}
|
|
998
|
+
/** A new version of a view: its stream starts over at the next publish (12.6). */
|
|
999
|
+
revise(name, version) {
|
|
1000
|
+
const v = this.set.views.get(name);
|
|
1001
|
+
if (!v)
|
|
1002
|
+
throw new Error(`no view ${name}`);
|
|
1003
|
+
v.version = version;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* The projection stream (12.6): the entries since the last publish of this view for this audience, one
|
|
1007
|
+
* per row that is new or changed, and one removal per row that left. Numbered per view and audience; a
|
|
1008
|
+
* new version of the view starts over at 1, its first entry marked `reset`.
|
|
1009
|
+
*/
|
|
1010
|
+
stream(name, opts = {}) {
|
|
1011
|
+
const v = this.set.views.get(name);
|
|
1012
|
+
if (!v)
|
|
1013
|
+
throw new Error(`no view ${name}`);
|
|
1014
|
+
const audience = opts.audience ?? v.show;
|
|
1015
|
+
const key = `${name}|${audience}`;
|
|
1016
|
+
const version = v.version ?? "";
|
|
1017
|
+
const projection = version ? `${name} /${version}` : name;
|
|
1018
|
+
const had = this.streams.get(key);
|
|
1019
|
+
const last = had && had.version === version ? had : { version, rows: new Map(), seq: 0, log: [], published: false };
|
|
1020
|
+
const reset = !!had && had.version !== version;
|
|
1021
|
+
const now = new Map();
|
|
1022
|
+
for (const row of this.project(name, { ...opts, audience, all: true }).rows)
|
|
1023
|
+
now.set(String(row.record), row);
|
|
1024
|
+
const out = [];
|
|
1025
|
+
const next = { version, rows: new Map(), seq: last.seq, log: [...last.log], published: true };
|
|
1026
|
+
for (const [id, row] of now) {
|
|
1027
|
+
const rec = this.records.get(id);
|
|
1028
|
+
const buckets = rec ? this.bucketsFor(v, rec) : {};
|
|
1029
|
+
const order = rec ? this.sortOf(v, rec) : { sort: [] };
|
|
1030
|
+
const s = serialize({ row, buckets, order: order });
|
|
1031
|
+
next.rows.set(id, s);
|
|
1032
|
+
if (last.rows.get(id) !== s)
|
|
1033
|
+
out.push({ projection, audience, seq: ++next.seq, record: id, row, ...(Object.keys(buckets).length ? { buckets } : {}), ...(order.sort.length ? { sort: order.sort } : {}), ...(order.pin ? { pin: order.pin } : {}) });
|
|
1034
|
+
}
|
|
1035
|
+
for (const id of last.rows.keys())
|
|
1036
|
+
if (!now.has(id))
|
|
1037
|
+
out.push({ projection, audience, seq: ++next.seq, record: id, removed: true });
|
|
1038
|
+
if (reset && out[0])
|
|
1039
|
+
out[0].reset = true;
|
|
1040
|
+
next.log.push(...out);
|
|
1041
|
+
this.streams.set(key, next);
|
|
1042
|
+
return out;
|
|
1043
|
+
}
|
|
1044
|
+
/** The current version's entries after `seq`, for an index resuming from its cursor (12.6.2); at most `limit` when given. */
|
|
1045
|
+
entriesSince(name, seq, audience, limit) {
|
|
1046
|
+
const v = this.set.views.get(name);
|
|
1047
|
+
const s = this.streams.get(`${name}|${audience ?? v?.show ?? "public"}`);
|
|
1048
|
+
const all = (s?.log ?? []).filter((e) => e.seq > seq);
|
|
1049
|
+
return limit && limit > 0 ? all.slice(0, Math.floor(limit)) : all;
|
|
1050
|
+
}
|
|
1051
|
+
/** The portable shape (12.1): key, label, type and value for every value the audience may see. */
|
|
1052
|
+
portable(r, audience = "public", caller) {
|
|
1053
|
+
return Object.entries(r.values).flatMap(([key, v]) => {
|
|
1054
|
+
if (!this.canSee(key, audience, caller))
|
|
1055
|
+
return [];
|
|
1056
|
+
const f = this.dict.facets.get(key);
|
|
1057
|
+
return [{ key, label: f?.label ?? label(key), type: f?.type ?? "raw", value: v }];
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
/** The keys a view reads (12.6), with level prefixes kept. */
|
|
1061
|
+
readSet(name) {
|
|
1062
|
+
const v = this.set.views.get(name);
|
|
1063
|
+
if (!v)
|
|
1064
|
+
return new Set();
|
|
1065
|
+
const keys = [];
|
|
1066
|
+
if (v.when)
|
|
1067
|
+
keys.push(...parseConditionKeys(v.when));
|
|
1068
|
+
if (v.of)
|
|
1069
|
+
keys.push(...parseConditionKeys(v.of.replace(/context\.\w+/g, '""')));
|
|
1070
|
+
keys.push(...v.order.map((o) => o.key));
|
|
1071
|
+
if (v.list)
|
|
1072
|
+
keys.push("crubal:items");
|
|
1073
|
+
for (const s of v.shapes)
|
|
1074
|
+
for (const sl of this.set.shapes.get(s)?.slots ?? []) {
|
|
1075
|
+
if (sl.from.startsWith("view:"))
|
|
1076
|
+
keys.push(...this.readSet(sl.from.slice(5)));
|
|
1077
|
+
else
|
|
1078
|
+
keys.push(...slotKeys(sl.from));
|
|
1079
|
+
}
|
|
1080
|
+
for (const f of v.filters)
|
|
1081
|
+
keys.push(...(this.set.filters.get(f)?.dependent ?? []));
|
|
1082
|
+
for (const f of v.filters)
|
|
1083
|
+
keys.push(this.set.filters.get(f)?.facet ?? f);
|
|
1084
|
+
for (const k of [...keys])
|
|
1085
|
+
if (this.set.shown.has(k) || this.set.shownFor.has(k))
|
|
1086
|
+
keys.push(k);
|
|
1087
|
+
return new Set(keys.filter((k) => k !== "id"));
|
|
1088
|
+
}
|
|
1089
|
+
/** Which of a view's rows a write makes stale: the written record, or what reads it through. */
|
|
1090
|
+
staleAfter(name, write) {
|
|
1091
|
+
const v = this.set.views.get(name);
|
|
1092
|
+
if (!v)
|
|
1093
|
+
return [];
|
|
1094
|
+
const reads = this.readSet(name);
|
|
1095
|
+
const out = new Set();
|
|
1096
|
+
// The envelope is in every read set (12.6): a status, wears, within or of change stales the row.
|
|
1097
|
+
const was = this.records.get(write.id);
|
|
1098
|
+
const envelope = ["status", "wears", "within", "of"].some((m) => serialize((write[m] ?? "")) !== serialize((was?.[m] ?? "")));
|
|
1099
|
+
if (envelope)
|
|
1100
|
+
out.add(write.id);
|
|
1101
|
+
for (const key of Object.keys(write.values)) {
|
|
1102
|
+
if (reads.has(key) && (!v.level || write.level === v.level))
|
|
1103
|
+
out.add(write.id);
|
|
1104
|
+
if (reads.has(`${write.level}::${key}`) && write.of)
|
|
1105
|
+
out.add(write.of);
|
|
1106
|
+
if (reads.has(key) && v.level && write.level !== v.level) {
|
|
1107
|
+
for (const r of this.records.childrenOf(write.id, "of", v.level))
|
|
1108
|
+
out.add(r.id);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
// A write to a shared part stales the rows that read it through a link (1.6, 12.6): the linking records.
|
|
1112
|
+
for (const read of reads) {
|
|
1113
|
+
const ls = linkStep(read, this.dict);
|
|
1114
|
+
if (!ls)
|
|
1115
|
+
continue;
|
|
1116
|
+
// Only a write of what the link points at (its kind, or a class it wears) can be a shared part here.
|
|
1117
|
+
const to = this.dict.facets.get(ls.link)?.to;
|
|
1118
|
+
if (!to || !(to === write.kind || (write.wears ?? []).includes(to)))
|
|
1119
|
+
continue;
|
|
1120
|
+
if (!envelope && !(leafOf(ls.rest, this.dict) in write.values))
|
|
1121
|
+
continue;
|
|
1122
|
+
const linkers = [...this.records.byKey(ls.link, { $link: write.id }), ...this.records.byKey(ls.link, [{ $link: write.id }])];
|
|
1123
|
+
for (const r of linkers)
|
|
1124
|
+
if (!v.level || r.level === v.level)
|
|
1125
|
+
out.add(r.id);
|
|
1126
|
+
}
|
|
1127
|
+
// A write to the list's items (12.2) stales every row: those it holds now, and those it will hold.
|
|
1128
|
+
if (v.list && write.id === v.list) {
|
|
1129
|
+
for (const r of this.listed(v))
|
|
1130
|
+
out.add(r.id);
|
|
1131
|
+
const items = write.values["crubal:items"];
|
|
1132
|
+
for (const x of Array.isArray(items) ? items : items === undefined ? [] : [items])
|
|
1133
|
+
out.add(isObj(x) && "$link" in x ? String(x.$link) : String(x));
|
|
1134
|
+
out.delete(write.id);
|
|
1135
|
+
}
|
|
1136
|
+
// A page whose nested view holds, or would hold, the written record is stale (12.1).
|
|
1137
|
+
for (const s of v.shapes)
|
|
1138
|
+
for (const sl of this.set.shapes.get(s)?.slots ?? []) {
|
|
1139
|
+
if (!sl.from.startsWith("view:"))
|
|
1140
|
+
continue;
|
|
1141
|
+
const inner = this.set.views.get(sl.from.slice(5));
|
|
1142
|
+
if (!inner)
|
|
1143
|
+
continue;
|
|
1144
|
+
for (const page of this.select(v, { audience: v.show })) {
|
|
1145
|
+
const o = { audience: v.show, context: page };
|
|
1146
|
+
const is = was ? this.selects(inner, was, o) : false;
|
|
1147
|
+
const will = this.selects(inner, write, o);
|
|
1148
|
+
if (is || will)
|
|
1149
|
+
out.add(page.id);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
return [...out];
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
function parseConditionKeys(text) {
|
|
1156
|
+
const out = [];
|
|
1157
|
+
const walk = (e) => {
|
|
1158
|
+
if (e.op === "test")
|
|
1159
|
+
out.push(e.path.replace(/^(count|least|most|sum) of /, ""));
|
|
1160
|
+
else if (e.op === "not")
|
|
1161
|
+
walk(e.a);
|
|
1162
|
+
else {
|
|
1163
|
+
walk(e.a);
|
|
1164
|
+
walk(e.b);
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
walk(parseCondition(text));
|
|
1168
|
+
return out;
|
|
1169
|
+
}
|
|
1170
|
+
//# sourceMappingURL=views.js.map
|