@blueshed/joined 0.0.0-stage → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/.claude/skills/joined/SKILL.md +17 -0
  2. package/.claude/skills/joined/reference.md +768 -0
  3. package/LICENSE +19 -0
  4. package/README.md +115 -2
  5. package/docs/design.md +148 -0
  6. package/docs/introduction.md +193 -0
  7. package/docs/learning.md +76 -0
  8. package/docs/stories.md +82 -0
  9. package/examples/app.css +27 -0
  10. package/examples/cafe/books.html +38 -0
  11. package/examples/cafe/books.json +13 -0
  12. package/examples/cafe/books.ts +64 -0
  13. package/examples/cafe/cafe.css +512 -0
  14. package/examples/cafe/front.html +115 -0
  15. package/examples/cafe/front.ts +7 -0
  16. package/examples/cafe/generated/books.elements.ts +52 -0
  17. package/examples/cafe/generated/books.queries.ts +11 -0
  18. package/examples/cafe/generated/books.rules.ts +42 -0
  19. package/examples/cafe/generated/kitchen.elements.ts +87 -0
  20. package/examples/cafe/generated/kitchen.queries.ts +47 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +98 -0
  22. package/examples/cafe/generated/menu.elements.ts +61 -0
  23. package/examples/cafe/generated/menu.queries.ts +28 -0
  24. package/examples/cafe/generated/menu.rules.ts +65 -0
  25. package/examples/cafe/generated/order.elements.ts +87 -0
  26. package/examples/cafe/generated/order.queries.ts +47 -0
  27. package/examples/cafe/generated/order.rules.ts +95 -0
  28. package/examples/cafe/generated/staff.elements.ts +55 -0
  29. package/examples/cafe/generated/staff.queries.ts +27 -0
  30. package/examples/cafe/generated/staff.rules.ts +59 -0
  31. package/examples/cafe/generated/supplies.elements.ts +62 -0
  32. package/examples/cafe/generated/supplies.queries.ts +43 -0
  33. package/examples/cafe/generated/supplies.rules.ts +84 -0
  34. package/examples/cafe/generated/till.elements.ts +93 -0
  35. package/examples/cafe/generated/till.queries.ts +57 -0
  36. package/examples/cafe/generated/till.rules.ts +113 -0
  37. package/examples/cafe/index.html +70 -0
  38. package/examples/cafe/kitchen.css +107 -0
  39. package/examples/cafe/kitchen.html +39 -0
  40. package/examples/cafe/kitchen.ts +125 -0
  41. package/examples/cafe/menu.html +55 -0
  42. package/examples/cafe/menu.json +41 -0
  43. package/examples/cafe/menu.ts +84 -0
  44. package/examples/cafe/migrations/001-cafe.ts +11 -0
  45. package/examples/cafe/order.html +37 -0
  46. package/examples/cafe/order.ts +45 -0
  47. package/examples/cafe/rail-drag.ts +30 -0
  48. package/examples/cafe/routes.ts +32 -0
  49. package/examples/cafe/staff.json +20 -0
  50. package/examples/cafe/stories.jsonl +43 -0
  51. package/examples/cafe/supplies.html +77 -0
  52. package/examples/cafe/supplies.json +33 -0
  53. package/examples/cafe/supplies.ts +170 -0
  54. package/examples/cafe/till.json +95 -0
  55. package/examples/cafe/till.ts +122 -0
  56. package/examples/cafe/trust.ts +20 -0
  57. package/examples/cafe/views.ts +171 -0
  58. package/examples/docs.ts +28 -0
  59. package/examples/film.jpg +0 -0
  60. package/examples/hello/generated/elements.ts +45 -0
  61. package/examples/hello/generated/queries.ts +24 -0
  62. package/examples/hello/generated/rules.ts +45 -0
  63. package/examples/hello/hello.css +27 -0
  64. package/examples/hello/hello.json +1 -0
  65. package/examples/hello/index.html +32 -0
  66. package/examples/hello/migrations/001-hello.ts +6 -0
  67. package/examples/hello/page.ts +49 -0
  68. package/examples/hello/routes.ts +6 -0
  69. package/examples/hello/stories.jsonl +3 -0
  70. package/examples/index.html +146 -0
  71. package/examples/page.ts +11 -0
  72. package/examples/people/adding.ts +20 -0
  73. package/examples/people/generated/elements.ts +68 -0
  74. package/examples/people/generated/queries.ts +28 -0
  75. package/examples/people/generated/rules.ts +85 -0
  76. package/examples/people/links.ts +124 -0
  77. package/examples/people/migrations/001-people.ts +6 -0
  78. package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
  79. package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
  80. package/examples/people/order.ts +61 -0
  81. package/examples/people/people.css +65 -0
  82. package/examples/people/people.json +26 -0
  83. package/examples/people/routes.ts +12 -0
  84. package/examples/people/stories.jsonl +20 -0
  85. package/examples/people/trust.ts +14 -0
  86. package/examples/people/view.ts +115 -0
  87. package/examples/routes.ts +11 -0
  88. package/examples/trip/answer-rows.ts +70 -0
  89. package/examples/trip/answers.ts +11 -0
  90. package/examples/trip/bar.ts +89 -0
  91. package/examples/trip/calendar-map.css +709 -0
  92. package/examples/trip/calendar-map.ts +249 -0
  93. package/examples/trip/drags.ts +143 -0
  94. package/examples/trip/drawer.ts +250 -0
  95. package/examples/trip/event-form.ts +199 -0
  96. package/examples/trip/generated/elements.ts +144 -0
  97. package/examples/trip/generated/queries.ts +46 -0
  98. package/examples/trip/generated/rules.ts +239 -0
  99. package/examples/trip/holding.ts +61 -0
  100. package/examples/trip/ics.ts +117 -0
  101. package/examples/trip/index.html +82 -0
  102. package/examples/trip/line-stops.ts +92 -0
  103. package/examples/trip/line-words.ts +79 -0
  104. package/examples/trip/line.ts +121 -0
  105. package/examples/trip/map.ts +234 -0
  106. package/examples/trip/mercator.ts +28 -0
  107. package/examples/trip/migrations/001-trip.ts +7 -0
  108. package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
  109. package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
  110. package/examples/trip/migrations/004-create-stays.ts +6 -0
  111. package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
  112. package/examples/trip/month.ts +87 -0
  113. package/examples/trip/other-weeks.ts +67 -0
  114. package/examples/trip/page.ts +121 -0
  115. package/examples/trip/peek.ts +71 -0
  116. package/examples/trip/people-chips.ts +74 -0
  117. package/examples/trip/place-search.ts +51 -0
  118. package/examples/trip/places.ts +34 -0
  119. package/examples/trip/routes.ts +27 -0
  120. package/examples/trip/shell.ts +39 -0
  121. package/examples/trip/stays.css +51 -0
  122. package/examples/trip/stays.ts +68 -0
  123. package/examples/trip/stories.jsonl +72 -0
  124. package/examples/trip/time.ts +46 -0
  125. package/examples/trip/told.ts +48 -0
  126. package/examples/trip/trip.json +69 -0
  127. package/examples/trip/trust.ts +51 -0
  128. package/examples/trip/week.ts +237 -0
  129. package/examples/trip/words.ts +4 -0
  130. package/examples/trip/writes.ts +91 -0
  131. package/examples/trip/zones.ts +16 -0
  132. package/examples/trips/card.ts +149 -0
  133. package/examples/trips/generated/elements.ts +60 -0
  134. package/examples/trips/generated/queries.ts +28 -0
  135. package/examples/trips/generated/rules.ts +62 -0
  136. package/examples/trips/index.html +47 -0
  137. package/examples/trips/map.ts +52 -0
  138. package/examples/trips/migrations/001-trips.ts +8 -0
  139. package/examples/trips/new-trip.ts +46 -0
  140. package/examples/trips/page.ts +9 -0
  141. package/examples/trips/routes.ts +7 -0
  142. package/examples/trips/stories.jsonl +12 -0
  143. package/examples/trips/trips.css +183 -0
  144. package/examples/trips/trips.json +7 -0
  145. package/examples/weeks/derive.ts +23 -0
  146. package/examples/weeks/generated/elements.ts +52 -0
  147. package/examples/weeks/generated/rules.ts +33 -0
  148. package/examples/weeks/routes.ts +4 -0
  149. package/examples/weeks/weeks.json +1 -0
  150. package/examples/welcome.css +299 -0
  151. package/package.json +55 -4
  152. package/src/attachment.ts +70 -0
  153. package/src/cli.ts +52 -0
  154. package/src/client.ts +98 -0
  155. package/src/compile.ts +2034 -0
  156. package/src/css.d.ts +5 -0
  157. package/src/definitions.ts +268 -0
  158. package/src/demo.css +29 -0
  159. package/src/demo.ts +42 -0
  160. package/src/draft.ts +69 -0
  161. package/src/engine.ts +288 -0
  162. package/src/file-value.ts +13 -0
  163. package/src/files.ts +187 -0
  164. package/src/follow.ts +56 -0
  165. package/src/hues.ts +3 -0
  166. package/src/icon-names.ts +77 -0
  167. package/src/icon.png +0 -0
  168. package/src/icons.ts +32 -0
  169. package/src/keep.ts +33 -0
  170. package/src/link.ts +31 -0
  171. package/src/mcp.ts +252 -0
  172. package/src/members/demo.ts +53 -0
  173. package/src/members/generated/elements.ts +68 -0
  174. package/src/members/generated/queries.ts +29 -0
  175. package/src/members/generated/rules.ts +65 -0
  176. package/src/members/group.ts +294 -0
  177. package/src/members/keys.ts +221 -0
  178. package/src/members/members.json +9 -0
  179. package/src/members/migrations/001-members.ts +6 -0
  180. package/src/members/migrations/002-guard-members.ts +11 -0
  181. package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
  182. package/src/members/panel.css +208 -0
  183. package/src/members/panel.ts +398 -0
  184. package/src/members/routes.ts +4 -0
  185. package/src/members/stories.jsonl +27 -0
  186. package/src/members/trust.ts +116 -0
  187. package/src/migrate.ts +597 -0
  188. package/src/migrations/001-joined.ts +13 -0
  189. package/src/migrations/002-group-keys.ts +16 -0
  190. package/src/migrations/003-change-inverse.ts +10 -0
  191. package/src/migrations/004-change-followed.ts +6 -0
  192. package/src/ops.ts +61 -0
  193. package/src/page.css +79 -0
  194. package/src/page.ts +413 -0
  195. package/src/parts.css +471 -0
  196. package/src/parts.ts +152 -0
  197. package/src/server.ts +862 -0
  198. package/src/settings.ts +94 -0
  199. package/src/starter.ts +89 -0
  200. package/src/store.ts +815 -0
  201. package/src/stories.ts +387 -0
  202. package/src/toast.ts +52 -0
  203. package/src/together.ts +167 -0
  204. package/src/tokens.css +85 -0
  205. package/src/tokens.json +457 -0
  206. package/src/upkeep.ts +86 -0
  207. package/src/visitors.ts +43 -0
  208. package/src/write.ts +567 -0
  209. package/starter/CLAUDE.md +37 -0
  210. package/starter/gitignore +3 -0
  211. package/starter/tests/hello-page.test.ts +14 -0
  212. package/starter/tests/hello.test.ts +8 -0
  213. package/starter/tsconfig.json +17 -0
