@blueshed/joined 0.0.0-stage → 0.1.19
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 +17 -0
- package/.claude/skills/joined/reference.md +768 -0
- package/LICENSE +19 -0
- package/README.md +115 -2
- package/docs/design.md +148 -0
- package/docs/introduction.md +193 -0
- package/docs/learning.md +76 -0
- package/docs/stories.md +82 -0
- package/examples/app.css +27 -0
- package/examples/cafe/books.html +38 -0
- package/examples/cafe/books.json +13 -0
- package/examples/cafe/books.ts +64 -0
- package/examples/cafe/cafe.css +512 -0
- package/examples/cafe/front.html +115 -0
- package/examples/cafe/front.ts +7 -0
- package/examples/cafe/generated/books.elements.ts +52 -0
- package/examples/cafe/generated/books.queries.ts +11 -0
- package/examples/cafe/generated/books.rules.ts +42 -0
- package/examples/cafe/generated/kitchen.elements.ts +87 -0
- package/examples/cafe/generated/kitchen.queries.ts +47 -0
- package/examples/cafe/generated/kitchen.rules.ts +98 -0
- package/examples/cafe/generated/menu.elements.ts +61 -0
- package/examples/cafe/generated/menu.queries.ts +28 -0
- package/examples/cafe/generated/menu.rules.ts +65 -0
- package/examples/cafe/generated/order.elements.ts +87 -0
- package/examples/cafe/generated/order.queries.ts +47 -0
- package/examples/cafe/generated/order.rules.ts +95 -0
- package/examples/cafe/generated/staff.elements.ts +55 -0
- package/examples/cafe/generated/staff.queries.ts +27 -0
- package/examples/cafe/generated/staff.rules.ts +59 -0
- package/examples/cafe/generated/supplies.elements.ts +62 -0
- package/examples/cafe/generated/supplies.queries.ts +43 -0
- package/examples/cafe/generated/supplies.rules.ts +84 -0
- package/examples/cafe/generated/till.elements.ts +93 -0
- package/examples/cafe/generated/till.queries.ts +57 -0
- package/examples/cafe/generated/till.rules.ts +113 -0
- package/examples/cafe/index.html +70 -0
- package/examples/cafe/kitchen.css +107 -0
- package/examples/cafe/kitchen.html +39 -0
- package/examples/cafe/kitchen.ts +125 -0
- package/examples/cafe/menu.html +55 -0
- package/examples/cafe/menu.json +41 -0
- package/examples/cafe/menu.ts +84 -0
- package/examples/cafe/migrations/001-cafe.ts +11 -0
- package/examples/cafe/order.html +37 -0
- package/examples/cafe/order.ts +45 -0
- package/examples/cafe/rail-drag.ts +30 -0
- package/examples/cafe/routes.ts +32 -0
- package/examples/cafe/staff.json +20 -0
- package/examples/cafe/stories.jsonl +43 -0
- package/examples/cafe/supplies.html +77 -0
- package/examples/cafe/supplies.json +33 -0
- package/examples/cafe/supplies.ts +170 -0
- package/examples/cafe/till.json +95 -0
- package/examples/cafe/till.ts +122 -0
- package/examples/cafe/trust.ts +20 -0
- package/examples/cafe/views.ts +171 -0
- package/examples/docs.ts +28 -0
- package/examples/film.jpg +0 -0
- package/examples/hello/generated/elements.ts +45 -0
- package/examples/hello/generated/queries.ts +24 -0
- package/examples/hello/generated/rules.ts +45 -0
- package/examples/hello/hello.css +27 -0
- package/examples/hello/hello.json +1 -0
- package/examples/hello/index.html +32 -0
- package/examples/hello/migrations/001-hello.ts +6 -0
- package/examples/hello/page.ts +49 -0
- package/examples/hello/routes.ts +6 -0
- package/examples/hello/stories.jsonl +3 -0
- package/examples/index.html +146 -0
- package/examples/page.ts +11 -0
- package/examples/people/adding.ts +20 -0
- package/examples/people/generated/elements.ts +68 -0
- package/examples/people/generated/queries.ts +28 -0
- package/examples/people/generated/rules.ts +85 -0
- package/examples/people/links.ts +124 -0
- package/examples/people/migrations/001-people.ts +6 -0
- package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
- package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
- package/examples/people/order.ts +61 -0
- package/examples/people/people.css +65 -0
- package/examples/people/people.json +26 -0
- package/examples/people/routes.ts +12 -0
- package/examples/people/stories.jsonl +20 -0
- package/examples/people/trust.ts +14 -0
- package/examples/people/view.ts +115 -0
- package/examples/routes.ts +11 -0
- package/examples/trip/answer-rows.ts +70 -0
- package/examples/trip/answers.ts +11 -0
- package/examples/trip/bar.ts +89 -0
- package/examples/trip/calendar-map.css +709 -0
- package/examples/trip/calendar-map.ts +249 -0
- package/examples/trip/drags.ts +143 -0
- package/examples/trip/drawer.ts +250 -0
- package/examples/trip/event-form.ts +199 -0
- package/examples/trip/generated/elements.ts +144 -0
- package/examples/trip/generated/queries.ts +46 -0
- package/examples/trip/generated/rules.ts +239 -0
- package/examples/trip/holding.ts +61 -0
- package/examples/trip/ics.ts +117 -0
- package/examples/trip/index.html +82 -0
- package/examples/trip/line-stops.ts +92 -0
- package/examples/trip/line-words.ts +79 -0
- package/examples/trip/line.ts +121 -0
- package/examples/trip/map.ts +234 -0
- package/examples/trip/mercator.ts +28 -0
- package/examples/trip/migrations/001-trip.ts +7 -0
- package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
- package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
- package/examples/trip/migrations/004-create-stays.ts +6 -0
- package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
- package/examples/trip/month.ts +87 -0
- package/examples/trip/other-weeks.ts +67 -0
- package/examples/trip/page.ts +121 -0
- package/examples/trip/peek.ts +71 -0
- package/examples/trip/people-chips.ts +74 -0
- package/examples/trip/place-search.ts +51 -0
- package/examples/trip/places.ts +34 -0
- package/examples/trip/routes.ts +27 -0
- package/examples/trip/shell.ts +39 -0
- package/examples/trip/stays.css +51 -0
- package/examples/trip/stays.ts +68 -0
- package/examples/trip/stories.jsonl +72 -0
- package/examples/trip/time.ts +46 -0
- package/examples/trip/told.ts +48 -0
- package/examples/trip/trip.json +69 -0
- package/examples/trip/trust.ts +51 -0
- package/examples/trip/week.ts +237 -0
- package/examples/trip/words.ts +4 -0
- package/examples/trip/writes.ts +91 -0
- package/examples/trip/zones.ts +16 -0
- package/examples/trips/card.ts +149 -0
- package/examples/trips/generated/elements.ts +60 -0
- package/examples/trips/generated/queries.ts +28 -0
- package/examples/trips/generated/rules.ts +62 -0
- package/examples/trips/index.html +47 -0
- package/examples/trips/map.ts +52 -0
- package/examples/trips/migrations/001-trips.ts +8 -0
- package/examples/trips/new-trip.ts +46 -0
- package/examples/trips/page.ts +9 -0
- package/examples/trips/routes.ts +7 -0
- package/examples/trips/stories.jsonl +12 -0
- package/examples/trips/trips.css +183 -0
- package/examples/trips/trips.json +7 -0
- package/examples/weeks/derive.ts +23 -0
- package/examples/weeks/generated/elements.ts +52 -0
- package/examples/weeks/generated/rules.ts +33 -0
- package/examples/weeks/routes.ts +4 -0
- package/examples/weeks/weeks.json +1 -0
- package/examples/welcome.css +299 -0
- package/package.json +51 -4
- package/src/attachment.ts +70 -0
- package/src/cli.ts +52 -0
- package/src/client.ts +98 -0
- package/src/compile.ts +2034 -0
- package/src/css.d.ts +5 -0
- package/src/definitions.ts +268 -0
- package/src/demo.css +29 -0
- package/src/demo.ts +42 -0
- package/src/draft.ts +69 -0
- package/src/engine.ts +288 -0
- package/src/file-value.ts +13 -0
- package/src/files.ts +187 -0
- package/src/follow.ts +56 -0
- package/src/hues.ts +3 -0
- package/src/icon-names.ts +77 -0
- package/src/icon.png +0 -0
- package/src/icons.ts +32 -0
- package/src/keep.ts +33 -0
- package/src/link.ts +31 -0
- package/src/mcp.ts +252 -0
- package/src/members/demo.ts +53 -0
- package/src/members/generated/elements.ts +68 -0
- package/src/members/generated/queries.ts +29 -0
- package/src/members/generated/rules.ts +65 -0
- package/src/members/group.ts +294 -0
- package/src/members/keys.ts +221 -0
- package/src/members/members.json +9 -0
- package/src/members/migrations/001-members.ts +6 -0
- package/src/members/migrations/002-guard-members.ts +11 -0
- package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
- package/src/members/panel.css +208 -0
- package/src/members/panel.ts +398 -0
- package/src/members/routes.ts +4 -0
- package/src/members/stories.jsonl +27 -0
- package/src/members/trust.ts +116 -0
- package/src/migrate.ts +597 -0
- package/src/migrations/001-joined.ts +13 -0
- package/src/migrations/002-group-keys.ts +16 -0
- package/src/migrations/003-change-inverse.ts +10 -0
- package/src/migrations/004-change-followed.ts +6 -0
- package/src/ops.ts +61 -0
- package/src/page.css +79 -0
- package/src/page.ts +413 -0
- package/src/parts.css +471 -0
- package/src/parts.ts +152 -0
- package/src/server.ts +862 -0
- package/src/settings.ts +94 -0
- package/src/starter.ts +89 -0
- package/src/store.ts +815 -0
- package/src/stories.ts +387 -0
- package/src/toast.ts +52 -0
- package/src/together.ts +167 -0
- package/src/tokens.css +85 -0
- package/src/tokens.json +457 -0
- package/src/upkeep.ts +86 -0
- package/src/visitors.ts +43 -0
- package/src/write.ts +567 -0
- package/starter/CLAUDE.md +37 -0
- package/starter/gitignore +3 -0
- package/starter/tests/hello-page.test.ts +14 -0
- package/starter/tests/hello.test.ts +8 -0
- package/starter/tsconfig.json +17 -0
package/src/compile.ts
ADDED
|
@@ -0,0 +1,2034 @@
|
|
|
1
|
+
// The compiler: from each app's stories (examples/<app>/stories.jsonl), the model they need, then
|
|
2
|
+
// the server's rules (generated/rules.ts) and the page's elements (generated/elements.ts). A
|
|
3
|
+
// collection, a field, an op: each exists because a story does it, and nothing else does. A field
|
|
4
|
+
// holding a list of ids, named for another document's collection, links to its items. A
|
|
5
|
+
// collection is an element and its items are elements inside it, named with one prefix:
|
|
6
|
+
// <j-people><j-person>. The same stories always write the same files.
|
|
7
|
+
//
|
|
8
|
+
// The model is also the tables (the skill's reference, §14): a collection a table, with the id the database
|
|
9
|
+
// mints and a column a field; a list of ids a table of pairs. When the stories say more than an
|
|
10
|
+
// app's migrations so far make, the next migration is written beside them (src/migrate.ts), so one
|
|
11
|
+
// history makes the tables in SQLite now and in Postgres later. Never written by hand.
|
|
12
|
+
|
|
13
|
+
import { existsSync } from "node:fs";
|
|
14
|
+
import { basename, relative } from "node:path";
|
|
15
|
+
import {
|
|
16
|
+
grantOf,
|
|
17
|
+
grantsOf,
|
|
18
|
+
whoCode,
|
|
19
|
+
whoRules,
|
|
20
|
+
whoSql,
|
|
21
|
+
type Definitions,
|
|
22
|
+
type Query,
|
|
23
|
+
type Where,
|
|
24
|
+
} 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";
|
|
28
|
+
import { settingsCode, settingsSaid, settingsUnchecked } from "./settings.ts";
|
|
29
|
+
import { partsOf, told as toldOf, unwritten, writtenBefore } from "./together.ts";
|
|
30
|
+
import { guestRole, visitorsRefused } from "./visitors.ts";
|
|
31
|
+
|
|
32
|
+
type Write = { doc: string; ops: Op[]; why?: string };
|
|
33
|
+
/** A story: who writes it (as), the write it does (or cannot), who sees it (seen) and who mustn't (unseen), the
|
|
34
|
+
* words a cannot is refused in (refused), what a does leaves, path by path (then), and the writes before it, each
|
|
35
|
+
* name's in order (premise). */
|
|
36
|
+
export type Story = {
|
|
37
|
+
story: string;
|
|
38
|
+
as?: string;
|
|
39
|
+
does?: Write;
|
|
40
|
+
cannot?: Write;
|
|
41
|
+
seen?: string[];
|
|
42
|
+
unseen?: string[];
|
|
43
|
+
refused?: string;
|
|
44
|
+
then?: Record<string, unknown>;
|
|
45
|
+
premise?: Record<string, Write[]> | Write[];
|
|
46
|
+
};
|
|
47
|
+
type Coll = {
|
|
48
|
+
fields: Record<string, Type>;
|
|
49
|
+
required: string[];
|
|
50
|
+
/** Each add's story, and the fields it gives: what made a field needed, or not. */
|
|
51
|
+
adding: { story: string; fields: string[] }[];
|
|
52
|
+
adds: number;
|
|
53
|
+
replace: string[];
|
|
54
|
+
removeField: string[];
|
|
55
|
+
removeItem: boolean;
|
|
56
|
+
/** The lists an id is added to, one at a time (/events/2/people/-), and taken from (/events/2/people/3). */
|
|
57
|
+
link: string[];
|
|
58
|
+
unlink: string[];
|
|
59
|
+
/** The fields the server fills (definitions' fills), with what: "now", or a value. */
|
|
60
|
+
fills?: Record<string, unknown>;
|
|
61
|
+
/** The field whose time, when it comes, the server clears (definitions' timed). */
|
|
62
|
+
timed?: string;
|
|
63
|
+
/** The document's own fields (hello's greeting, /greeting): a collection named for it, of one item. */
|
|
64
|
+
own?: true;
|
|
65
|
+
/** The fields it takes from what a link points at, once, when it's added (definitions' copies). */
|
|
66
|
+
copies?: { from: string; fields: string[]; to: string; at: string };
|
|
67
|
+
};
|
|
68
|
+
/** A document's model: its name, and its collections. */
|
|
69
|
+
type Model = { doc: string; collections: Record<string, Coll> };
|
|
70
|
+
|
|
71
|
+
const COLUMN = {
|
|
72
|
+
string: "text",
|
|
73
|
+
"date-time": "text",
|
|
74
|
+
zone: "text",
|
|
75
|
+
instant: "text",
|
|
76
|
+
duration: "text",
|
|
77
|
+
place: "text",
|
|
78
|
+
file: "text",
|
|
79
|
+
boolean: "boolean",
|
|
80
|
+
integer: "integer",
|
|
81
|
+
decimal: "real",
|
|
82
|
+
} as const;
|
|
83
|
+
|
|
84
|
+
/** The forms a string is read as: a wall clock with no zone, to the second; the zone a wall clock is in, as the
|
|
85
|
+
* world's time zones name it (Asia/Tokyo, Europe/London, UTC); an instant, in UTC; a duration in days, hours, minutes
|
|
86
|
+
* and seconds (ISO 8601's); a place, as a geo URI's latitude and longitude; a file, as its bytes' SHA-256 names it
|
|
87
|
+
* in the bucket, so it never changes. A field every value of which is one
|
|
88
|
+
* is that, and refused otherwise. */
|
|
89
|
+
export const FORMS = {
|
|
90
|
+
"date-time": /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/,
|
|
91
|
+
zone: /^(UTC|(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)(\/[A-Za-z][A-Za-z0-9_+-]*){1,2})$/,
|
|
92
|
+
instant: /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{3})?Z$/,
|
|
93
|
+
duration: /^P(?=\d|T\d)(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,
|
|
94
|
+
place: /^geo:-?(90(\.0+)?|[1-8]?\d(\.\d+)?),-?(180(\.0+)?|(1[0-7]\d|[1-9]?\d)(\.\d+)?)$/,
|
|
95
|
+
file: /^file:[0-9a-f]{64}\.[a-z0-9]{1,8}$/,
|
|
96
|
+
} as const;
|
|
97
|
+
/** What a type is said as, where a value isn't one. */
|
|
98
|
+
export const SAID: Record<Type, string> = {
|
|
99
|
+
string: "a string",
|
|
100
|
+
"date-time": "a date and time (YYYY-MM-DDTHH:MM:SS)",
|
|
101
|
+
zone: "a time zone (Asia/Tokyo)",
|
|
102
|
+
instant: "an instant (YYYY-MM-DDTHH:MM:SSZ)",
|
|
103
|
+
duration: "a length of time (PT2H30M)",
|
|
104
|
+
place: "a place (geo:lat,lon)",
|
|
105
|
+
file: "a file (file:<its SHA-256>.<ext>)",
|
|
106
|
+
boolean: "a boolean",
|
|
107
|
+
integer: "a whole number",
|
|
108
|
+
decimal: "a number",
|
|
109
|
+
ids: "a list of ids",
|
|
110
|
+
};
|
|
111
|
+
const STRINGS: Type[] = ["string", "date-time", "zone", "instant", "duration", "place", "file"];
|
|
112
|
+
|
|
113
|
+
/** Whether a value is an object of fields (an order's terms), not a list. */
|
|
114
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
115
|
+
/** An add's fields, an object's each named for both (terms.days). */
|
|
116
|
+
const flatKeys = (value: Record<string, unknown>) =>
|
|
117
|
+
Object.entries(value).flatMap(([f, v]) => (isObject(v) ? Object.keys(v).map((k) => `${f}.${k}`) : [f]));
|
|
118
|
+
|
|
119
|
+
/** A value's type: a string's form, a number's fraction, or none it can be. */
|
|
120
|
+
const typeOf = (v: unknown): Type | undefined =>
|
|
121
|
+
typeof v === "string"
|
|
122
|
+
? /^\$[1-9]\d*$/.test(v)
|
|
123
|
+
? // "$n", the id an add before it in the same write was given
|
|
124
|
+
"integer"
|
|
125
|
+
: ((Object.keys(FORMS) as (keyof typeof FORMS)[]).find((k) => FORMS[k].test(v)) ?? "string")
|
|
126
|
+
: typeof v === "number"
|
|
127
|
+
? Number.isInteger(v)
|
|
128
|
+
? "integer"
|
|
129
|
+
: "decimal"
|
|
130
|
+
: typeof v === "boolean"
|
|
131
|
+
? "boolean"
|
|
132
|
+
: Array.isArray(v) && v.every(Number.isInteger)
|
|
133
|
+
? "ids"
|
|
134
|
+
: undefined;
|
|
135
|
+
/** The type two values of a field are together: strings of two forms are strings, and a fraction makes a decimal. */
|
|
136
|
+
const both = (a: Type, b: Type): Type | undefined =>
|
|
137
|
+
a === b
|
|
138
|
+
? a
|
|
139
|
+
: STRINGS.includes(a) && STRINGS.includes(b)
|
|
140
|
+
? "string"
|
|
141
|
+
: [a, b].every((t) => t === "integer" || t === "decimal")
|
|
142
|
+
? "decimal"
|
|
143
|
+
: undefined;
|
|
144
|
+
|
|
145
|
+
/** A model with what its definitions say the server fills and clears: each a field of the server's, which no
|
|
146
|
+
* 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 a document
|
|
148
|
+
* that isn't a kind. */
|
|
149
|
+
export function filled(model: Model, defs: Definitions, from: string) {
|
|
150
|
+
const at = (coll: string, what: string) => {
|
|
151
|
+
const c = model.collections[coll];
|
|
152
|
+
if (!c) throw new Error(`${from}: ${what} names ${coll}, which no story has`);
|
|
153
|
+
return c;
|
|
154
|
+
};
|
|
155
|
+
for (const [coll, fills] of Object.entries(defs.fills ?? {})) {
|
|
156
|
+
const c = at(coll, "fills");
|
|
157
|
+
for (const [f, v] of Object.entries(fills)) {
|
|
158
|
+
// (a field that moves only as the stories move it is filled as it's added, and moved after: an add never gives it)
|
|
159
|
+
const moved = defs.moves?.[coll] === f && !c.adding.some((a) => a.fields.includes(f));
|
|
160
|
+
// (a code is made new by a replace, the server making it: a board's secret link, rotated)
|
|
161
|
+
const renewed = v === "random" && !c.adding.some((a) => a.fields.includes(f));
|
|
162
|
+
if (c.fields[f] && !moved && !renewed)
|
|
163
|
+
throw new Error(`${from}: ${coll}' ${f} is the server's to fill, so no story gives it`);
|
|
164
|
+
// "me": the member who adds it, an id
|
|
165
|
+
const t = v === "now" ? "instant" : v === "me" ? "integer" : typeOf(v);
|
|
166
|
+
if (!t || t === "ids")
|
|
167
|
+
throw new Error(`${from}: ${coll}' ${f} is filled with a string, a boolean, a number, "now" or "me"`);
|
|
168
|
+
c.fields[f] = t;
|
|
169
|
+
(c.fills ??= {})[f] = v;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
// an order: a collection held by a number of its own
|
|
173
|
+
for (const [coll, by] of Object.entries(defs.order ?? {})) {
|
|
174
|
+
const c = at(coll, "order");
|
|
175
|
+
if (c.fields[by] !== "integer" && c.fields[by] !== "decimal")
|
|
176
|
+
throw new Error(`${from}: ${coll}' order is by ${by}, which isn't a number of theirs`);
|
|
177
|
+
}
|
|
178
|
+
// a window: a collection's field the page holds a part by, a parameter each, named as a query's are
|
|
179
|
+
for (const [coll, params] of Object.entries(defs.window ?? {})) {
|
|
180
|
+
const c = at(coll, "window");
|
|
181
|
+
for (const [p, by] of Object.entries(params)) {
|
|
182
|
+
if (!/^[a-z][a-z0-9]*$/.test(p)) throw new Error(`${from}: ${p} cannot be a window's parameter (a-z and 0-9)`);
|
|
183
|
+
const field = typeof by === "string" ? by : by.from;
|
|
184
|
+
if (!c.fields[field] || c.fields[field] === "ids")
|
|
185
|
+
throw new Error(`${from}: ${coll}' window ${p} is by ${field}, which isn't a field of one value`);
|
|
186
|
+
if (typeof by !== "string" && (c.fields[field] !== "date-time" || !/^P\d+D$/.test(by.for)))
|
|
187
|
+
throw new Error(`${from}: ${coll}' window ${p} is a span of days (P7D) from a date and time`);
|
|
188
|
+
if (typeof by !== "string" && by.length !== undefined && c.fields[by.length] !== "duration")
|
|
189
|
+
throw new Error(`${from}: ${coll}' window ${p}'s length is ${by.length}, which isn't a duration of theirs`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
for (const [coll, f] of Object.entries(defs.timed ?? {})) {
|
|
193
|
+
const c = at(coll, "timed");
|
|
194
|
+
if (defs.kind) throw new Error(`${from}: a kind's documents aren't timed`);
|
|
195
|
+
if (c.fields[f] !== "instant")
|
|
196
|
+
throw new Error(`${from}: ${coll}' ${f} is timed, so the stories give it an instant`);
|
|
197
|
+
if (c.required.includes(f))
|
|
198
|
+
throw new Error(`${from}: ${coll}' ${f} is timed, and cleared, so not every add gives it`);
|
|
199
|
+
c.timed = f;
|
|
200
|
+
}
|
|
201
|
+
return model;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** What a document's definitions hold of it as a write leaves it (unique, noOverlap), as code: holds(d, touched),
|
|
205
|
+
* each item the write touched against the rest of its collection, why it doesn't hold or null. None, if they
|
|
206
|
+
* hold nothing. */
|
|
207
|
+
export function heldBy(collections: Record<string, Coll>, defs: Definitions, from: string) {
|
|
208
|
+
const colls = [...new Set([...Object.keys(defs.unique ?? {}), ...Object.keys(defs.noOverlap ?? {})])];
|
|
209
|
+
if (!colls.length) return "";
|
|
210
|
+
const field = (coll: string, f: string, what: string) => {
|
|
211
|
+
const t = collections[coll]?.fields[f];
|
|
212
|
+
if (!t || t === "ids") throw new Error(`${from}: ${what} names ${coll}' ${f}, which isn't a field of one value`);
|
|
213
|
+
return t;
|
|
214
|
+
};
|
|
215
|
+
const v = (f: string) => `i[${JSON.stringify(f)}]`;
|
|
216
|
+
let durations = false;
|
|
217
|
+
let code = "";
|
|
218
|
+
for (const coll of colls) {
|
|
219
|
+
if (!collections[coll]) throw new Error(`${from}: unique and noOverlap name ${coll}, which no story has`);
|
|
220
|
+
const tests: string[] = [];
|
|
221
|
+
for (const u of defs.unique?.[coll] ?? []) {
|
|
222
|
+
const fs = typeof u === "string" ? [u] : u;
|
|
223
|
+
fs.forEach((f) => field(coll, f, "unique"));
|
|
224
|
+
const same = fs
|
|
225
|
+
.map((f) => `a[${JSON.stringify(f)}] !== undefined && ${v(f)} === a[${JSON.stringify(f)}]`)
|
|
226
|
+
.join(" && ");
|
|
227
|
+
// each in a block of its own: a collection may have several
|
|
228
|
+
tests.push(
|
|
229
|
+
` {`,
|
|
230
|
+
` const b = all.find((i) => i.id !== a.id && ${same});`,
|
|
231
|
+
` if (b) return ${JSON.stringify(`${coll} `)} + b.id + ${JSON.stringify(` has that ${fs.join(" and ")} already`)};`,
|
|
232
|
+
` }`,
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
const o = defs.noOverlap?.[coll];
|
|
236
|
+
if (o) {
|
|
237
|
+
const [s, e] = o.range,
|
|
238
|
+
st = field(coll, s, "noOverlap"),
|
|
239
|
+
et = field(coll, e, "noOverlap");
|
|
240
|
+
const time = st === "instant" || st === "date-time";
|
|
241
|
+
if (!time && st !== "integer" && st !== "decimal")
|
|
242
|
+
throw new Error(`${from}: noOverlap's ${coll}' ${s} is a time or a number`);
|
|
243
|
+
if (et !== st && !(time && et === "duration") && !(!time && (et === "integer" || et === "decimal")))
|
|
244
|
+
throw new Error(
|
|
245
|
+
`${from}: noOverlap's ${coll}' ${e} is a time or a number as ${s} is, or a duration on from it`,
|
|
246
|
+
);
|
|
247
|
+
durations ||= et === "duration";
|
|
248
|
+
const at = (f: string, t: Type, none: string) =>
|
|
249
|
+
`(${v(f)} === undefined ? ${none} : ${t === "instant" ? `Date.parse(${v(f)})` : t === "date-time" ? `Date.parse(${v(f)} + "Z")` : v(f)})`;
|
|
250
|
+
const start = at(s, st, "-Infinity"),
|
|
251
|
+
end =
|
|
252
|
+
et === "duration"
|
|
253
|
+
? `(${v(s)} === undefined || ${v(e)} === undefined ? Infinity : ${start} + ms(${v(e)}))`
|
|
254
|
+
: at(e, et, "Infinity");
|
|
255
|
+
const same = (o.same ?? []).map((f) => (field(coll, f, "noOverlap"), `${v(f)} === a[${JSON.stringify(f)}]`));
|
|
256
|
+
const words = `are at one time${o.same?.length ? `, of one ${o.same.join(" and ")}` : ""}: move or remove one first`;
|
|
257
|
+
tests.push(
|
|
258
|
+
` const span = (i: any): [number, number] => [${start}, ${end}];`,
|
|
259
|
+
` const [from, until] = span(a);`,
|
|
260
|
+
` if (until < from) return ${JSON.stringify(`${coll} `)} + a.id + " ends before it starts";`,
|
|
261
|
+
` const c = all.find((i) => i.id !== a.id${same.map((x) => ` && ${x}`).join("")} && span(i)[0] < until && from < span(i)[1]);`,
|
|
262
|
+
` if (c) return ${JSON.stringify(`${coll} `)} + a.id + " and " + c.id + ${JSON.stringify(` ${words}`)};`,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
code += ` for (const id of touched[${JSON.stringify(coll)}] ?? []) {
|
|
266
|
+
const all = (d[${JSON.stringify(coll)}] ?? []) as any[];
|
|
267
|
+
const a = all.find((i) => i.id === id);
|
|
268
|
+
if (!a) continue;
|
|
269
|
+
${tests.join("\n")}
|
|
270
|
+
}
|
|
271
|
+
`;
|
|
272
|
+
}
|
|
273
|
+
return `
|
|
274
|
+
/** Why the document, as a write leaves it, breaks what its definitions hold (unique, noOverlap): each item the
|
|
275
|
+
* write touched, against the rest of its collection. Null if it holds. */
|
|
276
|
+
export function holds(d: Record<string, unknown>, touched: Record<string, number[]>): string | null {
|
|
277
|
+
${
|
|
278
|
+
durations
|
|
279
|
+
? ` const ms = (p: string) => {
|
|
280
|
+
const [, D = 0, H = 0, M = 0, S = 0] = (/^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$/.exec(p) ?? []).map((n) => Number(n ?? 0));
|
|
281
|
+
return (((D * 24 + H) * 60 + M) * 60 + S) * 1000;
|
|
282
|
+
};
|
|
283
|
+
`
|
|
284
|
+
: ""
|
|
285
|
+
}${code} return null;
|
|
286
|
+
}
|
|
287
|
+
`;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** A derived document's model (an app's derive.ts), from an example of it (<doc>.json): each list a collection,
|
|
291
|
+
* each field's type read off every item's value, a field needed if every item has it. It has no ops: nothing
|
|
292
|
+
* writes it, the server derives it. */
|
|
293
|
+
export function modelFrom(doc: string, example: Record<string, unknown>, from: string): Model {
|
|
294
|
+
const model: Model = { doc, collections: {} };
|
|
295
|
+
for (const [name, items] of Object.entries(example)) {
|
|
296
|
+
if (!Array.isArray(items)) continue;
|
|
297
|
+
if (!items.length) throw new Error(`${from}: ${name} has no item to say what it holds`);
|
|
298
|
+
const c: Coll = {
|
|
299
|
+
fields: {},
|
|
300
|
+
required: [],
|
|
301
|
+
adding: [],
|
|
302
|
+
adds: 0,
|
|
303
|
+
replace: [],
|
|
304
|
+
removeField: [],
|
|
305
|
+
removeItem: false,
|
|
306
|
+
link: [],
|
|
307
|
+
unlink: [],
|
|
308
|
+
};
|
|
309
|
+
items.forEach((item: Record<string, unknown>, i) => {
|
|
310
|
+
const { id, ...fields } = item;
|
|
311
|
+
for (const [f, v] of Object.entries(fields)) {
|
|
312
|
+
const t = typeOf(v),
|
|
313
|
+
now = t && (c.fields[f] ? both(c.fields[f]!, t) : t);
|
|
314
|
+
if (!now) throw new Error(`${from}: ${name} ${id}'s ${f} isn't what the other items' ${f} is`);
|
|
315
|
+
c.fields[f] = now;
|
|
316
|
+
}
|
|
317
|
+
c.required = i ? c.required.filter((f) => f in fields) : Object.keys(fields);
|
|
318
|
+
});
|
|
319
|
+
model.collections[name] = c;
|
|
320
|
+
}
|
|
321
|
+
return model;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** An app's entities, each a table of its documents': every field any of them gives it, needed where every add of
|
|
325
|
+
* it gives it. Each document's collection holds them all (its stories say only what it may write), and so does one
|
|
326
|
+
* its where holds without writing it (an order's lines, on the kitchen's page). */
|
|
327
|
+
export function entities(
|
|
328
|
+
units: string[],
|
|
329
|
+
models: Record<string, Model>,
|
|
330
|
+
defs: Record<string, Definitions>,
|
|
331
|
+
defined: Definitions,
|
|
332
|
+
) {
|
|
333
|
+
const of: Record<string, Coll> = {};
|
|
334
|
+
for (const u of units)
|
|
335
|
+
for (const [name, c] of Object.entries(models[u]!.collections)) {
|
|
336
|
+
const e = of[name];
|
|
337
|
+
if (!e) {
|
|
338
|
+
of[name] = structuredClone(c);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
for (const [f, t] of Object.entries(c.fields)) e.fields[f] = e.fields[f] ? (both(e.fields[f]!, t) ?? t) : t;
|
|
342
|
+
if (c.adds) e.required = e.adds ? e.required.filter((f) => c.required.includes(f)) : [...c.required];
|
|
343
|
+
e.adds += c.adds;
|
|
344
|
+
e.adding.push(...c.adding);
|
|
345
|
+
}
|
|
346
|
+
for (const u of units) {
|
|
347
|
+
const m = models[u]!;
|
|
348
|
+
for (const name of Object.keys(defs[u]!.where?.[m.doc] ?? {}).filter((k) => k !== "holds"))
|
|
349
|
+
m.collections[name] ??= {
|
|
350
|
+
...structuredClone(of[name]!),
|
|
351
|
+
adds: 0,
|
|
352
|
+
adding: [],
|
|
353
|
+
replace: [],
|
|
354
|
+
removeField: [],
|
|
355
|
+
removeItem: false,
|
|
356
|
+
link: [],
|
|
357
|
+
unlink: [],
|
|
358
|
+
};
|
|
359
|
+
for (const [name, c] of Object.entries(m.collections))
|
|
360
|
+
if (!c.own && of[name]) Object.assign(c, { fields: { ...of[name]!.fields }, required: [...of[name]!.required] });
|
|
361
|
+
// and its links, of every field it now holds
|
|
362
|
+
const fields = new Set(Object.values(m.collections).flatMap((c) => Object.keys(c.fields)));
|
|
363
|
+
const links = Object.entries(defined.links ?? {}).filter(([f]) => fields.has(f));
|
|
364
|
+
if (links.length) defs[u]!.links = Object.fromEntries(links);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** 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
|
+
export function seeded(model: Model, seed: Record<string, unknown>, from: string) {
|
|
370
|
+
for (const [name, c] of Object.entries(model.collections))
|
|
371
|
+
for (const item of (c.own ? [ownOf(seed)] : (seed[name] ?? [])) as Record<string, unknown>[]) {
|
|
372
|
+
// a field the seed gives and no story does (an order's customer): a field too, its type the seed's; an
|
|
373
|
+
// object's each named for both; not an instance's column (order), nor the id
|
|
374
|
+
const given = Object.fromEntries(
|
|
375
|
+
Object.entries(item).flatMap(([f, v]) =>
|
|
376
|
+
isObject(v) ? Object.entries(v).map(([k, x]) => [`${f}.${k}`, x]) : [[f, v]],
|
|
377
|
+
),
|
|
378
|
+
);
|
|
379
|
+
for (const [f, v] of Object.entries(given))
|
|
380
|
+
if (f !== "id" && f !== model.doc && !(f in c.fields) && typeOf(v)) c.fields[f] = typeOf(v)!;
|
|
381
|
+
for (const [f, t] of Object.entries(c.fields)) {
|
|
382
|
+
const v = given[f];
|
|
383
|
+
if (v === undefined) continue;
|
|
384
|
+
const now = typeOf(v) && both(t, typeOf(v)!);
|
|
385
|
+
if (!now) throw new Error(`${from}: ${name} ${item.id}'s ${f} isn't ${SAID[t]}, as the stories give it`);
|
|
386
|
+
c.fields[f] = now;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return model;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** A document's own fields, as its seed or its query gives them: those of one value (not its version, nor a list),
|
|
393
|
+
* its one item's, id 1. */
|
|
394
|
+
export const ownOf = (doc: Record<string, unknown>) => ({
|
|
395
|
+
id: 1,
|
|
396
|
+
...Object.fromEntries(Object.entries(doc).filter(([k, v]) => k !== "version" && !Array.isArray(v))),
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
/** 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 };
|
|
401
|
+
/** Each link of a model: to the collection it's named for, in the document that holds it, or to the one its
|
|
402
|
+
* definition names (one id, where it says so), its own document's or another's. */
|
|
403
|
+
export function linksOf(
|
|
404
|
+
{ doc, collections }: Model,
|
|
405
|
+
defs: Definitions,
|
|
406
|
+
holders: Record<string, string>,
|
|
407
|
+
from: string,
|
|
408
|
+
): LinkOf {
|
|
409
|
+
return (f) => {
|
|
410
|
+
const l = defs.links?.[f];
|
|
411
|
+
const to = typeof l === "string" ? l : (l?.to ?? f);
|
|
412
|
+
return {
|
|
413
|
+
to,
|
|
414
|
+
one: typeof l === "object" && !!l.one,
|
|
415
|
+
// removed with what it links to (gone: "with"), not the removal refused
|
|
416
|
+
gone: typeof l === "object" && l.gone === "with",
|
|
417
|
+
// asked only of a link: a field that isn't one has no document
|
|
418
|
+
get at() {
|
|
419
|
+
const at = l && collections[to] ? doc : (holders[to] ?? (collections[to] ? doc : undefined));
|
|
420
|
+
if (!at) throw new Error(`${from}: ${f} is a list of ids, but no other document has a collection named ${to}`);
|
|
421
|
+
return at;
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
/** A collection's links that go with what they point at, in its own document (`goes`): removing that item removes
|
|
427
|
+
* this one first, in the same write. None, nothing said. */
|
|
428
|
+
const goes = (c: Coll, link: LinkOf, doc: string) => {
|
|
429
|
+
const fields = Object.entries(c.fields)
|
|
430
|
+
.filter(([f, t]) => {
|
|
431
|
+
const l = link(f);
|
|
432
|
+
return t === "integer" && l.gone && l.at === doc;
|
|
433
|
+
})
|
|
434
|
+
.map(([f]) => f);
|
|
435
|
+
return fields.length ? { goes: fields } : {};
|
|
436
|
+
};
|
|
437
|
+
/** A field's type, said: a list's, the document its ids are in; one id's, the collection. */
|
|
438
|
+
const typeSaid = (f: string, t: Type, link: LinkOf) =>
|
|
439
|
+
t === "ids"
|
|
440
|
+
? `${f} (ids in ${link(f).at})`
|
|
441
|
+
: t === "integer" && link(f).one
|
|
442
|
+
? `${f} (an id in ${link(f).to})`
|
|
443
|
+
: `${f} (${t})`;
|
|
444
|
+
/** What an add needs, said: each field it needs, and those it may have. */
|
|
445
|
+
export const needsSaid = (name: string, c: Coll, link: LinkOf) => {
|
|
446
|
+
const item = itemOf(name)!;
|
|
447
|
+
const optional = Object.entries(c.fields).filter(([f]) => !c.required.includes(f));
|
|
448
|
+
return `${an(item)} needs ${c.required.map((f) => typeSaid(f, c.fields[f]!, link)).join(", ")}${optional.length ? `; may have ${optional.map(([f, t]) => typeSaid(f, t, link)).join(", ")}` : ""}`;
|
|
449
|
+
};
|
|
450
|
+
/** What a link refuses an id with: one that isn't in the collection it's to. */
|
|
451
|
+
const linkSaid = (f: string, link: LinkOf) => `${f} links only to ${link(f).to} the ${link(f).at} document holds`;
|
|
452
|
+
/** A link to the group's members lets go of one who leaves (the group's rules say who may remove whom): a list
|
|
453
|
+
* drops them, one id is emptied. Any other link holds what it points at: it can't be removed from under it. */
|
|
454
|
+
const GROUP = "members";
|
|
455
|
+
/** A link to one item, as an add sends it: its id, or an add's before it in the same write, "$1". */
|
|
456
|
+
const REF = "number | `$${number}`";
|
|
457
|
+
/** What removing an item another links to is refused with, once and of many: what links to it, and where. */
|
|
458
|
+
const heldSaid = (coll: string, doc: string): [string, string] => [
|
|
459
|
+
`${itemOf(coll)} in ${doc} links to it`,
|
|
460
|
+
`${itemOf(coll)}s in ${doc} link to it`,
|
|
461
|
+
];
|
|
462
|
+
|
|
463
|
+
/** The tables a model is: each collection one, a field a column (null where no story needs it, or an
|
|
464
|
+
* item of the seed has none: the BDFL has no inviter); and a list of ids a table of its pairs,
|
|
465
|
+
* `<collection>_<field>`, one pair once. Each guarded, as the stories say: strict, a value kept as it's given
|
|
466
|
+
* and held to its type (a CHECK, named for the words it's refused in), an add to what it needs, a link to an item
|
|
467
|
+
* that's there, and a pair to once. */
|
|
468
|
+
export function tablesOf(
|
|
469
|
+
model: Model,
|
|
470
|
+
seed: Record<string, unknown> = {},
|
|
471
|
+
kind?: { column: string; root: string },
|
|
472
|
+
link: LinkOf = (f) => ({ to: f, at: model.doc, one: false }),
|
|
473
|
+
): Record<string, Table> {
|
|
474
|
+
const tables: Record<string, Table> = {};
|
|
475
|
+
for (const [name, c] of Object.entries(model.collections)) {
|
|
476
|
+
const columns: Record<string, Column> = {};
|
|
477
|
+
for (const [f, t] of Object.entries(c.fields)) {
|
|
478
|
+
if (t === "ids") {
|
|
479
|
+
tables[`${name}_${f}`] = {
|
|
480
|
+
columns: {
|
|
481
|
+
[name]: { type: "integer", to: { table: name, said: `${name} is one of ${name}`, onDelete: "cascade" } },
|
|
482
|
+
[f]: {
|
|
483
|
+
type: "integer",
|
|
484
|
+
to:
|
|
485
|
+
link(f).to === GROUP
|
|
486
|
+
? { table: GROUP, said: linkSaid(f, link), onDelete: "cascade" as const }
|
|
487
|
+
: { table: link(f).to, said: linkSaid(f, link), held: heldSaid(name, model.doc) },
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
unique: [[name, f]],
|
|
491
|
+
strict: true,
|
|
492
|
+
once: `${f} links to {${f}} already`,
|
|
493
|
+
};
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
const always = c.required.includes(f) && ((seed[name] ?? []) as Record<string, unknown>[]).every((i) => f in i);
|
|
497
|
+
const one = t === "integer" && link(f).one;
|
|
498
|
+
const member = one && link(f).to === GROUP;
|
|
499
|
+
columns[f] = {
|
|
500
|
+
type: COLUMN[t],
|
|
501
|
+
...(always && !member ? {} : { nullable: true as const }),
|
|
502
|
+
is: {
|
|
503
|
+
type: t in FORMS ? "form" : (t as "string" | "integer" | "decimal" | "boolean"),
|
|
504
|
+
...(t in FORMS ? { form: FORMS[t as keyof typeof FORMS].source } : {}),
|
|
505
|
+
said: `${f} is ${SAID[t]}`,
|
|
506
|
+
},
|
|
507
|
+
...(member
|
|
508
|
+
? { to: { table: GROUP, said: linkSaid(f, link), onDelete: "set null" as const } }
|
|
509
|
+
: one
|
|
510
|
+
? { to: { table: link(f).to, said: linkSaid(f, link), held: heldSaid(name, model.doc) } }
|
|
511
|
+
: {}),
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
// a kind's items are each kept with their instance: a column named for the kind, its root item's id
|
|
515
|
+
if (kind)
|
|
516
|
+
columns[kind.column] = {
|
|
517
|
+
type: "integer",
|
|
518
|
+
to: { table: kind.root, said: `${kind.column} is one of ${kind.root}`, held: heldSaid(name, model.doc) },
|
|
519
|
+
};
|
|
520
|
+
const needs = c.required.filter((f) => c.fields[f] !== "ids");
|
|
521
|
+
tables[name] = {
|
|
522
|
+
columns,
|
|
523
|
+
strict: true,
|
|
524
|
+
...(c.adds && needs.length ? { needs: { columns: needs, said: needsSaid(name, c, link) } } : {}),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
return Object.fromEntries(Object.entries(tables).sort(([a], [b]) => a.localeCompare(b)));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** What the compiler writes that SQLite and Postgres say differently: JSON built (an object; an item, its nulls left
|
|
531
|
+
* out; an object of an item's, holding nothing: none), rows gathered into a list (none: an empty one) and ids (none:
|
|
532
|
+
* nothing), a boolean as JSON, a date's days on (as SQLite's strftime writes it), and a value not another. */
|
|
533
|
+
type Sql = {
|
|
534
|
+
dialect: Dialect;
|
|
535
|
+
object(pairs: string): string;
|
|
536
|
+
item(pairs: string): string;
|
|
537
|
+
sub(pairs: string): string;
|
|
538
|
+
rows(x: string, order: string, from: string): string;
|
|
539
|
+
ids(x: string, order: string, from: string): string;
|
|
540
|
+
bool(v: string): string;
|
|
541
|
+
days(p: string, n: number): string;
|
|
542
|
+
/** Where a time ends, a length on (a duration), as a wall clock. */
|
|
543
|
+
ends(start: string, length: string): string;
|
|
544
|
+
not: string;
|
|
545
|
+
};
|
|
546
|
+
const SQLITE: Sql = {
|
|
547
|
+
dialect: "sqlite",
|
|
548
|
+
object: (p) => `json_object(${p})`,
|
|
549
|
+
item: (p) => `json_patch('{}', json_object(${p}))`,
|
|
550
|
+
sub: (p) => `json(NULLIF(json_patch('{}', json_object(${p})), '{}'))`,
|
|
551
|
+
rows: (x, order, from) => `json((SELECT json_group_array(${x} ORDER BY ${order})${from}))`,
|
|
552
|
+
ids: (x, order, from) => `json(NULLIF((SELECT json_group_array(${x} ORDER BY ${order})${from}), '[]'))`,
|
|
553
|
+
bool: (v) => `json(CASE ${v} WHEN 1 THEN 'true' WHEN 0 THEN 'false' END)`,
|
|
554
|
+
days: (p, n) => `strftime('%Y-%m-%dT%H:%M:%S', ${p}, '+${n} days')`,
|
|
555
|
+
ends: (s, l) => `ends(${s}, ${l})`,
|
|
556
|
+
not: "IS NOT",
|
|
557
|
+
};
|
|
558
|
+
const POSTGRES: Sql = {
|
|
559
|
+
dialect: "postgres",
|
|
560
|
+
object: (p) => `json_build_object(${p})`,
|
|
561
|
+
item: (p) => `json_strip_nulls(json_build_object(${p}))`,
|
|
562
|
+
sub: (p) => `NULLIF(jsonb_strip_nulls(jsonb_build_object(${p})), '{}')`,
|
|
563
|
+
rows: (x, order, from) => `(SELECT COALESCE(json_agg(${x} ORDER BY ${order}), '[]')${from})`,
|
|
564
|
+
ids: (x, order, from) => `(SELECT json_agg(${x} ORDER BY ${order})${from})`,
|
|
565
|
+
bool: (v) => `(CASE ${v} WHEN 1 THEN true WHEN 0 THEN false END)`,
|
|
566
|
+
days: (p, n) => `to_char(CAST(${p} AS timestamp) + interval '${n} days', 'YYYY-MM-DD"T"HH24:MI:SS')`,
|
|
567
|
+
ends: (s, l) => `to_char(CAST(${s} AS timestamp) + CAST(${l} AS interval), 'YYYY-MM-DD"T"HH24:MI:SS')`,
|
|
568
|
+
not: "IS DISTINCT FROM",
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
/** generated/queries.ts: the document as one statement over its tables, in SQLite's JSON functions and Postgres's. Its version,
|
|
572
|
+
* then each collection's items by id: a field with nothing in it left out, as the dialect (`Sql`) writes it; a boolean
|
|
573
|
+
* true or false, and a list its ids, gathered from its pairs (none: left out). The page stays flat: a link's ids,
|
|
574
|
+
* never what they point at. Its parameters, by name: $doc, the document; and of a kind's instance, $key, which. */
|
|
575
|
+
export function queriesOf(
|
|
576
|
+
{ doc, collections }: Model,
|
|
577
|
+
from: string,
|
|
578
|
+
kind?: string,
|
|
579
|
+
window: NonNullable<Definitions["window"]> = {},
|
|
580
|
+
where: Record<string, Where | Where[] | string> = {},
|
|
581
|
+
link?: LinkOf,
|
|
582
|
+
/** what each person sees of each collection (its definitions' owns), as SQL of a row: $member's */
|
|
583
|
+
owns: Record<string, string> = {},
|
|
584
|
+
/** its rules over values, as triggers (takesSql) */
|
|
585
|
+
takes: (d: Sql) => string[] = () => [],
|
|
586
|
+
/** each collection held in a field's order (its definitions' order), then by id */
|
|
587
|
+
order: Record<string, string> = {},
|
|
588
|
+
) {
|
|
589
|
+
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
590
|
+
const value = (v: unknown) =>
|
|
591
|
+
typeof v === "string" ? `'${v.replaceAll("'", "''")}'` : typeof v === "boolean" ? String(+v) : String(v);
|
|
592
|
+
/** The rows of a collection the document holds, as SQL of a row (`at`): its definitions' where, each field the value
|
|
593
|
+
* or one of them, the newest so many by a field; or those linking to the rows it holds of another collection. */
|
|
594
|
+
const held = (coll: string, at: string, d: Sql): string | null => {
|
|
595
|
+
const w = where[coll];
|
|
596
|
+
if (w === undefined) return null;
|
|
597
|
+
if (typeof w === "string") {
|
|
598
|
+
const by = Object.keys(collections[coll]!.fields).find((f) => link?.(f).one && link(f).to === w);
|
|
599
|
+
if (!by) throw new Error(`${from}: where says ${coll} are ${w}'s, but no link of theirs is to one of ${w}`);
|
|
600
|
+
// those it holds of that one: by its where, and its window
|
|
601
|
+
const of = [...windowed(w, "p", d), ...(held(w, "p", d) ? [`(${held(w, "p", d)})`] : [])];
|
|
602
|
+
return `${at}.${q(by)} IN (SELECT p.id FROM ${q(w)} p${of.length ? ` WHERE ${of.join(" AND ")}` : ""})`;
|
|
603
|
+
}
|
|
604
|
+
const is = (a: string, x: Where) =>
|
|
605
|
+
Object.entries(x)
|
|
606
|
+
.filter(([f]) => f !== "last" && f !== "by")
|
|
607
|
+
.map(([f, v]) =>
|
|
608
|
+
Array.isArray(v) ? `${a}.${q(f)} IN (${v.map(value).join(", ")})` : `${a}.${q(f)} = ${value(v)}`,
|
|
609
|
+
)
|
|
610
|
+
.join(" AND ") || "TRUE";
|
|
611
|
+
return (Array.isArray(w) ? w : [w])
|
|
612
|
+
.map((x) =>
|
|
613
|
+
x.last
|
|
614
|
+
? `${at}.id IN (SELECT x.id FROM ${q(coll)} x WHERE ${is("x", x)} ORDER BY x.${q(x.by ?? "id")} DESC, x.id DESC LIMIT ${x.last})`
|
|
615
|
+
: `(${is(at, x)})`,
|
|
616
|
+
)
|
|
617
|
+
.join(" OR ");
|
|
618
|
+
};
|
|
619
|
+
/** A window's rows of a collection, as SQL of a row (`at`): by each of its parameters given (none: all of them). */
|
|
620
|
+
function windowed(coll: string, at: string, d: Sql) {
|
|
621
|
+
return Object.entries(window[coll] ?? {}).map(([p, by]) =>
|
|
622
|
+
typeof by === "string"
|
|
623
|
+
? `($${p} IS NULL OR ${at}.${q(by)} = $${p})`
|
|
624
|
+
: by.length
|
|
625
|
+
? // what overlaps its days: starting before they end, ending after they begin
|
|
626
|
+
`($${p} IS NULL OR (${at}.${q(by.from)} < ${d.days(`$${p}`, days(by.for))} AND ${d.ends(`${at}.${q(by.from)}`, `${at}.${q(by.length)}`)} > ${d.days(`$${p}`, 0)}))`
|
|
627
|
+
: `($${p} IS NULL OR (${at}.${q(by.from)} >= $${p} AND ${at}.${q(by.from)} < ${d.days(`$${p}`, days(by.for))}))`,
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
/** Its items, its query and its triggers, as one dialect says them. */
|
|
631
|
+
const sqlOf = (d: Sql) => {
|
|
632
|
+
const items = Object.fromEntries(Object.entries(collections).map(([coll, c]) => [coll, itemSql(coll, c, d)]));
|
|
633
|
+
const of = (coll: string, c: Coll) => {
|
|
634
|
+
// the document's own fields: each at its top, from its one row
|
|
635
|
+
if (c.own)
|
|
636
|
+
return Object.entries(c.fields)
|
|
637
|
+
.map(([f, t]) => {
|
|
638
|
+
const one = `(SELECT t.${q(f)} FROM ${q(coll)} t WHERE t.id = 1)`;
|
|
639
|
+
return ` '${f}', ${t === "boolean" ? d.bool(one) : one}`;
|
|
640
|
+
})
|
|
641
|
+
.join(",\n");
|
|
642
|
+
// an instance's own: its root row, by its id, where the kind's root is its own (order:7's order); the rows
|
|
643
|
+
// naming it, by its column
|
|
644
|
+
const all = [
|
|
645
|
+
...(kind ? [`t.${q(kind)} = $key`] : []),
|
|
646
|
+
...windowed(coll, "t", d),
|
|
647
|
+
...(held(coll, "t", d) ? [`(${held(coll, "t", d)})`] : []),
|
|
648
|
+
// what the member sees (none given: all of it, the server's own read)
|
|
649
|
+
...(owns[coll] ? [`($member IS NULL OR ${owns[coll]})`] : []),
|
|
650
|
+
];
|
|
651
|
+
const where = all.length ? ` WHERE ${all.join(" AND ")}` : "";
|
|
652
|
+
const by = order[coll] ? `COALESCE(t.${q(order[coll]!)}, t.id), t.id` : "t.id";
|
|
653
|
+
return ` '${coll}', ${d.rows(items[coll]!, by, `\n FROM ${q(coll)} t${where}`)}`;
|
|
654
|
+
};
|
|
655
|
+
const query = `SELECT ${d.object(
|
|
656
|
+
`'version', COALESCE((SELECT version FROM documents WHERE name = $doc), 0),\n${Object.entries(collections)
|
|
657
|
+
.map(([coll, c]) => of(coll, c))
|
|
658
|
+
.join(",\n")}`,
|
|
659
|
+
)} AS doc`;
|
|
660
|
+
return { items, query, triggers: takes(d) };
|
|
661
|
+
};
|
|
662
|
+
const params = [...new Set(Object.values(window).flatMap((w) => Object.keys(w)))];
|
|
663
|
+
const [lite, pg] = [sqlOf(SQLITE), sqlOf(POSTGRES)];
|
|
664
|
+
return `// Written by src/compile.ts from ${from}: change the stories, not this.
|
|
665
|
+
|
|
666
|
+
/** Each collection's item, as one row of its table (\`t\`) is it: what the query gathers, and what the store keeps of a
|
|
667
|
+
* row a write changes, before and after, to tell each document holding it. */
|
|
668
|
+
export const items: Record<string, string> = ${JSON.stringify(lite.items, null, 2)};
|
|
669
|
+
|
|
670
|
+
/** ${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}\`;
|
|
672
|
+
|
|
673
|
+
/** Its rules over values (definitions' takes, gives and totals), as triggers the store makes in its database: run in
|
|
674
|
+
* each write's transaction, and told as any change is. */
|
|
675
|
+
export const triggers: string[] = ${JSON.stringify(lite.triggers, null, 2)};
|
|
676
|
+
|
|
677
|
+
/** Its items, its query and its triggers, as Postgres says them. */
|
|
678
|
+
export const postgres = ${JSON.stringify(pg, null, 2)};
|
|
679
|
+
`;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** An item as one row of its table (\`t\`) is it, as the dialect (`Sql`) writes it: its id, each field (a field with
|
|
683
|
+
* nothing in it left out; a boolean true or false), an object's fields in their object (one holding
|
|
684
|
+
* nothing, left out), and a list its ids, gathered from its pairs (none: left out). */
|
|
685
|
+
function itemSql(coll: string, c: Coll, d: Sql) {
|
|
686
|
+
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
687
|
+
const value = (f: string, t: Type) =>
|
|
688
|
+
t === "ids"
|
|
689
|
+
? d.ids(`p.${q(f)}`, "p.id", ` FROM ${q(`${coll}_${f}`)} p WHERE p.${q(coll)} = t.id`)
|
|
690
|
+
: t === "boolean"
|
|
691
|
+
? d.bool(`t.${q(f)}`)
|
|
692
|
+
: `t.${q(f)}`;
|
|
693
|
+
const objects = new Map<string, string[]>();
|
|
694
|
+
const fields: string[] = [];
|
|
695
|
+
for (const [f, t] of Object.entries(c.fields)) {
|
|
696
|
+
const [o, sub] = f.split(".") as [string, string?];
|
|
697
|
+
if (sub === undefined) fields.push(`'${f}', ${value(f, t)}`);
|
|
698
|
+
else {
|
|
699
|
+
if (!objects.has(o)) (objects.set(o, []), fields.push(o));
|
|
700
|
+
objects.get(o)!.push(`'${sub}', ${value(f, t)}`);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
for (const [o, subs] of objects) fields[fields.indexOf(o)] = `'${o}', ${d.sub(subs.join(", "))}`;
|
|
704
|
+
return d.item(`'id', t.id${fields.map((f) => `,\n ${f}`).join("")}`);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/** A window's test of an item, as code: the same definition its query's WHERE is written from (each parameter given,
|
|
708
|
+
* 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
|
+
function windowCode(window: NonNullable<Definitions["window"]>) {
|
|
710
|
+
const tests = Object.entries(window).map(([coll, params]) => {
|
|
711
|
+
const each = Object.entries(params).map(([p, by]) =>
|
|
712
|
+
typeof by === "string"
|
|
713
|
+
? `(p.${p} == null || item.${by} === p.${p})`
|
|
714
|
+
: by.length
|
|
715
|
+
? `(p.${p} == null || (typeof item.${by.from} === "string" && item.${by.from} < days(p.${p}, ${days(by.for)}) && ends(item.${by.from}, item.${by.length}) > days(p.${p}, 0)))`
|
|
716
|
+
: `(p.${p} == null || (typeof item.${by.from} === "string" && item.${by.from} >= p.${p} && item.${by.from} < days(p.${p}, ${days(by.for)})))`,
|
|
717
|
+
);
|
|
718
|
+
return `(coll !== ${JSON.stringify(coll)} || (${each.join(" && ")}))`;
|
|
719
|
+
});
|
|
720
|
+
const ranged = Object.values(window).some((ps) => Object.values(ps).some((by) => typeof by !== "string"));
|
|
721
|
+
const overlapping = Object.values(window).some((ps) =>
|
|
722
|
+
Object.values(ps).some((by) => typeof by !== "string" && by.length),
|
|
723
|
+
);
|
|
724
|
+
return `
|
|
725
|
+
/** Whether a window (its parameters, each given or null) holds an item of a collection: what its query's WHERE asks. */
|
|
726
|
+
export function inWindow(coll: string, item: any, p: Record<string, string | null>): boolean {
|
|
727
|
+
${ranged ? ` // a date's days on, as SQLite's strftime writes it: midnight, to the second\n const days = (d: string, n: number) => new Date(Date.parse(d + "T00:00:00Z") + n * 864e5).toISOString().slice(0, 19);\n` : ""}${overlapping ? ` // where a time ends, a length (a duration) on, as SQLite's ends() writes it\n const ends = (s: string, l: string) => { const [d = 0, h = 0, m = 0, x = 0] = /^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$/.exec(String(l))?.slice(1).map((n) => Number(n ?? 0)) ?? []; return new Date(Date.parse(s + "Z") + (((d * 24 + h) * 60 + m) * 60 + x) * 1000).toISOString().slice(0, 19); };\n` : ""} return ${tests.join(" && ")};
|
|
728
|
+
}
|
|
729
|
+
`;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** The rules over values (definitions' takes and gives), as SQL triggers: an item's field taken from (or given to) a
|
|
733
|
+
* field of what one link of it points at, while a condition holds (a field of what another link points at, or its own:
|
|
734
|
+
* true, or not some value), given back or taken again as either changes; and the field it's from refused below none,
|
|
735
|
+
* in the rule's words. Made by the store in its database, run in each write's transaction. */
|
|
736
|
+
export function takesSql(
|
|
737
|
+
defs: Definitions,
|
|
738
|
+
collections: Record<string, Coll>,
|
|
739
|
+
link: LinkOf,
|
|
740
|
+
kind: string | undefined,
|
|
741
|
+
from: string,
|
|
742
|
+
d: Sql = SQLITE,
|
|
743
|
+
): string[] {
|
|
744
|
+
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
745
|
+
const out: string[] = [];
|
|
746
|
+
const trigger = (t: Trigger) => triggerSql(d.dialect, { ...t, temp: true });
|
|
747
|
+
for (const [rule, sign, back] of [
|
|
748
|
+
["takes", "-", "+"],
|
|
749
|
+
["gives", "+", "-"],
|
|
750
|
+
] as const)
|
|
751
|
+
for (const [coll, t] of Object.entries(defs[rule] ?? {})) {
|
|
752
|
+
const c = collections[coll];
|
|
753
|
+
const [field, ...more] = Object.keys(t).filter((k) => k !== "while" && k !== "refused");
|
|
754
|
+
if (!c || !field || more.length || c.fields[field] !== "integer")
|
|
755
|
+
throw new Error(`${from}: ${rule} names one whole-number field of ${coll}`);
|
|
756
|
+
const [by, target] = t[field]!.split(".") as [string, string?];
|
|
757
|
+
// while: <link>.<field>, or the row's own <field>; true, or (!=) not a value
|
|
758
|
+
const [, on, flag, not] = /^(?:([a-z][a-z0-9-]*)\.)?([a-z][a-z0-9-]*)(?:!=(.+))?$/.exec(t.while) ?? [];
|
|
759
|
+
if (!target || !flag) throw new Error(`${from}: ${rule} is of <link>.<field>, while <link>.<field>`);
|
|
760
|
+
const into = link(by).to;
|
|
761
|
+
// the other link: one id, or the kind's column (an item's order)
|
|
762
|
+
const of = on === undefined ? null : on === kind ? defs.kind!.root : link(on).to;
|
|
763
|
+
const is = (v: string) => (not === undefined ? `${v} = 1` : `${v} ${d.not} '${not.replaceAll("'", "''")}'`);
|
|
764
|
+
const holds = (row: string) =>
|
|
765
|
+
is(of ? `(SELECT o.${q(flag)} FROM ${q(of)} o WHERE o.id = ${row}.${q(on!)})` : `${row}.${q(flag)}`);
|
|
766
|
+
const change = (by_: string, row: string) =>
|
|
767
|
+
`UPDATE ${q(into)} SET ${q(target)} = ${q(target)} ${by_} ${row}.${q(field)} WHERE id = ${row}.${q(by)}`;
|
|
768
|
+
const name = (w: string) => `joined_${rule}_${coll}_${w}`;
|
|
769
|
+
// its words: {<field>}, what was asked; any other {x}, that field of what it's from, as it was
|
|
770
|
+
const words = t.refused
|
|
771
|
+
.split(/(\{[a-z][a-z0-9-]*\})/)
|
|
772
|
+
.filter(Boolean)
|
|
773
|
+
.map((w) =>
|
|
774
|
+
/^\{.*\}$/.test(w)
|
|
775
|
+
? w.slice(1, -1) === field
|
|
776
|
+
? `(OLD.${q(target)} - NEW.${q(target)})`
|
|
777
|
+
: `OLD.${q(w.slice(1, -1))}`
|
|
778
|
+
: `'${w.replaceAll("'", "''")}'`,
|
|
779
|
+
)
|
|
780
|
+
.join(" || ");
|
|
781
|
+
if (of)
|
|
782
|
+
out.push(
|
|
783
|
+
trigger({
|
|
784
|
+
name: name("while"),
|
|
785
|
+
at: "AFTER",
|
|
786
|
+
event: `UPDATE OF ${q(flag)}`,
|
|
787
|
+
table: of,
|
|
788
|
+
when: `(${is(`NEW.${q(flag)}`)}) ${d.not} (${is(`OLD.${q(flag)}`)})`,
|
|
789
|
+
body: `UPDATE ${q(into)} SET ${q(target)} = ${q(target)} ${sign} (CASE WHEN ${is(`NEW.${q(flag)}`)} THEN 1 ELSE -1 END) * (SELECT COALESCE(SUM(i.${q(field)}), 0) FROM ${q(coll)} i WHERE i.${q(on!)} = NEW.id AND i.${q(by)} = ${q(into)}.id) WHERE id IN (SELECT ${q(by)} FROM ${q(coll)} WHERE ${q(on!)} = NEW.id);`,
|
|
790
|
+
}),
|
|
791
|
+
);
|
|
792
|
+
out.push(
|
|
793
|
+
trigger({
|
|
794
|
+
name: name("add"),
|
|
795
|
+
at: "AFTER",
|
|
796
|
+
event: "INSERT",
|
|
797
|
+
table: coll,
|
|
798
|
+
when: holds("NEW"),
|
|
799
|
+
body: `${change(sign, "NEW")};`,
|
|
800
|
+
}),
|
|
801
|
+
trigger({
|
|
802
|
+
name: name("remove"),
|
|
803
|
+
at: "AFTER",
|
|
804
|
+
event: "DELETE",
|
|
805
|
+
table: coll,
|
|
806
|
+
when: holds("OLD"),
|
|
807
|
+
body: `${change(back, "OLD")};`,
|
|
808
|
+
}),
|
|
809
|
+
trigger({
|
|
810
|
+
name: name("replace"),
|
|
811
|
+
at: "AFTER",
|
|
812
|
+
event: `UPDATE OF ${[field, by, ...(of ? [] : [flag])].map(q).join(", ")}`,
|
|
813
|
+
table: coll,
|
|
814
|
+
body: `${change(back, "OLD")} AND ${holds("OLD")}; ${change(sign, "NEW")} AND ${holds("NEW")};`,
|
|
815
|
+
}),
|
|
816
|
+
trigger({
|
|
817
|
+
name: name("none"),
|
|
818
|
+
at: "BEFORE",
|
|
819
|
+
event: `UPDATE OF ${q(target)}`,
|
|
820
|
+
table: into,
|
|
821
|
+
body: refuseSql(d.dialect, `NEW.${q(target)} < 0`, words),
|
|
822
|
+
}),
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
// a field kept as the sum of the rows linking to its item (definitions' totals): each change to them, summed again
|
|
826
|
+
for (const [coll, fields] of Object.entries(defs.totals ?? {}))
|
|
827
|
+
for (const [field, { of, by, sum, times }] of Object.entries(fields)) {
|
|
828
|
+
const again = (row: string) =>
|
|
829
|
+
`UPDATE ${q(coll)} SET ${q(field)} = (SELECT COALESCE(SUM(i.${q(sum)}${times ? ` * i.${q(times)}` : ""}), 0) FROM ${q(of)} i WHERE i.${q(by)} = ${row}.${q(by)}) WHERE id = ${row}.${q(by)};`;
|
|
830
|
+
const name = (w: string) => `joined_totals_${coll}_${field}_${w}`;
|
|
831
|
+
out.push(
|
|
832
|
+
trigger({ name: name("add"), at: "AFTER", event: "INSERT", table: of, body: again("NEW") }),
|
|
833
|
+
trigger({ name: name("remove"), at: "AFTER", event: "DELETE", table: of, body: again("OLD") }),
|
|
834
|
+
trigger({
|
|
835
|
+
name: name("replace"),
|
|
836
|
+
at: "AFTER",
|
|
837
|
+
event: "UPDATE",
|
|
838
|
+
table: of,
|
|
839
|
+
body: `${again("OLD")} ${again("NEW")}`,
|
|
840
|
+
}),
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
return out;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** A refusal's words as a pattern: each {x} in them, anything. */
|
|
847
|
+
const wordsOf = (refused: string) =>
|
|
848
|
+
new RegExp(
|
|
849
|
+
`^${refused
|
|
850
|
+
.split(/\{[a-z][a-z0-9-]*\}/)
|
|
851
|
+
.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, (c) => `\\${c}`))
|
|
852
|
+
.join(".+")}$`,
|
|
853
|
+
);
|
|
854
|
+
|
|
855
|
+
/** Of an app's definitions, a document's: those of its collections and their fields; and the kind, its roles and
|
|
856
|
+
* owns, to the document told on its instances (order:7), or to every one where there's no kind. */
|
|
857
|
+
export function definedFor(d: Definitions, m: Model, stories: Story[]): Definitions {
|
|
858
|
+
const has = (o?: Record<string, unknown>) =>
|
|
859
|
+
o && Object.fromEntries(Object.entries(o).filter(([c]) => c in m.collections));
|
|
860
|
+
const fields = new Set(Object.values(m.collections).flatMap((c) => Object.keys(c.fields)));
|
|
861
|
+
const out: Record<string, unknown> = {};
|
|
862
|
+
const links = Object.entries(d.links ?? {}).filter(([f]) => fields.has(f));
|
|
863
|
+
if (links.length) out.links = Object.fromEntries(links);
|
|
864
|
+
for (const k of [
|
|
865
|
+
"copies",
|
|
866
|
+
"unique",
|
|
867
|
+
"noOverlap",
|
|
868
|
+
"window",
|
|
869
|
+
"order",
|
|
870
|
+
"fills",
|
|
871
|
+
"timed",
|
|
872
|
+
"takes",
|
|
873
|
+
"gives",
|
|
874
|
+
"moves",
|
|
875
|
+
"totals",
|
|
876
|
+
"guests",
|
|
877
|
+
"visitors",
|
|
878
|
+
] as const) {
|
|
879
|
+
const mine = has(d[k] as Record<string, unknown> | undefined);
|
|
880
|
+
if (mine && Object.keys(mine).length) out[k] = mine;
|
|
881
|
+
}
|
|
882
|
+
if (d.where?.[m.doc]) out.where = { [m.doc]: d.where[m.doc]! };
|
|
883
|
+
const instance = stories.some((s) => (s.does ?? s.cannot)!.doc.includes(":"));
|
|
884
|
+
if (instance || !d.kind) for (const k of ["kind", "roles", "frozen", "waits"] as const) if (d[k]) out[k] = d[k];
|
|
885
|
+
// owns: one who-path, the kind's or every document's; or one a collection, its documents'
|
|
886
|
+
if ((instance || !d.kind) && typeof d.owns === "string") out.owns = d.owns;
|
|
887
|
+
const owned = typeof d.owns === "object" ? has(d.owns) : undefined;
|
|
888
|
+
if (owned && Object.keys(owned).length) out.owns = owned as Record<string, string>;
|
|
889
|
+
return out as Definitions;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** generated/queries.ts of a read-only document its definition says (each side's books), by member: each
|
|
893
|
+
* collection the rows of a table that name the member, with some fields, its side said, and its total. */
|
|
894
|
+
export function queryOf({ doc }: Model, from: string, spec: Query) {
|
|
895
|
+
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
|
|
896
|
+
const colls = Object.entries(spec).map(([coll, s]) => {
|
|
897
|
+
const sides = Object.entries(s.sides);
|
|
898
|
+
const side = `CASE ${sides.map(([f, w]) => `WHEN o.${q(f)} = $member THEN '${w}'`).join(" ")} END`;
|
|
899
|
+
// the sum of the rows linking to it, or of its own fields
|
|
900
|
+
const total = `o.${q(s.total.sum)}${s.total.times ? ` * o.${q(s.total.times)}` : ""}`;
|
|
901
|
+
const where = `${s.when ? `o.${q(s.when)} = 1 AND ` : ""}(${sides.map(([f]) => `o.${q(f)} = $member`).join(" OR ")})`;
|
|
902
|
+
return (d: Sql) =>
|
|
903
|
+
` '${coll}', ${d.rows(d.object(`'id', o.id, ${s.fields.map((f) => `'${f}', o.${q(f)}`).join(", ")}, 'side', ${side}, 'total', ${total}`), "o.id", `\n FROM ${q(s.from)} o WHERE ${where}`)}`;
|
|
904
|
+
});
|
|
905
|
+
const query = (d: Sql) =>
|
|
906
|
+
`SELECT ${d.object(`'version', COALESCE((SELECT version FROM documents WHERE name = $doc), 0),\n${colls.map((c) => c(d)).join(",\n")}`)} AS doc`;
|
|
907
|
+
return `// Written by src/compile.ts from ${from}: change the stories, not this.
|
|
908
|
+
|
|
909
|
+
/** ${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)}\`;
|
|
911
|
+
|
|
912
|
+
/** Its query, as Postgres says it. */
|
|
913
|
+
export const postgres = ${JSON.stringify({ query: query(POSTGRES) }, null, 2)};
|
|
914
|
+
`;
|
|
915
|
+
}
|
|
916
|
+
/** The tables a read-only document's query reads: what a change to them is told to. */
|
|
917
|
+
const readsOf = (spec: Query) => [...new Set(Object.values(spec).map((s) => s.from))].sort();
|
|
918
|
+
|
|
919
|
+
/** The tables a document's collections are, and their tables of pairs. */
|
|
920
|
+
const tablesRead = (collections: Record<string, Coll>) =>
|
|
921
|
+
Object.entries(collections)
|
|
922
|
+
.flatMap(([c, x]) => [c, ...Object.entries(x.fields).flatMap(([f, t]) => (t === "ids" ? [`${c}_${f}`] : []))])
|
|
923
|
+
.sort();
|
|
924
|
+
|
|
925
|
+
/** A window's span, in days: a duration of days alone (P7D), as SQLite's dates add them. */
|
|
926
|
+
const days = (d: string) => Number(/^P(\d+)D$/.exec(d)![1]);
|
|
927
|
+
|
|
928
|
+
/** The next migration the tables need beyond those in the folder: its file's name and text, or none. */
|
|
929
|
+
export async function nextMigration(dir: string, doc: string, tables: Record<string, Table>) {
|
|
930
|
+
const before = existsSync(dir) ? await fromFolder(dir) : [];
|
|
931
|
+
const { changes, byHand } = diff(stateOf(before), tables);
|
|
932
|
+
if (!changes.length && !byHand.length) return null;
|
|
933
|
+
const n = String(before.length + 1).padStart(3, "0");
|
|
934
|
+
const text = writeMigration(changes, byHand, "joined/migrate");
|
|
935
|
+
return { file: `${dir}/${n}-${before.length ? named(changes) || "by-hand" : doc}.ts`, text, byHand };
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/** A migration's name, from what it changes: add-events-notes, drop-greetings. */
|
|
939
|
+
const named = (changes: Change[]) =>
|
|
940
|
+
changes
|
|
941
|
+
.slice(0, 2)
|
|
942
|
+
.map((c) => [c.change.replace(/[A-Z].*/, ""), c.key, "column" in c ? c.column : ""].filter(Boolean).join("-"))
|
|
943
|
+
.join("-and-") + (changes.length > 2 ? "-and-more" : "");
|
|
944
|
+
|
|
945
|
+
/** What a story can't show, each a header line of an app's stories, after the cast (docs/plan.md, The definitions). */
|
|
946
|
+
const DEFINED = [
|
|
947
|
+
"links",
|
|
948
|
+
"roles",
|
|
949
|
+
"owns",
|
|
950
|
+
"kind",
|
|
951
|
+
"fills",
|
|
952
|
+
"timed",
|
|
953
|
+
"unique",
|
|
954
|
+
"noOverlap",
|
|
955
|
+
"window",
|
|
956
|
+
"order",
|
|
957
|
+
"copies",
|
|
958
|
+
"documents",
|
|
959
|
+
"takes",
|
|
960
|
+
"gives",
|
|
961
|
+
"where",
|
|
962
|
+
"moves",
|
|
963
|
+
"totals",
|
|
964
|
+
"guests",
|
|
965
|
+
"frozen",
|
|
966
|
+
"waits",
|
|
967
|
+
"visitors",
|
|
968
|
+
];
|
|
969
|
+
|
|
970
|
+
/** 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
|
+
* instance; a link, by a story writing the field; a role, by a does granting it and a cannot by someone without
|
|
972
|
+
* 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 the field. What the server fills, no story gives: it's the server's. */
|
|
974
|
+
export function unchecked(
|
|
975
|
+
defs: Definitions,
|
|
976
|
+
stories: Story[],
|
|
977
|
+
grants: Record<string, string[]>,
|
|
978
|
+
rolesOfTeller: (s: Story) => string[],
|
|
979
|
+
/** The app's other documents: a role any of them checks is checked. */
|
|
980
|
+
siblings: {
|
|
981
|
+
defs: Definitions;
|
|
982
|
+
stories: Story[];
|
|
983
|
+
grants: Record<string, string[]>;
|
|
984
|
+
rolesOfTeller: (s: Story) => string[];
|
|
985
|
+
}[] = [],
|
|
986
|
+
): string | null {
|
|
987
|
+
const writes = (s: Story) => [
|
|
988
|
+
...(s.does ? [s.does] : []),
|
|
989
|
+
...(s.cannot ? [s.cannot] : []),
|
|
990
|
+
...(Array.isArray(s.premise) ? s.premise : Object.values(s.premise ?? {}).flat()),
|
|
991
|
+
];
|
|
992
|
+
const ops = (s: Story) => writes(s).flatMap((w) => w.ops);
|
|
993
|
+
const gives = (o: Op, f: string) =>
|
|
994
|
+
parts(o.path).field === f ||
|
|
995
|
+
(o.op === "add" && parts(o.path).field === undefined && typeof o.value === "object" && f in (o.value ?? {}));
|
|
996
|
+
const on = (coll: string) => stories.some((s) => s.cannot?.ops.some((o) => parts(o.path).coll === coll));
|
|
997
|
+
if (defs.kind && !stories.some((s) => writes(s).some((w) => w.doc.includes(":"))))
|
|
998
|
+
return `kind is checked by no story: none is told on an instance (${defs.kind.root}'s, :1)`;
|
|
999
|
+
// (a link, a role, a window and a rule over values: by any document of the app, as its tables are all of theirs)
|
|
1000
|
+
const by = [{ defs, stories, grants, rolesOfTeller }, ...siblings];
|
|
1001
|
+
// (a link the server fills with its writer, "me", is written by every add)
|
|
1002
|
+
const filledMe = (f: string) => Object.values(defs.fills ?? {}).some((fields) => fields[f] === "me");
|
|
1003
|
+
for (const f of Object.keys(defs.links ?? {}))
|
|
1004
|
+
if (!filledMe(f) && !by.some((u) => u.stories.some((s) => ops(s).some((o) => gives(o, f)))))
|
|
1005
|
+
return `links names ${f}, which no story writes`;
|
|
1006
|
+
// a link that goes with what it points at: a story removes one of those
|
|
1007
|
+
for (const [f, l] of Object.entries(defs.links ?? {}))
|
|
1008
|
+
if (typeof l === "object" && l.gone === "with") {
|
|
1009
|
+
if (!l.one) return `links' ${f} goes with what it points at, so it's one id (one: true)`;
|
|
1010
|
+
const removes = (s: Story) =>
|
|
1011
|
+
s.does?.ops.some((o) => o.op === "remove" && parts(o.path).coll === l.to && parts(o.path).field === undefined);
|
|
1012
|
+
if (!by.some((u) => u.stories.some(removes)))
|
|
1013
|
+
return `links' ${f} goes with its ${itemOf(l.to)}, but no story removes one`;
|
|
1014
|
+
}
|
|
1015
|
+
// a role: owns or a where's holds naming it, or a does granting it and a cannot without it; a step's grant is its
|
|
1016
|
+
// op's (replace orders.status:placed>ready), and an add's first step too (add posts.status:>waiting, add posts)
|
|
1017
|
+
const opOf = (k: string) =>
|
|
1018
|
+
k.startsWith("add ") && k.includes(":>") ? k.slice(0, k.lastIndexOf(".", k.indexOf(":>"))) : k.split(":")[0];
|
|
1019
|
+
for (const role of Object.keys(defs.roles ?? {})) {
|
|
1020
|
+
const checked = by.some((u) => {
|
|
1021
|
+
const owns = typeof u.defs.owns === "string" ? [u.defs.owns] : Object.values(u.defs.owns ?? {});
|
|
1022
|
+
const holds = Object.values(u.defs.where ?? {}).flatMap((w) => (typeof w.holds === "string" ? [w.holds] : []));
|
|
1023
|
+
const named = [...owns, ...holds].some((p) => p.split("|").some((t) => t.trim() === role));
|
|
1024
|
+
const granted = Object.values(u.grants).some((g) => g.includes(role));
|
|
1025
|
+
const without = u.stories.some(
|
|
1026
|
+
(s) =>
|
|
1027
|
+
s.cannot &&
|
|
1028
|
+
!u.rolesOfTeller(s).includes(role) &&
|
|
1029
|
+
s.cannot.ops.some((o) =>
|
|
1030
|
+
Object.entries(u.grants).some(([k, g]) => opOf(k) === grantOf(o) && g.includes(role)),
|
|
1031
|
+
),
|
|
1032
|
+
);
|
|
1033
|
+
return named || (granted && without);
|
|
1034
|
+
});
|
|
1035
|
+
if (!checked)
|
|
1036
|
+
return `the role ${role} is checked by no story: a does granting it and a cannot without it, or owns naming it`;
|
|
1037
|
+
}
|
|
1038
|
+
if (defs.owns && !stories.some((s) => s.unseen?.length))
|
|
1039
|
+
return "owns is checked by no story: none says who mustn't hear it (unseen)";
|
|
1040
|
+
for (const [key, colls] of [
|
|
1041
|
+
["unique", defs.unique],
|
|
1042
|
+
["noOverlap", defs.noOverlap],
|
|
1043
|
+
] as const)
|
|
1044
|
+
for (const coll of Object.keys(colls ?? {}))
|
|
1045
|
+
if (!on(coll)) return `${key} names ${coll}, but no cannot story writes it`;
|
|
1046
|
+
for (const [coll, { from }] of Object.entries(defs.copies ?? {}))
|
|
1047
|
+
if (!stories.some((s) => s.does?.ops.some((o) => parts(o.path).coll === coll && o.op === "add" && gives(o, from))))
|
|
1048
|
+
return `copies names ${coll}' ${from}, but no story adds one by it`;
|
|
1049
|
+
if (defs.window && !by.some((u) => u.stories.some((s) => writes(s).some((w) => w.doc.includes("?")))))
|
|
1050
|
+
return "window is checked by no story: none is told on a window (trip?week=2026-11-02)";
|
|
1051
|
+
for (const [coll, f] of Object.entries(defs.timed ?? {}))
|
|
1052
|
+
if (!stories.some((s) => s.does?.ops.some((o) => parts(o.path).coll === coll && gives(o, f))))
|
|
1053
|
+
return `timed names ${coll}' ${f}, which no story gives`;
|
|
1054
|
+
// a rule over values, by a cannot refused in its words (what's there, and what was asked, filled in)
|
|
1055
|
+
for (const [rule, of] of [
|
|
1056
|
+
["takes", defs.takes],
|
|
1057
|
+
["gives", defs.gives],
|
|
1058
|
+
] as const)
|
|
1059
|
+
for (const [coll, { refused }] of Object.entries(of ?? {}))
|
|
1060
|
+
if (!by.some((u) => u.stories.some((s) => s.cannot && wordsOf(refused).test(s.refused ?? ""))))
|
|
1061
|
+
return `${rule} names ${coll}, but no cannot story is refused in its words`;
|
|
1062
|
+
// 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
|
+
// guest's cannot on one of another
|
|
1064
|
+
return settingsUnchecked(defs, stories, grants) ?? visitorsRefused(defs, stories, rolesOfTeller);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/** The stories language (docs/stories.md): the words a story, a write and an op may have, and no others. */
|
|
1068
|
+
const STORY = ["story", "as", "does", "cannot", "seen", "unseen", "refused", "then", "premise"],
|
|
1069
|
+
WRITE = ["doc", "ops", "why"],
|
|
1070
|
+
OP = ["op", "path", "value"];
|
|
1071
|
+
|
|
1072
|
+
/** Why a line of stories.jsonl isn't in the stories language, or null if it is. */
|
|
1073
|
+
export function unspoken(line: any): string | null {
|
|
1074
|
+
if (typeof line !== "object" || line === null || Array.isArray(line)) return "a line is an object";
|
|
1075
|
+
if ("cast" in line) return Object.keys(line).length === 1 ? null : "a cast line has cast alone";
|
|
1076
|
+
// a definition: a header line, one key
|
|
1077
|
+
const [only, ...more] = Object.keys(line);
|
|
1078
|
+
if (only !== undefined && DEFINED.includes(only))
|
|
1079
|
+
return more.length ? `a definition is a line of its own: ${only}, then ${more.join(", ")}` : null;
|
|
1080
|
+
const odd = Object.keys(line).find((k) => !STORY.includes(k));
|
|
1081
|
+
if (odd) return `${odd} isn't a story's word: ${STORY.join(", ")}`;
|
|
1082
|
+
if (typeof line.story !== "string") return "a story has its words";
|
|
1083
|
+
if (line.as !== undefined && typeof line.as !== "string") return "as is a member's name";
|
|
1084
|
+
if (!line.does === !line.cannot) return "a story does, or cannot: one of them";
|
|
1085
|
+
if (line.refused !== undefined && !line.cannot) return "refused goes with cannot";
|
|
1086
|
+
if (line.then !== undefined && !line.does) return "then goes with does";
|
|
1087
|
+
// each a path in the story's document (/orders/6/total), or in another, its name before it (menu/items/5/stock)
|
|
1088
|
+
const then = line.then ?? {};
|
|
1089
|
+
if (typeof then !== "object" || Array.isArray(then) || Object.keys(then).some((k) => !k.includes("/")))
|
|
1090
|
+
return "then is paths and the values they hold: /collection/id/field, or a document's name before it";
|
|
1091
|
+
if (["seen", "unseen"].some((k) => line[k] !== undefined && !Array.isArray(line[k])))
|
|
1092
|
+
return "seen and unseen are lists of names";
|
|
1093
|
+
// without as, a story is anonymous: the core's words alone, its premise a list of writes
|
|
1094
|
+
const anonymous = line.as === undefined;
|
|
1095
|
+
const members = ["seen", "unseen"].find((k) => anonymous && k in line);
|
|
1096
|
+
if (members) return `${members} is a members' word: a story with it has as`;
|
|
1097
|
+
if (line.premise !== undefined && Array.isArray(line.premise) !== anonymous)
|
|
1098
|
+
return anonymous ? "an anonymous story's premise is a list of writes" : "a premise is each name's writes";
|
|
1099
|
+
const before = anonymous ? (line.premise ?? []) : Object.values(line.premise ?? {}).flat();
|
|
1100
|
+
// a does (or cannot) of several writes, all or none (src/together.ts); each of a premise's, a write of its own
|
|
1101
|
+
const writes = partsOf(line.does ?? line.cannot);
|
|
1102
|
+
const unnamed = [writes, ...before.map((w: unknown) => [w])].map(unwritten).find(Boolean);
|
|
1103
|
+
if (unnamed) return unnamed;
|
|
1104
|
+
for (const w of [...writes, ...before] as any[]) {
|
|
1105
|
+
const word = Object.keys(w).find((k) => !WRITE.includes(k));
|
|
1106
|
+
if (word) return `${word} isn't a write's word: ${WRITE.join(", ")}`;
|
|
1107
|
+
if (anonymous && "why" in w) return "why is a members' word: a story with it has as";
|
|
1108
|
+
for (const o of w.ops ?? []) {
|
|
1109
|
+
const word = Object.keys(o).find((k) => !OP.includes(k));
|
|
1110
|
+
if (word) return `${word} isn't an op's word: ${OP.join(", ")}`;
|
|
1111
|
+
if (!["add", "replace", "remove"].includes(o.op)) return `${o.op} isn't an op: add, replace or remove`;
|
|
1112
|
+
if ((o.op === "remove") === "value" in o) return `${o.op} ${o.value === undefined ? "needs" : "has no"} value`;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return null;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/** The seeds as a story finds them: its premise's writes made on a copy, in order (an add given the next id, and a
|
|
1119
|
+
* later op's "$n" the id of its write's nth add; an instance's add kept with it). None, the seeds themselves. */
|
|
1120
|
+
export function premised(
|
|
1121
|
+
seeds: Record<string, Record<string, unknown>>,
|
|
1122
|
+
premise: Record<string, Write[]> | Write[] | undefined,
|
|
1123
|
+
/** 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
|
+
fillsOf: (doc: string, coll: string) => Record<string, unknown> | undefined,
|
|
1125
|
+
memberOf: (name: string) => number | undefined,
|
|
1126
|
+
): Record<string, Record<string, unknown>> {
|
|
1127
|
+
// each write with its teller (an anonymous story's, nobody)
|
|
1128
|
+
const writes: [string | null, Write][] = !premise
|
|
1129
|
+
? []
|
|
1130
|
+
: Array.isArray(premise)
|
|
1131
|
+
? premise.map((w) => [null, w])
|
|
1132
|
+
: Object.entries(premise).flatMap(([name, ws]) => ws.map((w) => [name, w] as [string, Write]));
|
|
1133
|
+
if (!writes.length) return seeds;
|
|
1134
|
+
const state = structuredClone(seeds);
|
|
1135
|
+
for (const [teller, w] of writes) {
|
|
1136
|
+
const [name, n] = w.doc.split("?")[0]!.split(":") as [string, string?];
|
|
1137
|
+
const doc = (state[name] ??= {});
|
|
1138
|
+
const added: number[] = [];
|
|
1139
|
+
const given = (v: unknown): unknown =>
|
|
1140
|
+
typeof v === "string" && /^\$\d+$/.test(v)
|
|
1141
|
+
? added[Number(v.slice(1)) - 1]
|
|
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) {
|
|
1148
|
+
const [, coll = "", key, ...path] = o.path.split("/");
|
|
1149
|
+
const rows = (doc[coll] ??= []) as Record<string, unknown>[];
|
|
1150
|
+
if (!Array.isArray(rows)) continue;
|
|
1151
|
+
if (o.op === "add" && key === "-") {
|
|
1152
|
+
const id = Math.max(0, ...rows.map((r) => Number(r.id))) + 1;
|
|
1153
|
+
added.push(id);
|
|
1154
|
+
// what the server fills, as it would: "me" its teller, "now" an instant, a code
|
|
1155
|
+
const filled = Object.entries(fillsOf(name, coll) ?? {}).map(([f, v]) => [
|
|
1156
|
+
f,
|
|
1157
|
+
v === "me" ? (teller === null ? null : (memberOf(teller) ?? null)) : v === "now" ? "2026-01-01T00:00:00Z" : v,
|
|
1158
|
+
]);
|
|
1159
|
+
rows.push({
|
|
1160
|
+
...Object.fromEntries(filled),
|
|
1161
|
+
...(given(o.value) as object),
|
|
1162
|
+
id,
|
|
1163
|
+
...(n ? { [name]: Number(n) } : {}),
|
|
1164
|
+
});
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
const row = rows.find((r) => r.id === Number(key));
|
|
1168
|
+
if (!row) continue;
|
|
1169
|
+
if (!path.length) {
|
|
1170
|
+
if (o.op === "remove") rows.splice(rows.indexOf(row), 1);
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
// a field (terms/days, an object's), or an id added to a list (/people/-)
|
|
1174
|
+
let at: any = row;
|
|
1175
|
+
for (const f of path.slice(0, -1)) at = at[f] ??= {};
|
|
1176
|
+
const last = path.at(-1)!;
|
|
1177
|
+
if (o.op === "remove") delete at[last];
|
|
1178
|
+
else if (last === "-") at.push?.(given(o.value));
|
|
1179
|
+
else at[last] = given(o.value);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return state;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/** The model the stories need, or an error naming the story that cannot say it; a list of ids a link declares
|
|
1186
|
+
* (`links`, a definition) typed by it, though every story gives it empty. */
|
|
1187
|
+
export function modelOf(stories: Story[], links: Definitions["links"] = {}): Model {
|
|
1188
|
+
// a kind's stories are each about an instance of it (shelf:1), and its model is the kind's
|
|
1189
|
+
const docs = [
|
|
1190
|
+
...new Set(stories.flatMap((s) => [s.does?.doc, s.cannot?.doc]).flatMap((d) => (d ? [d.split(/[:?]/)[0]!] : []))),
|
|
1191
|
+
];
|
|
1192
|
+
if (docs.length !== 1)
|
|
1193
|
+
throw new Error(`an app's stories write one document, not ${docs.length} (${docs.join(", ")})`);
|
|
1194
|
+
// the page keeps a document's version as body[data-<doc>], which a hyphen breaks
|
|
1195
|
+
if (!/^[a-z][a-z0-9]*$/.test(docs[0]!))
|
|
1196
|
+
throw new Error(`${docs[0]} cannot be a document's name (a-z and 0-9, starting with a letter)`);
|
|
1197
|
+
const model: Model = { doc: docs[0]!, collections: {} };
|
|
1198
|
+
// what a story leaves to another to say: an empty list's type, and a removed field's
|
|
1199
|
+
const later: { where: string; c: Coll; f: string; why: "empty" | "removed" | "unlinked" }[] = [];
|
|
1200
|
+
for (const s of stories) {
|
|
1201
|
+
for (const o of s.does?.ops ?? []) {
|
|
1202
|
+
const where = `"${s.story}"`;
|
|
1203
|
+
// a field of the document's own (/greeting): of its one item, in a collection named for it
|
|
1204
|
+
const own = /^\/[a-z][a-z0-9-]*$/.test(o.path) && o.op !== "add";
|
|
1205
|
+
const { coll: name, key: id, field, link, more } = parts(own ? `/${model.doc}/1${o.path}` : o.path);
|
|
1206
|
+
if (!name || more.length) throw new Error(`${where}: no ${o.op} at ${o.path}`);
|
|
1207
|
+
const c = (model.collections[name] ??= {
|
|
1208
|
+
fields: {},
|
|
1209
|
+
required: [],
|
|
1210
|
+
adding: [],
|
|
1211
|
+
adds: 0,
|
|
1212
|
+
replace: [],
|
|
1213
|
+
removeField: [],
|
|
1214
|
+
removeItem: false,
|
|
1215
|
+
link: [],
|
|
1216
|
+
unlink: [],
|
|
1217
|
+
...(own ? { own: true as const } : {}),
|
|
1218
|
+
});
|
|
1219
|
+
if (!c.own !== !own)
|
|
1220
|
+
throw new Error(
|
|
1221
|
+
`${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
|
+
);
|
|
1223
|
+
const typed = (f: string, v: unknown): void => {
|
|
1224
|
+
// (key is an item's id, and may what its person may do to it: the applier's own attributes)
|
|
1225
|
+
if (!/^[a-z][a-z0-9-]*$/.test(f.split(".").at(-1)!) || f === "key" || f === "may")
|
|
1226
|
+
throw new Error(`${where}: ${f} cannot be an attribute (a-z, 0-9 and -, and not key or may)`);
|
|
1227
|
+
// an object of fields: each of its fields a field of the item, named for both (terms.days), one value each
|
|
1228
|
+
if (isObject(v)) {
|
|
1229
|
+
if (f.includes(".")) throw new Error(`${where}: ${f} is an object in an object: one value each`);
|
|
1230
|
+
return Object.entries(v).forEach(([k, x]) => typed(`${f}.${k}`, x));
|
|
1231
|
+
}
|
|
1232
|
+
if (Array.isArray(v) && !v.length) return void later.push({ where, c, f, why: "empty" });
|
|
1233
|
+
const t = typeOf(v);
|
|
1234
|
+
if (!t) throw new Error(`${where}: ${f} is a string, a boolean, a number or a list of ids`);
|
|
1235
|
+
const was = c.fields[f];
|
|
1236
|
+
const now = was ? both(was, t) : t;
|
|
1237
|
+
if (!now) throw new Error(`${where}: ${f} is ${an(t)} here and ${an(was!)} in another story`);
|
|
1238
|
+
c.fields[f] = now;
|
|
1239
|
+
};
|
|
1240
|
+
const item = /^\d+$/.test(id);
|
|
1241
|
+
// one of an object's fields (/orders/1/terms/days), replaced
|
|
1242
|
+
if (item && field && link !== undefined && /^[a-z]/.test(link) && o.op === "replace") {
|
|
1243
|
+
const sub = `${field}.${link}`;
|
|
1244
|
+
(typed(sub, o.value), c.replace.includes(sub) || c.replace.push(sub));
|
|
1245
|
+
}
|
|
1246
|
+
// an id added to a list, or taken from it: the list is the field's, by its id
|
|
1247
|
+
else if (item && field && link !== undefined) {
|
|
1248
|
+
if (o.op === "add" && link === "-" && Number.isInteger(o.value))
|
|
1249
|
+
(typed(field, [o.value]), c.link.includes(field) || c.link.push(field));
|
|
1250
|
+
else if (o.op === "remove" && /^\d+$/.test(link))
|
|
1251
|
+
(c.unlink.includes(field) || c.unlink.push(field), later.push({ where, c, f: field, why: "unlinked" }));
|
|
1252
|
+
else throw new Error(`${where}: no story can ${o.op} at ${o.path}`);
|
|
1253
|
+
} else if (o.op === "add" && id === "-" && field === undefined) {
|
|
1254
|
+
const value = o.value as Record<string, unknown>;
|
|
1255
|
+
for (const [f, v] of Object.entries(value)) typed(f, v);
|
|
1256
|
+
// a field is needed if every story that adds one gives it
|
|
1257
|
+
const given = flatKeys(value);
|
|
1258
|
+
c.required = c.adds++ ? c.required.filter((f) => given.includes(f)) : given;
|
|
1259
|
+
c.adding.push({ story: s.story, fields: given });
|
|
1260
|
+
} else if (o.op === "replace" && item && field) {
|
|
1261
|
+
typed(field, o.value);
|
|
1262
|
+
// an object whole: each of its fields replaced
|
|
1263
|
+
for (const f of isObject(o.value) ? flatKeys({ [field]: o.value }) : [field])
|
|
1264
|
+
if (!c.replace.includes(f)) c.replace.push(f);
|
|
1265
|
+
} else if (o.op === "remove" && item && field === undefined) c.removeItem = true;
|
|
1266
|
+
else if (o.op === "remove" && item && field)
|
|
1267
|
+
(c.removeField.includes(field) || c.removeField.push(field),
|
|
1268
|
+
later.push({ where, c, f: field, why: "removed" }));
|
|
1269
|
+
else throw new Error(`${where}: no story can ${o.op} at ${o.path}`);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
for (const { where, c, f, why } of later) {
|
|
1273
|
+
const listed = links[f] !== undefined && (typeof links[f] === "string" || !links[f].one);
|
|
1274
|
+
if (why === "empty" && listed && !c.fields[f]) c.fields[f] = "ids";
|
|
1275
|
+
else if (why === "empty" && c.fields[f] !== "ids")
|
|
1276
|
+
throw new Error(
|
|
1277
|
+
`${where}: ${f} is an empty list, which says nothing of what it holds: give it an id in another story`,
|
|
1278
|
+
);
|
|
1279
|
+
if (why === "removed" && !c.fields[f]) throw new Error(`${where}: ${f} is removed, but no story gives one`);
|
|
1280
|
+
if (why === "unlinked" && c.fields[f] !== "ids")
|
|
1281
|
+
throw new Error(`${where}: an id is taken from ${f}, but no story gives a list of ids as ${f}`);
|
|
1282
|
+
if (why === "removed" && c.required.includes(f))
|
|
1283
|
+
throw new Error(`${where}: ${f} cannot be removed, since every story that adds one gives it`);
|
|
1284
|
+
}
|
|
1285
|
+
return model;
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
const Pascal = (s: string) =>
|
|
1289
|
+
s
|
|
1290
|
+
.split("-")
|
|
1291
|
+
.map((w) => w[0]!.toUpperCase() + w.slice(1))
|
|
1292
|
+
.join("");
|
|
1293
|
+
/** A collection's item, by English's regular plurals (and people), or null if the name isn't one. */
|
|
1294
|
+
export const itemOf = (coll: string) =>
|
|
1295
|
+
coll === "people"
|
|
1296
|
+
? "person"
|
|
1297
|
+
: /[^aeiou]ies$/.test(coll)
|
|
1298
|
+
? coll.slice(0, -3) + "y"
|
|
1299
|
+
: /(ss|x|ch|sh)es$/.test(coll)
|
|
1300
|
+
? coll.slice(0, -2)
|
|
1301
|
+
: /[^s]s$/.test(coll)
|
|
1302
|
+
? coll.slice(0, -1)
|
|
1303
|
+
: null;
|
|
1304
|
+
/** joined's own tables (src/migrations), which no app's collection may be named: it would be given
|
|
1305
|
+
* joined's table, and read back what's private in it. */
|
|
1306
|
+
const OWN_TABLES = ["documents", "changes", "member_keys", "agents", "farewells", "notices"];
|
|
1307
|
+
/** Every compiled element's name starts so: a custom element's name needs a hyphen. */
|
|
1308
|
+
const PREFIX = "j";
|
|
1309
|
+
const an = (w: string) => (/^[aeiou]/.test(w) ? `an ${w}` : `a ${w}`);
|
|
1310
|
+
|
|
1311
|
+
/** generated/rules.ts and generated/elements.ts for one app's model; holders: which document holds each other collection;
|
|
1312
|
+
* anonymous: whether every story is, none told as a member. */
|
|
1313
|
+
export function compile(
|
|
1314
|
+
{ doc, collections }: Model,
|
|
1315
|
+
from: string,
|
|
1316
|
+
holders: Record<string, string> = {},
|
|
1317
|
+
defs: Definitions = {},
|
|
1318
|
+
grants: Record<string, string[]> = {},
|
|
1319
|
+
anonymous = false,
|
|
1320
|
+
derivedFrom?: string[],
|
|
1321
|
+
fixed = false,
|
|
1322
|
+
readOnly?: Query,
|
|
1323
|
+
prefix = "",
|
|
1324
|
+
): { rules: string; elements: string } {
|
|
1325
|
+
const HEAD = `// Written by src/compile.ts from ${from}: change ${derivedFrom ? "it and its example" : fixed ? "its seed" : "the stories"}, not this.\n`;
|
|
1326
|
+
for (const name of Object.keys(collections)) {
|
|
1327
|
+
if (OWN_TABLES.includes(name) || /^sqlite/.test(name))
|
|
1328
|
+
throw new Error(`${from}: ${name} is a table of joined's own (or SQLite's): name the collection otherwise`);
|
|
1329
|
+
if (name.includes("_"))
|
|
1330
|
+
throw new Error(`${from}: ${name} has an underscore, which a table of pairs is named with: use a hyphen`);
|
|
1331
|
+
}
|
|
1332
|
+
for (const [name, c] of Object.entries(collections))
|
|
1333
|
+
if (!c.own && !itemOf(name))
|
|
1334
|
+
throw new Error(
|
|
1335
|
+
`${from}: ${name} is a collection, so its name is a plural (events, entries, boxes, people), and its items' a singular`,
|
|
1336
|
+
);
|
|
1337
|
+
// a list of ids links to the collection it is named for, in the document that holds it, or to the one its
|
|
1338
|
+
// definition names (one id, where it says so): its own document's, or another's
|
|
1339
|
+
const link = linksOf({ doc, collections }, defs, holders, from);
|
|
1340
|
+
// each collection's element, its items', their fields, and the collection each link is to: what the store
|
|
1341
|
+
// asks before an item is removed
|
|
1342
|
+
const shape = Object.fromEntries(
|
|
1343
|
+
Object.entries(collections).map(([name, c]) => [
|
|
1344
|
+
name,
|
|
1345
|
+
{
|
|
1346
|
+
place: `${PREFIX}-${name}`,
|
|
1347
|
+
tag: `${PREFIX}-${c.own ? name : itemOf(name)!}`,
|
|
1348
|
+
...(c.own ? { own: true } : {}),
|
|
1349
|
+
fields: c.fields,
|
|
1350
|
+
needs: c.required,
|
|
1351
|
+
links: Object.fromEntries(
|
|
1352
|
+
Object.entries(c.fields)
|
|
1353
|
+
.filter(([f, t]) => t === "ids" || (t === "integer" && link(f).one))
|
|
1354
|
+
.map(([f]) => [f, link(f).to]),
|
|
1355
|
+
),
|
|
1356
|
+
// its links that go with what they point at, in this document: the item removed with it
|
|
1357
|
+
...goes(c, link, doc),
|
|
1358
|
+
...(defs.order?.[name] ? { order: defs.order[name] } : {}),
|
|
1359
|
+
...(c.fills ? { fills: c.fills } : {}),
|
|
1360
|
+
...(c.timed ? { timed: c.timed } : {}),
|
|
1361
|
+
...(c.copies ? { copies: c.copies } : {}),
|
|
1362
|
+
},
|
|
1363
|
+
]),
|
|
1364
|
+
);
|
|
1365
|
+
for (const [f, l] of Object.entries(defs.links ?? {})) {
|
|
1366
|
+
const t = Object.values(collections).find((c) => c.fields[f])?.fields[f];
|
|
1367
|
+
const one = typeof l === "object" && !!l.one;
|
|
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}`);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
let rules = `${HEAD}
|
|
1373
|
+
export type Op = { op: "add" | "replace" | "remove"; path: string; value?: any };
|
|
1374
|
+
|
|
1375
|
+
/** 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. */
|
|
1377
|
+
export const doc = "${doc}";
|
|
1378
|
+
export const collections = ${JSON.stringify(shape, null, 2)} as const;
|
|
1379
|
+
/** Whether every story is anonymous, none told as a member: where every app's is, the project has no members. */
|
|
1380
|
+
export const anonymous = ${anonymous};
|
|
1381
|
+
/** What kind of document ${doc} is, by the flows it uses: static, changed only with a release (a page reads it, and
|
|
1382
|
+
* never subscribes); read-only, live, but no page writes it (derived); or shared, its members' to write. */
|
|
1383
|
+
export const type = "${fixed ? "static" : derivedFrom || readOnly ? "read-only" : "shared"}";
|
|
1384
|
+
${
|
|
1385
|
+
defs.where?.[doc]
|
|
1386
|
+
? `/** It holds only some of its tables' rows (its definitions' where): a change to any of them moves its version,
|
|
1387
|
+
* and each page holding it is told what changed of it. */
|
|
1388
|
+
export const view = true;
|
|
1389
|
+
export const reads = ${JSON.stringify(tablesRead(collections))};
|
|
1390
|
+
/** Who may hold it at all (its where's holds), each a role; null, anyone. */
|
|
1391
|
+
export const mayHold = ${JSON.stringify(typeof defs.where[doc]!.holds === "string" ? (defs.where[doc]!.holds as string).split("|").map((r) => r.trim()) : null)};
|
|
1392
|
+
`
|
|
1393
|
+
: ""
|
|
1394
|
+
}${
|
|
1395
|
+
readOnly
|
|
1396
|
+
? `/** The tables its query reads: a change to any of them moves its version, and is told to each page holding it, as
|
|
1397
|
+
* its member has it. */
|
|
1398
|
+
export const reads = ${JSON.stringify(readsOf(readOnly))};
|
|
1399
|
+
/** It's read as each member has it: a parameter of its query. */
|
|
1400
|
+
export const member = true;
|
|
1401
|
+
`
|
|
1402
|
+
: ""
|
|
1403
|
+
}/** The parts of ${doc} a page may hold alone, by its query's parameters (its definitions' window): null, none. */
|
|
1404
|
+
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` : ""}`;
|
|
1406
|
+
let elements = `${HEAD}
|
|
1407
|
+
// Each collection is an element, defined here: on a page, it holds the document, and its items
|
|
1408
|
+
// are put inside it. Each item is an element, defined by the page: as it is, or by a view that
|
|
1409
|
+
// extends it. A field is an attribute (a list of ids as IDREFS: "1 3"), and an item's key the
|
|
1410
|
+
// document's id for it. How an item looks is the app's: its view, or a display holding the
|
|
1411
|
+
// collection draws it. Ops go up as an "ops" event, for the page to send to ${doc}, with why they
|
|
1412
|
+
// were made if it's said; only the ops the stories allow can be sent. Each returns its write's answer.
|
|
1413
|
+
|
|
1414
|
+
import { hold, letGo, type Answer } from "joined/page";
|
|
1415
|
+
|
|
1416
|
+
// the document an element is of: its collection's doc attribute (an instance of a kind, shelf:1), or ${doc}
|
|
1417
|
+
const docOf = (el: Element) => el.closest("[doc]")?.getAttribute("doc") ?? "${doc}";
|
|
1418
|
+
// an element's ops go up as an "ops" event; what it returns is the write's answer, done or refused
|
|
1419
|
+
const send = (from: Element, ops: object[], why?: string) => new Promise<Answer>((answer) => from.dispatchEvent(new CustomEvent("ops", { bubbles: true, composed: true, detail: { doc: docOf(from), ops, why, answer } })));
|
|
1420
|
+
`;
|
|
1421
|
+
|
|
1422
|
+
const tsOf = (t: Type) =>
|
|
1423
|
+
t === "ids" ? "number[]" : t === "integer" || t === "decimal" ? "number" : t === "boolean" ? t : "string";
|
|
1424
|
+
const ops: string[] = [];
|
|
1425
|
+
for (const [name, c] of Object.entries(collections)) {
|
|
1426
|
+
if (c.own) {
|
|
1427
|
+
elements += ownElement(name, c);
|
|
1428
|
+
for (const f of c.replace) ops.push(`{ op: "replace"; path: "/${f}"; value: ${tsOf(c.fields[f]!)} }`);
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
const item = itemOf(name)!,
|
|
1432
|
+
tag = `${PREFIX}-${item}`,
|
|
1433
|
+
Class = Pascal(tag),
|
|
1434
|
+
place = `${PREFIX}-${name}`,
|
|
1435
|
+
Place = Pascal(place);
|
|
1436
|
+
const fields = Object.entries(c.fields);
|
|
1437
|
+
|
|
1438
|
+
// a link to one member is cleared as they're removed (its column set null): needed to add, yet, read, maybe gone
|
|
1439
|
+
const cleared = (f: string) => link(f).one && link(f).to === GROUP;
|
|
1440
|
+
const read = (f: string, t: Type) =>
|
|
1441
|
+
t === "boolean"
|
|
1442
|
+
? `this.hasAttribute("${f}")`
|
|
1443
|
+
: t === "integer" || t === "decimal"
|
|
1444
|
+
? c.required.includes(f) && !cleared(f)
|
|
1445
|
+
? `Number(this.getAttribute("${f}"))`
|
|
1446
|
+
: `this.hasAttribute("${f}") ? Number(this.getAttribute("${f}")) : undefined`
|
|
1447
|
+
: t === "ids"
|
|
1448
|
+
? `Object.freeze((this.getAttribute("${f}") ?? "").split(" ").filter(Boolean).map(Number))`
|
|
1449
|
+
: c.required.includes(f)
|
|
1450
|
+
? `this.getAttribute("${f}") ?? ""`
|
|
1451
|
+
: `this.getAttribute("${f}") ?? undefined`;
|
|
1452
|
+
// as read, a boolean or a list is always there: missing is false, or none
|
|
1453
|
+
const always = fields
|
|
1454
|
+
.filter(([f, t]) => (t === "boolean" || t === "ids") && !c.required.includes(f))
|
|
1455
|
+
.map(([f]) => JSON.stringify(f));
|
|
1456
|
+
const gone = fields.filter(([f]) => c.required.includes(f) && cleared(f)).map(([f]) => JSON.stringify(f));
|
|
1457
|
+
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)
|
|
1460
|
+
const sent = (f: string, t: Type) =>
|
|
1461
|
+
`${JSON.stringify(f)}${c.required.includes(f) ? "" : "?"}: ${link(f).one ? REF : tsOf(t)}`;
|
|
1462
|
+
const heads = [...new Set(fields.map(([f]) => f.split(".")[0]!))];
|
|
1463
|
+
const value = heads
|
|
1464
|
+
.map((h) => {
|
|
1465
|
+
const inner = fields.filter(([f]) => f.startsWith(`${h}.`));
|
|
1466
|
+
if (!inner.length) return sent(h, c.fields[h]!);
|
|
1467
|
+
const need = inner.some(([f]) => c.required.includes(f));
|
|
1468
|
+
return `${JSON.stringify(h)}${need ? "" : "?"}: { ${inner.map(([f, t]) => sent(f, t).replace(`"${h}.`, '"')).join("; ")} }`;
|
|
1469
|
+
})
|
|
1470
|
+
.join("; ");
|
|
1471
|
+
elements += `
|
|
1472
|
+
/** ${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)}${c.required.includes(f) ? "" : "?"}: ${tsOf(t)}`).join("; ")} };
|
|
1474
|
+
/** An add of ${an(item)}, as it's sent: its fields as the stories write them. */
|
|
1475
|
+
export type ${Class}Value = { ${value} };
|
|
1476
|
+
|
|
1477
|
+
/** <${tag} key>: ${fields.map(([f, t]) => typeSaid(f, t, link)).join(", ")}, each an attribute. */
|
|
1478
|
+
export class ${Class} extends HTMLElement {
|
|
1479
|
+
static observedAttributes = ${JSON.stringify([...fields.map(([f]) => f), "may"])};
|
|
1480
|
+
#data?: ${data};
|
|
1481
|
+
/** Its id in the document. */
|
|
1482
|
+
get key() { return Number(this.getAttribute("key")); }
|
|
1483
|
+
get path() { return \`/${name}/\${this.key}\`; }
|
|
1484
|
+
/** Its fields, read from its attributes once and again when one changes: frozen, since they're shared. */
|
|
1485
|
+
get data(): ${data} {
|
|
1486
|
+
return (this.#data ??= Object.freeze({ ${fields.map(([f, t]) => `${JSON.stringify(f)}: ${read(f, t)}`).join(", ")} }) as ${data});
|
|
1487
|
+
}
|
|
1488
|
+
/** How a view shows it, drawn again whenever an attribute changes (what its person may do, its may, too). */
|
|
1489
|
+
draw?(): void;
|
|
1490
|
+
attributeChangedCallback() { this.#data = undefined; this.draw?.(); }
|
|
1491
|
+
`;
|
|
1492
|
+
if (c.replace.length) {
|
|
1493
|
+
const F = c.replace.map((f) => JSON.stringify(f)).join(" | ");
|
|
1494
|
+
const one = `{ op: "replace", path: \`\${this.path}/\${field.replace(".", "/")}\`, value }`;
|
|
1495
|
+
// a list an id is both added to and taken from is replaced by those: two people linking at once both land
|
|
1496
|
+
const byId = c.replace.filter((f) => c.link.includes(f) && c.unlink.includes(f));
|
|
1497
|
+
const each = byId.length
|
|
1498
|
+
? `flatMap(([field, value]) => ${JSON.stringify(byId)}.includes(field) ? this.#ids(field as ${byId.map((f) => JSON.stringify(f)).join(" | ")}, value as number[]) : [${one}])`
|
|
1499
|
+
: `map(([field, value]) => (${one}))`;
|
|
1500
|
+
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
|
+
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`;
|
|
1503
|
+
}
|
|
1504
|
+
if (c.link.length)
|
|
1505
|
+
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`;
|
|
1506
|
+
if (c.unlink.length)
|
|
1507
|
+
elements += ` /** Take one id from a list (${c.unlink.join(", ")}). */\n unlink(field: ${c.unlink.map((f) => JSON.stringify(f)).join(" | ")}, id: number, why?: string) { return send(this, [{ op: "remove", path: \`\${this.path}/\${field}/\${id}\` }], why); }\n`;
|
|
1508
|
+
if (c.removeField.length)
|
|
1509
|
+
elements += ` /** Remove some of its fields (${c.removeField.join(", ")}), so that it has none. */\n removeField(...fields: (${c.removeField.map((f) => JSON.stringify(f)).join(" | ")})[]) { return send(this, fields.map((field) => ({ op: "remove", path: \`\${this.path}/\${field}\` }))); }\n`;
|
|
1510
|
+
// removeItem, as remove() is the DOM's own: the applier takes an item's element away with it
|
|
1511
|
+
if (c.removeItem)
|
|
1512
|
+
elements += ` /** Remove it from the document. */\n removeItem(why?: string) { return send(this, [{ op: "remove", path: this.path }], why); }\n`;
|
|
1513
|
+
elements += `}\n`;
|
|
1514
|
+
elements += `\n/** <${place}>: the document's ${name}, each a <${tag}> inside it. */\nexport class ${Place} extends HTMLElement {\n connectedCallback() { hold(this, docOf(this), "${name}", "${tag}", ${JSON.stringify(c.fields)}${defs.order?.[name] ? `, false, ${JSON.stringify(defs.order[name])}` : ""}); }\n disconnectedCallback() { letGo(this); }\n /** Its ${name}, as the document has them. */\n get items() { return [...this.children].filter((el): el is ${Class} => el.localName === "${tag}"); }\n`;
|
|
1515
|
+
if (c.adds)
|
|
1516
|
+
elements += ` /** Add ${name}: one write for all of them. */\n add(...values: ${Class}Value[]) { return send(this, values.map((value) => ({ op: "add", path: "/${name}/-", value }))); }\n`;
|
|
1517
|
+
elements += `}\ncustomElements.define("${place}", ${Place});\n`;
|
|
1518
|
+
// the ops the stories allow on this collection, for a write across the document's collections
|
|
1519
|
+
const at = `\`/${name}/\${number}`;
|
|
1520
|
+
if (c.adds) ops.push(`{ op: "add"; path: "/${name}/-"; value: ${Class}Value }`);
|
|
1521
|
+
for (const f of c.replace)
|
|
1522
|
+
ops.push(`{ op: "replace"; path: ${at}/${f.replace(".", "/")}\`; value: ${tsOf(c.fields[f]!)} }`);
|
|
1523
|
+
for (const f of c.removeField) ops.push(`{ op: "remove"; path: ${at}/${f}\` }`);
|
|
1524
|
+
for (const f of c.link) ops.push(`{ op: "add"; path: ${at}/${f}/-\`; value: number }`);
|
|
1525
|
+
for (const f of c.unlink) ops.push(`{ op: "remove"; path: ${at}/${f}/\${number}\` }`);
|
|
1526
|
+
if (c.removeItem) ops.push(`{ op: "remove"; path: ${at}\` }`);
|
|
1527
|
+
}
|
|
1528
|
+
const Doc = Pascal(doc);
|
|
1529
|
+
elements += `
|
|
1530
|
+
/** An op on ${doc} the stories allow, in any of its collections. */
|
|
1531
|
+
export type ${Doc}Op =${ops.length ? `\n | ${ops.join("\n | ")}` : " never"};
|
|
1532
|
+
|
|
1533
|
+
/** One write to ${doc} across its collections (a move with its legs): sent from an element of it, checked
|
|
1534
|
+
* whole by its rules, and made whole or not at all. */
|
|
1535
|
+
export function write(from: Element, ops: ${Doc}Op[], why?: string) { return send(from, ops, why); }
|
|
1536
|
+
`;
|
|
1537
|
+
rules += heldBy(collections, defs, from);
|
|
1538
|
+
// a derived document is derived for each page, its member's: it has no roles, and is published to no topic
|
|
1539
|
+
if (!derivedFrom && !readOnly)
|
|
1540
|
+
rules += whoRules(doc, Object.keys(collections), defs, grants, defs.kind && holders[defs.kind.root]);
|
|
1541
|
+
return { rules, elements };
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/** The element of a document's own fields (<j-hello greeting>): it holds its document, and is its one item, each
|
|
1545
|
+
* field an attribute; defined by the page, as an item's is, so a view may extend it. */
|
|
1546
|
+
function ownElement(doc: string, c: Coll) {
|
|
1547
|
+
const tag = `${PREFIX}-${doc}`,
|
|
1548
|
+
Class = Pascal(tag),
|
|
1549
|
+
fields = Object.entries(c.fields);
|
|
1550
|
+
const ts = (t: Type) => (t === "integer" || t === "decimal" ? "number" : t === "boolean" ? t : "string");
|
|
1551
|
+
const read = (f: string, t: Type) =>
|
|
1552
|
+
t === "boolean"
|
|
1553
|
+
? `this.hasAttribute("${f}")`
|
|
1554
|
+
: t === "integer" || t === "decimal"
|
|
1555
|
+
? `this.hasAttribute("${f}") ? Number(this.getAttribute("${f}")) : undefined`
|
|
1556
|
+
: `this.getAttribute("${f}") ?? undefined`;
|
|
1557
|
+
const F = c.replace.map((f) => JSON.stringify(f)).join(" | ");
|
|
1558
|
+
return `
|
|
1559
|
+
/** ${doc}'s own fields, as the stories give them. */
|
|
1560
|
+
export type ${Class}Data = { ${fields.map(([f, t]) => `${JSON.stringify(f)}?: ${ts(t)}`).join("; ")} };
|
|
1561
|
+
|
|
1562
|
+
/** <${tag}>: ${doc} itself, holding it, its own fields each an attribute. */
|
|
1563
|
+
export class ${Class} extends HTMLElement {
|
|
1564
|
+
static observedAttributes = ${JSON.stringify([...fields.map(([f]) => f), "may"])};
|
|
1565
|
+
#data?: ${Class}Data;
|
|
1566
|
+
/** Its fields, read from its attributes once and again when one changes: frozen, since they're shared. */
|
|
1567
|
+
get data(): ${Class}Data {
|
|
1568
|
+
return (this.#data ??= Object.freeze({ ${fields.map(([f, t]) => `${JSON.stringify(f)}: ${read(f, t)}`).join(", ")} }));
|
|
1569
|
+
}
|
|
1570
|
+
/** How a view shows it, drawn again whenever an attribute changes (what its person may do, its may, too). */
|
|
1571
|
+
draw?(): void;
|
|
1572
|
+
attributeChangedCallback() { this.#data = undefined; this.draw?.(); }
|
|
1573
|
+
connectedCallback() { hold(this, docOf(this), "${doc}", "${tag}", ${JSON.stringify(c.fields)}, true); }
|
|
1574
|
+
disconnectedCallback() { letGo(this); }
|
|
1575
|
+
${
|
|
1576
|
+
c.replace.length
|
|
1577
|
+
? ` /** Replace some of its fields (${c.replace.join(", ")}): one write for all of them. */
|
|
1578
|
+
replace(fields: Partial<Pick<${Class}Data, ${F}>>) {
|
|
1579
|
+
return send(this, Object.entries(fields).filter(([, value]) => value !== undefined).map(([field, value]) => ({ op: "replace", path: \`/\${field}\`, value })));
|
|
1580
|
+
}
|
|
1581
|
+
`
|
|
1582
|
+
: ""
|
|
1583
|
+
}}
|
|
1584
|
+
`;
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
/** Where the apps are, unless another folder is given: JOINED_APPS, or apps/ in the folder joined runs in. */
|
|
1588
|
+
export const APPS = Bun.env.JOINED_APPS || `${process.cwd()}/apps`;
|
|
1589
|
+
/** joined's own document, the members: an app of joined's, beside every app's. */
|
|
1590
|
+
export const OWN = `${import.meta.dir}/members`;
|
|
1591
|
+
/** Where what the pages change is kept, apart from the code: JOINED_DATA (on Railway, a volume), or .data/ in
|
|
1592
|
+
* the folder joined runs in. */
|
|
1593
|
+
export const DATA = Bun.env.JOINED_DATA || `${process.cwd()}/.data`;
|
|
1594
|
+
/** The store's engine (src/engine.ts): JOINED_ENGINE, sqlite or postgres. */
|
|
1595
|
+
export const ENGINE = (Bun.env.JOINED_ENGINE || "sqlite") as Dialect;
|
|
1596
|
+
/** The store's file, or Postgres's folder (src/store.ts): JOINED_DB, or joined.sqlite (postgres/) in the data folder. */
|
|
1597
|
+
export const DB = Bun.env.JOINED_DB || `${DATA}/${ENGINE === "postgres" ? "postgres" : "joined.sqlite"}`;
|
|
1598
|
+
|
|
1599
|
+
/** Each app's stories, read and compiled together, so that one document's links find another's
|
|
1600
|
+
* collections: joined's own members, and every app in the folder. A line without a story (a cast)
|
|
1601
|
+
* is the tests'. */
|
|
1602
|
+
export async function compiled(dir = APPS) {
|
|
1603
|
+
const models: Record<string, Model> = {},
|
|
1604
|
+
stories: Record<string, Story[]> = {},
|
|
1605
|
+
casts: Record<string, Record<string, string | null>> = {},
|
|
1606
|
+
defs: Record<string, Definitions> = {},
|
|
1607
|
+
dirs: Record<string, string> = { members: OWN };
|
|
1608
|
+
for await (const path of new Bun.Glob("*/stories.jsonl").scan(dir))
|
|
1609
|
+
dirs[path.split("/")[0]!] = `${dir}/${path.split("/")[0]}`;
|
|
1610
|
+
// a derived document's app: its derive.ts, and an example of it, in place of stories
|
|
1611
|
+
const derivedFrom: Record<string, string[]> = {};
|
|
1612
|
+
// the documents of an app told of several, each a unit named for it; and those its definitions query, read-only
|
|
1613
|
+
const split = new Set<string>(),
|
|
1614
|
+
readOnly: Record<string, NonNullable<Definitions["documents"]>[string]> = {},
|
|
1615
|
+
// a read-only document's: as its app's stories are, since it has none of its own
|
|
1616
|
+
anonymousOf: Record<string, boolean> = {};
|
|
1617
|
+
for await (const path of new Bun.Glob("*/derive.ts").scan(dir)) {
|
|
1618
|
+
const app = path.split("/")[0]!,
|
|
1619
|
+
at = `${dir}/${app}`;
|
|
1620
|
+
if (dirs[app]) throw new Error(`${app} has stories and a derive.ts: a document is written or derived, not both`);
|
|
1621
|
+
const { doc, from } = (await import(`${at}/derive.ts`)) as { doc: string; from: string[] };
|
|
1622
|
+
dirs[app] = at;
|
|
1623
|
+
derivedFrom[app] = from;
|
|
1624
|
+
stories[app] = [];
|
|
1625
|
+
casts[app] = {};
|
|
1626
|
+
defs[app] = {};
|
|
1627
|
+
models[app] = modelFrom(doc, await seedOf(`${at}/${doc}.json`), `${app}/${doc}.json`);
|
|
1628
|
+
}
|
|
1629
|
+
// a static document's app: its seed alone, with no stories and no derive.ts; it changes only with a release
|
|
1630
|
+
const statics = new Set<string>();
|
|
1631
|
+
for await (const path of new Bun.Glob("*/routes.ts").scan(dir)) {
|
|
1632
|
+
const app = path.split("/")[0]!,
|
|
1633
|
+
at = `${dir}/${app}`;
|
|
1634
|
+
if (dirs[app] || !existsSync(`${at}/${app}.json`)) continue;
|
|
1635
|
+
dirs[app] = at;
|
|
1636
|
+
statics.add(app);
|
|
1637
|
+
stories[app] = [];
|
|
1638
|
+
casts[app] = {};
|
|
1639
|
+
defs[app] = {};
|
|
1640
|
+
models[app] = modelFrom(app, await seedOf(`${at}/${app}.json`), `${app}/${app}.json`);
|
|
1641
|
+
}
|
|
1642
|
+
// every app's lines first: a story of several writes (src/together.ts) is told, a part each, by each part's app
|
|
1643
|
+
const linesOf: Record<string, any[]> = {};
|
|
1644
|
+
for (const [app, at] of Object.entries(dirs)) {
|
|
1645
|
+
if (derivedFrom[app] || statics.has(app)) continue;
|
|
1646
|
+
linesOf[app] = (await Bun.file(`${at}/stories.jsonl`).text())
|
|
1647
|
+
.split("\n")
|
|
1648
|
+
.filter((l) => l.trim())
|
|
1649
|
+
.map((l) => JSON.parse(l));
|
|
1650
|
+
linesOf[app].forEach((l, i) => {
|
|
1651
|
+
const why = unspoken(l);
|
|
1652
|
+
if (why) throw new Error(`${app}'s stories, line ${i + 1}: ${why}`);
|
|
1653
|
+
});
|
|
1654
|
+
}
|
|
1655
|
+
const toldBy = toldOf(
|
|
1656
|
+
Object.fromEntries(Object.entries(linesOf).map(([app, ls]) => [app, ls.filter((l) => l.story)])),
|
|
1657
|
+
);
|
|
1658
|
+
for (const [app, at] of Object.entries(dirs)) {
|
|
1659
|
+
if (derivedFrom[app] || statics.has(app)) continue;
|
|
1660
|
+
const lines = linesOf[app]!;
|
|
1661
|
+
if (existsSync(`${at}/definitions.ts`))
|
|
1662
|
+
throw new Error(
|
|
1663
|
+
`${app}/definitions.ts: definitions are its stories' header lines now, one a key, after the cast`,
|
|
1664
|
+
);
|
|
1665
|
+
// the cast first, then the definitions, then the stories
|
|
1666
|
+
const first = lines.findIndex((l) => l.story);
|
|
1667
|
+
lines.forEach((l, i) => {
|
|
1668
|
+
if (l.cast !== undefined && i !== 0)
|
|
1669
|
+
throw new Error(`${app}'s stories, line ${i + 1}: the cast is the first line`);
|
|
1670
|
+
if (!l.story && !l.cast && first !== -1 && i > first)
|
|
1671
|
+
throw new Error(`${app}'s stories, line ${i + 1}: a definition is a header line, before the stories`);
|
|
1672
|
+
});
|
|
1673
|
+
const header = lines.filter((l) => !l.story && !l.cast);
|
|
1674
|
+
const keys = header.map((l) => Object.keys(l)[0]!);
|
|
1675
|
+
const twice = keys.find((k, i) => keys.indexOf(k) !== i);
|
|
1676
|
+
if (twice) throw new Error(`${app}'s stories: ${twice} is defined twice`);
|
|
1677
|
+
// an app's entities are its own: its stories may be told of several documents over them (catalogue, order:7),
|
|
1678
|
+
// each a unit of its own, its files named for it
|
|
1679
|
+
const told = toldBy[app]!,
|
|
1680
|
+
cast = lines.find((l) => l.cast)?.cast ?? {},
|
|
1681
|
+
defined: Definitions = Object.assign({}, ...header);
|
|
1682
|
+
const bases = [...new Set(told.map((s) => (s.does ?? s.cannot)!.doc.split(/[:?]/)[0]!))];
|
|
1683
|
+
const several = bases.length > 1 || !!defined.documents;
|
|
1684
|
+
for (const unit of several ? bases : [app]) {
|
|
1685
|
+
dirs[unit] = at;
|
|
1686
|
+
if (several) split.add(unit);
|
|
1687
|
+
stories[unit] = several ? told.filter((s) => (s.does ?? s.cannot)!.doc.split(/[:?]/)[0] === unit) : told;
|
|
1688
|
+
casts[unit] = cast;
|
|
1689
|
+
models[unit] = modelOf(stories[unit]!, defined.links);
|
|
1690
|
+
defs[unit] = several ? definedFor(defined, models[unit]!, stories[unit]!) : defined;
|
|
1691
|
+
if (defs[unit]!.kind && defs[unit]!.kind!.root in models[unit]!.collections)
|
|
1692
|
+
throw new Error(`${app}'s stories: a kind's root, ${defs[unit]!.kind!.root}, is another document's collection`);
|
|
1693
|
+
filled(models[unit]!, defs[unit]!, `${app}'s definitions`);
|
|
1694
|
+
}
|
|
1695
|
+
entities(several ? bases : [app], models, defs, defined);
|
|
1696
|
+
// a read-only document over the app's entities, a query its definition says (each side's books)
|
|
1697
|
+
for (const [name, d] of Object.entries(defined.documents ?? {})) {
|
|
1698
|
+
dirs[name] = at;
|
|
1699
|
+
split.add(name);
|
|
1700
|
+
stories[name] = [];
|
|
1701
|
+
casts[name] = cast;
|
|
1702
|
+
defs[name] = {};
|
|
1703
|
+
models[name] = modelFrom(name, await seedOf(`${at}/${name}.json`), `${app}/${name}.json`);
|
|
1704
|
+
readOnly[name] = d;
|
|
1705
|
+
anonymousOf[name] = told.every((s) => s.as === undefined);
|
|
1706
|
+
}
|
|
1707
|
+
if (several && !bases.includes(app)) delete dirs[app];
|
|
1708
|
+
}
|
|
1709
|
+
// the seeds, as the documents begin: who each name in the stories is, and who that is to each document
|
|
1710
|
+
const seeds: Record<string, Record<string, unknown>> = {};
|
|
1711
|
+
for (const [app, m] of Object.entries(models)) {
|
|
1712
|
+
const file =
|
|
1713
|
+
app === "members" && existsSync(`${dir}/members.json`) ? `${dir}/members.json` : `${dirs[app]}/${m.doc}.json`;
|
|
1714
|
+
seeds[m.doc] = await seedOf(file);
|
|
1715
|
+
seeded(m, seeds[m.doc]!, relative(process.cwd(), file));
|
|
1716
|
+
}
|
|
1717
|
+
// a copy: each field taken from what a one-id link points at, its type that field's, once, when it's added
|
|
1718
|
+
for (const [app, d] of Object.entries(defs))
|
|
1719
|
+
for (const [coll, { from, fields }] of Object.entries(d.copies ?? {})) {
|
|
1720
|
+
const c = models[app]!.collections[coll],
|
|
1721
|
+
link = d.links?.[from];
|
|
1722
|
+
if (!c || typeof link !== "object" || !link.one)
|
|
1723
|
+
throw new Error(`${app}'s stories: copies are from a link to one id, which ${coll}' ${from} isn't`);
|
|
1724
|
+
const at = Object.values(models).find((m) => m.collections[link.to])!;
|
|
1725
|
+
for (const f of fields) {
|
|
1726
|
+
const t = at?.collections[link.to]!.fields[f];
|
|
1727
|
+
// the seed may hold a copy, as it was taken; a story never gives one
|
|
1728
|
+
if (
|
|
1729
|
+
!t ||
|
|
1730
|
+
c.adding.some((x) => x.fields.includes(f)) ||
|
|
1731
|
+
c.replace.includes(f) ||
|
|
1732
|
+
// a seed's copy may be a whole number where its target's is a decimal
|
|
1733
|
+
(c.fields[f] && both(c.fields[f]!, t) !== t)
|
|
1734
|
+
)
|
|
1735
|
+
throw new Error(`${app}'s stories: ${coll}' ${f} is copied, so no story gives it, and ${link.to} has it`);
|
|
1736
|
+
c.fields[f] = t;
|
|
1737
|
+
// and each other document over the table holds it too (the kitchen's lines, the till's)
|
|
1738
|
+
for (const m of Object.values(models))
|
|
1739
|
+
if (m !== models[app] && dirs[m.doc] === dirs[app] && m.collections[coll]) m.collections[coll]!.fields[f] = t;
|
|
1740
|
+
}
|
|
1741
|
+
c.copies = { from, fields, to: link.to, at: at.doc };
|
|
1742
|
+
}
|
|
1743
|
+
const members = (seeds.members?.members ?? []) as { id: number; name: string }[];
|
|
1744
|
+
// 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)
|
|
1746
|
+
const held: Record<string, string> = {};
|
|
1747
|
+
for (const [app, m] of Object.entries(models).sort(([a], [b]) => a.localeCompare(b)))
|
|
1748
|
+
for (const c of Object.keys(m.collections)) {
|
|
1749
|
+
if (held[c] && dirs[held[c]] !== dirs[app])
|
|
1750
|
+
throw new Error(`${held[c]} and ${app} both have a collection named ${c}`);
|
|
1751
|
+
held[c] ??= app;
|
|
1752
|
+
}
|
|
1753
|
+
/** Which other document holds each collection an app's document doesn't. */
|
|
1754
|
+
const holdersOf = (app: string): Record<string, string> =>
|
|
1755
|
+
Object.fromEntries(
|
|
1756
|
+
Object.entries(models)
|
|
1757
|
+
.filter(([a]) => a !== app)
|
|
1758
|
+
.flatMap(([, m]) => Object.keys(m.collections).map((c) => [c, m.doc])),
|
|
1759
|
+
);
|
|
1760
|
+
/** Each does's grants in an app, to the named role its teller has on the seeds, or member. */
|
|
1761
|
+
/** What each person sees of each of a document's collections (its owns), as SQL of a row, `t`: a collection owns
|
|
1762
|
+
* doesn't name, everyone's. */
|
|
1763
|
+
const ownsOf = (app: string): Record<string, string> => {
|
|
1764
|
+
const { owns, roles = {}, kind } = defs[app]!;
|
|
1765
|
+
if (!owns) return {};
|
|
1766
|
+
const m = models[app]!;
|
|
1767
|
+
const by = typeof owns === "string" ? Object.fromEntries(Object.keys(m.collections).map((c) => [c, owns])) : owns;
|
|
1768
|
+
const types = (c: string) => Object.values(models).find((x) => x.collections[c])?.collections[c]?.fields ?? {};
|
|
1769
|
+
const who = {
|
|
1770
|
+
roles,
|
|
1771
|
+
list: (c: string, f: string) => types(c)[f] === "ids",
|
|
1772
|
+
own: Object.keys(m.collections),
|
|
1773
|
+
...(kind ? { kind: { column: m.doc, root: kind.root } } : {}),
|
|
1774
|
+
};
|
|
1775
|
+
return Object.fromEntries(
|
|
1776
|
+
Object.entries(by).map(([c, path]) => [c, `(${whoSql(path, c, "t", who, `${app}'s owns`)})`]),
|
|
1777
|
+
);
|
|
1778
|
+
};
|
|
1779
|
+
/** 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[] }> = {};
|
|
1781
|
+
const grantsFor = (app: string) => {
|
|
1782
|
+
if (granted[app]) return granted[app]!;
|
|
1783
|
+
const roles = Object.entries(defs[app]!.roles ?? {}).map(
|
|
1784
|
+
([r, path]) => [r, whoFn(whoCode(path, [], app, !!defs[app]!.kind))] as const,
|
|
1785
|
+
);
|
|
1786
|
+
const memberOf = (name: string) => {
|
|
1787
|
+
const as = name in casts[app]! ? casts[app]![name] : name;
|
|
1788
|
+
return members.find((x) => x.name.toLowerCase() === as?.toLowerCase())?.id;
|
|
1789
|
+
};
|
|
1790
|
+
// a document as a story finds it (the seeds, its premise written on them); an instance of a kind, its items
|
|
1791
|
+
const readIn = (state: typeof seeds) => (d: string) => {
|
|
1792
|
+
const [name, n] = d.split("?")[0]!.split(":") as [string, string?];
|
|
1793
|
+
const seed = state[name] ?? {};
|
|
1794
|
+
if (!n) return seed;
|
|
1795
|
+
return Object.fromEntries(
|
|
1796
|
+
Object.entries(seed).map(([c, v]) => [c, Array.isArray(v) ? v.filter((i) => i[name] === Number(n)) : v]),
|
|
1797
|
+
);
|
|
1798
|
+
};
|
|
1799
|
+
// a kind's role's @field is its root item's
|
|
1800
|
+
const k = defs[app]!.kind;
|
|
1801
|
+
const rootOf = (d: string, state = seeds) =>
|
|
1802
|
+
k &&
|
|
1803
|
+
(readIn(state)(holdersOf(app)[k.root]!)[k.root] as { id: number }[] | undefined)?.find(
|
|
1804
|
+
(i) => i.id === Number(docParts(d).key),
|
|
1805
|
+
);
|
|
1806
|
+
// the item an op is to, as the story finds it (an add's, its value): one of a table any of the app's seeds gives
|
|
1807
|
+
const itemOf = (d: string, o?: Op, state = seeds): any => {
|
|
1808
|
+
if (!o) return undefined;
|
|
1809
|
+
const { coll, key } = parts(o.path);
|
|
1810
|
+
if (key === "-") return o.value;
|
|
1811
|
+
const rows = Object.values(models)
|
|
1812
|
+
.filter((m) => dirs[m.doc] === dirs[app])
|
|
1813
|
+
.map((m) => state[m.doc]?.[coll])
|
|
1814
|
+
.find(Array.isArray) as { id: number }[] | undefined;
|
|
1815
|
+
return rows?.find((i) => i.id === Number(key));
|
|
1816
|
+
};
|
|
1817
|
+
const { moves, guests } = defs[app]!;
|
|
1818
|
+
// each story's state, its premise written on the seeds as the server would write it, and in a story of several
|
|
1819
|
+
// writes the parts before its own (src/together.ts), which name its document: once a story (none, no premise: the
|
|
1820
|
+
// seeds)
|
|
1821
|
+
const fillsOf = (doc: string, coll: string) => defs[doc]?.fills?.[coll];
|
|
1822
|
+
const states = new WeakMap<Story, ReturnType<typeof writtenBefore>>();
|
|
1823
|
+
const writtenOf = (s: Story = { story: "" }) =>
|
|
1824
|
+
states.get(s) ??
|
|
1825
|
+
states
|
|
1826
|
+
.set(
|
|
1827
|
+
s,
|
|
1828
|
+
writtenBefore(
|
|
1829
|
+
s,
|
|
1830
|
+
premised(seeds, s.premise, fillsOf, memberOf),
|
|
1831
|
+
(state, w) => premised(state, s.as === undefined ? [w] : { [s.as]: [w] }, fillsOf, memberOf),
|
|
1832
|
+
(name) => defs[name]?.kind?.root,
|
|
1833
|
+
),
|
|
1834
|
+
)
|
|
1835
|
+
.get(s)!;
|
|
1836
|
+
const stateOf = (s?: Story) => writtenOf(s).state;
|
|
1837
|
+
const rolesOf = (m: number | null, doc: string, o?: Op, s?: Story) => {
|
|
1838
|
+
const { state, name } = writtenOf(s),
|
|
1839
|
+
d = name(doc),
|
|
1840
|
+
at = k ? rootOf(d, state) : itemOf(d, o, state);
|
|
1841
|
+
// (in a kind, an @field the item has is the item's: `at` the root, the item beside it)
|
|
1842
|
+
const named =
|
|
1843
|
+
m === null
|
|
1844
|
+
? []
|
|
1845
|
+
: roles
|
|
1846
|
+
.filter(([, is]) => is(m, readIn(state), [], at, d, k ? itemOf(d, o, state) : undefined))
|
|
1847
|
+
.map(([r]) => r);
|
|
1848
|
+
// 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
|
+
const root = k && guests?.[k.root],
|
|
1850
|
+
code = o && (root || guests?.[parts(o.path).coll]),
|
|
1851
|
+
of = root ? at : itemOf(d, o, state),
|
|
1852
|
+
given = docParts(d).params;
|
|
1853
|
+
return code && of && given[code] !== undefined && of[code] === given[code]
|
|
1854
|
+
? [...named, guestRole(defs[app]!, of)]
|
|
1855
|
+
: named;
|
|
1856
|
+
};
|
|
1857
|
+
// a step of a field that moves only as the stories move it: from where the story finds its item, to the value;
|
|
1858
|
+
// an add giving it, a step from nothing
|
|
1859
|
+
const keyOf = (o: Op, d: string, s?: Story) => {
|
|
1860
|
+
const { coll, key, field } = parts(o.path);
|
|
1861
|
+
const moved = moves?.[coll];
|
|
1862
|
+
if (o.op === "add" && key === "-" && field === undefined && moved && (o.value as any)?.[moved] !== undefined)
|
|
1863
|
+
return `${grantOf(o)}.${moved}:>${(o.value as any)[moved]}`;
|
|
1864
|
+
return o.op === "replace" && field !== undefined && moved === field
|
|
1865
|
+
? `${grantOf(o)}:${itemOf(d, o, stateOf(s))?.[field!]}>${o.value}`
|
|
1866
|
+
: grantOf(o);
|
|
1867
|
+
};
|
|
1868
|
+
const grants = grantsOf(stories[app]!, rolesOf, memberOf, keyOf);
|
|
1869
|
+
const rolesOfTeller = (s: Story) => {
|
|
1870
|
+
const w = (s.does ?? s.cannot)!;
|
|
1871
|
+
// 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);
|
|
1873
|
+
const m = memberOf(s.as);
|
|
1874
|
+
return m === undefined ? [] : rolesOf(m, w.doc, undefined, s);
|
|
1875
|
+
};
|
|
1876
|
+
return (granted[app] = { grants, rolesOfTeller });
|
|
1877
|
+
};
|
|
1878
|
+
/** A document's grants, once no definition of its is a guess: each must be checked by a story (a role, by any of
|
|
1879
|
+
* the app's documents). */
|
|
1880
|
+
const checkedFor = (app: string) => {
|
|
1881
|
+
const { grants, rolesOfTeller } = grantsFor(app);
|
|
1882
|
+
const siblings = Object.keys(models)
|
|
1883
|
+
.filter((u) => u !== app && dirs[u] === dirs[app] && stories[u]?.length)
|
|
1884
|
+
.map((u) => ({ defs: defs[u]!, stories: stories[u]!, ...grantsFor(u) }));
|
|
1885
|
+
// (a kind's settings are its root's fields, wherever that's held)
|
|
1886
|
+
const fieldsOf = (coll: string) =>
|
|
1887
|
+
Object.values(models).find((m) => m.collections[coll])?.collections[coll]!.fields;
|
|
1888
|
+
const why =
|
|
1889
|
+
settingsSaid(defs[app]!, fieldsOf) ?? unchecked(defs[app]!, stories[app]!, grants, rolesOfTeller, siblings);
|
|
1890
|
+
if (why) throw new Error(`${app}'s stories: ${why}`);
|
|
1891
|
+
return grants;
|
|
1892
|
+
};
|
|
1893
|
+
const out: Record<
|
|
1894
|
+
string,
|
|
1895
|
+
{
|
|
1896
|
+
dir: string;
|
|
1897
|
+
doc: string;
|
|
1898
|
+
model: Model;
|
|
1899
|
+
rules: string;
|
|
1900
|
+
elements: string;
|
|
1901
|
+
queries: string | null;
|
|
1902
|
+
tables: Record<string, Table>;
|
|
1903
|
+
/** Its files' names: a unit of an app of several documents, named for it (catalogue.rules.ts). */
|
|
1904
|
+
prefix: string;
|
|
1905
|
+
}
|
|
1906
|
+
> = {};
|
|
1907
|
+
for (const app of Object.keys(models).sort()) {
|
|
1908
|
+
const holders = holdersOf(app);
|
|
1909
|
+
// named from joined's own folder for its members, and from the apps' folder's for theirs
|
|
1910
|
+
const from = relative(
|
|
1911
|
+
dirs[app] === OWN ? `${import.meta.dir}/..` : `${dir}/..`,
|
|
1912
|
+
`${dirs[app]}/${derivedFrom[app] ? "derive.ts" : statics.has(app) ? `${app}.json` : "stories.jsonl"}`,
|
|
1913
|
+
);
|
|
1914
|
+
for (const d of derivedFrom[app] ?? [])
|
|
1915
|
+
if (!Object.values(models).some((m) => m.doc === d))
|
|
1916
|
+
throw new Error(`${from}: ${d} is derived from, but no app writes it`);
|
|
1917
|
+
const links = linksOf(models[app]!, defs[app]!, holders, from);
|
|
1918
|
+
out[app] = {
|
|
1919
|
+
dir: dirs[app]!,
|
|
1920
|
+
doc: models[app]!.doc,
|
|
1921
|
+
model: models[app]!,
|
|
1922
|
+
// a derived document is kept nowhere: it has no tables
|
|
1923
|
+
prefix: split.has(app) ? `${app}.` : "",
|
|
1924
|
+
tables:
|
|
1925
|
+
derivedFrom[app] || readOnly[app]
|
|
1926
|
+
? {}
|
|
1927
|
+
: tablesOf(
|
|
1928
|
+
models[app]!,
|
|
1929
|
+
await seedOf(`${dirs[app]}/${models[app]!.doc}.json`),
|
|
1930
|
+
defs[app]!.kind && { column: models[app]!.doc, root: defs[app]!.kind!.root },
|
|
1931
|
+
links,
|
|
1932
|
+
),
|
|
1933
|
+
// a derived document is kept nowhere: it has no query either
|
|
1934
|
+
queries: derivedFrom[app]
|
|
1935
|
+
? null
|
|
1936
|
+
: readOnly[app]
|
|
1937
|
+
? queryOf(models[app]!, from, readOnly[app]!)
|
|
1938
|
+
: queriesOf(
|
|
1939
|
+
models[app]!,
|
|
1940
|
+
from,
|
|
1941
|
+
defs[app]!.kind && models[app]!.doc,
|
|
1942
|
+
defs[app]!.window,
|
|
1943
|
+
defs[app]!.where?.[models[app]!.doc],
|
|
1944
|
+
links,
|
|
1945
|
+
ownsOf(app),
|
|
1946
|
+
(d) =>
|
|
1947
|
+
takesSql(defs[app]!, models[app]!.collections, links, defs[app]!.kind && models[app]!.doc, from, d),
|
|
1948
|
+
defs[app]!.order,
|
|
1949
|
+
),
|
|
1950
|
+
...compile(
|
|
1951
|
+
models[app]!,
|
|
1952
|
+
from,
|
|
1953
|
+
holders,
|
|
1954
|
+
defs[app],
|
|
1955
|
+
checkedFor(app),
|
|
1956
|
+
// a document with guests is held by them as guests, not by anyone
|
|
1957
|
+
anonymousOf[app] ?? (stories[app]!.every((s) => s.as === undefined) && !defs[app]!.guests),
|
|
1958
|
+
derivedFrom[app],
|
|
1959
|
+
statics.has(app),
|
|
1960
|
+
readOnly[app],
|
|
1961
|
+
split.has(app) ? `${app}.` : "",
|
|
1962
|
+
),
|
|
1963
|
+
};
|
|
1964
|
+
}
|
|
1965
|
+
return out;
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
/** A who-path's code as a function, to find who the stories' tellers are on the seeds as it compiles. */
|
|
1969
|
+
const whoFn = (code: string) =>
|
|
1970
|
+
new Function(
|
|
1971
|
+
`${new Bun.Transpiler({ loader: "ts" }).transformSync(`const is = (m: number, read: any, roles: string[], item: any, doc: string, at?: any) => ${code};`)} return is;`,
|
|
1972
|
+
)() as (m: number, read: (doc: string) => any, roles: string[], item: unknown, doc: string, at?: unknown) => boolean;
|
|
1973
|
+
|
|
1974
|
+
/** An app's seed, where its stories start (none: nothing seeded). */
|
|
1975
|
+
const seedOf = async (file: string) => ((await Bun.file(file).exists()) ? await Bun.file(file).json() : {});
|
|
1976
|
+
|
|
1977
|
+
/** Each app's generated/, written where it changed (the members' never does, unless joined's own stories
|
|
1978
|
+
* have: a project using joined writes nothing into it), and its next migration if the stories need one;
|
|
1979
|
+
* what was done, said, and a field an add needed and no longer does, with the story that let it go. */
|
|
1980
|
+
export async function writeAll(dir = APPS) {
|
|
1981
|
+
const out = await compiled(dir);
|
|
1982
|
+
const said = [`compiled ${Object.keys(out).join(", ")} → generated/`];
|
|
1983
|
+
// an app's tables are its own, whichever of its documents reads them: one history of them, the folder's
|
|
1984
|
+
const ofDir = new Map<string, Record<string, Table>>();
|
|
1985
|
+
for (const { dir, tables } of Object.values(out)) {
|
|
1986
|
+
// a table each of its documents has: what an add needs, from the one that adds
|
|
1987
|
+
const had = ofDir.get(dir) ?? {};
|
|
1988
|
+
for (const [k, t] of Object.entries(tables)) if (!had[k] || (t.needs && !had[k]!.needs)) had[k] = t;
|
|
1989
|
+
ofDir.set(dir, had);
|
|
1990
|
+
}
|
|
1991
|
+
const migrated = new Set<string>();
|
|
1992
|
+
for (const { dir, doc, model, rules, elements, queries, prefix } of Object.values(out)) {
|
|
1993
|
+
said.push(...loosened(await neededBefore(`${dir}/generated/${prefix}rules.ts`), model));
|
|
1994
|
+
await changed(`${dir}/generated/${prefix}rules.ts`, rules);
|
|
1995
|
+
await changed(`${dir}/generated/${prefix}elements.ts`, elements);
|
|
1996
|
+
if (queries) await changed(`${dir}/generated/${prefix}queries.ts`, queries);
|
|
1997
|
+
if (migrated.has(dir)) continue;
|
|
1998
|
+
migrated.add(dir);
|
|
1999
|
+
const tables = Object.fromEntries(Object.entries(ofDir.get(dir)!).sort(([a], [b]) => a.localeCompare(b)));
|
|
2000
|
+
const next = await nextMigration(`${dir}/migrations`, prefix ? basename(dir) : doc, tables);
|
|
2001
|
+
if (!next) continue;
|
|
2002
|
+
await Bun.write(next.file, next.text);
|
|
2003
|
+
said.push(`migration ${relative(process.cwd(), next.file)}`, ...next.byHand.map((b) => ` by hand: ${b}`));
|
|
2004
|
+
}
|
|
2005
|
+
return said.join("\n");
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
/** What each collection's add needed, as an app's generated/rules.ts said before it's written again: none, if
|
|
2009
|
+
* it's new. */
|
|
2010
|
+
async function neededBefore(file: string): Promise<Record<string, string[]>> {
|
|
2011
|
+
const f = Bun.file(file);
|
|
2012
|
+
const shape = (await f.exists()) && /export const collections = (\{[\s\S]*?\n\}) as const;/.exec(await f.text());
|
|
2013
|
+
if (!shape) return {};
|
|
2014
|
+
const colls = JSON.parse(shape[1]!) as Record<string, { needs?: string[] }>;
|
|
2015
|
+
return Object.fromEntries(Object.entries(colls).map(([c, { needs = [] }]) => [c, needs]));
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
/** A field an add needed before and no longer does, said with the story that adds one without it: the server now
|
|
2019
|
+
* takes an add without it, which no migration shows where its column could be empty already. */
|
|
2020
|
+
const loosened = (before: Record<string, string[]>, { doc, collections }: Model) =>
|
|
2021
|
+
Object.entries(collections).flatMap(([coll, c]) =>
|
|
2022
|
+
(c.adds ? (before[coll] ?? []) : [])
|
|
2023
|
+
.filter((f) => c.fields[f] && !c.required.includes(f))
|
|
2024
|
+
.map((f) => {
|
|
2025
|
+
const by = c.adding.find((a) => !a.fields.includes(f))!.story;
|
|
2026
|
+
return ` ${doc}: ${an(itemOf(coll)!)} no longer needs ${f}: "${by}" adds one without it`;
|
|
2027
|
+
}),
|
|
2028
|
+
);
|
|
2029
|
+
|
|
2030
|
+
/** A file written only where its text is new. */
|
|
2031
|
+
async function changed(file: string, text: string) {
|
|
2032
|
+
const f = Bun.file(file);
|
|
2033
|
+
if (!(await f.exists()) || (await f.text()) !== text) await Bun.write(file, text);
|
|
2034
|
+
}
|