@blueshed/joined 0.2.2 → 0.3.1
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/.claude/skills/joined/SKILL.md +9 -1
- package/.claude/skills/joined/reference.md +316 -63
- package/.claude/skills/joined-door/SKILL.md +57 -0
- package/README.md +19 -50
- package/docs/design.md +158 -37
- package/docs/introduction.md +27 -27
- package/docs/light-and-shadow.svg +2 -1
- package/docs/links-and-trust.svg +1 -0
- package/docs/stories-to-code.svg +2 -1
- package/docs/wire-op.svg +1 -0
- package/examples/README.md +20 -0
- package/examples/account/account.json +1 -0
- package/examples/account/derive.ts +41 -0
- package/examples/account/generated/elements.ts +52 -0
- package/examples/account/generated/rows.ts +22 -0
- package/examples/account/generated/rules.ts +32 -0
- package/examples/account/routes.ts +5 -0
- package/examples/app.css +11 -1
- package/examples/cafe/books.html +2 -2
- package/examples/cafe/cafe.css +96 -85
- package/examples/cafe/generated/books.rows.ts +22 -0
- package/examples/cafe/generated/books.rules.ts +3 -2
- package/examples/cafe/generated/kitchen.rows.ts +27 -0
- package/examples/cafe/generated/kitchen.rules.ts +11 -1
- package/examples/cafe/generated/menu.rows.ts +22 -0
- package/examples/cafe/generated/menu.rules.ts +3 -2
- package/examples/cafe/generated/order.rows.ts +27 -0
- package/examples/cafe/generated/order.rules.ts +11 -1
- package/examples/cafe/generated/staff.elements.ts +7 -2
- package/examples/cafe/generated/staff.rows.ts +22 -0
- package/examples/cafe/generated/staff.rules.ts +9 -1
- package/examples/cafe/generated/supplies.queries.ts +4 -2
- package/examples/cafe/generated/supplies.rows.ts +22 -0
- package/examples/cafe/generated/supplies.rules.ts +17 -1
- package/examples/cafe/generated/till.queries.ts +2 -0
- package/examples/cafe/generated/till.rows.ts +27 -0
- package/examples/cafe/generated/till.rules.ts +11 -1
- package/examples/cafe/index.html +14 -15
- package/examples/cafe/kitchen.css +11 -19
- package/examples/cafe/kitchen.ts +7 -3
- package/examples/cafe/look.ts +30 -0
- package/examples/cafe/menu.html +10 -26
- package/examples/cafe/menu.ts +8 -80
- package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
- package/examples/cafe/order.html +8 -7
- package/examples/cafe/order.ts +6 -2
- package/examples/cafe/routes.ts +0 -1
- package/examples/cafe/staff.json +5 -0
- package/examples/cafe/stories.jsonl +6 -2
- package/examples/cafe/supplies.html +35 -34
- package/examples/cafe/supplies.ts +59 -39
- package/examples/cafe/till.ts +19 -11
- package/examples/cafe/views.ts +7 -5
- package/examples/chart/arches.ts +150 -0
- package/examples/chart/chart.css +11 -0
- package/examples/chart/chart.json +87 -0
- package/examples/chart/generated/elements.ts +105 -0
- package/examples/chart/generated/queries.ts +36 -0
- package/examples/chart/generated/rows.ts +27 -0
- package/examples/chart/generated/rules.ts +111 -0
- package/examples/chart/grid.ts +118 -0
- package/examples/chart/index.html +78 -0
- package/examples/chart/migrations/001-chart.ts +6 -0
- package/examples/chart/migrations/002-create-conditions.ts +6 -0
- package/examples/chart/page.ts +20 -0
- package/examples/chart/routes.ts +7 -0
- package/examples/chart/stories.jsonl +14 -0
- package/examples/chart/teeth.ts +57 -0
- package/examples/desk/desk.css +6 -10
- package/examples/desk/generated/elements.ts +1 -1
- package/examples/desk/generated/rows.ts +22 -0
- package/examples/desk/generated/rules.ts +34 -1
- package/examples/desk/index.html +10 -3
- package/examples/desk/lanes.css +21 -19
- package/examples/desk/routes.ts +0 -2
- package/examples/desk/stories.jsonl +4 -3
- package/examples/desk/tally.css +1 -1
- package/examples/desk/thumbs.ts +2 -2
- package/examples/docs.ts +7 -4
- package/examples/hello/generated/elements.ts +2 -2
- package/examples/hello/generated/rules.ts +3 -2
- package/examples/hello/hello.css +2 -4
- package/examples/hello/index.html +10 -3
- package/examples/hello/page.ts +4 -4
- package/examples/index.html +20 -12
- package/examples/notes/generated/elements.ts +112 -0
- package/examples/notes/generated/queries.ts +42 -0
- package/examples/notes/generated/rows.ts +27 -0
- package/examples/notes/generated/rules.ts +133 -0
- package/examples/notes/index.html +32 -0
- package/examples/notes/look.ts +41 -0
- package/examples/notes/migrations/001-notes.ts +7 -0
- package/examples/notes/notes.json +78 -0
- package/examples/notes/page.ts +21 -0
- package/examples/notes/routes.ts +6 -0
- package/examples/notes/stories.jsonl +24 -0
- package/examples/page.ts +9 -2
- package/examples/people/generated/rows.ts +22 -0
- package/examples/people/generated/rules.ts +11 -1
- package/examples/people/links.ts +8 -9
- package/examples/people/people.css +1 -1
- package/examples/people/routes.ts +1 -3
- package/examples/people/stories.jsonl +1 -0
- package/examples/people/view.ts +5 -2
- package/examples/trip/generated/elements.ts +5 -3
- package/examples/trip/generated/queries.ts +12 -1
- package/examples/trip/generated/rows.ts +27 -0
- package/examples/trip/generated/rules.ts +56 -2
- package/examples/trip/index.html +58 -12
- package/examples/trip/line.css +186 -0
- package/examples/trip/line.ts +51 -40
- package/examples/trip/page.ts +65 -71
- package/examples/trip/routes.ts +9 -5
- package/examples/trip/stays.css +13 -13
- package/examples/trip/stays.ts +15 -10
- package/examples/trip/stories.jsonl +2 -0
- package/examples/trip/told.ts +3 -26
- package/examples/trip/trip.css +16 -0
- package/examples/trips/generated/elements.ts +1 -1
- package/examples/trips/generated/rows.ts +22 -0
- package/examples/trips/generated/rules.ts +9 -1
- package/examples/trips/index.html +10 -10
- package/examples/trips/map.ts +3 -14
- package/examples/trips/new-trip.ts +14 -16
- package/examples/trips/trips.css +24 -23
- package/examples/weeks/generated/elements.ts +1 -1
- package/examples/weeks/generated/queries.ts +11 -0
- package/examples/weeks/generated/rows.ts +22 -0
- package/examples/weeks/generated/rules.ts +11 -5
- package/examples/weeks/routes.ts +3 -2
- package/examples/weeks/stories.jsonl +1 -0
- package/examples/welcome.css +43 -33
- package/package.json +8 -2
- package/src/attachment.ts +17 -2
- package/src/awesome.ts +103 -0
- package/src/board.css +76 -0
- package/src/board.ts +173 -0
- package/src/cli.ts +28 -3
- package/src/compile.ts +821 -109
- package/src/definitions.ts +113 -27
- package/src/demo.css +2 -5
- package/src/draft.ts +48 -27
- package/src/drawer.ts +248 -0
- package/src/engine.ts +253 -170
- package/src/fields.ts +341 -0
- package/src/file-value.ts +12 -2
- package/src/files.ts +113 -33
- package/src/ground.ts +110 -0
- package/src/icon-names.ts +19 -2
- package/src/keep.ts +16 -3
- package/src/kit.ts +51 -0
- package/src/link.ts +3 -3
- package/src/map.css +140 -0
- package/src/map.ts +200 -0
- package/src/mcp.ts +129 -24
- package/src/members/demo.ts +13 -12
- package/src/members/generated/rows.ts +22 -0
- package/src/members/generated/rules.ts +3 -2
- package/src/members/group.ts +105 -55
- package/src/members/keys.ts +95 -79
- package/src/members/panel.css +40 -35
- package/src/members/panel.ts +58 -37
- package/src/migrate.ts +178 -125
- package/src/migrations/005-change-kept.ts +7 -0
- package/src/month.css +129 -0
- package/src/month.ts +179 -0
- package/src/ops.ts +40 -1
- package/src/page.css +11 -2
- package/src/page.ts +68 -17
- package/src/parts.css +614 -230
- package/src/parts.ts +259 -36
- package/src/plane.css +61 -0
- package/src/plane.ts +153 -0
- package/src/postgres-server.ts +60 -0
- package/src/reading.css +73 -0
- package/src/reading.ts +238 -0
- package/src/rows.css +289 -0
- package/src/rows.ts +864 -0
- package/src/search.css +80 -0
- package/src/search.ts +130 -0
- package/src/server.ts +355 -137
- package/src/settings.ts +9 -4
- package/src/sheet.ts +116 -0
- package/src/skill.ts +40 -0
- package/src/slots.css +90 -0
- package/src/slots.ts +213 -0
- package/src/specs.ts +38 -0
- package/src/starter.ts +19 -2
- package/src/store.ts +224 -161
- package/src/stories.ts +43 -11
- package/src/surface.ts +164 -0
- package/src/time.ts +2 -0
- package/src/timeline.css +111 -0
- package/src/timeline.ts +235 -0
- package/src/toast.ts +21 -48
- package/src/together.ts +15 -24
- package/src/tokens.css +89 -3
- package/src/tokens.json +287 -7
- package/src/tool.ts +210 -0
- package/src/upkeep.ts +47 -22
- package/src/views.css +43 -0
- package/src/views.ts +111 -0
- package/src/week.css +150 -0
- package/src/week.ts +254 -0
- package/src/write.ts +326 -78
- package/starter/CHANGELOG.md +8 -0
- package/starter/CLAUDE.md +9 -3
- package/starter/bunfig +5 -0
- package/starter/githooks/pre-commit +13 -0
- package/starter/prettierignore +5 -0
- package/starter/tests/hello.test.ts +2 -0
- package/starter/tests/records.test.ts +40 -0
- package/starter/todo.jsonl +0 -0
- package/docs/learning.md +0 -76
- package/examples/cafe/trust.ts +0 -20
- package/examples/desk/trust.ts +0 -24
- package/examples/people/trust.ts +0 -14
- package/examples/trip/answer-rows.ts +0 -70
- package/examples/trip/bar.ts +0 -89
- package/examples/trip/calendar-map.css +0 -711
- package/examples/trip/calendar-map.ts +0 -249
- package/examples/trip/drags.ts +0 -143
- package/examples/trip/drawer.ts +0 -250
- package/examples/trip/event-form.ts +0 -200
- package/examples/trip/holding.ts +0 -61
- package/examples/trip/map.ts +0 -234
- package/examples/trip/month.ts +0 -87
- package/examples/trip/other-weeks.ts +0 -67
- package/examples/trip/peek.ts +0 -71
- package/examples/trip/people-chips.ts +0 -74
- package/examples/trip/shell.ts +0 -39
- package/examples/trip/trust.ts +0 -51
- package/examples/trip/week.ts +0 -237
- package/examples/trip/writes.ts +0 -91
- package/examples/trip/zones.ts +0 -16
- package/examples/weeks/derive.ts +0 -23
- package/src/scrim.ts +0 -81
package/src/compile.ts
CHANGED
|
@@ -16,15 +16,19 @@ import {
|
|
|
16
16
|
grantOf,
|
|
17
17
|
grantsOf,
|
|
18
18
|
whoCode,
|
|
19
|
+
pathSaid,
|
|
19
20
|
whoRules,
|
|
20
21
|
whoSql,
|
|
22
|
+
kindFrozen,
|
|
21
23
|
type Definitions,
|
|
24
|
+
type Frozen,
|
|
25
|
+
type Counted,
|
|
22
26
|
type Query,
|
|
23
27
|
type Where,
|
|
24
28
|
} from "./definitions.ts";
|
|
25
|
-
import { refuseSql, triggerSql, type Dialect, type Trigger } from "./engine.ts";
|
|
26
|
-
import { diff, fromFolder, stateOf, writeMigration, type Change, type Column, type Table } from "./migrate.ts";
|
|
27
|
-
import { docParts, parts, type Op, type Type } from "./ops.ts";
|
|
29
|
+
import { constraintSql, refuseSql, triggerSql, type Dialect, type Trigger } from "./engine.ts";
|
|
30
|
+
import { diff, fromFolder, isAdd, stateOf, writeMigration, type Change, type Column, type Table } from "./migrate.ts";
|
|
31
|
+
import { docParts, linksNamed, NTH, parts, type Linked, type Op, type Type } from "./ops.ts";
|
|
28
32
|
import { settingsCode, settingsSaid, settingsUnchecked } from "./settings.ts";
|
|
29
33
|
import { partsOf, told as toldOf, unwritten, writtenBefore } from "./together.ts";
|
|
30
34
|
import { guestRole, visitorsRefused } from "./visitors.ts";
|
|
@@ -58,12 +62,18 @@ type Coll = {
|
|
|
58
62
|
unlink: string[];
|
|
59
63
|
/** The fields the server fills (definitions' fills), with what: "now", or a value. */
|
|
60
64
|
fills?: Record<string, unknown>;
|
|
65
|
+
/** Where the zone of a wall clock it fills "now" is said, the first that says one: the item's own, its kind's
|
|
66
|
+
* root's, the document's own. */
|
|
67
|
+
clock?: ("item" | "root" | "document")[];
|
|
61
68
|
/** The field whose time, when it comes, the server clears (definitions' timed). */
|
|
62
69
|
timed?: string;
|
|
63
70
|
/** The document's own fields (hello's greeting, /greeting): a collection named for it, of one item. */
|
|
64
71
|
own?: true;
|
|
65
72
|
/** The fields it takes from what a link points at, once, when it's added (definitions' copies). */
|
|
66
73
|
copies?: { from: string; fields: string[]; to: string; at: string };
|
|
74
|
+
/** Where no story adds one (the seed's items are all there are): the fields every seed item has, typed as there,
|
|
75
|
+
* as a field an add needs is; its tables are as they were, since the seed isn't what the store holds. */
|
|
76
|
+
seedHas?: string[];
|
|
67
77
|
};
|
|
68
78
|
/** A document's model: its name, and its collections. */
|
|
69
79
|
type Model = { doc: string; collections: Record<string, Coll> };
|
|
@@ -109,6 +119,9 @@ export const SAID: Record<Type, string> = {
|
|
|
109
119
|
ids: "a list of ids",
|
|
110
120
|
};
|
|
111
121
|
const STRINGS: Type[] = ["string", "date-time", "zone", "instant", "duration", "place", "file"];
|
|
122
|
+
/** The forms that have a view of their own, which a page pops (docs/design.md, "A peek"): a time its month, a place its
|
|
123
|
+
* map, a file its picture. */
|
|
124
|
+
const VIEWED: Type[] = ["date-time", "instant", "place", "file"];
|
|
112
125
|
|
|
113
126
|
/** Whether a value is an object of fields (an order's terms), not a list. */
|
|
114
127
|
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -116,12 +129,13 @@ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "obj
|
|
|
116
129
|
const flatKeys = (value: Record<string, unknown>) =>
|
|
117
130
|
Object.entries(value).flatMap(([f, v]) => (isObject(v) ? Object.keys(v).map((k) => `${f}.${k}`) : [f]));
|
|
118
131
|
|
|
119
|
-
/** A value's type: a string's form, a number's fraction, or none it can be.
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
132
|
+
/** A value's type: a string's form, a number's fraction, or none it can be. Where a link is (`link`), "$n" is an id:
|
|
133
|
+
* the id an add before it in the same write was given; anywhere else it's words. */
|
|
134
|
+
const typeOf = (v: unknown, link = false): Type | undefined => {
|
|
135
|
+
const id = (x: unknown) => Number.isInteger(x) || (link && typeof x === "string" && NTH.test(x));
|
|
136
|
+
return typeof v === "string"
|
|
137
|
+
? id(v)
|
|
138
|
+
? "integer"
|
|
125
139
|
: ((Object.keys(FORMS) as (keyof typeof FORMS)[]).find((k) => FORMS[k].test(v)) ?? "string")
|
|
126
140
|
: typeof v === "number"
|
|
127
141
|
? Number.isInteger(v)
|
|
@@ -129,9 +143,11 @@ const typeOf = (v: unknown): Type | undefined =>
|
|
|
129
143
|
: "decimal"
|
|
130
144
|
: typeof v === "boolean"
|
|
131
145
|
? "boolean"
|
|
132
|
-
:
|
|
146
|
+
: // a list of ids is a link: any of them an add's before it in the same write ("$1")
|
|
147
|
+
Array.isArray(v) && v.every((x) => Number.isInteger(x) || (typeof x === "string" && NTH.test(x)))
|
|
133
148
|
? "ids"
|
|
134
149
|
: undefined;
|
|
150
|
+
};
|
|
135
151
|
/** The type two values of a field are together: strings of two forms are strings, and a fraction makes a decimal. */
|
|
136
152
|
const both = (a: Type, b: Type): Type | undefined =>
|
|
137
153
|
a === b
|
|
@@ -144,14 +160,28 @@ const both = (a: Type, b: Type): Type | undefined =>
|
|
|
144
160
|
|
|
145
161
|
/** A model with what its definitions say the server fills and clears: each a field of the server's, which no
|
|
146
162
|
* story gives (a "random" code a story may replace, the server making it new), its type its fill's ("now" an
|
|
147
|
-
* instant); a timed field an instant the stories give, in
|
|
148
|
-
* that isn't a kind. */
|
|
149
|
-
export function filled(
|
|
163
|
+
* instant, or a wall clock where the seed's items, `seed`, give it one); a timed field an instant the stories give, in
|
|
164
|
+
* a document that isn't a kind. */
|
|
165
|
+
export function filled(
|
|
166
|
+
model: Model,
|
|
167
|
+
defs: Definitions,
|
|
168
|
+
from: string,
|
|
169
|
+
seed: (coll: string) => Record<string, unknown>[] = () => [],
|
|
170
|
+
) {
|
|
150
171
|
const at = (coll: string, what: string) => {
|
|
151
172
|
const c = model.collections[coll];
|
|
152
173
|
if (!c) throw new Error(`${from}: ${what} names ${coll}, which no story has`);
|
|
153
174
|
return c;
|
|
154
175
|
};
|
|
176
|
+
const nowIs = (coll: string, f: string): Type => {
|
|
177
|
+
const given = new Set(seed(coll).flatMap((i) => (i[f] === undefined ? [] : [typeOf(i[f])])));
|
|
178
|
+
const [t = "instant", ...more] = given;
|
|
179
|
+
if (more.length || (t !== "instant" && t !== "date-time"))
|
|
180
|
+
throw new Error(
|
|
181
|
+
`${from}: ${coll}' ${f} is filled "now", so its seed gives it ${SAID.instant} or ${SAID["date-time"]}, each the same`,
|
|
182
|
+
);
|
|
183
|
+
return t;
|
|
184
|
+
};
|
|
155
185
|
for (const [coll, fills] of Object.entries(defs.fills ?? {})) {
|
|
156
186
|
const c = at(coll, "fills");
|
|
157
187
|
for (const [f, v] of Object.entries(fills)) {
|
|
@@ -162,7 +192,7 @@ export function filled(model: Model, defs: Definitions, from: string) {
|
|
|
162
192
|
if (c.fields[f] && !moved && !renewed)
|
|
163
193
|
throw new Error(`${from}: ${coll}' ${f} is the server's to fill, so no story gives it`);
|
|
164
194
|
// "me": the member who adds it, an id
|
|
165
|
-
const t = v === "now" ?
|
|
195
|
+
const t = v === "now" ? nowIs(coll, f) : v === "me" ? "integer" : typeOf(v);
|
|
166
196
|
if (!t || t === "ids")
|
|
167
197
|
throw new Error(`${from}: ${coll}' ${f} is filled with a string, a boolean, a number, "now" or "me"`);
|
|
168
198
|
c.fields[f] = t;
|
|
@@ -205,7 +235,14 @@ export function filled(model: Model, defs: Definitions, from: string) {
|
|
|
205
235
|
* each item the write touched against the rest of its collection, why it doesn't hold or null. None, if they
|
|
206
236
|
* hold nothing. */
|
|
207
237
|
export function heldBy(collections: Record<string, Coll>, defs: Definitions, from: string) {
|
|
208
|
-
const
|
|
238
|
+
const together = (coll: string) => listsOf(defs.mine?.[coll]).filter((m) => typeof m !== "string");
|
|
239
|
+
const colls = [
|
|
240
|
+
...new Set([
|
|
241
|
+
...Object.keys(defs.unique ?? {}),
|
|
242
|
+
...Object.keys(defs.noOverlap ?? {}),
|
|
243
|
+
...Object.keys(defs.mine ?? {}).filter((c) => together(c).length),
|
|
244
|
+
]),
|
|
245
|
+
];
|
|
209
246
|
if (!colls.length) return "";
|
|
210
247
|
const field = (coll: string, f: string, what: string) => {
|
|
211
248
|
const t = collections[coll]?.fields[f];
|
|
@@ -232,6 +269,15 @@ export function heldBy(collections: Record<string, Coll>, defs: Definitions, fro
|
|
|
232
269
|
` }`,
|
|
233
270
|
);
|
|
234
271
|
}
|
|
272
|
+
// lists each member's own, together: nobody in two of them
|
|
273
|
+
for (const fs of together(coll))
|
|
274
|
+
tests.push(
|
|
275
|
+
` {`,
|
|
276
|
+
` const lists = ${JSON.stringify(fs)}.map((f) => (a[f] ?? []) as number[]);`,
|
|
277
|
+
` if (lists.some((l, n) => l.some((m) => lists.slice(n + 1).some((o) => o.includes(m)))))`,
|
|
278
|
+
` return ${JSON.stringify(`${coll} `)} + a.id + ${JSON.stringify(` has someone in two of ${fs.join(" and ")}: take one back first`)};`,
|
|
279
|
+
` }`,
|
|
280
|
+
);
|
|
235
281
|
const o = defs.noOverlap?.[coll];
|
|
236
282
|
if (o) {
|
|
237
283
|
const [s, e] = o.range,
|
|
@@ -287,6 +333,111 @@ ${
|
|
|
287
333
|
`;
|
|
288
334
|
}
|
|
289
335
|
|
|
336
|
+
/** An item's frozen, by collection (definitions' frozen, an item's own, not a kind's). */
|
|
337
|
+
export const itemsFrozen = (defs: Definitions): Record<string, Frozen> =>
|
|
338
|
+
defs.frozen && !kindFrozen(defs.frozen) ? (defs.frozen as Record<string, Frozen>) : {};
|
|
339
|
+
|
|
340
|
+
/** The lists held as a write leaves them (definitions' within, then apart), by collection: each a list of ids, as
|
|
341
|
+
* the item's other list (`of`) is. */
|
|
342
|
+
export function listRules(defs: Definitions, collections: Record<string, Coll>, from: string) {
|
|
343
|
+
const out: Record<string, { lists: string[]; of?: string; refused: string }[]> = {};
|
|
344
|
+
for (const [key, all] of [
|
|
345
|
+
["within", defs.within],
|
|
346
|
+
["apart", defs.apart],
|
|
347
|
+
] as const)
|
|
348
|
+
for (const [coll, rules] of Object.entries(all ?? {}))
|
|
349
|
+
for (const r of rules as { lists: string[]; of?: string; refused: string }[]) {
|
|
350
|
+
for (const l of [...r.lists, ...(r.of ? [r.of] : [])])
|
|
351
|
+
if (collections[coll]?.fields[l] !== "ids")
|
|
352
|
+
throw new Error(`${from}: ${key} names ${coll}' ${l}, which isn't a list of ids`);
|
|
353
|
+
if (typeof r.refused !== "string")
|
|
354
|
+
throw new Error(`${from}: ${key} says the words a write is refused in: refused`);
|
|
355
|
+
(out[coll] ??= []).push(r);
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** generated/rules.ts's listsHold, of SQLite (definitions' within and apart): each item the write touched, as it leaves
|
|
361
|
+
* it, why its lists don't hold, or null. Postgres holds them by its triggers (takesSql). None, if there are none. */
|
|
362
|
+
export function listsHeldBy(collections: Record<string, Coll>, defs: Definitions, from: string) {
|
|
363
|
+
const all = Object.entries(listRules(defs, collections, from));
|
|
364
|
+
if (!all.length) return "";
|
|
365
|
+
return `
|
|
366
|
+
/** Why the lists of an item the write touched don't hold as it leaves them (its definitions' within and apart), or null:
|
|
367
|
+
* asked on SQLite, as Postgres's triggers ask it at the write's end. */
|
|
368
|
+
export function listsHold(d: Record<string, unknown>, touched: Record<string, number[]>): string | null {
|
|
369
|
+
${all
|
|
370
|
+
.map(
|
|
371
|
+
([coll, rules]) => ` for (const id of touched[${JSON.stringify(coll)}] ?? []) {
|
|
372
|
+
const a = ((d[${JSON.stringify(coll)}] ?? []) as any[]).find((i) => i.id === id);
|
|
373
|
+
if (!a) continue;
|
|
374
|
+
const ids = (l: string): number[] => a[l] ?? [];
|
|
375
|
+
${rules
|
|
376
|
+
.map(({ lists, of, refused }) =>
|
|
377
|
+
of
|
|
378
|
+
? ` if (!${JSON.stringify(lists)}.every((l) => ids(l).every((k) => ids(${JSON.stringify(of)}).includes(k)))) return ${JSON.stringify(refused)};`
|
|
379
|
+
: ` {
|
|
380
|
+
const given = ${JSON.stringify(lists)}.flatMap(ids);
|
|
381
|
+
if (new Set(given).size !== given.length) return ${JSON.stringify(refused)};
|
|
382
|
+
}`,
|
|
383
|
+
)
|
|
384
|
+
.join("\n")}
|
|
385
|
+
}
|
|
386
|
+
`,
|
|
387
|
+
)
|
|
388
|
+
.join("")} return null;
|
|
389
|
+
}
|
|
390
|
+
`;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** A collection's lists that are each member's own, as its mine says them: none, where its mine is of values. */
|
|
394
|
+
const listsOf = (mine: NonNullable<Definitions["mine"]>[string] | undefined) =>
|
|
395
|
+
Array.isArray(mine) ? mine.map((m) => (typeof m === "object" && !Array.isArray(m) ? Object.keys(m)[0]! : m)) : [];
|
|
396
|
+
/** The words each field that's each member's own is refused in, where its mine says them, by collection. */
|
|
397
|
+
const mineSaid = (defs: Definitions) =>
|
|
398
|
+
Object.fromEntries(
|
|
399
|
+
Object.entries(defs.mine ?? {}).flatMap(([coll, fs]) => {
|
|
400
|
+
const said = Array.isArray(fs) ? fs.filter((m) => typeof m === "object" && !Array.isArray(m)) : [];
|
|
401
|
+
return said.length ? [[coll, Object.assign({}, ...said) as Record<string, string>]] : [];
|
|
402
|
+
}),
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
/** The collections of values that are each member's own (definitions' mine, { of, by }), by collection: the link to
|
|
406
|
+
* the item each is of, and the link to its member. Both are one id, `by` a member's. None, if there are none. */
|
|
407
|
+
export function theirsOf(collections: Record<string, Coll>, defs: Definitions, from: string) {
|
|
408
|
+
const out = Object.entries(defs.mine ?? {}).filter(
|
|
409
|
+
(e): e is [string, { of: string; by: string }] => !Array.isArray(e[1]),
|
|
410
|
+
);
|
|
411
|
+
for (const [coll, { of, by }] of out) {
|
|
412
|
+
const one = (f: string) => {
|
|
413
|
+
const l = defs.links?.[f];
|
|
414
|
+
return collections[coll]?.fields[f] === "integer" && typeof l === "object" && !!l.one ? l.to : undefined;
|
|
415
|
+
};
|
|
416
|
+
if (!one(of)) throw new Error(`${from}: mine names ${coll}' ${of}, which isn't a link to one item`);
|
|
417
|
+
if (one(by) !== "members") throw new Error(`${from}: mine names ${coll}' ${by}, which isn't a link to one member`);
|
|
418
|
+
}
|
|
419
|
+
return out.length ? Object.fromEntries(out) : null;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** The lists that are each member's own (definitions' mine), by collection: each a list of ids linking to the members,
|
|
423
|
+
* or a link to one member. None, if there are none. */
|
|
424
|
+
export function mineOf(collections: Record<string, Coll>, defs: Definitions, from: string) {
|
|
425
|
+
const out = Object.entries(defs.mine ?? {})
|
|
426
|
+
.filter(([, fs]) => Array.isArray(fs))
|
|
427
|
+
.map(([coll, fs]) => [coll, listsOf(fs).flat()] as const);
|
|
428
|
+
for (const [coll, fs] of out)
|
|
429
|
+
for (const f of fs)
|
|
430
|
+
if (
|
|
431
|
+
!(collections[coll]?.fields[f] === "ids" && (f === "members" || defs.links?.[f] === "members")) &&
|
|
432
|
+
!(
|
|
433
|
+
collections[coll]?.fields[f] === "integer" &&
|
|
434
|
+
((l) => typeof l === "object" && l.to === "members" && !!l.one)(defs.links?.[f])
|
|
435
|
+
)
|
|
436
|
+
)
|
|
437
|
+
throw new Error(`${from}: mine names ${coll}' ${f}, which isn't a list of members, nor a link to one`);
|
|
438
|
+
return out.length ? Object.fromEntries(out) : null;
|
|
439
|
+
}
|
|
440
|
+
|
|
290
441
|
/** A derived document's model (an app's derive.ts), from an example of it (<doc>.json): each list a collection,
|
|
291
442
|
* each field's type read off every item's value, a field needed if every item has it. It has no ops: nothing
|
|
292
443
|
* writes it, the server derives it. */
|
|
@@ -309,6 +460,9 @@ export function modelFrom(doc: string, example: Record<string, unknown>, from: s
|
|
|
309
460
|
items.forEach((item: Record<string, unknown>, i) => {
|
|
310
461
|
const { id, ...fields } = item;
|
|
311
462
|
for (const [f, v] of Object.entries(fields)) {
|
|
463
|
+
// its item's element's attribute, as a written document's field is: never a capital (likeName arrived likename)
|
|
464
|
+
const why = unnamed(f);
|
|
465
|
+
if (why) throw new Error(`${from}: ${name}' ${why}`);
|
|
312
466
|
const t = typeOf(v),
|
|
313
467
|
now = t && (c.fields[f] ? both(c.fields[f]!, t) : t);
|
|
314
468
|
if (!now) throw new Error(`${from}: ${name} ${id}'s ${f} isn't what the other items' ${f} is`);
|
|
@@ -365,6 +519,65 @@ export function entities(
|
|
|
365
519
|
}
|
|
366
520
|
}
|
|
367
521
|
|
|
522
|
+
/** Every element's own attributes, which a field of an item can't be: its element would be styled, hidden or moved by
|
|
523
|
+
* the field's value (class, style, hidden, slot), or its id or tab order taken (id, tabindex). title is left a field:
|
|
524
|
+
* the tooltip it gives is what it says. */
|
|
525
|
+
const ELEMENTS_OWN = [
|
|
526
|
+
"accesskey",
|
|
527
|
+
"autocapitalize",
|
|
528
|
+
"autofocus",
|
|
529
|
+
"class",
|
|
530
|
+
"contenteditable",
|
|
531
|
+
"dir",
|
|
532
|
+
"draggable",
|
|
533
|
+
"enterkeyhint",
|
|
534
|
+
"exportparts",
|
|
535
|
+
"hidden",
|
|
536
|
+
"id",
|
|
537
|
+
"inert",
|
|
538
|
+
"inputmode",
|
|
539
|
+
"is",
|
|
540
|
+
"lang",
|
|
541
|
+
"nonce",
|
|
542
|
+
"part",
|
|
543
|
+
"popover",
|
|
544
|
+
"slot",
|
|
545
|
+
"spellcheck",
|
|
546
|
+
"style",
|
|
547
|
+
"tabindex",
|
|
548
|
+
"translate",
|
|
549
|
+
];
|
|
550
|
+
/** Why a field can't be named so, or null: it's its item element's attribute, so a-z, 0-9 and -; not key or may (an
|
|
551
|
+
* item's id, and what its person may do to it: the applier's own); nor an attribute every element has. */
|
|
552
|
+
export function unnamed(f: string): string | null {
|
|
553
|
+
const last = f.split(".").at(-1)!;
|
|
554
|
+
if (!/^[a-z][a-z0-9-]*$/.test(last) || f === "key" || f === "may")
|
|
555
|
+
return `${f} cannot be an attribute (a-z, 0-9 and -, and not key or may)`;
|
|
556
|
+
if (ELEMENTS_OWN.includes(last))
|
|
557
|
+
return `${f} cannot be a field: its item's element is given each field as an attribute, and ${last} is every HTML element's own (it would change how the element is drawn or found): name it otherwise (a boat's class, design)`;
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Why a link's field isn't given as the link is, or null: every collection with the field gives it as one id (one) or
|
|
562
|
+
* a list of ids, since a link's name is its own wherever the app says it. Each collection is named as where says it
|
|
563
|
+
* (crossings, or race's crossings), so a field given otherwise is named beside one given as the link. */
|
|
564
|
+
export function linkGiven(
|
|
565
|
+
f: string,
|
|
566
|
+
l: NonNullable<Definitions["links"]>[string],
|
|
567
|
+
colls: [string, Coll][],
|
|
568
|
+
from: string,
|
|
569
|
+
): string | null {
|
|
570
|
+
const one = typeof l === "object" && !!l.one;
|
|
571
|
+
const as = one ? "one id" : "a list of ids";
|
|
572
|
+
const has = colls.filter(([, c]) => c.fields[f]);
|
|
573
|
+
const right = has.filter(([, c]) => c.fields[f] === (one ? "integer" : "ids"));
|
|
574
|
+
const wrong = has.find(([, c]) => c.fields[f] !== (one ? "integer" : "ids"));
|
|
575
|
+
if (!right.length) return `${from}: links names ${f}, but no story gives ${as} as ${f}`;
|
|
576
|
+
if (!wrong) return null;
|
|
577
|
+
const to = typeof l === "string" ? l : l.to;
|
|
578
|
+
return `${from}: ${f} is a link to ${to} (${as}), as ${right[0]![0]}' ${f} is, but ${wrong[0]}' ${f} is ${SAID[wrong[1].fields[f]!]}: a link's name is its own in every document of the app, so name one of them otherwise`;
|
|
579
|
+
}
|
|
580
|
+
|
|
368
581
|
/** A model with its seed read too: a field's type is what every value given it is, in a story or the seed. */
|
|
369
582
|
export function seeded(model: Model, seed: Record<string, unknown>, from: string) {
|
|
370
583
|
for (const [name, c] of Object.entries(model.collections))
|
|
@@ -377,7 +590,11 @@ export function seeded(model: Model, seed: Record<string, unknown>, from: string
|
|
|
377
590
|
),
|
|
378
591
|
);
|
|
379
592
|
for (const [f, v] of Object.entries(given))
|
|
380
|
-
if (f !== "id" && f !== model.doc && !(f in c.fields) && typeOf(v))
|
|
593
|
+
if (f !== "id" && f !== model.doc && !(f in c.fields) && typeOf(v)) {
|
|
594
|
+
const not = ELEMENTS_OWN.includes(f.split(".").at(-1)!) && unnamed(f);
|
|
595
|
+
if (not) throw new Error(`${from}: ${name} ${item.id}'s ${not}`);
|
|
596
|
+
c.fields[f] = typeOf(v)!;
|
|
597
|
+
}
|
|
381
598
|
for (const [f, t] of Object.entries(c.fields)) {
|
|
382
599
|
const v = given[f];
|
|
383
600
|
if (v === undefined) continue;
|
|
@@ -397,7 +614,7 @@ export const ownOf = (doc: Record<string, unknown>) => ({
|
|
|
397
614
|
});
|
|
398
615
|
|
|
399
616
|
/** Where a link of a model points: the collection it's to, the document holding that, and whether it's one id. */
|
|
400
|
-
export type LinkOf = (field: string) => { to: string; at: string; one: boolean; gone?: boolean };
|
|
617
|
+
export type LinkOf = (field: string) => { to: string; at: string; one: boolean; gone?: boolean; part?: boolean };
|
|
401
618
|
/** Each link of a model: to the collection it's named for, in the document that holds it, or to the one its
|
|
402
619
|
* definition names (one id, where it says so), its own document's or another's. */
|
|
403
620
|
export function linksOf(
|
|
@@ -414,15 +631,27 @@ export function linksOf(
|
|
|
414
631
|
one: typeof l === "object" && !!l.one,
|
|
415
632
|
// removed with what it links to (gone: "with"), not the removal refused
|
|
416
633
|
gone: typeof l === "object" && l.gone === "with",
|
|
634
|
+
// structure, not a reference: what the item is part of (part: true), as one that goes with it is
|
|
635
|
+
part: typeof l === "object" && (l.part === true || l.gone === "with"),
|
|
417
636
|
// asked only of a link: a field that isn't one has no document
|
|
418
637
|
get at() {
|
|
419
638
|
const at = l && collections[to] ? doc : (holders[to] ?? (collections[to] ? doc : undefined));
|
|
420
|
-
if (!at)
|
|
639
|
+
if (!at)
|
|
640
|
+
throw new Error(
|
|
641
|
+
`${from}: ${f} is a list of ids, but no other document has a collection named ${to}: name it for one, or say what it links to in a header line ({"links":{"${f}":"members"}})`,
|
|
642
|
+
);
|
|
421
643
|
return at;
|
|
422
644
|
},
|
|
423
645
|
};
|
|
424
646
|
};
|
|
425
647
|
}
|
|
648
|
+
/** A collection's links, each the collection it's to: a list of ids, or one id where its link says so. */
|
|
649
|
+
const linksIn = (c: Coll, link: LinkOf) =>
|
|
650
|
+
Object.fromEntries(
|
|
651
|
+
Object.entries(c.fields)
|
|
652
|
+
.filter(([f, t]) => t === "ids" || (t === "integer" && link(f).one))
|
|
653
|
+
.map(([f]) => [f, link(f).to]),
|
|
654
|
+
);
|
|
426
655
|
/** A collection's links that go with what they point at, in its own document (`goes`): removing that item removes
|
|
427
656
|
* this one first, in the same write. None, nothing said. */
|
|
428
657
|
const goes = (c: Coll, link: LinkOf, doc: string) => {
|
|
@@ -493,7 +722,10 @@ export function tablesOf(
|
|
|
493
722
|
};
|
|
494
723
|
continue;
|
|
495
724
|
}
|
|
496
|
-
|
|
725
|
+
// (an object's field, terms.days, in its object)
|
|
726
|
+
const [o, sub] = f.split(".") as [string, string?];
|
|
727
|
+
const has = (i: Record<string, unknown>) => (sub === undefined ? o in i : isObject(i[o]) && sub in i[o]);
|
|
728
|
+
const always = c.required.includes(f) && ((seed[name] ?? []) as Record<string, unknown>[]).every(has);
|
|
497
729
|
const one = t === "integer" && link(f).one;
|
|
498
730
|
const member = one && link(f).to === GROUP;
|
|
499
731
|
columns[f] = {
|
|
@@ -568,6 +800,9 @@ const POSTGRES: Sql = {
|
|
|
568
800
|
not: "IS DISTINCT FROM",
|
|
569
801
|
};
|
|
570
802
|
|
|
803
|
+
/** SQL as a template literal holds it: each backslash, backtick and ${ escaped, so it's the SQL as written. */
|
|
804
|
+
const templated = (sql: string) => sql.replace(/\\|`|\$\{/g, (c) => `\\${c}`);
|
|
805
|
+
|
|
571
806
|
/** generated/queries.ts: the document as one statement over its tables, in SQLite's JSON functions and Postgres's. Its version,
|
|
572
807
|
* then each collection's items by id: a field with nothing in it left out, as the dialect (`Sql`) writes it; a boolean
|
|
573
808
|
* true or false, and a list its ids, gathered from its pairs (none: left out). The page stays flat: a link's ids,
|
|
@@ -668,7 +903,7 @@ export function queriesOf(
|
|
|
668
903
|
export const items: Record<string, string> = ${JSON.stringify(lite.items, null, 2)};
|
|
669
904
|
|
|
670
905
|
/** ${doc}, whole, as one statement over its tables (SQLite): its parameters $doc${kind ? ", and $key, the instance (" + kind + ":1)" : ""}${params.length ? `, and its window's, ${params.map((p) => `$${p}`).join(", ")}` : ""}${Object.keys(owns).length ? ", and $member, who's asking (none: all of it)" : ""}. */
|
|
671
|
-
export const query = \`${lite.query}\`;
|
|
906
|
+
export const query = \`${templated(lite.query)}\`;
|
|
672
907
|
|
|
673
908
|
/** Its rules over values (definitions' takes, gives and totals), as triggers the store makes in its database: run in
|
|
674
909
|
* each write's transaction, and told as any change is. */
|
|
@@ -707,13 +942,15 @@ function itemSql(coll: string, c: Coll, d: Sql) {
|
|
|
707
942
|
/** A window's test of an item, as code: the same definition its query's WHERE is written from (each parameter given,
|
|
708
943
|
* a field equal to it, or a date and time in the days from it), so publish asks of a row what the read asks. */
|
|
709
944
|
function windowCode(window: NonNullable<Definitions["window"]>) {
|
|
945
|
+
// an item's field, as code: by its name, or in brackets where it's hyphened (set-by)
|
|
946
|
+
const at = (f: string) => (/^[a-z][a-z0-9]*$/.test(f) ? `item.${f}` : `item[${JSON.stringify(f)}]`);
|
|
710
947
|
const tests = Object.entries(window).map(([coll, params]) => {
|
|
711
948
|
const each = Object.entries(params).map(([p, by]) =>
|
|
712
949
|
typeof by === "string"
|
|
713
|
-
? `(p.${p} == null ||
|
|
950
|
+
? `(p.${p} == null || ${at(by)} === p.${p})`
|
|
714
951
|
: by.length
|
|
715
|
-
? `(p.${p} == null || (typeof
|
|
716
|
-
: `(p.${p} == null || (typeof
|
|
952
|
+
? `(p.${p} == null || (typeof ${at(by.from)} === "string" && ${at(by.from)} < days(p.${p}, ${days(by.for)}) && ends(${at(by.from)}, ${at(by.length)}) > days(p.${p}, 0)))`
|
|
953
|
+
: `(p.${p} == null || (typeof ${at(by.from)} === "string" && ${at(by.from)} >= p.${p} && ${at(by.from)} < days(p.${p}, ${days(by.for)})))`,
|
|
717
954
|
);
|
|
718
955
|
return `(coll !== ${JSON.stringify(coll)} || (${each.join(" && ")}))`;
|
|
719
956
|
});
|
|
@@ -822,6 +1059,104 @@ export function takesSql(
|
|
|
822
1059
|
}),
|
|
823
1060
|
);
|
|
824
1061
|
}
|
|
1062
|
+
const said = (w: string) => `'${w.replaceAll("'", "''")}'`;
|
|
1063
|
+
// an item added only in the write adding what a link of it points at (definitions' addedWith): that item noted as
|
|
1064
|
+
// added in the write (joined_touched, as it was before: none)
|
|
1065
|
+
for (const [coll, links] of Object.entries(defs.addedWith ?? {}))
|
|
1066
|
+
for (const [f, refused] of Object.entries(links)) {
|
|
1067
|
+
if (collections[coll]?.fields[f] !== "integer" || !link(f).one)
|
|
1068
|
+
throw new Error(`${from}: addedWith names ${coll}' ${f}, which isn't a link to one item`);
|
|
1069
|
+
const noted = `${d.dialect === "sqlite" ? "temp" : "pg_temp"}.joined_touched`;
|
|
1070
|
+
out.push(
|
|
1071
|
+
trigger({
|
|
1072
|
+
name: `joined_with_${coll}_${f}`,
|
|
1073
|
+
at: "BEFORE",
|
|
1074
|
+
event: "INSERT",
|
|
1075
|
+
table: coll,
|
|
1076
|
+
body: refuseSql(
|
|
1077
|
+
d.dialect,
|
|
1078
|
+
`NOT EXISTS (SELECT 1 FROM ${noted} t WHERE t.tbl = '${link(f).to}' AND t.id = NEW.${q(f)} AND t.before IS NULL)`,
|
|
1079
|
+
said(refused),
|
|
1080
|
+
),
|
|
1081
|
+
}),
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
// an item kept as it is once it's settled (definitions' frozen, by collection): its fields changed by no write while
|
|
1085
|
+
// its own yes-or-no field is true
|
|
1086
|
+
for (const [coll, { by, fields, refused }] of Object.entries(itemsFrozen(defs))) {
|
|
1087
|
+
const c = collections[coll];
|
|
1088
|
+
if (c?.fields[by] !== "boolean")
|
|
1089
|
+
throw new Error(`${from}: frozen is by ${by}, which isn't a yes-or-no field of ${coll}`);
|
|
1090
|
+
const cols = Object.keys(c.fields).filter(
|
|
1091
|
+
(k) => c.fields[k] !== "ids" && (!fields || fields.some((x) => k === x || k.startsWith(`${x}.`))),
|
|
1092
|
+
);
|
|
1093
|
+
for (const x of fields ?? [])
|
|
1094
|
+
if (!cols.some((k) => k === x || k.startsWith(`${x}.`)))
|
|
1095
|
+
throw new Error(`${from}: frozen names ${coll}' ${x}, which isn't one of its fields`);
|
|
1096
|
+
out.push(
|
|
1097
|
+
trigger({
|
|
1098
|
+
name: `joined_frozen_${coll}`,
|
|
1099
|
+
at: "BEFORE",
|
|
1100
|
+
event: "UPDATE",
|
|
1101
|
+
table: coll,
|
|
1102
|
+
body: refuseSql(
|
|
1103
|
+
d.dialect,
|
|
1104
|
+
`OLD.${q(by)} = 1 AND (${cols.map((k) => `NEW.${q(k)} ${d.not} OLD.${q(k)}`).join(" OR ")})`,
|
|
1105
|
+
said(refused),
|
|
1106
|
+
),
|
|
1107
|
+
}),
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
// a field of words that's never none (definitions' notEmpty): an add's, and one changed (a row that's so already,
|
|
1111
|
+
// from before it was said, is left, and may be put back by an undo)
|
|
1112
|
+
for (const [coll, fields] of Object.entries(defs.notEmpty ?? {}))
|
|
1113
|
+
for (const f of fields) {
|
|
1114
|
+
if (collections[coll]?.fields[f] !== "string")
|
|
1115
|
+
throw new Error(`${from}: notEmpty names ${coll}' ${f}, which isn't a field of words`);
|
|
1116
|
+
const none = `trim(NEW.${q(f)}, ' \t\r\n') = ''`;
|
|
1117
|
+
for (const [event, cond] of [
|
|
1118
|
+
["INSERT", `${isAdd(coll)} AND ${none}`],
|
|
1119
|
+
["UPDATE", `NEW.${q(f)} ${d.not} OLD.${q(f)} AND ${none}`],
|
|
1120
|
+
] as const)
|
|
1121
|
+
out.push(
|
|
1122
|
+
trigger({
|
|
1123
|
+
name: `joined_empty_${coll}_${f}_${event.toLowerCase()}`,
|
|
1124
|
+
at: "BEFORE",
|
|
1125
|
+
event,
|
|
1126
|
+
table: coll,
|
|
1127
|
+
body: refuseSql(d.dialect, cond, said(emptySaid(f))),
|
|
1128
|
+
}),
|
|
1129
|
+
);
|
|
1130
|
+
}
|
|
1131
|
+
// lists held as the write leaves it (definitions' within and apart): on Postgres, a trigger at its end (SQLite's are
|
|
1132
|
+
// held by code, listsHold, as it has no trigger that waits)
|
|
1133
|
+
// (checked of both, written of Postgres)
|
|
1134
|
+
const lists = Object.entries(listRules(defs, collections, from));
|
|
1135
|
+
if (d.dialect === "postgres")
|
|
1136
|
+
for (const [coll, rules] of lists)
|
|
1137
|
+
rules.forEach(({ lists, of, refused }, n) => {
|
|
1138
|
+
const pairs = (l: string) => q(`${coll}_${l}`);
|
|
1139
|
+
const cond = of
|
|
1140
|
+
? lists
|
|
1141
|
+
.map(
|
|
1142
|
+
(l) =>
|
|
1143
|
+
`EXISTS (SELECT 1 FROM ${pairs(l)} l WHERE l.${q(coll)} = item AND NOT EXISTS (SELECT 1 FROM ${pairs(of)} p WHERE p.${q(coll)} = item AND p.${q(of)} = l.${q(l)}))`,
|
|
1144
|
+
)
|
|
1145
|
+
.join(" OR ")
|
|
1146
|
+
: `EXISTS (SELECT v FROM (${lists.map((l) => `SELECT ${q(l)} AS v FROM ${pairs(l)} WHERE ${q(coll)} = item`).join(" UNION ALL ")}) a GROUP BY v HAVING COUNT(*) > 1)`;
|
|
1147
|
+
out.push(
|
|
1148
|
+
...constraintSql({
|
|
1149
|
+
name: `joined_${of ? "within" : "apart"}_${coll}_${n}`,
|
|
1150
|
+
// what could leave it unheld: an id put in a list, or (within) taken from the list it must be in
|
|
1151
|
+
on: [
|
|
1152
|
+
...lists.map((l) => ({ table: `${coll}_${l}`, event: "INSERT" })),
|
|
1153
|
+
...(of ? [{ table: `${coll}_${of}`, event: "DELETE" }] : []),
|
|
1154
|
+
],
|
|
1155
|
+
item: q(coll),
|
|
1156
|
+
body: `IF ${cond} THEN RAISE EXCEPTION '%', ${said(refused)}; END IF;`,
|
|
1157
|
+
}),
|
|
1158
|
+
);
|
|
1159
|
+
});
|
|
825
1160
|
// a field kept as the sum of the rows linking to its item (definitions' totals): each change to them, summed again
|
|
826
1161
|
for (const [coll, fields] of Object.entries(defs.totals ?? {}))
|
|
827
1162
|
for (const [field, { of, by, sum, times }] of Object.entries(fields)) {
|
|
@@ -852,6 +1187,22 @@ const wordsOf = (refused: string) =>
|
|
|
852
1187
|
.join(".+")}$`,
|
|
853
1188
|
);
|
|
854
1189
|
|
|
1190
|
+
/** An app's definitions with what they imply said: of values each member's own (mine, { of, by }), whose one is the
|
|
1191
|
+
* server's to fill, with its writer, and a member has one for an item at most. */
|
|
1192
|
+
export function implied(d: Definitions): Definitions {
|
|
1193
|
+
const fills: Record<string, Record<string, unknown>> = { ...d.fills },
|
|
1194
|
+
unique: Record<string, (string | string[])[]> = { ...d.unique };
|
|
1195
|
+
const own = Object.entries(d.mine ?? {}).filter(
|
|
1196
|
+
(e): e is [string, { of: string; by: string }] => !Array.isArray(e[1]),
|
|
1197
|
+
);
|
|
1198
|
+
if (!own.length) return d;
|
|
1199
|
+
for (const [coll, { of, by }] of own) {
|
|
1200
|
+
fills[coll] = { ...fills[coll], [by]: "me" };
|
|
1201
|
+
unique[coll] = [...(unique[coll] ?? []), [of, by]];
|
|
1202
|
+
}
|
|
1203
|
+
return { ...d, fills, unique };
|
|
1204
|
+
}
|
|
1205
|
+
|
|
855
1206
|
/** Of an app's definitions, a document's: those of its collections and their fields; and the kind, its roles and
|
|
856
1207
|
* owns, to the document told on its instances (order:7), or to every one where there's no kind. */
|
|
857
1208
|
export function definedFor(d: Definitions, m: Model, stories: Story[]): Definitions {
|
|
@@ -862,9 +1213,11 @@ export function definedFor(d: Definitions, m: Model, stories: Story[]): Definiti
|
|
|
862
1213
|
const links = Object.entries(d.links ?? {}).filter(([f]) => fields.has(f));
|
|
863
1214
|
if (links.length) out.links = Object.fromEntries(links);
|
|
864
1215
|
for (const k of [
|
|
1216
|
+
"title",
|
|
865
1217
|
"copies",
|
|
866
1218
|
"unique",
|
|
867
1219
|
"noOverlap",
|
|
1220
|
+
"mine",
|
|
868
1221
|
"window",
|
|
869
1222
|
"order",
|
|
870
1223
|
"fills",
|
|
@@ -875,13 +1228,21 @@ export function definedFor(d: Definitions, m: Model, stories: Story[]): Definiti
|
|
|
875
1228
|
"totals",
|
|
876
1229
|
"guests",
|
|
877
1230
|
"visitors",
|
|
1231
|
+
"addedWith",
|
|
1232
|
+
"within",
|
|
1233
|
+
"apart",
|
|
1234
|
+
"notEmpty",
|
|
878
1235
|
] as const) {
|
|
879
1236
|
const mine = has(d[k] as Record<string, unknown> | undefined);
|
|
880
1237
|
if (mine && Object.keys(mine).length) out[k] = mine;
|
|
881
1238
|
}
|
|
882
1239
|
if (d.where?.[m.doc]) out.where = { [m.doc]: d.where[m.doc]! };
|
|
883
1240
|
const instance = stories.some((s) => (s.does ?? s.cannot)!.doc.includes(":"));
|
|
884
|
-
|
|
1241
|
+
// frozen: a kind's, as its roles are; an item's own, its collection's document's
|
|
1242
|
+
const kinds = ["kind", "roles", "waits", ...(kindFrozen(d.frozen) ? ["frozen" as const] : [])] as const;
|
|
1243
|
+
if (instance || !d.kind) for (const k of kinds) if (d[k]) out[k] = d[k] as never;
|
|
1244
|
+
const frozen = kindFrozen(d.frozen) ? undefined : has(d.frozen as Record<string, Frozen> | undefined);
|
|
1245
|
+
if (frozen && Object.keys(frozen).length) out.frozen = frozen as Record<string, Frozen>;
|
|
885
1246
|
// owns: one who-path, the kind's or every document's; or one a collection, its documents'
|
|
886
1247
|
if ((instance || !d.kind) && typeof d.owns === "string") out.owns = d.owns;
|
|
887
1248
|
const owned = typeof d.owns === "object" ? has(d.owns) : undefined;
|
|
@@ -894,8 +1255,9 @@ export function definedFor(d: Definitions, m: Model, stories: Story[]): Definiti
|
|
|
894
1255
|
export function queryOf({ doc }: Model, from: string, spec: Query) {
|
|
895
1256
|
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
896
1257
|
const colls = Object.entries(spec).map(([coll, s]) => {
|
|
1258
|
+
if ("count" in s) return counted(coll, s);
|
|
897
1259
|
const sides = Object.entries(s.sides);
|
|
898
|
-
const side = `CASE ${sides.map(([f, w]) => `WHEN o.${q(f)} = $member THEN '${w}'`).join(" ")} END`;
|
|
1260
|
+
const side = `CASE ${sides.map(([f, w]) => `WHEN o.${q(f)} = $member THEN '${w.replaceAll("'", "''")}'`).join(" ")} END`;
|
|
899
1261
|
// the sum of the rows linking to it, or of its own fields
|
|
900
1262
|
const total = `o.${q(s.total.sum)}${s.total.times ? ` * o.${q(s.total.times)}` : ""}`;
|
|
901
1263
|
const where = `${s.when ? `o.${q(s.when)} = 1 AND ` : ""}(${sides.map(([f]) => `o.${q(f)} = $member`).join(" OR ")})`;
|
|
@@ -907,14 +1269,40 @@ export function queryOf({ doc }: Model, from: string, spec: Query) {
|
|
|
907
1269
|
return `// Written by src/compile.ts from ${from}: change the stories, not this.
|
|
908
1270
|
|
|
909
1271
|
/** ${doc}, as a member has it, one statement over the app's tables (SQLite): its parameters $doc and $member. */
|
|
910
|
-
export const query = \`${query(SQLITE)}\`;
|
|
1272
|
+
export const query = \`${templated(query(SQLITE))}\`;
|
|
911
1273
|
|
|
912
1274
|
/** Its query, as Postgres says it. */
|
|
913
1275
|
export const postgres = ${JSON.stringify({ query: query(POSTGRES) }, null, 2)};
|
|
914
1276
|
`;
|
|
915
1277
|
}
|
|
1278
|
+
/** A read-only document's collection counting rows by what they link to and their week (definitions' documents,
|
|
1279
|
+
* Counted): each item seen by the member, its rows by week, numbered in order. */
|
|
1280
|
+
function counted(coll: string, s: Counted) {
|
|
1281
|
+
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
1282
|
+
const [[by, to]] = Object.entries(s.by) as [[string, string]];
|
|
1283
|
+
const seen = s.seen
|
|
1284
|
+
.map((l) => `EXISTS (SELECT 1 FROM ${q(`${to}_${l}`)} p WHERE p.${q(to)} = o.${q(by)} AND p.${q(l)} = $member)`)
|
|
1285
|
+
.join(" OR ");
|
|
1286
|
+
return (d: Sql) => {
|
|
1287
|
+
// the Monday of the week a wall clock's day is in
|
|
1288
|
+
const week =
|
|
1289
|
+
d.dialect === "sqlite"
|
|
1290
|
+
? `date(o.${q(s.week)}, 'weekday 0', '-6 days')`
|
|
1291
|
+
: `to_char(date_trunc('week', CAST(o.${q(s.week)} AS timestamp)), 'YYYY-MM-DD')`;
|
|
1292
|
+
const rows = `SELECT ROW_NUMBER() OVER (ORDER BY o.${q(by)}, ${week}) AS id, o.${q(by)} AS item, ${week} AS week, COUNT(*) AS n FROM ${q(s.from)} o WHERE (${seen}) GROUP BY o.${q(by)}, ${week}`;
|
|
1293
|
+
return ` '${coll}', ${d.rows(d.object(`'id', w.id, '${by}', w.item, 'week', w.week, '${s.count}', w.n`), "w.id", `\n FROM (${rows}) w`)}`;
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
|
|
916
1297
|
/** The tables a read-only document's query reads: what a change to them is told to. */
|
|
917
|
-
const readsOf = (spec: Query) =>
|
|
1298
|
+
const readsOf = (spec: Query) =>
|
|
1299
|
+
[
|
|
1300
|
+
...new Set(
|
|
1301
|
+
Object.values(spec).flatMap((s) =>
|
|
1302
|
+
"count" in s ? [s.from, ...s.seen.map((l) => `${Object.values(s.by)[0]}_${l}`)] : [s.from],
|
|
1303
|
+
),
|
|
1304
|
+
),
|
|
1305
|
+
].sort();
|
|
918
1306
|
|
|
919
1307
|
/** The tables a document's collections are, and their tables of pairs. */
|
|
920
1308
|
const tablesRead = (collections: Record<string, Coll>) =>
|
|
@@ -942,16 +1330,21 @@ const named = (changes: Change[]) =>
|
|
|
942
1330
|
.map((c) => [c.change.replace(/[A-Z].*/, ""), c.key, "column" in c ? c.column : ""].filter(Boolean).join("-"))
|
|
943
1331
|
.join("-and-") + (changes.length > 2 ? "-and-more" : "");
|
|
944
1332
|
|
|
945
|
-
/** What a
|
|
1333
|
+
/** What a field of words that's never none (definitions' notEmpty) is refused with. */
|
|
1334
|
+
export const emptySaid = (f: string) => `${f} cannot be empty`;
|
|
1335
|
+
|
|
1336
|
+
/** What a story can't show, each a header line of an app's stories, after the cast (the skill's §15). */
|
|
946
1337
|
const DEFINED = [
|
|
947
1338
|
"links",
|
|
948
1339
|
"roles",
|
|
1340
|
+
"title",
|
|
949
1341
|
"owns",
|
|
950
1342
|
"kind",
|
|
951
1343
|
"fills",
|
|
952
1344
|
"timed",
|
|
953
1345
|
"unique",
|
|
954
1346
|
"noOverlap",
|
|
1347
|
+
"mine",
|
|
955
1348
|
"window",
|
|
956
1349
|
"order",
|
|
957
1350
|
"copies",
|
|
@@ -965,23 +1358,28 @@ const DEFINED = [
|
|
|
965
1358
|
"frozen",
|
|
966
1359
|
"waits",
|
|
967
1360
|
"visitors",
|
|
1361
|
+
"addedWith",
|
|
1362
|
+
"within",
|
|
1363
|
+
"apart",
|
|
1364
|
+
"notEmpty",
|
|
968
1365
|
];
|
|
969
1366
|
|
|
970
1367
|
/** Why a definition is checked by no story, or null: each must be, or it's a guess. A kind, by a story on an
|
|
971
1368
|
* instance; a link, by a story writing the field; a role, by a does granting it and a cannot by someone without
|
|
972
1369
|
* it, or by owns naming it; owns, by a story someone mustn't hear (unseen); unique and noOverlap, by a cannot on the
|
|
973
|
-
* collection; timed, by a story giving
|
|
1370
|
+
* collection; notEmpty, by a cannot emptying the field; timed, by a story giving it. What the server fills, no story gives: it's the server's. */
|
|
974
1371
|
export function unchecked(
|
|
975
1372
|
defs: Definitions,
|
|
976
1373
|
stories: Story[],
|
|
977
1374
|
grants: Record<string, string[]>,
|
|
978
|
-
|
|
1375
|
+
/** Who a story's teller is, to the item an op is to (none: to the document). */
|
|
1376
|
+
rolesOfTeller: (s: Story, o?: Op) => string[],
|
|
979
1377
|
/** The app's other documents: a role any of them checks is checked. */
|
|
980
1378
|
siblings: {
|
|
981
1379
|
defs: Definitions;
|
|
982
1380
|
stories: Story[];
|
|
983
1381
|
grants: Record<string, string[]>;
|
|
984
|
-
rolesOfTeller: (s: Story) => string[];
|
|
1382
|
+
rolesOfTeller: (s: Story, o?: Op) => string[];
|
|
985
1383
|
}[] = [],
|
|
986
1384
|
): string | null {
|
|
987
1385
|
const writes = (s: Story) => [
|
|
@@ -1003,6 +1401,10 @@ export function unchecked(
|
|
|
1003
1401
|
for (const f of Object.keys(defs.links ?? {}))
|
|
1004
1402
|
if (!filledMe(f) && !by.some((u) => u.stories.some((s) => ops(s).some((o) => gives(o, f)))))
|
|
1005
1403
|
return `links names ${f}, which no story writes`;
|
|
1404
|
+
// a link that's part of what it points at is one id: a thing is part of one thing
|
|
1405
|
+
for (const [f, l] of Object.entries(defs.links ?? {}))
|
|
1406
|
+
if (typeof l === "object" && l.part && !l.one)
|
|
1407
|
+
return `links' ${f} is part of what it points at, so it's one id (one: true)`;
|
|
1006
1408
|
// a link that goes with what it points at: a story removes one of those
|
|
1007
1409
|
for (const [f, l] of Object.entries(defs.links ?? {}))
|
|
1008
1410
|
if (typeof l === "object" && l.gone === "with") {
|
|
@@ -1022,13 +1424,13 @@ export function unchecked(
|
|
|
1022
1424
|
const holds = Object.values(u.defs.where ?? {}).flatMap((w) => (typeof w.holds === "string" ? [w.holds] : []));
|
|
1023
1425
|
const named = [...owns, ...holds].some((p) => p.split("|").some((t) => t.trim() === role));
|
|
1024
1426
|
const granted = Object.values(u.grants).some((g) => g.includes(role));
|
|
1025
|
-
const without = u.stories.some(
|
|
1026
|
-
(s)
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1427
|
+
const without = u.stories.some((s) =>
|
|
1428
|
+
// (who its teller is to the item each op is to: an @field role is the item's)
|
|
1429
|
+
s.cannot?.ops.some(
|
|
1430
|
+
(o) =>
|
|
1431
|
+
!u.rolesOfTeller(s, o).includes(role) &&
|
|
1030
1432
|
Object.entries(u.grants).some(([k, g]) => opOf(k) === grantOf(o) && g.includes(role)),
|
|
1031
|
-
|
|
1433
|
+
),
|
|
1032
1434
|
);
|
|
1033
1435
|
return named || (granted && without);
|
|
1034
1436
|
});
|
|
@@ -1043,6 +1445,24 @@ export function unchecked(
|
|
|
1043
1445
|
] as const)
|
|
1044
1446
|
for (const coll of Object.keys(colls ?? {}))
|
|
1045
1447
|
if (!on(coll)) return `${key} names ${coll}, but no cannot story writes it`;
|
|
1448
|
+
for (const [coll, fs] of Object.entries(defs.notEmpty ?? {}))
|
|
1449
|
+
for (const f of fs) {
|
|
1450
|
+
const emptied = (o: Op) => {
|
|
1451
|
+
const v = parts(o.path).field === f ? o.value : o.value?.[f];
|
|
1452
|
+
return parts(o.path).coll === coll && typeof v === "string" && !v.trim();
|
|
1453
|
+
};
|
|
1454
|
+
if (!stories.some((s) => s.refused === emptySaid(f) && s.cannot?.ops.some(emptied)))
|
|
1455
|
+
return `notEmpty names ${coll}' ${f}, but no cannot story empties it, refused in "${emptySaid(f)}"`;
|
|
1456
|
+
}
|
|
1457
|
+
for (const [coll, fs] of Object.entries(defs.mine ?? {})) {
|
|
1458
|
+
for (const f of listsOf(fs).flat())
|
|
1459
|
+
if (!stories.some((s) => s.cannot?.ops.some((o) => parts(o.path).coll === coll && gives(o, f))))
|
|
1460
|
+
return `mine names ${coll}' ${f}, but no cannot story writes it`;
|
|
1461
|
+
// values each member's own: a cannot story changes or removes one (another's)
|
|
1462
|
+
const anothers = (o: Op) => parts(o.path).coll === coll && parts(o.path).key !== "-" && o.op !== "add";
|
|
1463
|
+
if (!Array.isArray(fs) && !stories.some((s) => s.cannot?.ops.some(anothers)))
|
|
1464
|
+
return `mine names ${coll}, but no cannot story changes another's`;
|
|
1465
|
+
}
|
|
1046
1466
|
for (const [coll, { from }] of Object.entries(defs.copies ?? {}))
|
|
1047
1467
|
if (!stories.some((s) => s.does?.ops.some((o) => parts(o.path).coll === coll && o.op === "add" && gives(o, from))))
|
|
1048
1468
|
return `copies names ${coll}' ${from}, but no story adds one by it`;
|
|
@@ -1061,9 +1481,47 @@ export function unchecked(
|
|
|
1061
1481
|
return `${rule} names ${coll}, but no cannot story is refused in its words`;
|
|
1062
1482
|
// a kind's settings, each by a cannot refused in its words; a guest's level: a guest's does on an item of one, and a
|
|
1063
1483
|
// guest's cannot on one of another
|
|
1484
|
+
// what holds an item or its lists, each by a cannot refused in its words
|
|
1485
|
+
const refusing = (words: string) => stories.some((s) => s.cannot && s.refused === words);
|
|
1486
|
+
for (const [key, all] of [
|
|
1487
|
+
["addedWith", Object.values(defs.addedWith ?? {}).flatMap((l) => Object.values(l))],
|
|
1488
|
+
["frozen", Object.values(itemsFrozen(defs)).map((x) => x.refused)],
|
|
1489
|
+
["within", Object.values(defs.within ?? {}).flatMap((rs) => rs.map((r) => r.refused))],
|
|
1490
|
+
["apart", Object.values(defs.apart ?? {}).flatMap((rs) => rs.map((r) => r.refused))],
|
|
1491
|
+
[
|
|
1492
|
+
"links' holds",
|
|
1493
|
+
Object.entries(defs.links ?? {}).flatMap(([f, l]) =>
|
|
1494
|
+
typeof l === "object" && l.holds ? [namesSaid(f, l.holds)] : [],
|
|
1495
|
+
),
|
|
1496
|
+
],
|
|
1497
|
+
] as const)
|
|
1498
|
+
for (const words of all)
|
|
1499
|
+
if (!refusing(words)) return `${key} is checked by no story: none cannot, refused in "${words}"`;
|
|
1064
1500
|
return settingsUnchecked(defs, stories, grants) ?? visitorsRefused(defs, stories, rolesOfTeller);
|
|
1065
1501
|
}
|
|
1066
1502
|
|
|
1503
|
+
/** What a link that names only those a who-path finds is refused with, when it names another (links' holds). */
|
|
1504
|
+
export const namesSaid = (f: string, path: string) => `${f} names someone who isn't among ${pathSaid(path)}`;
|
|
1505
|
+
/** generated/rules.ts's names: each link of this document's fields that names only those a who-path of collections
|
|
1506
|
+
* finds (links' holds), as a test of the id named, and the words another is refused in. */
|
|
1507
|
+
const namesCode = (defs: Definitions, colls: { fields: Record<string, unknown> }[]) => {
|
|
1508
|
+
const names = Object.entries(defs.links ?? {}).flatMap(([f, l]) =>
|
|
1509
|
+
typeof l === "object" && l.holds && colls.some((c) => f in c.fields)
|
|
1510
|
+
? [
|
|
1511
|
+
` ${JSON.stringify(f)}: [(m, read, doc) => ${whoCode(l.holds, defs.roles ?? {}, `links' ${f} holds`)}, ${JSON.stringify(namesSaid(f, l.holds))}],`,
|
|
1512
|
+
]
|
|
1513
|
+
: [],
|
|
1514
|
+
);
|
|
1515
|
+
return names.length
|
|
1516
|
+
? `/** Each link whose every id names one a who-path finds, its test and the words another is refused in (its
|
|
1517
|
+
* definitions' links, holds). */
|
|
1518
|
+
export const names: Record<string, readonly [(m: number, read: (doc: string) => any, doc: string) => boolean, string]> = {
|
|
1519
|
+
${names.join("\n")}
|
|
1520
|
+
};
|
|
1521
|
+
`
|
|
1522
|
+
: "";
|
|
1523
|
+
};
|
|
1524
|
+
|
|
1067
1525
|
/** The stories language (docs/stories.md): the words a story, a write and an op may have, and no others. */
|
|
1068
1526
|
const STORY = ["story", "as", "does", "cannot", "seen", "unseen", "refused", "then", "premise"],
|
|
1069
1527
|
WRITE = ["doc", "ops", "why"],
|
|
@@ -1123,6 +1581,10 @@ export function premised(
|
|
|
1123
1581
|
/** What the server fills on an add to a document's collection, and who a name is: an add filled as it would be */
|
|
1124
1582
|
fillsOf: (doc: string, coll: string) => Record<string, unknown> | undefined,
|
|
1125
1583
|
memberOf: (name: string) => number | undefined,
|
|
1584
|
+
/** A document's collections, each its links: where a "$n" is read (src/ops.ts, linksNamed) */
|
|
1585
|
+
collectionsOf: (doc: string) => Linked | undefined,
|
|
1586
|
+
/** What a field is: whether "now" is an instant or a wall clock (none said, an instant) */
|
|
1587
|
+
typeIn: (doc: string, coll: string, field: string) => Type | undefined = () => undefined,
|
|
1126
1588
|
): Record<string, Record<string, unknown>> {
|
|
1127
1589
|
// each write with its teller (an anonymous story's, nobody)
|
|
1128
1590
|
const writes: [string | null, Write][] = !premise
|
|
@@ -1136,29 +1598,29 @@ export function premised(
|
|
|
1136
1598
|
const [name, n] = w.doc.split("?")[0]!.split(":") as [string, string?];
|
|
1137
1599
|
const doc = (state[name] ??= {});
|
|
1138
1600
|
const added: number[] = [];
|
|
1139
|
-
const
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
: Array.isArray(v)
|
|
1143
|
-
? v.map(given)
|
|
1144
|
-
: isObject(v)
|
|
1145
|
-
? Object.fromEntries(Object.entries(v).map(([f, x]) => [f, given(x)]))
|
|
1146
|
-
: v;
|
|
1147
|
-
for (const o of w.ops) {
|
|
1601
|
+
for (const op of w.ops) {
|
|
1602
|
+
// a later op's "$n" where a link is: the id its write's nth add was given
|
|
1603
|
+
const o = linksNamed(op, collectionsOf(name), (n) => added[n - 1]);
|
|
1148
1604
|
const [, coll = "", key, ...path] = o.path.split("/");
|
|
1149
1605
|
const rows = (doc[coll] ??= []) as Record<string, unknown>[];
|
|
1150
1606
|
if (!Array.isArray(rows)) continue;
|
|
1151
1607
|
if (o.op === "add" && key === "-") {
|
|
1152
1608
|
const id = Math.max(0, ...rows.map((r) => Number(r.id))) + 1;
|
|
1153
1609
|
added.push(id);
|
|
1154
|
-
// what the server fills, as it would: "me" its teller, "now" an instant, a code
|
|
1610
|
+
// what the server fills, as it would: "me" its teller, "now" an instant (or a wall clock), a code
|
|
1155
1611
|
const filled = Object.entries(fillsOf(name, coll) ?? {}).map(([f, v]) => [
|
|
1156
1612
|
f,
|
|
1157
|
-
v === "me"
|
|
1613
|
+
v === "me"
|
|
1614
|
+
? teller === null
|
|
1615
|
+
? null
|
|
1616
|
+
: (memberOf(teller) ?? null)
|
|
1617
|
+
: v === "now"
|
|
1618
|
+
? `2026-01-01T00:00:00${typeIn(name, coll, f) === "date-time" ? "" : "Z"}`
|
|
1619
|
+
: v,
|
|
1158
1620
|
]);
|
|
1159
1621
|
rows.push({
|
|
1160
1622
|
...Object.fromEntries(filled),
|
|
1161
|
-
...(
|
|
1623
|
+
...(o.value as object),
|
|
1162
1624
|
id,
|
|
1163
1625
|
...(n ? { [name]: Number(n) } : {}),
|
|
1164
1626
|
});
|
|
@@ -1170,13 +1632,16 @@ export function premised(
|
|
|
1170
1632
|
if (o.op === "remove") rows.splice(rows.indexOf(row), 1);
|
|
1171
1633
|
continue;
|
|
1172
1634
|
}
|
|
1173
|
-
// a field (terms/days, an object's), or an id added to a list (/people
|
|
1635
|
+
// a field (terms/days, an object's), or an id added to a list (/people/-: a list there yet, or a new one) or
|
|
1636
|
+
// taken from it (/people/2: the id 2, wherever it is in the list)
|
|
1174
1637
|
let at: any = row;
|
|
1175
|
-
for (const f of path.slice(0, -1)) at = at[f] ??= {};
|
|
1176
1638
|
const last = path.at(-1)!;
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1639
|
+
path.slice(0, -1).forEach((f, i) => (at = at[f] ??= last === "-" && i === path.length - 2 ? [] : {}));
|
|
1640
|
+
if (o.op === "remove" && Array.isArray(at)) {
|
|
1641
|
+
if (at.includes(Number(last))) at.splice(at.indexOf(Number(last)), 1);
|
|
1642
|
+
} else if (o.op === "remove") delete at[last];
|
|
1643
|
+
else if (last === "-") at.push?.(o.value);
|
|
1644
|
+
else at[last] = o.value;
|
|
1180
1645
|
}
|
|
1181
1646
|
}
|
|
1182
1647
|
return state;
|
|
@@ -1221,16 +1686,17 @@ export function modelOf(stories: Story[], links: Definitions["links"] = {}): Mod
|
|
|
1221
1686
|
`${where}: ${model.doc}'s own fields are kept as a collection named for it, so it has no collection called ${name}: name one otherwise`,
|
|
1222
1687
|
);
|
|
1223
1688
|
const typed = (f: string, v: unknown): void => {
|
|
1224
|
-
|
|
1225
|
-
if (
|
|
1226
|
-
throw new Error(`${where}: ${f} cannot be an attribute (a-z, 0-9 and -, and not key or may)`);
|
|
1689
|
+
const not = unnamed(f);
|
|
1690
|
+
if (not) throw new Error(`${where}: ${not}`);
|
|
1227
1691
|
// an object of fields: each of its fields a field of the item, named for both (terms.days), one value each
|
|
1228
1692
|
if (isObject(v)) {
|
|
1229
1693
|
if (f.includes(".")) throw new Error(`${where}: ${f} is an object in an object: one value each`);
|
|
1230
1694
|
return Object.entries(v).forEach(([k, x]) => typed(`${f}.${k}`, x));
|
|
1231
1695
|
}
|
|
1232
1696
|
if (Array.isArray(v) && !v.length) return void later.push({ where, c, f, why: "empty" });
|
|
1233
|
-
|
|
1697
|
+
// ("$n" is an add's id where a link is: a list of ids, or a link to one)
|
|
1698
|
+
const l = links[f];
|
|
1699
|
+
const t = typeOf(v, Array.isArray(v) || (typeof l === "object" && !!l.one));
|
|
1234
1700
|
if (!t) throw new Error(`${where}: ${f} is a string, a boolean, a number or a list of ids`);
|
|
1235
1701
|
const was = c.fields[f];
|
|
1236
1702
|
const now = was ? both(was, t) : t;
|
|
@@ -1290,10 +1756,22 @@ const Pascal = (s: string) =>
|
|
|
1290
1756
|
.split("-")
|
|
1291
1757
|
.map((w) => w[0]!.toUpperCase() + w.slice(1))
|
|
1292
1758
|
.join("");
|
|
1293
|
-
/**
|
|
1759
|
+
/** English's irregular plurals a domain keeps as its words (a dental chart's teeth): each, its singular. */
|
|
1760
|
+
const IRREGULAR: Record<string, string> = {
|
|
1761
|
+
people: "person",
|
|
1762
|
+
teeth: "tooth",
|
|
1763
|
+
feet: "foot",
|
|
1764
|
+
children: "child",
|
|
1765
|
+
men: "man",
|
|
1766
|
+
women: "woman",
|
|
1767
|
+
mice: "mouse",
|
|
1768
|
+
geese: "goose",
|
|
1769
|
+
};
|
|
1770
|
+
/** A collection's item, by English's plurals (its regular ones, and the irregular a domain keeps), or null if the
|
|
1771
|
+
* name isn't one. */
|
|
1294
1772
|
export const itemOf = (coll: string) =>
|
|
1295
|
-
coll
|
|
1296
|
-
?
|
|
1773
|
+
Object.hasOwn(IRREGULAR, coll)
|
|
1774
|
+
? IRREGULAR[coll]!
|
|
1297
1775
|
: /[^aeiou]ies$/.test(coll)
|
|
1298
1776
|
? coll.slice(0, -3) + "y"
|
|
1299
1777
|
: /(ss|x|ch|sh)es$/.test(coll)
|
|
@@ -1321,7 +1799,7 @@ export function compile(
|
|
|
1321
1799
|
fixed = false,
|
|
1322
1800
|
readOnly?: Query,
|
|
1323
1801
|
prefix = "",
|
|
1324
|
-
): { rules: string; elements: string } {
|
|
1802
|
+
): { rules: string; elements: string; rows: string | null } {
|
|
1325
1803
|
const HEAD = `// Written by src/compile.ts from ${from}: change ${derivedFrom ? "it and its example" : fixed ? "its seed" : "the stories"}, not this.\n`;
|
|
1326
1804
|
for (const name of Object.keys(collections)) {
|
|
1327
1805
|
if (OWN_TABLES.includes(name) || /^sqlite/.test(name))
|
|
@@ -1348,32 +1826,39 @@ export function compile(
|
|
|
1348
1826
|
...(c.own ? { own: true } : {}),
|
|
1349
1827
|
fields: c.fields,
|
|
1350
1828
|
needs: c.required,
|
|
1351
|
-
links:
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1829
|
+
links: linksIn(c, link),
|
|
1830
|
+
// what each field pops, tapped where a page says it (docs/design.md, "A peek"): a value with a form, that
|
|
1831
|
+
// form's view; a reference, the collection it points at. A plain value pops nothing, nor a link that is
|
|
1832
|
+
// structure (part), which a page places the item by
|
|
1833
|
+
pops: Object.fromEntries(
|
|
1834
|
+
Object.entries(c.fields).flatMap(([f, t]): [string, { form: Type } | { to: string }][] =>
|
|
1835
|
+
VIEWED.includes(t)
|
|
1836
|
+
? [[f, { form: t }]]
|
|
1837
|
+
: (t === "ids" || (t === "integer" && link(f).one)) && !link(f).part
|
|
1838
|
+
? [[f, { to: link(f).to }]]
|
|
1839
|
+
: [],
|
|
1840
|
+
),
|
|
1355
1841
|
),
|
|
1356
1842
|
// its links that go with what they point at, in this document: the item removed with it
|
|
1357
1843
|
...goes(c, link, doc),
|
|
1358
1844
|
...(defs.order?.[name] ? { order: defs.order[name] } : {}),
|
|
1359
1845
|
...(c.fills ? { fills: c.fills } : {}),
|
|
1846
|
+
...(c.clock ? { clock: c.clock } : {}),
|
|
1360
1847
|
...(c.timed ? { timed: c.timed } : {}),
|
|
1361
1848
|
...(c.copies ? { copies: c.copies } : {}),
|
|
1362
1849
|
},
|
|
1363
1850
|
]),
|
|
1364
1851
|
);
|
|
1365
1852
|
for (const [f, l] of Object.entries(defs.links ?? {})) {
|
|
1366
|
-
const
|
|
1367
|
-
|
|
1368
|
-
if (t !== (one ? "integer" : "ids"))
|
|
1369
|
-
throw new Error(`${from}: links names ${f}, but no story gives ${one ? "one id" : "a list of ids"} as ${f}`);
|
|
1853
|
+
const said = linkGiven(f, l, Object.entries(collections), from);
|
|
1854
|
+
if (said) throw new Error(said);
|
|
1370
1855
|
}
|
|
1371
1856
|
|
|
1372
1857
|
let rules = `${HEAD}
|
|
1373
1858
|
export type Op = { op: "add" | "replace" | "remove"; path: string; value?: any };
|
|
1374
1859
|
|
|
1375
1860
|
/** The document, and each collection: its element, the element its items are, their fields, those an add needs, and
|
|
1376
|
-
* what each link is to. */
|
|
1861
|
+
* what each link is to and what each field pops (a value with a form, its view; a reference, what it points at). */
|
|
1377
1862
|
export const doc = "${doc}";
|
|
1378
1863
|
export const collections = ${JSON.stringify(shape, null, 2)} as const;
|
|
1379
1864
|
/** Whether every story is anonymous, none told as a member: where every app's is, the project has no members. */
|
|
@@ -1402,7 +1887,7 @@ export const member = true;
|
|
|
1402
1887
|
: ""
|
|
1403
1888
|
}/** The parts of ${doc} a page may hold alone, by its query's parameters (its definitions' window): null, none. */
|
|
1404
1889
|
export const window = ${JSON.stringify(defs.window ?? null)};
|
|
1405
|
-
${defs.window && !defs.where?.[doc] ? windowCode(defs.window) : ""}${defs.moves ? `/** Each field whose value moves only as the stories move it, each step by its roles (its definitions' moves). */\nexport const moves = ${JSON.stringify(defs.moves)};\n` : ""}${defs.guests ? `/** The field holding an item's own code: a page holding ${doc} by it is the item's guest (its definitions' guests). */\nexport const guests = ${JSON.stringify(defs.guests)};\n` : ""}${settingsCode(doc, defs)}${defs.visitors ? `/** The field of its kind's root holding the level its guest is, the role guest: that level (its definitions' visitors). */\nexport const visitors = ${JSON.stringify(defs.visitors)};\n` : ""}${derivedFrom ? "" : `/** The document as one statement over its tables (generated/${prefix}queries.ts). */\nexport { query, postgres${readOnly ? "" : ", items, triggers"} } from "./${prefix}queries.ts";\n`}${derivedFrom ? `/** The documents this one is derived from (its derive.ts): what the server derives it again on a write to. */\nexport const derived = ${JSON.stringify(derivedFrom)};\n` : ""}`;
|
|
1890
|
+
${defs.window && !defs.where?.[doc] ? windowCode(defs.window) : ""}${namesCode(defs, Object.values(collections))}${defs.moves ? `/** Each field whose value moves only as the stories move it, each step by its roles (its definitions' moves). */\nexport const moves = ${JSON.stringify(defs.moves)};\n` : ""}${defs.guests ? `/** The field holding an item's own code: a page holding ${doc} by it is the item's guest (its definitions' guests). */\nexport const guests = ${JSON.stringify(defs.guests)};\n` : ""}${settingsCode(doc, defs)}${defs.visitors ? `/** The field of its kind's root holding the level its guest is, the role guest: that level (its definitions' visitors). */\nexport const visitors = ${JSON.stringify(defs.visitors)};\n` : ""}${derivedFrom ? "" : `/** The document as one statement over its tables (generated/${prefix}queries.ts). */\nexport { query, postgres${readOnly ? "" : ", items, triggers"} } from "./${prefix}queries.ts";\n`}${derivedFrom ? `/** The documents this one is derived from (its derive.ts): what the server derives it again on a write to. */\nexport const derived = ${JSON.stringify(derivedFrom)};\n` : ""}`;
|
|
1406
1891
|
let elements = `${HEAD}
|
|
1407
1892
|
// Each collection is an element, defined here: on a page, it holds the document, and its items
|
|
1408
1893
|
// are put inside it. Each item is an element, defined by the page: as it is, or by a view that
|
|
@@ -1437,28 +1922,30 @@ const send = (from: Element, ops: object[], why?: string) => new Promise<Answer>
|
|
|
1437
1922
|
|
|
1438
1923
|
// a link to one member is cleared as they're removed (its column set null): needed to add, yet, read, maybe gone
|
|
1439
1924
|
const cleared = (f: string) => link(f).one && link(f).to === GROUP;
|
|
1925
|
+
// what's always there as it's read: a field every add gives, or where nothing adds one, every seed item has
|
|
1926
|
+
const there = (f: string) => c.required.includes(f) || (!!c.seedHas?.includes(f) && !cleared(f));
|
|
1440
1927
|
const read = (f: string, t: Type) =>
|
|
1441
1928
|
t === "boolean"
|
|
1442
1929
|
? `this.hasAttribute("${f}")`
|
|
1443
1930
|
: t === "integer" || t === "decimal"
|
|
1444
|
-
?
|
|
1931
|
+
? there(f) && !cleared(f)
|
|
1445
1932
|
? `Number(this.getAttribute("${f}"))`
|
|
1446
1933
|
: `this.hasAttribute("${f}") ? Number(this.getAttribute("${f}")) : undefined`
|
|
1447
1934
|
: t === "ids"
|
|
1448
1935
|
? `Object.freeze((this.getAttribute("${f}") ?? "").split(" ").filter(Boolean).map(Number))`
|
|
1449
|
-
:
|
|
1936
|
+
: there(f)
|
|
1450
1937
|
? `this.getAttribute("${f}") ?? ""`
|
|
1451
1938
|
: `this.getAttribute("${f}") ?? undefined`;
|
|
1452
1939
|
// as read, a boolean or a list is always there: missing is false, or none
|
|
1453
1940
|
const always = fields
|
|
1454
|
-
.filter(([f, t]) => (t === "boolean" || t === "ids") && !
|
|
1941
|
+
.filter(([f, t]) => (t === "boolean" || t === "ids") && !there(f))
|
|
1455
1942
|
.map(([f]) => JSON.stringify(f));
|
|
1456
1943
|
const gone = fields.filter(([f]) => c.required.includes(f) && cleared(f)).map(([f]) => JSON.stringify(f));
|
|
1457
1944
|
const data = `${gone.length ? `Omit<${Class}Data, ${gone.join(" | ")}> & Partial<Pick<${Class}Data, ${gone.join(" | ")}>>` : `${Class}Data`}${always.length ? ` & Required<Pick<${Class}Data, ${always.join(" | ")}>>` : ""}`;
|
|
1458
|
-
// what an add sends, as the stories write it: a dotted field nested ({ terms: { days } }), and a link to one item
|
|
1459
|
-
// may name an add before it in the same write ("$1", the id the store will give it)
|
|
1945
|
+
// what an add sends, as the stories write it: a dotted field nested ({ terms: { days } }), and a link, to one item
|
|
1946
|
+
// or a list's, may name an add before it in the same write ("$1", the id the store will give it)
|
|
1460
1947
|
const sent = (f: string, t: Type) =>
|
|
1461
|
-
`${JSON.stringify(f)}${c.required.includes(f) ? "" : "?"}: ${link(f).one ? REF : tsOf(t)}`;
|
|
1948
|
+
`${JSON.stringify(f)}${c.required.includes(f) ? "" : "?"}: ${link(f).one ? REF : t === "ids" ? `(${REF})[]` : tsOf(t)}`;
|
|
1462
1949
|
const heads = [...new Set(fields.map(([f]) => f.split(".")[0]!))];
|
|
1463
1950
|
const value = heads
|
|
1464
1951
|
.map((h) => {
|
|
@@ -1470,7 +1957,7 @@ const send = (from: Element, ops: object[], why?: string) => new Promise<Answer>
|
|
|
1470
1957
|
.join("; ");
|
|
1471
1958
|
elements += `
|
|
1472
1959
|
/** ${an(item)[0]!.toUpperCase() + an(item).slice(1)}'s fields, as the stories give them. */
|
|
1473
|
-
export type ${Class}Data = { ${fields.map(([f, t]) => `${JSON.stringify(f)}${
|
|
1960
|
+
export type ${Class}Data = { ${fields.map(([f, t]) => `${JSON.stringify(f)}${there(f) ? "" : "?"}: ${tsOf(t)}`).join("; ")} };
|
|
1474
1961
|
/** An add of ${an(item)}, as it's sent: its fields as the stories write them. */
|
|
1475
1962
|
export type ${Class}Value = { ${value} };
|
|
1476
1963
|
|
|
@@ -1499,7 +1986,7 @@ export class ${Class} extends HTMLElement {
|
|
|
1499
1986
|
: `map(([field, value]) => (${one}))`;
|
|
1500
1987
|
elements += ` /** Replace some of its fields (${c.replace.join(", ")}): one write for all of them${byId.length ? `; a list of ids (${byId.join(", ")}) by the ids added to it and taken from it` : ""}. */\n replace(fields: Partial<Pick<${Class}Data, ${F}>>, why?: string) {\n return send(this, Object.entries(fields).filter(([, value]) => value !== undefined).${each}, why);\n }\n`;
|
|
1501
1988
|
if (byId.length)
|
|
1502
|
-
elements += ` /** A list's ids, as the ids added to it and taken from it. */\n #ids(field: ${byId.map((f) => JSON.stringify(f)).join(" | ")}, ids: number[]) {\n const had = this.data[field];\n return [...ids.filter((id) => !had.includes(id)).map((id) => ({ op: "add", path: \`\${this.path}/\${field}/-\`, value: id })), ...had.filter((id) => !ids.includes(id)).map((id) => ({ op: "remove", path: \`\${this.path}/\${field}/\${id}\` }))];\n }\n`;
|
|
1989
|
+
elements += ` /** A list's ids, as the ids added to it and taken from it; emptied, where this person may take the whole list and not\n * its ids one by one (an answer taken back), the list taken. */\n #ids(field: ${byId.map((f) => JSON.stringify(f)).join(" | ")}, ids: number[]) {\n const had = this.data[field], may = (this.getAttribute("may") ?? "").split(" ");\n if (!ids.length && had.length && may.includes(\`remove:\${field}\`) && !may.includes(\`remove:\${field}[]\`)) return [{ op: "remove", path: \`\${this.path}/\${field}\` }];\n return [...ids.filter((id) => !had.includes(id)).map((id) => ({ op: "add", path: \`\${this.path}/\${field}/-\`, value: id })), ...had.filter((id) => !ids.includes(id)).map((id) => ({ op: "remove", path: \`\${this.path}/\${field}/\${id}\` }))];\n }\n`;
|
|
1503
1990
|
}
|
|
1504
1991
|
if (c.link.length)
|
|
1505
1992
|
elements += ` /** Link it to one more id in a list (${c.link.join(", ")}): the ids there already are left as they are. */\n link(field: ${c.link.map((f) => JSON.stringify(f)).join(" | ")}, id: number, why?: string) { return send(this, [{ op: "add", path: \`\${this.path}/\${field}/-\`, value: id }], why); }\n`;
|
|
@@ -1534,11 +2021,149 @@ export type ${Doc}Op =${ops.length ? `\n | ${ops.join("\n | ")}` : " never"};
|
|
|
1534
2021
|
* whole by its rules, and made whole or not at all. */
|
|
1535
2022
|
export function write(from: Element, ops: ${Doc}Op[], why?: string) { return send(from, ops, why); }
|
|
1536
2023
|
`;
|
|
1537
|
-
rules += heldBy(collections, defs, from);
|
|
2024
|
+
rules += heldBy(collections, defs, from) + listsHeldBy(collections, defs, from);
|
|
2025
|
+
const theirs = theirsOf(collections, defs, from);
|
|
2026
|
+
if (theirs)
|
|
2027
|
+
rules += `\n/** The collections of values that are each member's own (its definitions' mine): the link to the item each is of, and to its member, who alone changes or removes it. */\nexport const own: Record<string, { of: string; by: string }> = ${JSON.stringify(theirs)};\n`;
|
|
2028
|
+
const own = mineOf(collections, defs, from);
|
|
2029
|
+
if (own)
|
|
2030
|
+
rules += `\n/** The lists that are each member's own (its definitions' mine), or links to one: a member gives and takes only their own id. */\nexport const mine: Record<string, string[]> = ${JSON.stringify(own)};\n${Object.keys(mineSaid(defs)).length ? `/** The words a write giving or taking another's is refused in, where its mine says them. */\nexport const mineSaid: Record<string, Record<string, string>> = ${JSON.stringify(mineSaid(defs))};\n` : ""}`;
|
|
1538
2031
|
// a derived document is derived for each page, its member's: it has no roles, and is published to no topic
|
|
1539
2032
|
if (!derivedFrom && !readOnly)
|
|
1540
2033
|
rules += whoRules(doc, Object.keys(collections), defs, grants, defs.kind && holders[defs.kind.root]);
|
|
1541
|
-
|
|
2034
|
+
// a derived or read-only document is rows too, which none may change: the kit reads it as any other (a timeline of
|
|
2035
|
+
// a sequence derived from starts, results as rows)
|
|
2036
|
+
const rows = fixed ? null : rowsOf({ doc, collections }, defs, link, HEAD, prefix, grants);
|
|
2037
|
+
return { rules, elements, rows };
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
/** generated/rows.ts: each collection of a document as rows, drawn by joined/rows (src/rows.ts) as this says it, so
|
|
2041
|
+
* nothing is guessed as it runs. What names an item: the first words an add needs, else its first words. What each
|
|
2042
|
+
* field is called: its name. How each is held: each member's own (mine), moved by its steps (moves), the server's
|
|
2043
|
+
* (fills, copies, totals), a link to one item, a list of ids; else asked for by its type. None, of a document with
|
|
2044
|
+
* no collection (its own fields are its page's). */
|
|
2045
|
+
export function rowsOf(
|
|
2046
|
+
{ doc, collections }: Model,
|
|
2047
|
+
defs: Definitions,
|
|
2048
|
+
link: LinkOf,
|
|
2049
|
+
head: string,
|
|
2050
|
+
prefix: string,
|
|
2051
|
+
grants: Record<string, string[]> = {},
|
|
2052
|
+
) {
|
|
2053
|
+
const filled = (coll: string, f: string) =>
|
|
2054
|
+
f in (collections[coll]!.fills ?? {}) ||
|
|
2055
|
+
!!collections[coll]!.copies?.fields.includes(f) ||
|
|
2056
|
+
f in (defs.totals?.[coll] ?? {});
|
|
2057
|
+
// what names an item: the field its title says (definitions' title), else its first field of words
|
|
2058
|
+
const titleOf = (coll: string) => {
|
|
2059
|
+
const said = defs.title?.[coll];
|
|
2060
|
+
if (said !== undefined) {
|
|
2061
|
+
if (!STRINGS.includes(collections[coll]!.fields[said] as Type))
|
|
2062
|
+
throw new Error(`${doc}: title names ${coll}' ${said}, which isn't a field of words its stories give`);
|
|
2063
|
+
return said;
|
|
2064
|
+
}
|
|
2065
|
+
return [...collections[coll]!.required, ...Object.keys(collections[coll]!.fields)].find(
|
|
2066
|
+
(f) => collections[coll]!.fields[f] === "string" && !filled(coll, f) && defs.moves?.[coll] !== f,
|
|
2067
|
+
);
|
|
2068
|
+
};
|
|
2069
|
+
// a link to one that an add needs, to a collection of this document: the item it's of, and drawn under
|
|
2070
|
+
const underOf = (name: string) =>
|
|
2071
|
+
collections[name]!.required.filter((f) => collections[name]!.fields[f] === "integer" && link(f).one)
|
|
2072
|
+
.map((f) => ({ field: f, in: link(f).to }))
|
|
2073
|
+
.find((u) => u.in !== name && link(u.field).at === doc && collections[u.in] && !collections[u.in]!.own);
|
|
2074
|
+
const toOf = (f: string) => ({
|
|
2075
|
+
tag: `${PREFIX}-${itemOf(link(f).to)}`,
|
|
2076
|
+
...(link(f).at === doc && collections[link(f).to] ? { title: titleOf(link(f).to) } : {}),
|
|
2077
|
+
...(link(f).to === "members" ? { people: true } : {}),
|
|
2078
|
+
});
|
|
2079
|
+
// where a field that moves may be, in the order the stories take it there: the step an add gives it, then each
|
|
2080
|
+
// step a story moves it from or to (the grants' "replace questions.status:open>settled")
|
|
2081
|
+
const stepsOf = (coll: string, f: string) => {
|
|
2082
|
+
const first = defs.fills?.[coll]?.[f],
|
|
2083
|
+
step = new RegExp(`^(?:add|replace) ${coll}\\.${f}:(.*)>(.*)$`);
|
|
2084
|
+
const told = Object.keys(grants).flatMap((g) => step.exec(g)?.slice(1) ?? []);
|
|
2085
|
+
return [...new Set([...(typeof first === "string" ? [first] : []), ...told].filter(Boolean))];
|
|
2086
|
+
};
|
|
2087
|
+
const specs = Object.entries(collections)
|
|
2088
|
+
.filter(([, c]) => !c.own)
|
|
2089
|
+
.map(([name, c]) => ({
|
|
2090
|
+
doc,
|
|
2091
|
+
name,
|
|
2092
|
+
place: `${PREFIX}-${name}`,
|
|
2093
|
+
tag: `${PREFIX}-${itemOf(name)!}`,
|
|
2094
|
+
one: itemOf(name)!,
|
|
2095
|
+
title: titleOf(name),
|
|
2096
|
+
under: underOf(name),
|
|
2097
|
+
// values each member's own, of the item they're under: never rows of their own
|
|
2098
|
+
...(defs.mine?.[name] && !Array.isArray(defs.mine[name]) ? { mine: defs.mine[name] } : {}),
|
|
2099
|
+
// (one of an object's fields, terms.days, isn't drawn yet)
|
|
2100
|
+
fields: Object.entries(c.fields)
|
|
2101
|
+
.filter(([f]) => !f.includes("."))
|
|
2102
|
+
.map(([f, type]) => {
|
|
2103
|
+
const own =
|
|
2104
|
+
type === "ids" &&
|
|
2105
|
+
listsOf(defs.mine?.[name])
|
|
2106
|
+
.map((g) => [g].flat())
|
|
2107
|
+
.find((g) => g.includes(f));
|
|
2108
|
+
return {
|
|
2109
|
+
name: f,
|
|
2110
|
+
type,
|
|
2111
|
+
...(c.required.includes(f) ? { needed: true } : {}),
|
|
2112
|
+
...(own
|
|
2113
|
+
? { how: "mine", with: own.filter((o) => o !== f) }
|
|
2114
|
+
: defs.moves?.[name] === f
|
|
2115
|
+
? { how: "moves", steps: stepsOf(name, f) }
|
|
2116
|
+
: filled(name, f)
|
|
2117
|
+
? { how: "filled" }
|
|
2118
|
+
: type === "ids"
|
|
2119
|
+
? { how: "ids" }
|
|
2120
|
+
: type === "integer" && link(f).one
|
|
2121
|
+
? { how: "one" }
|
|
2122
|
+
: {}),
|
|
2123
|
+
...(type === "ids" || (type === "integer" && link(f).one) ? { to: toOf(f) } : {}),
|
|
2124
|
+
// a reference, which pops what it points at: any link that isn't structure (part)
|
|
2125
|
+
...((type === "ids" || (type === "integer" && link(f).one)) && !link(f).part ? { ref: true as const } : {}),
|
|
2126
|
+
};
|
|
2127
|
+
}),
|
|
2128
|
+
}));
|
|
2129
|
+
if (!specs.length) return null;
|
|
2130
|
+
const Item = (tag: string) => Pascal(tag);
|
|
2131
|
+
const inner = (s: (typeof specs)[number]) => specs.filter((n) => n.under?.in === s.name);
|
|
2132
|
+
return `${head}
|
|
2133
|
+
// Each collection of ${doc} as rows (joined/rows, the skill's §3): a page defines the ones it shows, as they are or
|
|
2134
|
+
// extended, by define() from joined/rows, and holds each collection's element in its rows:
|
|
2135
|
+
// ${specs.map((s) => `<${s.place}-rows>${[s, ...inner(s)].map((n) => `<${n.place}></${n.place}>`).join("")}</${s.place}-rows>`).join("\n// ")}
|
|
2136
|
+
// A collection whose items are each of one of another's is drawn under it there, where its element is put in too.
|
|
2137
|
+
// To change what one says or does, extend its class and override a part (label, named, says, facts, deeds, row,
|
|
2138
|
+
// step, asks); to change how it looks, style its parts (::part(row), title, state, facts, deeds, mine, step, add,
|
|
2139
|
+
// under, drawer). Its sheet, a search of it and how a field reads are joined/kit's, given these collections by
|
|
2140
|
+
// use(specs) (define() gives a display's own). To draw something else altogether, don't define it: a display of the app's own holds the same
|
|
2141
|
+
// elements. Never change this file: change the stories.
|
|
2142
|
+
|
|
2143
|
+
import { rows, type Spec } from "joined/rows";
|
|
2144
|
+
import { ${specs.map((s) => Item(s.tag)).join(", ")} } from "./${prefix}elements.ts";
|
|
2145
|
+
${specs.map((s) => `\nconst ${s.name.replaceAll("-", "_")}: Spec = ${JSON.stringify(s)};`).join("")}
|
|
2146
|
+
|
|
2147
|
+
/** Each collection as joined's kit (joined/kit) is given it, by name: use(specs). */
|
|
2148
|
+
export const specs = { ${specs.map((s) => `"${s.name}": ${s.name.replaceAll("-", "_")}`).join(", ")} };
|
|
2149
|
+
${specs
|
|
2150
|
+
.map(
|
|
2151
|
+
(s) => `
|
|
2152
|
+
/** <${s.place}-rows>: ${doc}'s ${s.name} as rows${s.title ? `, each named by its ${s.title}` : ""}${
|
|
2153
|
+
inner(s).length
|
|
2154
|
+
? `, its ${inner(s)
|
|
2155
|
+
.map((n) => n.name)
|
|
2156
|
+
.join(" and ")} under it`
|
|
2157
|
+
: ""
|
|
2158
|
+
}. */
|
|
2159
|
+
export class ${Item(s.place)}Rows extends rows(${s.name.replaceAll("-", "_")}, { ${[s, ...inner(s)].map((n) => `"${n.tag}": ${Item(n.tag)}`).join(", ")} }${inner(
|
|
2160
|
+
s,
|
|
2161
|
+
)
|
|
2162
|
+
.map((n) => `, ${n.name.replaceAll("-", "_")}`)
|
|
2163
|
+
.join("")}) {}
|
|
2164
|
+
`,
|
|
2165
|
+
)
|
|
2166
|
+
.join("")}`;
|
|
1542
2167
|
}
|
|
1543
2168
|
|
|
1544
2169
|
/** The element of a document's own fields (<j-hello greeting>): it holds its document, and is its one item, each
|
|
@@ -1548,16 +2173,20 @@ function ownElement(doc: string, c: Coll) {
|
|
|
1548
2173
|
Class = Pascal(tag),
|
|
1549
2174
|
fields = Object.entries(c.fields);
|
|
1550
2175
|
const ts = (t: Type) => (t === "integer" || t === "decimal" ? "number" : t === "boolean" ? t : "string");
|
|
2176
|
+
// what its seed always has, no story removing it: there as it's read
|
|
2177
|
+
const there = (f: string) => !!c.seedHas?.includes(f);
|
|
1551
2178
|
const read = (f: string, t: Type) =>
|
|
1552
2179
|
t === "boolean"
|
|
1553
2180
|
? `this.hasAttribute("${f}")`
|
|
1554
2181
|
: t === "integer" || t === "decimal"
|
|
1555
|
-
?
|
|
1556
|
-
|
|
2182
|
+
? there(f)
|
|
2183
|
+
? `Number(this.getAttribute("${f}"))`
|
|
2184
|
+
: `this.hasAttribute("${f}") ? Number(this.getAttribute("${f}")) : undefined`
|
|
2185
|
+
: `this.getAttribute("${f}") ?? ${there(f) ? '""' : "undefined"}`;
|
|
1557
2186
|
const F = c.replace.map((f) => JSON.stringify(f)).join(" | ");
|
|
1558
2187
|
return `
|
|
1559
2188
|
/** ${doc}'s own fields, as the stories give them. */
|
|
1560
|
-
export type ${Class}Data = { ${fields.map(([f, t]) => `${JSON.stringify(f)}
|
|
2189
|
+
export type ${Class}Data = { ${fields.map(([f, t]) => `${JSON.stringify(f)}${there(f) || t === "boolean" ? "" : "?"}: ${ts(t)}`).join("; ")} };
|
|
1561
2190
|
|
|
1562
2191
|
/** <${tag}>: ${doc} itself, holding it, its own fields each an attribute. */
|
|
1563
2192
|
export class ${Class} extends HTMLElement {
|
|
@@ -1591,8 +2220,11 @@ export const OWN = `${import.meta.dir}/members`;
|
|
|
1591
2220
|
/** Where what the pages change is kept, apart from the code: JOINED_DATA (on Railway, a volume), or .data/ in
|
|
1592
2221
|
* the folder joined runs in. */
|
|
1593
2222
|
export const DATA = Bun.env.JOINED_DATA || `${process.cwd()}/.data`;
|
|
1594
|
-
/** The store's engine (src/engine.ts): JOINED_ENGINE, sqlite or postgres
|
|
1595
|
-
|
|
2223
|
+
/** The store's engine (src/engine.ts): JOINED_ENGINE, sqlite or postgres; else Postgres where JOINED_POSTGRES names
|
|
2224
|
+
* a server, else SQLite. */
|
|
2225
|
+
export const engineOf = (env: Record<string, string | undefined>) =>
|
|
2226
|
+
(env.JOINED_ENGINE || (env.JOINED_POSTGRES ? "postgres" : "sqlite")) as Dialect;
|
|
2227
|
+
export const ENGINE = engineOf(Bun.env);
|
|
1596
2228
|
/** The store's file, or Postgres's folder (src/store.ts): JOINED_DB, or joined.sqlite (postgres/) in the data folder. */
|
|
1597
2229
|
export const DB = Bun.env.JOINED_DB || `${DATA}/${ENGINE === "postgres" ? "postgres" : "joined.sqlite"}`;
|
|
1598
2230
|
|
|
@@ -1678,9 +2310,13 @@ export async function compiled(dir = APPS) {
|
|
|
1678
2310
|
// each a unit of its own, its files named for it
|
|
1679
2311
|
const told = toldBy[app]!,
|
|
1680
2312
|
cast = lines.find((l) => l.cast)?.cast ?? {},
|
|
1681
|
-
defined: Definitions = Object.assign({}, ...header);
|
|
2313
|
+
defined: Definitions = implied(Object.assign({}, ...header));
|
|
1682
2314
|
const bases = [...new Set(told.map((s) => (s.does ?? s.cannot)!.doc.split(/[:?]/)[0]!))];
|
|
1683
2315
|
const several = bases.length > 1 || !!defined.documents;
|
|
2316
|
+
// (an app's items are in any of its documents' seeds)
|
|
2317
|
+
const seedsOf = await Promise.all((several ? bases : [app]).map((u) => seedOf(`${at}/${u}.json`)));
|
|
2318
|
+
const seedIn = (coll: string) =>
|
|
2319
|
+
seedsOf.flatMap((s) => (Array.isArray(s[coll]) ? (s[coll] as Record<string, unknown>[]) : []));
|
|
1684
2320
|
for (const unit of several ? bases : [app]) {
|
|
1685
2321
|
dirs[unit] = at;
|
|
1686
2322
|
if (several) split.add(unit);
|
|
@@ -1690,13 +2326,24 @@ export async function compiled(dir = APPS) {
|
|
|
1690
2326
|
defs[unit] = several ? definedFor(defined, models[unit]!, stories[unit]!) : defined;
|
|
1691
2327
|
if (defs[unit]!.kind && defs[unit]!.kind!.root in models[unit]!.collections)
|
|
1692
2328
|
throw new Error(`${app}'s stories: a kind's root, ${defs[unit]!.kind!.root}, is another document's collection`);
|
|
1693
|
-
|
|
2329
|
+
if (defs[unit]!.kind?.files !== undefined && defs[unit]!.kind!.files !== "apart")
|
|
2330
|
+
throw new Error(`${app}'s stories: a kind's files are "apart", or not said`);
|
|
2331
|
+
filled(models[unit]!, defs[unit]!, `${app}'s definitions`, seedIn);
|
|
1694
2332
|
}
|
|
2333
|
+
// a link's name is the link's in every document the app tells (a race's crossings' boat, and an entry's)
|
|
2334
|
+
if (several)
|
|
2335
|
+
for (const [f, l] of Object.entries(defined.links ?? {})) {
|
|
2336
|
+
const colls = bases.flatMap((u) =>
|
|
2337
|
+
Object.entries(models[u]!.collections).map(([n, c]): [string, Coll] => [`${u}'s ${n}`, c]),
|
|
2338
|
+
);
|
|
2339
|
+
const said = colls.some(([, c]) => c.fields[f]) && linkGiven(f, l, colls, `${app}'s stories`);
|
|
2340
|
+
if (said) throw new Error(said);
|
|
2341
|
+
}
|
|
1695
2342
|
entities(several ? bases : [app], models, defs, defined);
|
|
1696
2343
|
// a read-only document over the app's entities, a query its definition says (each side's books)
|
|
1697
2344
|
for (const [name, d] of Object.entries(defined.documents ?? {})) {
|
|
1698
2345
|
dirs[name] = at;
|
|
1699
|
-
split.add(name);
|
|
2346
|
+
if (name !== app) split.add(name);
|
|
1700
2347
|
stories[name] = [];
|
|
1701
2348
|
casts[name] = cast;
|
|
1702
2349
|
defs[name] = {};
|
|
@@ -1704,7 +2351,7 @@ export async function compiled(dir = APPS) {
|
|
|
1704
2351
|
readOnly[name] = d;
|
|
1705
2352
|
anonymousOf[name] = told.every((s) => s.as === undefined);
|
|
1706
2353
|
}
|
|
1707
|
-
if (several && !bases.includes(app)) delete dirs[app];
|
|
2354
|
+
if (several && !bases.includes(app) && !readOnly[app]) delete dirs[app];
|
|
1708
2355
|
}
|
|
1709
2356
|
// the seeds, as the documents begin: who each name in the stories is, and who that is to each document
|
|
1710
2357
|
const seeds: Record<string, Record<string, unknown>> = {};
|
|
@@ -1714,6 +2361,24 @@ export async function compiled(dir = APPS) {
|
|
|
1714
2361
|
seeds[m.doc] = await seedOf(file);
|
|
1715
2362
|
seeded(m, seeds[m.doc]!, relative(process.cwd(), file));
|
|
1716
2363
|
}
|
|
2364
|
+
// a wall clock filled "now" is on the clock of a zone, said by the field named for it: the item's own, its kind's
|
|
2365
|
+
// root's, the document's own
|
|
2366
|
+
for (const [app, m] of Object.entries(models))
|
|
2367
|
+
for (const [coll, c] of Object.entries(m.collections)) {
|
|
2368
|
+
const f = Object.entries(c.fills ?? {}).find(([f, v]) => v === "now" && c.fields[f] === "date-time")?.[0];
|
|
2369
|
+
if (!f) continue;
|
|
2370
|
+
const root = defs[app]!.kind?.root,
|
|
2371
|
+
says = (x?: Coll) => x?.fields.zone === "zone";
|
|
2372
|
+
c.clock = [
|
|
2373
|
+
...(says(c) ? ["item" as const] : []),
|
|
2374
|
+
...(root && Object.values(models).some((o) => says(o.collections[root])) ? ["root" as const] : []),
|
|
2375
|
+
...(Object.values(m.collections).some((o) => o.own && says(o)) ? ["document" as const] : []),
|
|
2376
|
+
];
|
|
2377
|
+
if (!c.clock.length)
|
|
2378
|
+
throw new Error(
|
|
2379
|
+
`${app}'s stories: ${coll}' ${f} is filled "now" as a wall clock, so a zone is said: a field named zone, a time zone, of the item, of its kind's root or of the document's own`,
|
|
2380
|
+
);
|
|
2381
|
+
}
|
|
1717
2382
|
// a copy: each field taken from what a one-id link points at, its type that field's, once, when it's added
|
|
1718
2383
|
for (const [app, d] of Object.entries(defs))
|
|
1719
2384
|
for (const [coll, { from, fields }] of Object.entries(d.copies ?? {})) {
|
|
@@ -1740,14 +2405,38 @@ export async function compiled(dir = APPS) {
|
|
|
1740
2405
|
}
|
|
1741
2406
|
c.copies = { from, fields, to: link.to, at: at.doc };
|
|
1742
2407
|
}
|
|
2408
|
+
// where no story adds an item, the seed's are all there are: a field every one has is typed there, as a needed one
|
|
2409
|
+
for (const [app, m] of Object.entries(models)) {
|
|
2410
|
+
if (derivedFrom[app] || readOnly[app] || defs[app]!.kind) continue;
|
|
2411
|
+
for (const [name, c] of Object.entries(m.collections)) {
|
|
2412
|
+
const added = Object.values(models).some((o) => dirs[o.doc] === dirs[app] && o.collections[name]?.adds);
|
|
2413
|
+
const items = (c.own ? [ownOf(seeds[m.doc]!)] : (seeds[m.doc]![name] ?? [])) as Record<string, unknown>[];
|
|
2414
|
+
if (added || c.copies || !items.length) continue;
|
|
2415
|
+
const has = Object.keys(c.fields).filter(
|
|
2416
|
+
(f) =>
|
|
2417
|
+
!c.required.includes(f) &&
|
|
2418
|
+
!c.removeField.includes(f) &&
|
|
2419
|
+
items.every((i) => (f.includes(".") ? (i[f.split(".")[0]!] as any)?.[f.split(".")[1]!] : i[f]) != null),
|
|
2420
|
+
);
|
|
2421
|
+
if (has.length) c.seedHas = has;
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
1743
2424
|
const members = (seeds.members?.members ?? []) as { id: number; name: string }[];
|
|
1744
2425
|
// an element's name is one per page: no two documents have a collection of one name
|
|
1745
|
-
// across apps; an app's documents may each hold one of its tables (the till's orders, the kitchen's)
|
|
2426
|
+
// across apps; an app's documents may each hold one of its tables (the till's orders, the kitchen's); and two
|
|
2427
|
+
// derived documents may each derive one kind of item, its fields the same, one element for both
|
|
1746
2428
|
const held: Record<string, string> = {};
|
|
1747
2429
|
for (const [app, m] of Object.entries(models).sort(([a], [b]) => a.localeCompare(b)))
|
|
1748
2430
|
for (const c of Object.keys(m.collections)) {
|
|
1749
|
-
|
|
1750
|
-
|
|
2431
|
+
const other = held[c],
|
|
2432
|
+
derived = !!other && !!derivedFrom[app] && !!derivedFrom[other],
|
|
2433
|
+
alike =
|
|
2434
|
+
derived &&
|
|
2435
|
+
JSON.stringify(models[other!]!.collections[c]!.fields) === JSON.stringify(m.collections[c]!.fields);
|
|
2436
|
+
if (other && dirs[other] !== dirs[app] && !alike)
|
|
2437
|
+
throw new Error(
|
|
2438
|
+
`${other} and ${app} both have a collection named ${c}${derived ? ": two derived documents share one only where its items are the same, field for field" : ""}`,
|
|
2439
|
+
);
|
|
1751
2440
|
held[c] ??= app;
|
|
1752
2441
|
}
|
|
1753
2442
|
/** Which other document holds each collection an app's document doesn't. */
|
|
@@ -1777,11 +2466,12 @@ export async function compiled(dir = APPS) {
|
|
|
1777
2466
|
);
|
|
1778
2467
|
};
|
|
1779
2468
|
/** Each document's grants, and who its tellers are on the seeds: worked out once. */
|
|
1780
|
-
const granted: Record<string, { grants: Record<string, string[]>; rolesOfTeller: (s: Story) => string[] }> =
|
|
2469
|
+
const granted: Record<string, { grants: Record<string, string[]>; rolesOfTeller: (s: Story, o?: Op) => string[] }> =
|
|
2470
|
+
{};
|
|
1781
2471
|
const grantsFor = (app: string) => {
|
|
1782
2472
|
if (granted[app]) return granted[app]!;
|
|
1783
2473
|
const roles = Object.entries(defs[app]!.roles ?? {}).map(
|
|
1784
|
-
([r, path]) => [r, whoFn(whoCode(path, []
|
|
2474
|
+
([r, path]) => [r, whoFn(whoCode(path, defs[app]!.roles!, app, !!defs[app]!.kind, [r]))] as const,
|
|
1785
2475
|
);
|
|
1786
2476
|
const memberOf = (name: string) => {
|
|
1787
2477
|
const as = name in casts[app]! ? casts[app]![name] : name;
|
|
@@ -1819,6 +2509,19 @@ export async function compiled(dir = APPS) {
|
|
|
1819
2509
|
// writes the parts before its own (src/together.ts), which name its document: once a story (none, no premise: the
|
|
1820
2510
|
// seeds)
|
|
1821
2511
|
const fillsOf = (doc: string, coll: string) => defs[doc]?.fills?.[coll];
|
|
2512
|
+
const typeIn = (doc: string, coll: string, f: string) => models[doc]?.collections[coll]?.fields[f];
|
|
2513
|
+
// a document's collections, each its links: where a write's "$n" is read
|
|
2514
|
+
const collectionsOf = (doc: string): Linked | undefined => {
|
|
2515
|
+
const m = models[doc];
|
|
2516
|
+
if (!m) return undefined;
|
|
2517
|
+
const link = linksOf(m, defs[doc]!, {}, doc);
|
|
2518
|
+
return Object.fromEntries(
|
|
2519
|
+
Object.entries(m.collections).map(([c, x]) => [
|
|
2520
|
+
c,
|
|
2521
|
+
{ links: linksIn(x, link), ...(x.own ? { own: true } : {}) },
|
|
2522
|
+
]),
|
|
2523
|
+
);
|
|
2524
|
+
};
|
|
1822
2525
|
const states = new WeakMap<Story, ReturnType<typeof writtenBefore>>();
|
|
1823
2526
|
const writtenOf = (s: Story = { story: "" }) =>
|
|
1824
2527
|
states.get(s) ??
|
|
@@ -1827,9 +2530,11 @@ export async function compiled(dir = APPS) {
|
|
|
1827
2530
|
s,
|
|
1828
2531
|
writtenBefore(
|
|
1829
2532
|
s,
|
|
1830
|
-
premised(seeds, s.premise, fillsOf, memberOf),
|
|
1831
|
-
(state, w) =>
|
|
2533
|
+
premised(seeds, s.premise, fillsOf, memberOf, collectionsOf, typeIn),
|
|
2534
|
+
(state, w) =>
|
|
2535
|
+
premised(state, s.as === undefined ? [w] : { [s.as]: [w] }, fillsOf, memberOf, collectionsOf, typeIn),
|
|
1832
2536
|
(name) => defs[name]?.kind?.root,
|
|
2537
|
+
collectionsOf,
|
|
1833
2538
|
),
|
|
1834
2539
|
)
|
|
1835
2540
|
.get(s)!;
|
|
@@ -1842,9 +2547,7 @@ export async function compiled(dir = APPS) {
|
|
|
1842
2547
|
const named =
|
|
1843
2548
|
m === null
|
|
1844
2549
|
? []
|
|
1845
|
-
: roles
|
|
1846
|
-
.filter(([, is]) => is(m, readIn(state), [], at, d, k ? itemOf(d, o, state) : undefined))
|
|
1847
|
-
.map(([r]) => r);
|
|
2550
|
+
: roles.filter(([, is]) => is(m, readIn(state), at, d, k ? itemOf(d, o, state) : undefined)).map(([r]) => r);
|
|
1848
2551
|
// a guest: a page holding the document by the item's own code, or in a kind, its root's (as the runtime asks)
|
|
1849
2552
|
const root = k && guests?.[k.root],
|
|
1850
2553
|
code = o && (root || guests?.[parts(o.path).coll]),
|
|
@@ -1866,12 +2569,13 @@ export async function compiled(dir = APPS) {
|
|
|
1866
2569
|
: grantOf(o);
|
|
1867
2570
|
};
|
|
1868
2571
|
const grants = grantsOf(stories[app]!, rolesOf, memberOf, keyOf);
|
|
1869
|
-
|
|
2572
|
+
// who a story's teller is, to the item an op is to
|
|
2573
|
+
const rolesOfTeller = (s: Story, o?: Op) => {
|
|
1870
2574
|
const w = (s.does ?? s.cannot)!;
|
|
1871
2575
|
// an anonymous story's teller: a guest, where it holds the document by a code (as its first op finds it)
|
|
1872
|
-
if (s.as === undefined) return rolesOf(null, w.doc, w.ops[0], s);
|
|
2576
|
+
if (s.as === undefined) return rolesOf(null, w.doc, o ?? w.ops[0], s);
|
|
1873
2577
|
const m = memberOf(s.as);
|
|
1874
|
-
return m === undefined ? [] : rolesOf(m, w.doc,
|
|
2578
|
+
return m === undefined ? [] : rolesOf(m, w.doc, o, s);
|
|
1875
2579
|
};
|
|
1876
2580
|
return (granted[app] = { grants, rolesOfTeller });
|
|
1877
2581
|
};
|
|
@@ -1898,12 +2602,20 @@ export async function compiled(dir = APPS) {
|
|
|
1898
2602
|
model: Model;
|
|
1899
2603
|
rules: string;
|
|
1900
2604
|
elements: string;
|
|
2605
|
+
rows: string | null;
|
|
1901
2606
|
queries: string | null;
|
|
1902
2607
|
tables: Record<string, Table>;
|
|
1903
2608
|
/** Its files' names: a unit of an app of several documents, named for it (catalogue.rules.ts). */
|
|
1904
2609
|
prefix: string;
|
|
1905
2610
|
}
|
|
1906
2611
|
> = {};
|
|
2612
|
+
/** Whether a document is anyone's, every story of it told by nobody: one with guests is held by them as guests,
|
|
2613
|
+
* and a derived one is anyone's only where all it's derived from is. */
|
|
2614
|
+
const anonymous = (app: string): boolean =>
|
|
2615
|
+
anonymousOf[app] ??
|
|
2616
|
+
(derivedFrom[app]
|
|
2617
|
+
? derivedFrom[app].every((d) => anonymous(Object.keys(models).find((a) => models[a]!.doc === d)!))
|
|
2618
|
+
: stories[app]!.every((s) => s.as === undefined) && !defs[app]!.guests);
|
|
1907
2619
|
for (const app of Object.keys(models).sort()) {
|
|
1908
2620
|
const holders = holdersOf(app);
|
|
1909
2621
|
// named from joined's own folder for its members, and from the apps' folder's for theirs
|
|
@@ -1953,8 +2665,7 @@ export async function compiled(dir = APPS) {
|
|
|
1953
2665
|
holders,
|
|
1954
2666
|
defs[app],
|
|
1955
2667
|
checkedFor(app),
|
|
1956
|
-
|
|
1957
|
-
anonymousOf[app] ?? (stories[app]!.every((s) => s.as === undefined) && !defs[app]!.guests),
|
|
2668
|
+
anonymous(app),
|
|
1958
2669
|
derivedFrom[app],
|
|
1959
2670
|
statics.has(app),
|
|
1960
2671
|
readOnly[app],
|
|
@@ -1968,8 +2679,8 @@ export async function compiled(dir = APPS) {
|
|
|
1968
2679
|
/** A who-path's code as a function, to find who the stories' tellers are on the seeds as it compiles. */
|
|
1969
2680
|
const whoFn = (code: string) =>
|
|
1970
2681
|
new Function(
|
|
1971
|
-
`${new Bun.Transpiler({ loader: "ts" }).transformSync(`const is = (m: number, read: any,
|
|
1972
|
-
)() as (m: number, read: (doc: string) => any,
|
|
2682
|
+
`${new Bun.Transpiler({ loader: "ts" }).transformSync(`const is = (m: number, read: any, item: any, doc: string, at?: any) => ${code};`)} return is;`,
|
|
2683
|
+
)() as (m: number, read: (doc: string) => any, item: unknown, doc: string, at?: unknown) => boolean;
|
|
1973
2684
|
|
|
1974
2685
|
/** An app's seed, where its stories start (none: nothing seeded). */
|
|
1975
2686
|
const seedOf = async (file: string) => ((await Bun.file(file).exists()) ? await Bun.file(file).json() : {});
|
|
@@ -1989,10 +2700,11 @@ export async function writeAll(dir = APPS) {
|
|
|
1989
2700
|
ofDir.set(dir, had);
|
|
1990
2701
|
}
|
|
1991
2702
|
const migrated = new Set<string>();
|
|
1992
|
-
for (const { dir, doc, model, rules, elements, queries, prefix } of Object.values(out)) {
|
|
2703
|
+
for (const { dir, doc, model, rules, elements, rows, queries, prefix } of Object.values(out)) {
|
|
1993
2704
|
said.push(...loosened(await neededBefore(`${dir}/generated/${prefix}rules.ts`), model));
|
|
1994
2705
|
await changed(`${dir}/generated/${prefix}rules.ts`, rules);
|
|
1995
2706
|
await changed(`${dir}/generated/${prefix}elements.ts`, elements);
|
|
2707
|
+
if (rows) await changed(`${dir}/generated/${prefix}rows.ts`, rows);
|
|
1996
2708
|
if (queries) await changed(`${dir}/generated/${prefix}queries.ts`, queries);
|
|
1997
2709
|
if (migrated.has(dir)) continue;
|
|
1998
2710
|
migrated.add(dir);
|