package/src/store.ts ADDED
@@ -0,0 +1,815 @@
1
+ // Where the documents are kept (the skill's reference, §14): one database, SQLite's file or Postgres's folder (the
2
+ // engine, src/engine.ts), made by migrations. joined's own
3
+ // tables first (src/migrations: each document's version, and every change), then each app's, which
4
+ // the compiler writes from its stories (<app>/migrations): a collection a table, a field a column, a
5
+ // list of ids a table of pairs. A write is one transaction, and synchronous, so nothing comes between its parts.
6
+ // The database notes each row it changes, whoever changed it (the write, or a rule as it follows: a trigger per
7
+ // table, as the row was before its first change); once the write is done, each document holding a row it changed
8
+ // is told it in its own paths (an item come into it added, one gone removed, a field changed replaced), a row of
9
+ // its change each, at its next version. Once it commits, the changes are the server's to publish. A page catching
10
+ // up is sent the changes since the version it had; an old change it can't need is let go (`trim`).
11
+
12
+ import { existsSync } from "node:fs";
13
+ import { dropTriggerSql, Refused, triggerSql, type Engine } from "./engine.ts";
14
+ import {
15
+ dropTriggers,
16
+ fromFolder,
17
+ guardHeld,
18
+ linked,
19
+ migrate,
20
+ nextId as nextIdIn,
21
+ passed,
22
+ stateOf,
23
+ type State,
24
+ } from "./migrate.ts";
25
+ import { docParts, parts, valueAt, type Change, type Op, type Type } from "./ops.ts";
26
+
27
+ /** An app's compiled rules, as the store reads them: its document, each collection's tag, fields and links (the
28
+ * collection each is to), and its kind: a document for each item of another's collection (doc:root), its rows
29
+ * kept with it by a column. */
30
+ export type Rules = {
31
+ doc: string;
32
+ collections: Record<
33
+ string,
34
+ {
35
+ place: string;
36
+ tag: string;
37
+ fields: Record<string, Type>;
38
+ links: Record<string, string>;
39
+ /** Its links that go with what they point at: that item removed, this one is removed first. */
40
+ goes?: string[];
41
+ fills?: Record<string, unknown>;
42
+ timed?: string;
43
+ own?: boolean;
44
+ copies?: { from: string; fields: string[]; to: string; at: string };
45
+ }
46
+ >;
47
+ kind: { root: string; doc: string; column: string } | null;
48
+ /** The field holding an item's own code (definitions' guests); of a kind, its root's: a board's secret link. */
49
+ guests?: Record<string, string>;
50
+ /** The document as one statement over its tables (generated/queries.ts): $doc, $key of a kind's instance, and
51
+ * each of its window's parameters. */
52
+ query: string;
53
+ /** Each collection's item as one row of its table (`t`) is it, in SQL: what the query gathers, and what's kept of
54
+ * a row a write changes. */
55
+ items?: Record<string, string>;
56
+ /** Its rules over values (definitions' takes), as triggers made in the database. */
57
+ triggers?: readonly string[];
58
+ /** Its query, items and triggers in Postgres's SQL, where they're said differently. */
59
+ postgres?: { query: string; items?: Record<string, string>; triggers?: readonly string[] };
60
+ /** It holds only some of its tables' rows (definitions' where): told what changed of it as a whole, not by row. */
61
+ view?: boolean;
62
+ /** Read as each member has it (each side's books): the member a parameter of its query. */
63
+ member?: boolean;
64
+ /** Each person sees only some of it (owns): the member a parameter of its query (none: all of it). */
65
+ sees?: boolean | null;
66
+ /** The parts a page may hold alone, each collection's by its parameters: a field equal to it, or a date and time in
67
+ * the days from it. */
68
+ window?: Record<string, Record<string, string | { from: string; for: string }>> | null;
69
+ };
70
+ type Item = { id: number; [field: string]: unknown };
71
+ /** A document as a page is sent it whole: its version, and each collection's items. */
72
+ export type Doc = { version: number; [collection: string]: unknown };
73
+ /** A change as its row keeps it, beside what a page is told: the ops that put it back, the version it undoes, if
74
+ * it's an undo, and whether a rule made it, following a write. */
75
+ export type Kept = Change & { inverse: Op[]; undoes: number | null; followed: boolean };
76
+ /** A row a write changed, as the document holding it has it: its collection, its id, the item it was and is (none:
77
+ * added, or removed), and of a kind's, the instance it was and is of. */
78
+ export type Row = {
79
+ coll: string;
80
+ id: number;
81
+ before: Item | null;
82
+ after: Item | null;
83
+ was: number | null;
84
+ is: number | null;
85
+ };
86
+ /** A write the store won't make, and why: a page is told it in these words. */
87
+ export { Refused };
88
+
89
+ /** Two values the same, as JSON: an object's fields in any order, and nothing (null) the same as none. */
90
+ function same(a: unknown, b: unknown): boolean {
91
+ if (a === b || (a == null && b == null)) return true;
92
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
93
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
94
+ const keys = (o: object) => Object.keys(o).filter((k) => (o as any)[k] != null);
95
+ return keys(a).length === keys(b).length && keys(a).every((k) => same((a as any)[k], (b as any)[k]));
96
+ }
97
+
98
+ /** A document's window's parameters, in order. */
99
+ const windowOf = (rules: Rules) => [...new Set(Object.values(rules.window ?? {}).flatMap((w) => Object.keys(w)))];
100
+ /** A window as it's written, the one way it may be (a page and a topic name it so): its document, then each of its
101
+ * parameters given, in its order; null if one isn't its, or a date isn't one. */
102
+ /** The field holding a kind's root item's code (its definitions' guests naming the root): a page holding an instance
103
+ * by it is that item's guest (a board's secret link, `board:1?code=…`). None, but in a kind that says it. */
104
+ export const rootCode = (rules: Pick<Rules, "kind" | "guests">) =>
105
+ rules.kind ? rules.guests?.[rules.kind.root] : undefined;
106
+ /** The root item an instance of a kind is of (board:1's board), as the document holding it has it now. */
107
+ export const rootItem = (rules: Pick<Rules, "kind">, doc: string, read: (doc: string) => Doc) =>
108
+ (read(rules.kind!.doc)[rules.kind!.root] as Record<string, unknown>[] | undefined)?.find(
109
+ (i) => i.id === Number(docParts(doc).key),
110
+ );
111
+ const windowed = (base: string, rules: Rules, params: Record<string, string>) => {
112
+ // (a kind's instance held by its root's code, a guest's, is whole: its code is its name's, and holds back nothing)
113
+ const code = rootCode(rules);
114
+ const own = [...windowOf(rules), ...(code ? [code] : [])];
115
+ const ranged = new Set(
116
+ Object.values(rules.window ?? {}).flatMap((w) =>
117
+ Object.entries(w).flatMap(([p, by]) => (typeof by === "string" ? [] : [p])),
118
+ ),
119
+ );
120
+ if (Object.keys(params).some((p) => !own.includes(p) || (ranged.has(p) && !/^\d{4}-\d{2}-\d{2}$/.test(params[p]!))))
121
+ return null;
122
+ const given = own.filter((p) => p in params);
123
+ return given.length ? `${base}?${new URLSearchParams(given.map((p) => [p, params[p]!])).toString()}` : null;
124
+ };
125
+ /** A document's own fields, as its seed or its query gives them: its one item's, id 1. */
126
+ const ownOf = (doc: Record<string, unknown>) => ({
127
+ id: 1,
128
+ ...Object.fromEntries(Object.entries(doc).filter(([k, v]) => k !== "version" && !Array.isArray(v))),
129
+ });
130
+ /** An item's fields as its columns: an object's each named for both (terms.days). */
131
+ const flat = (v: Record<string, unknown>) =>
132
+ Object.fromEntries(
133
+ Object.entries(v).flatMap(([f, x]) =>
134
+ x && typeof x === "object" && !Array.isArray(x) ? Object.entries(x).map(([k, y]) => [`${f}.${k}`, y]) : [[f, x]],
135
+ ),
136
+ );
137
+ /** An item's columns as its fields: an object's (terms.days) in its object. */
138
+ const nest = (v: Record<string, unknown>) => {
139
+ const out: Record<string, any> = {};
140
+ for (const [f, x] of Object.entries(v)) {
141
+ const [o, sub] = f.split(".") as [string, string?];
142
+ if (sub === undefined) out[o] = x;
143
+ else (out[o] ??= {})[sub] = x;
144
+ }
145
+ return out;
146
+ };
147
+ /** An object's fields, its columns. */
148
+ const subsOf = (c: Rules["collections"][string], field: string) =>
149
+ Object.keys(c.fields).filter((f) => f.startsWith(`${field}.`));
150
+ /** An item, said: its element's name, without its prefix (j-person, a person). */
151
+ const an = (tag: string) => (/^j-[aeiou]/.test(tag) ? `an ${tag.slice(2)}` : `a ${tag.slice(2)}`);
152
+
153
+ /** An item's change as ops in its document's paths: added whole, removed, or each field changed replaced (one of an
154
+ * object's, by its own path), or removed where it's gone. `own`: a document's own fields (/greeting). */
155
+ export function rowOps(coll: string, before: Item | null, after: Item | null, own = false): Op[] {
156
+ if (!before && !after) return [];
157
+ const at = own ? "" : `/${coll}/${(after ?? before)!.id}`;
158
+ if (!before && !own) return [{ op: "add", path: `/${coll}/-`, value: after }];
159
+ if (!after) return own ? [] : [{ op: "remove", path: at }];
160
+ const ops: Op[] = [];
161
+ const field = (path: string, was: unknown, is: unknown) => {
162
+ if (same(was, is)) return;
163
+ ops.push(is === undefined || is === null ? { op: "remove", path } : { op: "replace", path, value: is });
164
+ };
165
+ const was = before ?? ({} as Item);
166
+ for (const f of new Set([...Object.keys(was), ...Object.keys(after)])) {
167
+ if (f === "id") continue;
168
+ const [b, a] = [was[f], after[f]];
169
+ const object = (v: unknown) => typeof v === "object" && v !== null && !Array.isArray(v);
170
+ if (object(b) || object(a))
171
+ for (const k of new Set([...Object.keys(b ?? {}), ...Object.keys(a ?? {})]))
172
+ field(`${at}/${f}/${k}`, (b as any)?.[k], (a as any)?.[k]);
173
+ else field(`${at}/${f}`, b, a);
174
+ }
175
+ return ops;
176
+ }
177
+ /** A document's change from what it was to what it is, as ops in its paths: each collection's items, by id. */
178
+ export function docOps(before: Doc, after: Doc): Op[] {
179
+ const ops: Op[] = [];
180
+ for (const coll of new Set([...Object.keys(before), ...Object.keys(after)])) {
181
+ if (coll === "version") continue;
182
+ const list = (d: Doc) => (Array.isArray(d[coll]) ? (d[coll] as Item[]) : []);
183
+ const had = new Map(list(before).map((i) => [i.id, i])),
184
+ has = new Map(list(after).map((i) => [i.id, i]));
185
+ for (const id of new Set([...had.keys(), ...has.keys()]))
186
+ ops.push(...rowOps(coll, had.get(id) ?? null, has.get(id) ?? null));
187
+ }
188
+ return ops;
189
+ }
190
+
191
+ const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
192
+ const OWN = `${import.meta.dir}/migrations`;
193
+ /** How many changes a page may be behind and still catch up by them, not the whole document. */
194
+ const BEHIND = 500;
195
+
196
+ /** The store in its database: migrated, joined's own and then each app's, in the order given. */
197
+ export async function openStore(db: Engine, given: { name: string; dir: string; rules: Rules }[]) {
198
+ // each app's SQL as its engine says it
199
+ const apps = given.map((a) => ({
200
+ ...a,
201
+ rules: { ...a.rules, ...(db.dialect === "postgres" ? a.rules.postgres : {}) },
202
+ }));
203
+ // what a write changes, noted by the database as each row was before its first change (none: added), whoever
204
+ // changes it, in the connection's own table; a Postgres store's triggers last, and are made again below
205
+ db.run(
206
+ `CREATE TEMP TABLE IF NOT EXISTS joined_touched (n ${db.dialect === "sqlite" ? "INTEGER PRIMARY KEY" : "SERIAL PRIMARY KEY"}, tbl TEXT NOT NULL, id INTEGER NOT NULL, was INTEGER, before TEXT, UNIQUE (tbl, id))`,
207
+ );
208
+ if (db.dialect === "postgres")
209
+ for (const like of ["joined_touch_%", "joined_takes_%", "joined_gives_%", "joined_totals_%"])
210
+ dropTriggers(db, like);
211
+ // each app's migrations, as its own: told its tables, so another's being there doesn't make it old here
212
+ const histories: Awaited<ReturnType<typeof fromFolder>>[] = [];
213
+ for (const [app, dir] of [["joined", OWN], ...apps.map((a) => [a.name, `${a.dir}/migrations`])] as const) {
214
+ const list = existsSync(dir) ? await fromFolder(dir) : [];
215
+ migrate(db, app, list);
216
+ histories.push(list);
217
+ }
218
+ // each link a foreign key (Postgres's made now) and guarded where it points, now every app's tables are there (one
219
+ // app's may link to another's after it)
220
+ const tables: State = Object.assign({}, ...histories.map(stateOf));
221
+ db.transaction(() => {
222
+ for (const [key, t] of Object.entries(tables)) (linked(db, key, t), guardHeld(db, key, t));
223
+ })();
224
+ // a collection the migrations made no table for, or a field no column (or pairs), or a kind's rows no column to be
225
+ // kept with their instance by: its stories changed, and weren't compiled (or a migration that had run was changed)
226
+ for (const { name, rules } of apps.filter((a) => !a.rules.member))
227
+ for (const [coll, c] of Object.entries(rules.collections)) {
228
+ const cols = db.columns(coll);
229
+ if (!cols.length) throw new Error(`${name}'s ${coll} has no table: bun run compile writes its migrations`);
230
+ for (const f of [...Object.keys(c.fields), ...(rules.kind ? [rules.kind.column] : [])])
231
+ if (c.fields[f] === "ids" ? !db.columns(`${coll}_${f}`).length : !cols.includes(f))
232
+ throw new Error(`${name}'s ${coll}.${f} has nowhere to be kept: bun run compile writes its migrations`);
233
+ }
234
+ const docs = new Map(apps.map((a) => [a.rules.doc, a.rules]));
235
+ /** The document holding each collection, and the column a kind's rows are kept with their instance by (a kind's
236
+ * root, its own, by its id). */
237
+ // (a document holding only some of a table's rows, its where's, is told what changed of it as a whole: a table
238
+ // whose documents are all such is noted, and told by row to none)
239
+ const holding = new Map<string, { rules: Rules | null; of: string; item: string }>();
240
+ for (const { rules } of apps)
241
+ for (const coll of Object.keys(rules.items ? rules.collections : {})) {
242
+ const k = rules.kind;
243
+ const of = !k ? "NULL" : `t.${q(k.column)}`;
244
+ if (!holding.get(coll)?.rules)
245
+ holding.set(coll, { rules: rules.view ? null : rules, of, item: rules.items![coll]! });
246
+ }
247
+ // a trigger on each table, and on its tables of pairs, its item's
248
+ const noted = `${db.temp}.joined_touched`;
249
+ for (const [coll, { of, item }] of holding) {
250
+ const rules = apps.find((a) => a.rules.collections[coll])!.rules;
251
+ const keep = (row: string) =>
252
+ `INSERT INTO ${noted} (tbl, id, was, before) SELECT '${coll}', t.id, ${of}, CAST(${item} AS TEXT) FROM ${q(coll)} t WHERE t.id = ${row} ON CONFLICT DO NOTHING;`;
253
+ const on = (name: string, event: string, table: string, body: string) =>
254
+ db.run(triggerSql(db.dialect, { name: `joined_touch_${name}`, at: "BEFORE", event, table, body, temp: true }));
255
+ on(
256
+ `${coll}_insert`,
257
+ "INSERT",
258
+ coll,
259
+ `INSERT INTO ${noted} (tbl, id) VALUES ('${coll}', NEW.id) ON CONFLICT DO NOTHING;`,
260
+ );
261
+ on(`${coll}_update`, "UPDATE", coll, keep("OLD.id"));
262
+ on(`${coll}_delete`, "DELETE", coll, keep("OLD.id"));
263
+ for (const [f, t] of Object.entries(rules.collections[coll]!.fields))
264
+ if (t === "ids") {
265
+ on(`${coll}_${f}_insert`, "INSERT", `${coll}_${f}`, keep(`NEW.${q(coll)}`));
266
+ on(`${coll}_${f}_delete`, "DELETE", `${coll}_${f}`, keep(`OLD.${q(coll)}`));
267
+ }
268
+ }
269
+ // the rules over values, run in each write's transaction: made once the seeds are in (a seed is the state as it
270
+ // is: a supply delivered before isn't delivered again as it's taken)
271
+ const ruled = apps.flatMap(({ rules }) => rules.triggers ?? []);
272
+ const rule = (on: boolean) => {
273
+ for (const sql of ruled) db.run(on ? sql : dropTriggerSql(db.dialect, sql));
274
+ };
275
+ rule(true);
276
+ /** The rows a write changed, in the order it first changed them: each as it was and is. */
277
+ const touched = (): Row[] =>
278
+ (
279
+ db.query(`SELECT tbl, id, was, before FROM ${noted} ORDER BY n`).all() as {
280
+ tbl: string;
281
+ id: number;
282
+ was: number | null;
283
+ before: string | null;
284
+ }[]
285
+ ).map(({ tbl, id, was, before }) => {
286
+ const { of, item } = holding.get(tbl)!;
287
+ const now = db
288
+ .query(`SELECT ${of} AS is_, CAST(${item} AS TEXT) AS item FROM ${q(tbl)} t WHERE t.id = ?`)
289
+ .get(id) as {
290
+ is_: number | null;
291
+ item: string;
292
+ } | null;
293
+ return {
294
+ coll: tbl,
295
+ id,
296
+ before: before === null ? null : JSON.parse(before),
297
+ after: now && JSON.parse(now.item),
298
+ was,
299
+ is: now?.is_ ?? null,
300
+ };
301
+ });
302
+ /** Each document a write's rows are in, by name (an instance's, shelf:1), and its ops in its own paths, with their
303
+ * inverse. The rows the write's own ops made, in the document written (`made`, by collection and id), are its ops
304
+ * as made. (An item never moves from one instance to another: no op writes the column it's kept with them by.) */
305
+ function told(rows: Row[], doc: string, made: Set<string>) {
306
+ const out = new Map<string, { ops: Op[]; inverse: Op[]; rows: Row[] }>();
307
+ const at = (name: string) => out.get(name) ?? out.set(name, { ops: [], inverse: [], rows: [] }).get(name)!;
308
+ for (const r of rows) {
309
+ const { rules } = holding.get(r.coll)!;
310
+ if (!rules) continue;
311
+ const own = !!rules.collections[r.coll]!.own;
312
+ const named = (n: number | null) => (rules.kind ? (n === null ? null : `${rules.doc}:${n}`) : rules.doc);
313
+ const name = named(r.after ? r.is : r.was);
314
+ if (!name) continue;
315
+ at(name).rows.push(r);
316
+ if (name === doc && made.has(`${r.coll}/${r.id}`)) continue;
317
+ at(name).ops.push(...rowOps(r.coll, r.before, r.after, own));
318
+ at(name).inverse.unshift(...rowOps(r.coll, r.after, r.before, own));
319
+ }
320
+ return out;
321
+ }
322
+ // a document's own fields are its one row's, there from the start (a store from before has it, empty)
323
+ for (const { rules } of apps)
324
+ for (const [coll, c] of Object.entries(rules.collections))
325
+ if (c.own) db.run(`INSERT INTO ${q(coll)} (id) VALUES (1) ON CONFLICT DO NOTHING`);
326
+ /** A document's rules, and, of a kind's instance (shelf:1), the column its rows are kept by and its root item.
327
+ * A name is one way of writing it alone: shelf:01 and shelf:1.0 are no document. */
328
+ const of = (doc: string) => {
329
+ const [, name = "", n] = /^([a-z][a-z0-9-]*)(?::([1-9]\d*))?$/.exec(doc) ?? [];
330
+ const rules = docs.get(name),
331
+ kind = rules?.kind;
332
+ return { rules, by: kind && n !== undefined ? { column: kind.column, n: Number(n) } : null };
333
+ };
334
+ /** The SQL that keeps a query to a document's own rows: an instance's, by its column. */
335
+ const mine = (doc: string, coll?: string) => {
336
+ const { rules, by } = of(doc);
337
+ return by ? { sql: ` AND ${q(by.column)} = ?`, args: [by.n] } : { sql: "", args: [] };
338
+ };
339
+ const collectionOf = (doc: string, coll: string) => {
340
+ const c = of(doc).rules?.collections[coll];
341
+ if (!c) throw new Refused(`${doc} has no ${coll}`);
342
+ return c;
343
+ };
344
+
345
+ const nextId = (coll: string) => nextIdIn(db, coll);
346
+
347
+ /** A field's value as a column holds it: a boolean 0 or 1, nothing null; anything else as it's given, for the
348
+ * table to hold to what it is. A Postgres column makes a value its type if it can (a number given for a string, its
349
+ * text): what it was given is asked first, in the words its CHECK has. */
350
+ const cell = (coll: string, f: string, t: Type, v: unknown) => {
351
+ const out = v === undefined ? null : t === "boolean" && typeof v === "boolean" ? +v : v;
352
+ const is = db.dialect === "postgres" && out !== null ? tables[coll]?.columns[f]?.is : undefined;
353
+ if (
354
+ is &&
355
+ !(is.type === "integer"
356
+ ? Number.isInteger(out)
357
+ : is.type === "decimal"
358
+ ? typeof out === "number"
359
+ : is.type === "boolean"
360
+ ? out === 0 || out === 1
361
+ : typeof out === "string" && (is.type === "string" || new RegExp(is.form!).test(out)))
362
+ )
363
+ throw new Refused(is.said);
364
+ return out;
365
+ };
366
+
367
+ /** A list's ids, each a pair: one named twice is refused by its table, in its words. */
368
+ function setPairs(coll: string, field: string, id: number, ids: number[]) {
369
+ db.run(`DELETE FROM ${q(`${coll}_${field}`)} WHERE ${q(coll)} = ?`, [id]);
370
+ for (const to of ids)
371
+ db.run(`INSERT INTO ${q(`${coll}_${field}`)} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
372
+ nextId(`${coll}_${field}`),
373
+ id,
374
+ to,
375
+ ]);
376
+ }
377
+
378
+ /** One id added to an item's list (its table refusing one there already, or one that's no item), or taken from
379
+ * it: refused if it isn't there. */
380
+ function pair(coll: string, field: string, id: number, to: number, add: boolean) {
381
+ const table = q(`${coll}_${field}`);
382
+ if (!add && !db.query(`SELECT 1 FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`).get(id, to))
383
+ throw new Refused(`${field} doesn't link to ${to}`);
384
+ if (add)
385
+ db.run(`INSERT INTO ${table} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
386
+ nextId(`${coll}_${field}`),
387
+ id,
388
+ to,
389
+ ]);
390
+ else db.run(`DELETE FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`, [id, to]);
391
+ }
392
+
393
+ /** The collection of a document's own fields (hello's), if it has them: named for it, of one item. */
394
+ const ownColl = (doc: string) =>
395
+ Object.entries(of(docParts(doc).base).rules?.collections ?? {}).find(([, c]) => c.own)?.[0];
396
+ /** A path to one of a document's own fields (/greeting), as its one item's (/hello/1/greeting); and back. */
397
+ const inward = (doc: string, o: Op): Op => {
398
+ const own = ownColl(doc);
399
+ return own && /^\/[a-z][a-z0-9-]*$/.test(o.path) ? { ...o, path: `/${own}/1${o.path}` } : o;
400
+ };
401
+ const outward = (doc: string, o: Op): Op => {
402
+ const own = ownColl(doc);
403
+ return own && o.path.startsWith(`/${own}/1/`) ? { ...o, path: o.path.slice(`/${own}/1`.length) } : o;
404
+ };
405
+
406
+ /** An item as the document has it: its fields, null ones left out, and its lists (none: left out). */
407
+ function itemAt(coll: string, c: Rules["collections"][string], id: number): Item {
408
+ const row = db.query(`SELECT * FROM ${q(coll)} WHERE id = ?`).get(id) as Item;
409
+ const item: Item = { id };
410
+ for (const [f, t] of Object.entries(c.fields)) {
411
+ if (t === "ids") {
412
+ const ids = db
413
+ .query(`SELECT ${q(f)} AS to_ FROM ${q(`${coll}_${f}`)} WHERE ${q(coll)} = ? ORDER BY id`)
414
+ .all(id) as { to_: number }[];
415
+ if (ids.length) item[f] = ids.map((r) => r.to_);
416
+ } else if (row[f] !== null) item[f] = t === "boolean" ? row[f] === 1 : row[f];
417
+ }
418
+ return item;
419
+ }
420
+
421
+ /** An op made on the rows, and the ops that put back what it did (its inverse): an add given the next id,
422
+ * which the pages are told, or, putting back an item removed, the id it had (an undo's, its value's id); an id
423
+ * added to a list or taken from it, the one pair. */
424
+ function apply(doc: string, o: Op, undoing: boolean): { applied: Op; inverse: Op[] } {
425
+ const { coll, key, field, link } = parts(o.path);
426
+ const c = collectionOf(doc, coll);
427
+ // one of an object's fields (/orders/1/terms/days, its column terms.days), or an object whole (/orders/1/terms)
428
+ const sub = field !== undefined && link !== undefined && !/^(\d+|-)$/.test(link) ? `${field}.${link}` : undefined;
429
+ const whole = field !== undefined && link === undefined && !(field in c.fields) ? subsOf(c, field) : [];
430
+ if (field !== undefined && (sub ? !(sub in c.fields) : !(field in c.fields) && !whole.length))
431
+ throw new Refused(`no ${o.op} at ${o.path}`);
432
+ if (o.op === "add" && link === undefined) {
433
+ const { id: back, ...given } = (o.value ?? {}) as Record<string, unknown>,
434
+ value = flat(given),
435
+ { by } = of(doc);
436
+ // an id is the store's to give, but to an item an undo puts back
437
+ if (back !== undefined && !undoing) throw new Refused("id is the server's to give");
438
+ const other = Object.keys(value).find((f) => !(f in c.fields));
439
+ if (other) throw new Refused(`${an(c.tag)} has no ${other}`);
440
+ const id = (back as number | undefined) ?? nextId(coll);
441
+ const cols = Object.keys(value).filter((f) => c.fields[f] !== "ids");
442
+ const all = by ? [...cols, by.column] : cols;
443
+ db.run(
444
+ `INSERT INTO ${q(coll)} (${["id", ...all].map(q).join(", ")}) VALUES (${["?", ...all.map(() => "?")].join(", ")})`,
445
+ [id, ...cols.map((f) => cell(coll, f, c.fields[f]!, value[f])), ...(by ? [by.n] : [])] as any[],
446
+ );
447
+ for (const f of Object.keys(value).filter((f) => c.fields[f] === "ids"))
448
+ setPairs(coll, f, id, value[f] as number[]);
449
+ return {
450
+ applied: { op: "add", path: `/${coll}/-`, value: { ...nest(value), id } },
451
+ inverse: [{ op: "remove", path: `/${coll}/${id}` }],
452
+ };
453
+ }
454
+ const id = Number(key);
455
+ const { sql, args } = mine(doc, coll);
456
+ if (!db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${sql}`).get(id, ...args))
457
+ throw new Refused(`no ${c.tag} at ${o.path}`);
458
+ const was = itemAt(coll, c, id);
459
+ let inverse: Op[];
460
+ if (sub || whole.length) {
461
+ // an object's fields, each its column: one, or all of them (one not given, emptied)
462
+ const cols = sub ? [sub] : whole,
463
+ given = sub ? { [sub]: o.value } : flat({ [field!]: o.value ?? {} });
464
+ for (const col of cols)
465
+ db.run(`UPDATE ${q(coll)} SET ${q(col)} = ? WHERE id = ?`, [
466
+ o.op === "remove" ? null : cell(coll, col, c.fields[col]!, given[col]),
467
+ id,
468
+ ] as any[]);
469
+ const path = `/${coll}/${id}/${field}${sub ? `/${link}` : ""}`,
470
+ had = sub
471
+ ? was[sub]
472
+ : nest(Object.fromEntries(whole.flatMap((col) => (col in was ? [[col, was[col]]] : []))))[field!];
473
+ inverse = [had === undefined ? { op: "remove", path } : { op: "replace", path, value: had }];
474
+ } else if (link !== undefined) {
475
+ const to = o.op === "add" ? (o.value as number) : Number(link);
476
+ pair(coll, field!, id, to, o.op === "add");
477
+ inverse = [
478
+ o.op === "add"
479
+ ? { op: "remove", path: `/${coll}/${id}/${field}/${to}` }
480
+ : { op: "add", path: `/${coll}/${id}/${field}/-`, value: to },
481
+ ];
482
+ } else if (o.op === "remove" && field === undefined) {
483
+ for (const [f, t] of Object.entries(c.fields)) if (t === "ids") setPairs(coll, f, id, []);
484
+ db.run(`DELETE FROM ${q(coll)} WHERE id = ?`, [id]);
485
+ inverse = [{ op: "add", path: `/${coll}/-`, value: was }];
486
+ } else {
487
+ if (c.fields[field!] === "ids") setPairs(coll, field!, id, o.op === "remove" ? [] : (o.value as number[]));
488
+ else
489
+ db.run(`UPDATE ${q(coll)} SET ${q(field!)} = ? WHERE id = ?`, [
490
+ o.op === "remove" ? null : cell(coll, field!, c.fields[field!]!, o.value),
491
+ id,
492
+ ] as any[]);
493
+ const path = `/${coll}/${id}/${field}`;
494
+ inverse = [was[field!] === undefined ? { op: "remove", path } : { op: "replace", path, value: was[field!] }];
495
+ }
496
+ return { applied: o, inverse };
497
+ }
498
+
499
+ const versionOf = (doc: string) =>
500
+ (db.query("SELECT version FROM documents WHERE name = ?").get(doc) as { version: number } | null)?.version;
501
+ /** A document's version moved on, its new one: an instance of a kind is begun by its first write, at version 0. */
502
+ function moved(doc: string) {
503
+ const was = versionOf(doc);
504
+ if (was === undefined)
505
+ db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, 0)", [nextId("documents"), doc]);
506
+ db.run("UPDATE documents SET version = ? WHERE name = ?", [(was ?? 0) + 1, doc]);
507
+ return (was ?? 0) + 1;
508
+ }
509
+
510
+ return {
511
+ db,
512
+ /** Whether a document holds an item: what a link may point at. */
513
+ has: (doc: string, coll: string, id: number) =>
514
+ !!of(doc).rules?.collections[coll] &&
515
+ !!db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${mine(doc, coll).sql}`).get(id, ...mine(doc, coll).args),
516
+ /** Whether a document can be held: one of the documents, or an instance of a kind whose root item is there. */
517
+ exists(doc: string) {
518
+ const { base, params } = docParts(doc);
519
+ const { rules, by } = of(base);
520
+ if (!rules || base.includes(":") !== !!rules.kind) return false;
521
+ // a window is written one way alone: its parameters, in its order, each once, a date one a date
522
+ if (doc.includes("?") && doc !== windowed(base, rules, params)) return false;
523
+ return !by || this.has(rules.kind!.doc, rules.kind!.root, by.n);
524
+ },
525
+
526
+ /** A document, whole, as a page is sent it, read by its query: each item with its fields, null ones left out,
527
+ * and its lists. */
528
+ read(doc: string, member?: number): Doc {
529
+ const { base, params } = docParts(doc);
530
+ const { rules, by } = of(base);
531
+ // each of its window's parameters, given or not (null: the whole of it); a document read by member, its
532
+ // member's (nobody: 0)
533
+ const window = Object.fromEntries(windowOf(rules!).map((p) => [p, params[p] ?? null]));
534
+ const row = db.query(rules!.query).get({
535
+ doc: base,
536
+ ...(by ? { key: by.n } : {}),
537
+ ...window,
538
+ ...(rules!.member ? { member: member ?? 0 } : rules!.sees ? { member: member ?? null } : {}),
539
+ }) as {
540
+ doc: string;
541
+ };
542
+ return JSON.parse(row.doc);
543
+ },
544
+
545
+ /** A write, made whole or not at all, in one transaction: its ops made on the rows, what else must land with it
546
+ * (`within`: the group's keys), and what the rules over values do as they follow. Then each document holding a row
547
+ * it changed is told it in its own paths, at its next version, in a row of its change: the document written always
548
+ * (first, its ops as they leave it), and every other a rule reached (`followed`). `undoes`, the version an undo
549
+ * puts back. Its changes, with the ops as they were made (what an add was given), and the rows it changed; or a
550
+ * refusal, with why. */
551
+ write(
552
+ name: string,
553
+ ops: Op[],
554
+ by: number | null,
555
+ via: string | null,
556
+ within?: (applied: Op[]) => void,
557
+ { undoes }: { undoes?: number } = {},
558
+ ): { changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] } {
559
+ // a window's write is its document's
560
+ const doc = docParts(name).base;
561
+ return db.transaction(() => {
562
+ db.run(`DELETE FROM ${noted}`);
563
+ // a value naming an add before it in this write ("$1", the first add's) is the id that add was given
564
+ const done: ReturnType<typeof apply>[] = [];
565
+ const minted: number[] = [];
566
+ const named = (v: unknown): unknown =>
567
+ typeof v === "string" && /^\$[1-9]\d*$/.test(v)
568
+ ? (minted[Number(v.slice(1)) - 1] ?? v)
569
+ : Array.isArray(v)
570
+ ? v.map(named)
571
+ : v && typeof v === "object"
572
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, named(x)]))
573
+ : v;
574
+ for (const o of ops) {
575
+ const d = apply(
576
+ doc,
577
+ inward(doc, { ...o, ...("value" in o ? { value: named(o.value) } : {}) }),
578
+ undoes !== undefined,
579
+ );
580
+ if (d.applied.op === "add" && parts(d.applied.path).key === "-") minted.push(d.applied.value.id);
581
+ done.push(d);
582
+ }
583
+ const applied = done.map((d) => outward(doc, d.applied));
584
+ within?.(applied);
585
+ // the document written is told its ops as made (what an add was given), and what a rule changed of it besides
586
+ const made = new Set(
587
+ done.map(({ applied: o }) => {
588
+ const { coll, key } = parts(o.path);
589
+ return `${coll}/${key === "-" ? o.value.id : key}`;
590
+ }),
591
+ );
592
+ const all = touched(),
593
+ names = told(all, doc, made);
594
+ const own = names.get(doc) ?? { ops: [], inverse: [], rows: [] };
595
+ // an item it added as the write left it: what the server filled, and what a rule worked out (an order's total)
596
+ const left = new Map(all.map((r) => [`${r.coll}/${r.id}`, r.after]));
597
+ names.set(doc, {
598
+ ...own,
599
+ ops: [
600
+ ...applied.map((o, i) => {
601
+ const { coll, key } = parts(done[i]!.applied.path);
602
+ const after = key === "-" && left.get(`${coll}/${o.value.id}`);
603
+ return after ? { ...o, value: after } : o;
604
+ }),
605
+ ...own.ops,
606
+ ],
607
+ inverse: [...own.inverse, ...done.flatMap((d) => d.inverse.map((o) => outward(doc, o))).reverse()],
608
+ });
609
+ const changes = [doc, ...[...names.keys()].filter((n) => n !== doc)].map((name) => {
610
+ const { ops, inverse } = names.get(name)!,
611
+ version = moved(name);
612
+ db.run(
613
+ "INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
614
+ [
615
+ nextId("changes"),
616
+ name,
617
+ version,
618
+ JSON.stringify(ops),
619
+ JSON.stringify(inverse),
620
+ name === doc ? (undoes ?? null) : null,
621
+ name === doc ? null : 1,
622
+ by,
623
+ via,
624
+ new Date().toISOString(),
625
+ ],
626
+ );
627
+ return { doc: name, version, ops, by, via };
628
+ });
629
+ return {
630
+ changes,
631
+ applied,
632
+ rows: Object.fromEntries([...names].map(([name, { rows }]) => [name, rows])),
633
+ // every table it changed, whatever holds it (a document holding only some of a table's rows is told as a whole)
634
+ tables: [...new Set(all.map((r) => r.coll))],
635
+ };
636
+ })();
637
+ },
638
+
639
+ /** A document's version moved on, with no change of its own to keep (one read as each member has it, whose
640
+ * rows a write changed): its new version. */
641
+ moved,
642
+
643
+ /** A change as its row keeps it: its ops, their inverse, what it undoes, and whether a rule made it;
644
+ * or undefined, if it isn't kept (let go, or from before inverses were). */
645
+ change(doc: string, version: number): Kept | undefined {
646
+ const r = db
647
+ .query("SELECT ops, inverse, undoes, followed, member, via FROM changes WHERE doc = ? AND version = ?")
648
+ .get(doc, version) as {
649
+ ops: string;
650
+ inverse: string | null;
651
+ undoes: number | null;
652
+ followed: number | null;
653
+ member: number | null;
654
+ via: string | null;
655
+ } | null;
656
+ if (!r?.inverse) return undefined;
657
+ return {
658
+ doc,
659
+ version,
660
+ ops: JSON.parse(r.ops),
661
+ by: r.member,
662
+ via: r.via,
663
+ inverse: JSON.parse(r.inverse),
664
+ undoes: r.undoes,
665
+ followed: r.followed === 1,
666
+ };
667
+ },
668
+
669
+ /** The ops that undo a change, guarded as delta's walk is: what it left at each path it changed (an item it
670
+ * added, whole; a field it set or cleared; an id it put in a list or took out) must be there still. A value
671
+ * someone has changed since refuses the undo, saying where: undone, it would lose their change. */
672
+ undoing(doc: string, version: number): Op[] {
673
+ const c = this.change(doc, version);
674
+ if (!c) throw new Refused(`${doc}'s change ${version} isn't kept, so it can't be undone`);
675
+ if (c.followed) throw new Refused(`${doc}'s change ${version} followed another write: undo that`);
676
+ const left = new Map<string, unknown>();
677
+ for (const o of c.ops.map((o) => inward(doc, o))) {
678
+ const { coll, key, field, link } = parts(o.path);
679
+ if (o.op === "add" && field === undefined) {
680
+ left.set(`/${coll}/${o.value.id}`, { ...o.value });
681
+ continue;
682
+ }
683
+ const item = `/${coll}/${key}`;
684
+ if (field === undefined) left.set(item, undefined);
685
+ else if (link !== undefined && /^(\d+|-)$/.test(link))
686
+ left.set(`${item}/${field}/${o.op === "add" ? o.value : link}`, o.op === "add");
687
+ else {
688
+ // a field, or one of an object's (terms.days)
689
+ const f = link === undefined ? field : `${field}.${link}`;
690
+ const v = o.op === "remove" || (Array.isArray(o.value) && !o.value.length) ? undefined : o.value;
691
+ const whole = left.get(item) as Item | undefined;
692
+ if (whole) Object.assign(whole, nest({ ...flat(whole), [f]: v }));
693
+ else left.set(`${item}/${f}`, v);
694
+ }
695
+ }
696
+ // each row as it is now, read by its id (a document holding only some rows may hold it no longer)
697
+ const at = (coll: string, id: string) => {
698
+ if (of(doc).rules!.collections[coll]?.own) return ownOf(this.read(doc)) as Item;
699
+ const row = db
700
+ .query(`SELECT ${holding.get(coll)!.item} AS item FROM ${q(coll)} t WHERE t.id = ?`)
701
+ .get(Number(id)) as {
702
+ item: string;
703
+ } | null;
704
+ return row ? (JSON.parse(row.item) as Item) : undefined;
705
+ };
706
+ for (const [path, was] of left) {
707
+ const [, coll, id, field, to] = path.split("/") as [string, string, string, string?, string?];
708
+ const here = at(coll, id);
709
+ const still =
710
+ field === undefined
711
+ ? same(here, was)
712
+ : to === undefined
713
+ ? !!here && same(valueAt(here, field), was)
714
+ : !!here && ((here[field] as number[] | undefined) ?? []).includes(Number(to)) === was;
715
+ if (!still) throw new Refused(`${path} has changed since, so it can't be undone`);
716
+ }
717
+ return c.inverse;
718
+ },
719
+
720
+ /** The changes after a version, in order, for a page catching up; null when they aren't all here (a
721
+ * document brought in from its JSON has no changes for the versions before it), or it's too far
722
+ * behind, or ahead (a page from before the store was): then it must be sent the document whole. */
723
+ since(doc: string, version: number): Change[] | null {
724
+ const now = versionOf(doc) ?? 0;
725
+ if (version > now || now - version > BEHIND) return null;
726
+ const rows = db
727
+ .query("SELECT version, ops, member, via FROM changes WHERE doc = ? AND version > ? ORDER BY version")
728
+ .all(doc, version) as { version: number; ops: string; member: number | null; via: string | null }[];
729
+ if (rows.length !== now - version) return null;
730
+ return rows.map((r) => ({ doc, version: r.version, ops: JSON.parse(r.ops), by: r.member, via: r.via }));
731
+ },
732
+
733
+ /** The changes made before a time (ms) that no page catching up needs, each beyond its document's last
734
+ * BEHIND, let go; how many. */
735
+ trim: (before: number) =>
736
+ db.run(
737
+ "DELETE FROM changes WHERE at < ? AND version <= (SELECT version FROM documents WHERE name = changes.doc) - ?",
738
+ [new Date(before).toISOString(), BEHIND],
739
+ ).changes,
740
+
741
+ /** A document's version, or a kind's (order: every instance's, together): what a document derived from it is
742
+ * versioned by. */
743
+ versions: (name: string) =>
744
+ (
745
+ db
746
+ .query("SELECT COALESCE(SUM(version), 0) AS n FROM documents WHERE name = ? OR name LIKE ? || ':%'")
747
+ .get(name, name) as { n: number }
748
+ ).n,
749
+
750
+ /** Whether a document is here yet: a new store is begun from a document's JSON (`take`). */
751
+ holds: (doc: string) => versionOf(doc) !== undefined,
752
+
753
+ /** A document begun from its JSON (the seed, or a file from before the store): its items with their ids,
754
+ * each sequence past the largest, and its version; all in one transaction. `again`: a static document's, its
755
+ * seed a release's, in place of what was. */
756
+ take(doc: string, json: Doc, again = false) {
757
+ const rules = docs.get(doc)!;
758
+ db.transaction(() => {
759
+ // a seed's items may link to those further on: its links whole by commit
760
+ db.defer();
761
+ if (again) {
762
+ for (const [coll, c] of Object.entries(rules.collections)) {
763
+ for (const [f, t] of Object.entries(c.fields)) if (t === "ids") db.run(`DELETE FROM ${q(`${coll}_${f}`)}`);
764
+ db.run(`DELETE FROM ${q(coll)}`);
765
+ }
766
+ db.run("DELETE FROM documents WHERE name = ?", [doc]);
767
+ }
768
+ for (const [coll, c] of Object.entries(rules.collections)) {
769
+ // an item the seed gives no id is numbered after the largest it gives, as an add would be
770
+ const listed = (c.own ? [ownOf(json)] : (json[coll] ?? [])) as Item[];
771
+ let last = Math.max(0, ...listed.map((i) => (typeof i.id === "number" ? i.id : 0)));
772
+ const items = listed.map((i) => (typeof i.id === "number" ? i : { ...i, id: ++last }));
773
+ for (const given of items) {
774
+ // an object's fields each their column (terms.days)
775
+ const item = flat(given) as Item;
776
+ // a kind's seed says each item's instance, by its column
777
+ const cols = [...Object.keys(c.fields), ...(rules.kind ? [rules.kind.column] : [])].filter(
778
+ (f) => c.fields[f] !== "ids" && item[f] !== undefined,
779
+ );
780
+ // (the document's own row is there already: put in its place)
781
+ if (c.own) db.run(`DELETE FROM ${q(coll)} WHERE id = 1`);
782
+ db.run(
783
+ `INSERT INTO ${q(coll)} (${["id", ...cols].map(q).join(", ")}) VALUES (${["?", ...cols.map(() => "?")].join(", ")})`,
784
+ [item.id, ...cols.map((f) => cell(coll, f, c.fields[f] ?? "integer", item[f]))] as any[],
785
+ );
786
+ }
787
+ // the pairs once every item is in: a list may name an item of this collection further on
788
+ for (const item of c.own ? [] : items)
789
+ for (const [f, t] of Object.entries(c.fields))
790
+ if (t === "ids" && Array.isArray(item[f])) setPairs(coll, f, item.id, item[f] as number[]);
791
+ passed(db, coll, c.own ? 1 : last);
792
+ }
793
+ db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, ?)", [nextId("documents"), doc, json.version]);
794
+ })();
795
+ },
796
+
797
+ /** Documents begun from their JSON, together, in one transaction: one's may link to another's. */
798
+ takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
799
+ rule(false);
800
+ try {
801
+ db.transaction(() => {
802
+ db.defer();
803
+ for (const { doc, json, again } of docs) this.take(doc, json, again);
804
+ })();
805
+ } finally {
806
+ rule(true);
807
+ }
808
+ },
809
+
810
+ /** The file let go (a server stopped). */
811
+ close: () => db.close(),
812
+ };
813
+ }
814
+
815
+ export type Store = Awaited<ReturnType<typeof openStore>>;