@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/migrate.ts ADDED
@@ -0,0 +1,597 @@
1
+ // joined's migrations (the skill's reference, §14): each app's tables as a history from empty, one numbered
2
+ // file a step (<app>/migrations/NNN-<what>.ts, exporting its `changes`), each run once, in order, at
3
+ // start, in a transaction with its record; a step may move or fill rows too (its `up`, after its changes).
4
+ // Folded in order, the changes are the tables the history
5
+ // leads to (`stateOf`); what the stories say beyond them (`diff`) is the next migration, which the
6
+ // compiler writes (`writeMigration`); a rename it can't know, it says is a person's to write. The SQL
7
+ // is what SQLite and Postgres both take: CREATE TABLE, ALTER TABLE, and ids from joined's own
8
+ // sequences, never AUTOINCREMENT. A database made before these were joined's (delta's, until 0.8)
9
+ // keeps them under delta's names, and is brought over once, as it is.
10
+
11
+ import { refuseSql, triggerSql, type Dialect, type Engine } from "./engine.ts";
12
+ import { readdirSync } from "node:fs";
13
+ import { join, resolve } from "node:path";
14
+
15
+ type ColumnType = "text" | "integer" | "real" | "boolean" | "json" | "timestamptz";
16
+ /** What a column's value is, which the database holds it to, refusing in `said`: a string, one of a form (a regular
17
+ * expression), a whole number, any number, or a boolean. */
18
+ export type Is = { type: "string" | "form" | "integer" | "decimal" | "boolean"; form?: string; said: string };
19
+ /** A column beside a table's id: its type, whether it may be empty, what its value is (`is`), and the table whose
20
+ * row's id it holds (`to`, a link: a foreign key), each refused in its words: an id that's no row (`said`), and a
21
+ * row removed while this links to it (`held`, said once and of many, `{n}` how many). */
22
+ export type Column = {
23
+ type: ColumnType;
24
+ nullable?: true;
25
+ is?: Is;
26
+ to?: { table: string; said: string; held?: [string, string]; onDelete?: "cascade" | "set null" };
27
+ };
28
+ /** A table: its columns, and the sets of columns no two rows share; guarded (`strict`), each value kept as it's given
29
+ * and held to what it is, an add held to the columns it `needs`, and its unique set to `once`, each in its words (a
30
+ * `{column}` in them is the value written). */
31
+ export type Table = {
32
+ columns: Record<string, Column>;
33
+ unique?: string[][];
34
+ strict?: true;
35
+ needs?: { columns: string[]; said: string };
36
+ once?: string;
37
+ };
38
+ /** The tables a history leads to, by name. */
39
+ export type State = Record<string, Table>;
40
+ export type Change =
41
+ | { change: "createTable"; key: string; table: Table }
42
+ | { change: "dropTable"; key: string }
43
+ | { change: "renameTable"; key: string; to: string }
44
+ | { change: "addColumn"; key: string; column: string; def: Column }
45
+ | { change: "dropColumn"; key: string; column: string }
46
+ | { change: "renameColumn"; key: string; column: string; to: string }
47
+ | { change: "guardTable"; key: string; table: Table };
48
+ /** What a step does to the rows, once its changes are made, in its transaction: moves or fills them, by
49
+ * SQL; a row it adds takes `nextId(table)`, so no write later meets it. */
50
+ export type Up = (db: Engine, tools: { nextId: (table: string) => number }) => void;
51
+ /** One step of a history: its name (the file's), recorded once it has run, its changes, and its `up`. */
52
+ export type Migration = { id: string; changes: Change[]; up?: Up };
53
+
54
+ // as a migration may write them: "text", "integer?" (may be empty), or { type, nullable }; and a
55
+ // unique set as a column, a list of them, or { columns } (`temporal: false` is from before 0.8)
56
+ type ColumnIn = Column | ColumnType | `${ColumnType}?`;
57
+ type TableIn = {
58
+ columns: Record<string, ColumnIn>;
59
+ unique?: (string | string[] | { columns: string[] })[];
60
+ temporal?: false;
61
+ strict?: true;
62
+ needs?: { columns: string[]; said: string };
63
+ once?: string;
64
+ };
65
+
66
+ const column = (c: ColumnIn): Column =>
67
+ typeof c !== "string"
68
+ ? {
69
+ type: c.type,
70
+ ...(c.nullable ? { nullable: true as const } : {}),
71
+ ...(c.is ? { is: { ...c.is } } : {}),
72
+ ...(c.to ? { to: { ...c.to, ...(c.to.held ? { held: [...c.to.held] as [string, string] } : {}) } } : {}),
73
+ }
74
+ : c.endsWith("?")
75
+ ? { type: c.slice(0, -1) as ColumnType, nullable: true }
76
+ : { type: c as ColumnType };
77
+ const tableOf = (def: TableIn): Table => {
78
+ const unique = (def.unique ?? []).map((u) =>
79
+ typeof u === "string" ? [u] : Array.isArray(u) ? [...u] : [...u.columns],
80
+ );
81
+ return {
82
+ columns: Object.fromEntries(Object.entries(def.columns).map(([name, c]) => [name, column(c)])),
83
+ ...(unique.length ? { unique } : {}),
84
+ ...(def.strict ? { strict: true as const } : {}),
85
+ ...(def.needs ? { needs: { columns: [...def.needs.columns], said: def.needs.said } } : {}),
86
+ ...(def.once ? { once: def.once } : {}),
87
+ };
88
+ };
89
+
90
+ /** Make a table: `createTable("people", { columns: { name: "text" } })`. */
91
+ export const createTable = (key: string, def: TableIn): Change => ({ change: "createTable", key, table: tableOf(def) });
92
+ /** Drop a table, and every row of it. */
93
+ export const dropTable = (key: string): Change => ({ change: "dropTable", key });
94
+ /** Rename a table, keeping its rows. */
95
+ export const renameTable = (key: string, to: string): Change => ({ change: "renameTable", key, to });
96
+ /** Add a column: every row takes its empty value. */
97
+ export const addColumn = (key: string, name: string, def: ColumnIn): Change => ({
98
+ change: "addColumn",
99
+ key,
100
+ column: name,
101
+ def: column(def),
102
+ });
103
+ /** Drop a column, and its values. */
104
+ export const dropColumn = (key: string, name: string): Change => ({ change: "dropColumn", key, column: name });
105
+ /** A table guarded as it's given: what its values are (made again, its rows kept, where that changed), what it links
106
+ * to, what an add needs. */
107
+ export const guardTable = (key: string, def: TableIn): Change => ({
108
+ change: "guardTable",
109
+ key,
110
+ table: tableOf(def),
111
+ });
112
+ /** Rename a column, keeping its values. */
113
+ export const renameColumn = (key: string, name: string, to: string): Change => ({
114
+ change: "renameColumn",
115
+ key,
116
+ column: name,
117
+ to,
118
+ });
119
+
120
+ /** The tables after one change, from those before it; a change that names what isn't there is refused. */
121
+ export function applyChange(state: State, c: Change): State {
122
+ const next = structuredClone(state);
123
+ const there = (key: string) => {
124
+ if (!next[key]) throw new Error(`${c.change} names a table the history hasn't made: ${key}`);
125
+ return next[key]!;
126
+ };
127
+ const free = (key: string) => {
128
+ if (next[key]) throw new Error(`${c.change}: ${key} is made already`);
129
+ };
130
+ if (c.change === "createTable") (free(c.key), (next[c.key] = structuredClone(c.table)));
131
+ else if (c.change === "dropTable") (there(c.key), delete next[c.key]);
132
+ else if (c.change === "renameTable") (free(c.to), (next[c.to] = there(c.key)), delete next[c.key]);
133
+ else if (c.change === "guardTable") (there(c.key), (next[c.key] = structuredClone(c.table)));
134
+ else {
135
+ const t = there(c.key);
136
+ if ((c.change === "addColumn") === c.column in t.columns)
137
+ throw new Error(
138
+ `${c.change}: ${c.key}.${c.column} ${c.change === "addColumn" ? "is there already" : "isn't there"}`,
139
+ );
140
+ if (c.change === "addColumn") t.columns[c.column] = { ...c.def };
141
+ else if (c.change === "dropColumn") delete t.columns[c.column];
142
+ else {
143
+ if (c.to in t.columns) throw new Error(`renameColumn: ${c.key}.${c.to} is there already`);
144
+ t.columns = Object.fromEntries(Object.entries(t.columns).map(([k, d]) => [k === c.column ? c.to : k, d]));
145
+ if (t.unique) t.unique = t.unique.map((u) => u.map((x) => (x === c.column ? c.to : x)));
146
+ }
147
+ }
148
+ return next;
149
+ }
150
+
151
+ /** The tables a history leads to: every change of every migration, in order. */
152
+ export const stateOf = (migrations: { changes: Change[] }[]): State =>
153
+ migrations.reduce((s, m) => m.changes.reduce(applyChange, s), {} as State);
154
+
155
+ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
156
+ /** A column's type and whether it may be empty: what only a person changes. */
157
+ const bare = ({ type, nullable }: Column) => ({ type, ...(nullable ? { nullable } : {}) });
158
+ /** A column made optional, its type as it was: no row is refused by it, so it isn't a person's to write. */
159
+ const loosened = (was: Column, now: Column) => was.type === now.type && !was.nullable && !!now.nullable;
160
+ /** What guards a table: whether it's strict, what each of the columns given is and links to, what an add needs. */
161
+ const guards = (t: Table, columns: string[]) => ({
162
+ strict: !!t.strict,
163
+ columns: columns.map((c) => [t.columns[c]!.is ?? null, t.columns[c]!.to ?? null]),
164
+ needs: t.needs ?? null,
165
+ once: t.once ?? null,
166
+ });
167
+
168
+ /** What the tables wanted say beyond the history: the changes that make one the other, and what only a
169
+ * person can say (a rename, a column's type changed, a unique set changed). */
170
+ export function diff(state: State, want: State): { changes: Change[]; byHand: string[] } {
171
+ const changes: Change[] = [],
172
+ byHand: string[] = [];
173
+ for (const [key, t] of Object.entries(want)) {
174
+ const was = state[key];
175
+ if (!was) {
176
+ changes.push({ change: "createTable", key, table: t });
177
+ continue;
178
+ }
179
+ const gone = Object.keys(was.columns).filter((c) => !(c in t.columns));
180
+ const added = Object.keys(t.columns).filter((c) => !(c in was.columns));
181
+ for (const c of added) changes.push({ change: "addColumn", key, column: c, def: t.columns[c]! });
182
+ for (const c of gone) changes.push({ change: "dropColumn", key, column: c });
183
+ // what guards a table changed (what its values are, what it links to, what an add needs): made again, once its
184
+ // columns are added and dropped
185
+ const both = Object.keys(t.columns).filter((c) => c in was.columns);
186
+ // (each column's type, and whether it may be empty, as they were, unless it's only made optional: any other
187
+ // change of those is a person's to write)
188
+ const freed = both.filter((c) => loosened(was.columns[c]!, t.columns[c]!));
189
+ if (freed.length || !same(guards(was, both), guards(t, both)))
190
+ changes.push({
191
+ change: "guardTable",
192
+ key,
193
+ table: {
194
+ ...t,
195
+ columns: Object.fromEntries(
196
+ Object.entries(t.columns).map(([c, { nullable, ...d }]) => [
197
+ c,
198
+ c in was.columns
199
+ ? { ...d, ...bare((freed.includes(c) ? t : was).columns[c]!) }
200
+ : { ...d, ...(nullable ? { nullable } : {}) },
201
+ ]),
202
+ ),
203
+ },
204
+ });
205
+ if (gone.length && added.length)
206
+ byHand.push(
207
+ `${key}: ${gone.join(", ")} gone and ${added.join(", ")} new: if one is the other renamed, make it renameColumn (a drop loses its values)`,
208
+ );
209
+ for (const c of Object.keys(t.columns))
210
+ if (c in was.columns && !freed.includes(c) && !same(bare(was.columns[c]!), bare(t.columns[c]!)))
211
+ byHand.push(
212
+ `${key}.${c}: ${JSON.stringify(bare(t.columns[c]!))}, was ${JSON.stringify(bare(was.columns[c]!))}`,
213
+ );
214
+ if (!same(was.unique ?? [], t.unique ?? []))
215
+ byHand.push(`${key}: unique ${JSON.stringify(t.unique ?? [])}, was ${JSON.stringify(was.unique ?? [])}`);
216
+ }
217
+ for (const key of Object.keys(state)) if (!(key in want)) changes.push({ change: "dropTable", key });
218
+ return { changes, byHand };
219
+ }
220
+
221
+ /** A value as a person would write it: keys unquoted where they may be. */
222
+ function literal(v: unknown): string {
223
+ if (Array.isArray(v)) return `[${v.map(literal).join(", ")}]`;
224
+ if (v && typeof v === "object")
225
+ return `{ ${Object.entries(v)
226
+ .map(([k, x]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${literal(x)}`)
227
+ .join(", ")} }`;
228
+ return JSON.stringify(v);
229
+ }
230
+
231
+ /** A change as it's written in a migration. */
232
+ const source = (c: Change): string => {
233
+ const { change, ...rest } = c;
234
+ return `${change}(${Object.values(rest).map(literal).join(", ")})`;
235
+ };
236
+
237
+ /** The next migration's file: its changes, and what is a person's to write, as comments; `from` is where
238
+ * it imports this module. */
239
+ export function writeMigration(changes: Change[], byHand: string[], from: string): string {
240
+ const used = [...new Set(changes.map((c) => c.change))].sort();
241
+ return [
242
+ "// Made by `bun run compile` from the stories: what they say beyond the migrations before it.",
243
+ ...byHand.map((b) => `// By hand: ${b}`),
244
+ `import { ${used.join(", ")} } from ${JSON.stringify(from)};`,
245
+ "",
246
+ "export const changes = [",
247
+ ...changes.map((c) => ` ${source(c)},`),
248
+ "];",
249
+ "",
250
+ ].join("\n");
251
+ }
252
+
253
+ /** The migrations in a folder, by name: each `NNN-what.ts`, its id its name without `.ts`; one with an `up`
254
+ * may change no table. */
255
+ export async function fromFolder(dir: string): Promise<Migration[]> {
256
+ const out: Migration[] = [];
257
+ for (const file of readdirSync(dir)
258
+ .filter((f) => f.endsWith(".ts"))
259
+ .sort()) {
260
+ const { changes = [], up } = await import(resolve(join(dir, file)));
261
+ if (!Array.isArray(changes) || (!changes.length && typeof up !== "function"))
262
+ throw new Error(`${dir}/${file} exports no changes, nor an up`);
263
+ out.push({ id: file.slice(0, -3), changes, ...(typeof up === "function" ? { up } : {}) });
264
+ }
265
+ return out;
266
+ }
267
+
268
+ const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
269
+ /** What each column type is in SQL, SQLite's and Postgres's, and its empty value (a column added takes it, or null).
270
+ * A boolean is 0 or 1 in both, a time its ISO text. */
271
+ const SQL: Record<ColumnType, Record<Dialect, string> & { empty: string }> = {
272
+ text: { sqlite: "TEXT", postgres: "TEXT", empty: "''" },
273
+ json: { sqlite: "TEXT", postgres: "TEXT", empty: "NULL" },
274
+ timestamptz: { sqlite: "TEXT", postgres: "TEXT", empty: "NULL" },
275
+ integer: { sqlite: "INTEGER", postgres: "BIGINT", empty: "0" },
276
+ real: { sqlite: "REAL", postgres: "DOUBLE PRECISION", empty: "0" },
277
+ boolean: { sqlite: "INTEGER", postgres: "INTEGER", empty: "0" },
278
+ };
279
+ /** Where joined records what has run, and keeps each table's last id. */
280
+ const RAN = "joined_migrations",
281
+ SEQUENCES = "joined_sequences";
282
+ const has = (db: Engine, table: string) => db.columns(table).length > 0;
283
+ const uniqueName = (table: string, columns: string[]) => `idx_${table}_unique_${columns.join("_")}`;
284
+ /** A table's unique indexes, by name and columns. */
285
+ const uniquesOf = (db: Engine, table: string): { name: string; columns: string[] }[] =>
286
+ db.dialect === "sqlite"
287
+ ? (db.query(`PRAGMA index_list(${q(table)})`).all() as { name: string; origin: string }[])
288
+ .filter((i) => i.origin === "c")
289
+ .map((i) => ({
290
+ name: i.name,
291
+ columns: (db.query(`PRAGMA index_info(${q(i.name)})`).all() as { name: string }[]).map((c) => c.name),
292
+ }))
293
+ : (
294
+ db
295
+ .query(
296
+ `SELECT i.relname AS name, json_agg(a.attname ORDER BY k.n)::text AS columns FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
297
+ CROSS JOIN LATERAL unnest(x.indkey) WITH ORDINALITY k(attnum, n) JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum
298
+ WHERE x.indrelid = to_regclass(?) AND x.indisunique AND NOT x.indisprimary GROUP BY i.relname`,
299
+ )
300
+ .all(q(table)) as { name: string; columns: string }[]
301
+ ).map((i) => ({ name: i.name, columns: JSON.parse(i.columns) }));
302
+ const makeUnique = (db: Engine, table: string, columns: string[]) =>
303
+ db.run(
304
+ `CREATE UNIQUE INDEX IF NOT EXISTS ${q(uniqueName(table, columns))} ON ${q(table)} (${columns.map(q).join(", ")})`,
305
+ );
306
+
307
+ /** Words as SQL: a string, each `{column}` in it the value written (NEW's). */
308
+ const words = (said: string) =>
309
+ said
310
+ .split(/(\{[a-z][a-z0-9-]*\})/)
311
+ .filter(Boolean)
312
+ .map((p) => (/^\{[a-z][a-z0-9-]*\}$/.test(p) ? `NEW.${q(p.slice(1, -1))}` : `'${p.replaceAll("'", "''")}'`))
313
+ .join(" || ");
314
+ /** What a value is, as SQLite asks it: of a strict table, kept as it was given (ANY), so a number given for a string
315
+ * is a number still. Postgres's columns are their types, a value written into one made it if it can be: what it was
316
+ * given is the store's to ask (`fits`), and a form and a boolean the CHECK's. */
317
+ const isSql = (dialect: Dialect, c: string, is: Is) =>
318
+ dialect === "postgres"
319
+ ? is.type === "form"
320
+ ? `${c} ~ '${is.form!.replaceAll("'", "''")}'`
321
+ : is.type === "boolean"
322
+ ? `${c} IN (0, 1)`
323
+ : "TRUE"
324
+ : is.type === "string"
325
+ ? `typeof(${c}) = 'text'`
326
+ : is.type === "form"
327
+ ? `typeof(${c}) = 'text' AND ${c} REGEXP '${is.form!.replaceAll("'", "''")}'`
328
+ : is.type === "integer"
329
+ ? `typeof(${c}) = 'integer'`
330
+ : is.type === "decimal"
331
+ ? `typeof(${c}) IN ('integer', 'real')`
332
+ : `typeof(${c}) = 'integer' AND ${c} IN (0, 1)`;
333
+ /** A column as SQL: a strict table's value as it's given (ANY), held to what it is, in its words. */
334
+ const columnSql = (db: Engine, name: string, d: Column, strict?: true) =>
335
+ `${q(name)} ${strict && d.is && db.dialect === "sqlite" ? "ANY" : SQL[d.type][db.dialect]}${d.nullable ? "" : " NOT NULL"}${checkSql(db, name, d)}${references(db, d)}`;
336
+ /** A column's guard of its value, named for its words. */
337
+ const checkSql = (db: Engine, name: string, d: Column) =>
338
+ d.is ? ` CONSTRAINT ${q(d.is.said)} CHECK (${q(name)} IS NULL OR ${isSql(db.dialect, q(name), d.is)})` : "";
339
+ /** A link as a foreign key: to its table's id, a row linked to never removed from under it (Postgres's held at
340
+ * the statement's end, or the transaction's, deferred, as SQLite's are). SQLite's is made with its column, and may
341
+ * name a table not there yet; Postgres's once every app's tables are (`linked`). */
342
+ const references = (db: Engine, d: Column, made = false) =>
343
+ !d.to || (db.dialect === "postgres" && !made)
344
+ ? ""
345
+ : ` REFERENCES ${q(d.to.table)} (id) ON DELETE ${
346
+ d.to.onDelete?.toUpperCase() ?? (db.dialect === "sqlite" ? "RESTRICT" : "NO ACTION")
347
+ }${db.dialect === "postgres" ? " DEFERRABLE" : ""}`;
348
+ const tableSql = (db: Engine, key: string, t: Table) =>
349
+ `CREATE TABLE ${q(key)} (id ${SQL.integer[db.dialect]} NOT NULL, ${[
350
+ ...Object.entries(t.columns).map(([n, d]) => columnSql(db, n, d, t.strict)),
351
+ "PRIMARY KEY (id)",
352
+ ].join(", ")})${t.strict && db.dialect === "sqlite" ? " STRICT" : ""}`;
353
+ /** The triggers named so, whatever table each is on, dropped. */
354
+ export const dropTriggers = (db: Engine, like: string) => {
355
+ const found = db
356
+ .query(
357
+ db.dialect === "sqlite"
358
+ ? "SELECT name, tbl_name AS tbl FROM sqlite_master WHERE type = 'trigger' AND name LIKE ?"
359
+ : "SELECT tgname AS name, c.relname AS tbl FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid WHERE NOT t.tgisinternal AND tgname LIKE ?",
360
+ )
361
+ .all(like) as { name: string; tbl: string }[];
362
+ for (const { name, tbl } of found)
363
+ db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
364
+ };
365
+ /** A table's guards that a CHECK can't say, as its triggers: an add without what it needs (an add: the row its
366
+ * sequence has just given out); a link to a row that
367
+ * isn't there; a unique set written again. Each refused in its words, the first that says so. */
368
+ function guardWith(db: Engine, key: string, t: Table | undefined) {
369
+ for (const when of ["insert", "update"]) dropTriggers(db, `joined_${key}_${when}`);
370
+ guardHeld(db, key, t);
371
+ if (!t) return;
372
+ const links = Object.entries(t.columns).flatMap(([c, d]): [string, string][] =>
373
+ d.to
374
+ ? [[`NEW.${q(c)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(d.to.table)} WHERE id = NEW.${q(c)})`, d.to.said]]
375
+ : [],
376
+ );
377
+ // an add is the row given the table's next id: a document brought in (a seed) has its own, and an item an undo
378
+ // puts back the one it had; those are held to their links by the foreign keys, at commit
379
+ const add = `NEW.id = (SELECT last FROM ${SEQUENCES} WHERE collection = '${key}')`;
380
+ const insert: [string, string][] = [];
381
+ if (t.needs)
382
+ insert.push([`${add} AND (${t.needs.columns.map((c) => `NEW.${q(c)} IS NULL`).join(" OR ")})`, t.needs.said]);
383
+ for (const [cond, said] of links) insert.push([`${add} AND ${cond}`, said]);
384
+ if (t.once && t.unique?.[0])
385
+ insert.push([
386
+ `EXISTS (SELECT 1 FROM ${q(key)} WHERE ${t.unique[0].map((c) => `${q(c)} = NEW.${q(c)}`).join(" AND ")})`,
387
+ t.once,
388
+ ]);
389
+ const trigger = (when: string, cases: [string, string][]) =>
390
+ cases.length &&
391
+ db.run(
392
+ triggerSql(db.dialect, {
393
+ name: `joined_${key}_${when}`,
394
+ at: "BEFORE",
395
+ event: when.toUpperCase(),
396
+ table: key,
397
+ body: cases.map(([cond, said]) => refuseSql(db.dialect, cond, words(said))).join(" "),
398
+ }),
399
+ );
400
+ trigger("insert", insert);
401
+ trigger("update", links);
402
+ }
403
+
404
+ /** A Postgres table's links made its foreign keys, each once the table it links to is there (another app's may come
405
+ * later: the store makes them, once every app's have run). */
406
+ export function linked(db: Engine, key: string, t: Table | undefined) {
407
+ if (db.dialect === "sqlite") return;
408
+ for (const [c, d] of Object.entries(t?.columns ?? {})) {
409
+ const name = `${key}_${c}_fkey`;
410
+ if (
411
+ d.to &&
412
+ has(db, d.to.table) &&
413
+ !db.query("SELECT 1 FROM pg_constraint WHERE conrelid = to_regclass(?) AND conname = ?").get(q(key), name)
414
+ )
415
+ db.run(`ALTER TABLE ${q(key)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(c)})${references(db, d, true)}`);
416
+ }
417
+ }
418
+
419
+ /** A table's links guarded where they point: a row linked to, removed, is refused before its foreign key would, in
420
+ * words saying how many link to it. A trigger on the table linked to, made once that's there (another app's may
421
+ * come later: the store makes them all again, once every app's have run). */
422
+ export function guardHeld(db: Engine, key: string, t: Table | undefined) {
423
+ dropTriggers(db, `joined_${key}_held_%`);
424
+ for (const [c, d] of Object.entries(t?.columns ?? {}))
425
+ if (d.to?.held && has(db, d.to.table)) {
426
+ const n = `(SELECT COUNT(*) FROM ${q(key)} WHERE ${q(c)} = OLD.id)`;
427
+ const [one, many] = d.to.held.map((w) => `'${w.replaceAll("'", "''")}'`);
428
+ db.run(
429
+ triggerSql(db.dialect, {
430
+ name: `joined_${key}_held_${c}`,
431
+ at: "BEFORE",
432
+ event: "DELETE",
433
+ table: d.to.table,
434
+ body: refuseSql(
435
+ db.dialect,
436
+ `${n} > 0`,
437
+ `'/${d.to.table}/' || OLD.id || ' cannot be removed: ' || ${n} || ' ' || CASE ${n} WHEN 1 THEN ${one} ELSE ${many} END`,
438
+ ),
439
+ }),
440
+ );
441
+ }
442
+ }
443
+
444
+ /** What a table's CHECKs and foreign keys say: whether it's strict, what each column's value is, whether it may be
445
+ * empty, and the table it links to. */
446
+ const checks = (t: Table) => [
447
+ !!t.strict,
448
+ Object.entries(t.columns).map(([c, d]) => [
449
+ c,
450
+ d.is ?? null,
451
+ !!d.nullable,
452
+ d.to?.table ?? null,
453
+ d.to?.onDelete ?? null,
454
+ ]),
455
+ ];
456
+
457
+ /** One change made on the database, the tables before it and after: its table's triggers made again from what it
458
+ * is. */
459
+ function make(db: Engine, c: Change, before: State, after: State) {
460
+ guardWith(db, c.key, undefined);
461
+ if (c.change === "createTable") {
462
+ if (!has(db, c.key)) db.run(tableSql(db, c.key, c.table));
463
+ for (const u of c.table.unique ?? []) makeUnique(db, c.key, u);
464
+ } else if (c.change === "guardTable") {
465
+ // its triggers alone, unless what a CHECK says changed: then
466
+ if (same(checks(before[c.key]!), checks(c.table))) return guardWith(db, c.key, after[c.key]);
467
+ // Postgres changes a table's CHECKs and foreign keys in place: each dropped, and made again from what it is
468
+ if (db.dialect === "postgres") {
469
+ for (const { name } of db
470
+ .query("SELECT conname AS name FROM pg_constraint WHERE conrelid = to_regclass(?) AND contype IN ('c', 'f')")
471
+ .all(q(c.key)) as { name: string }[])
472
+ db.run(`ALTER TABLE ${q(c.key)} DROP CONSTRAINT ${q(name)}`);
473
+ for (const [col, d] of Object.entries(c.table.columns)) {
474
+ if (d.is) db.run(`ALTER TABLE ${q(c.key)} ADD${checkSql(db, col, d)}`);
475
+ // a column made optional (one made needed is a person's, and its empty rows theirs to fill)
476
+ if (d.nullable) db.run(`ALTER TABLE ${q(c.key)} ALTER COLUMN ${q(col)} DROP NOT NULL`);
477
+ }
478
+ linked(db, c.key, c.table);
479
+ return guardWith(db, c.key, after[c.key]);
480
+ }
481
+ // made anew beside it, its rows copied, and put in its place; what else names it (another's trigger) isn't
482
+ // rewritten as it's renamed, so it names this one
483
+ const there = db.columns(c.key),
484
+ was = Object.keys(c.table.columns).filter((col) => there.includes(col));
485
+ db.run(tableSql(db, `${c.key}__new`, c.table));
486
+ db.run(
487
+ `INSERT INTO ${q(`${c.key}__new`)} (${["id", ...was].map(q).join(", ")}) SELECT ${["id", ...was].map(q).join(", ")} FROM ${q(c.key)}`,
488
+ );
489
+ db.run(`DROP TABLE ${q(c.key)}`);
490
+ db.run("PRAGMA legacy_alter_table = ON");
491
+ db.run(`ALTER TABLE ${q(`${c.key}__new`)} RENAME TO ${q(c.key)}`);
492
+ db.run("PRAGMA legacy_alter_table = OFF");
493
+ for (const u of c.table.unique ?? []) makeUnique(db, c.key, u);
494
+ } else if (c.change === "dropTable") {
495
+ db.run(`DROP TABLE IF EXISTS ${q(c.key)}`);
496
+ db.run(`DELETE FROM ${SEQUENCES} WHERE collection = ?`, [c.key]);
497
+ } else if (c.change === "renameTable") {
498
+ db.run(`ALTER TABLE ${q(c.key)} RENAME TO ${q(c.to)}`);
499
+ guardWith(db, c.to, after[c.to]);
500
+ for (const u of uniquesOf(db, c.to)) (db.run(`DROP INDEX ${q(u.name)}`), makeUnique(db, c.to, u.columns));
501
+ db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
502
+ } else if (c.change === "addColumn") {
503
+ // every row takes the column's empty value; one with none (json, a time) is left to be empty
504
+ const { empty } = SQL[c.def.type];
505
+ const fill = c.def.nullable || empty === "NULL" ? "" : ` NOT NULL DEFAULT ${empty}`;
506
+ db.run(
507
+ `ALTER TABLE ${q(c.key)} ADD COLUMN ${columnSql(db, c.column, { ...c.def, nullable: true }, after[c.key]!.strict)}${fill}`,
508
+ );
509
+ } else if (c.change === "dropColumn") {
510
+ for (const u of uniquesOf(db, c.key)) if (u.columns.includes(c.column)) db.run(`DROP INDEX ${q(u.name)}`);
511
+ db.run(`ALTER TABLE ${q(c.key)} DROP COLUMN ${q(c.column)}`);
512
+ } else {
513
+ db.run(`ALTER TABLE ${q(c.key)} RENAME COLUMN ${q(c.column)} TO ${q(c.to)}`);
514
+ for (const u of uniquesOf(db, c.key)) db.run(`DROP INDEX ${q(u.name)}`);
515
+ for (const u of after[c.key]!.unique ?? []) makeUnique(db, c.key, u);
516
+ }
517
+ guardWith(db, c.key, after[c.key]);
518
+ }
519
+
520
+ /** An app's migrations not yet run here, run in order, each with its `up` and its record in one transaction; the
521
+ * ids it ran. A database from before 0.8 has delta's names for joined's two tables: they're renamed,
522
+ * and what they hold is kept. */
523
+ export function migrate(db: Engine, app: string, list: Migration[]): string[] {
524
+ db.transaction(() => {
525
+ for (const [was, now] of [
526
+ ["delta_migrations", RAN],
527
+ ["_delta_sequences", SEQUENCES],
528
+ ] as const)
529
+ if (has(db, was) && !has(db, now)) db.run(`ALTER TABLE ${q(was)} RENAME TO ${now}`);
530
+ db.run(
531
+ `CREATE TABLE IF NOT EXISTS ${RAN} (app TEXT NOT NULL, id TEXT NOT NULL, ran_at TEXT NOT NULL, PRIMARY KEY (app, id))`,
532
+ );
533
+ db.run(`CREATE TABLE IF NOT EXISTS ${SEQUENCES} (collection TEXT PRIMARY KEY, last INTEGER NOT NULL)`);
534
+ }).immediate();
535
+ const done = new Set((db.query(`SELECT id FROM ${RAN} WHERE app = ?`).all(app) as { id: string }[]).map((r) => r.id));
536
+ const ran: string[] = [];
537
+ let state: State = {};
538
+ for (const m of list) {
539
+ const before = state;
540
+ state = m.changes.reduce(applyChange, state);
541
+ if (done.has(m.id)) continue;
542
+ // SQLite makes a table again by dropping it, and a drop deletes its rows first, taking with them the rows that
543
+ // link to it (or refused by them): its foreign keys are off while it runs (they can't be turned off inside its
544
+ // transaction), and checked whole before it commits
545
+ const rebuilds = db.dialect === "sqlite" && m.changes.some((c) => c.change === "guardTable");
546
+ if (rebuilds) db.run("PRAGMA foreign_keys = OFF");
547
+ try {
548
+ db.transaction(() => {
549
+ // a table made again beside itself is put in its place by commit, its links whole again by then
550
+ db.defer();
551
+ m.changes.reduce((s, c) => {
552
+ const after = applyChange(s, c);
553
+ make(db, c, s, after);
554
+ return after;
555
+ }, before);
556
+ // the transaction is synchronous: an up that awaits would land outside it
557
+ if ((m.up?.(db, { nextId: (table) => nextId(db, table) }) as unknown) instanceof Promise)
558
+ throw new Error("its up is async: an up is synchronous, as the transaction is");
559
+ if (rebuilds) {
560
+ const loose = db.query("PRAGMA foreign_key_check").get() as { table: string; parent: string } | null;
561
+ if (loose) throw new Error(`${loose.table} links to no row of ${loose.parent}`);
562
+ }
563
+ db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
564
+ }).immediate();
565
+ } catch (e) {
566
+ throw new Error(`${app}'s migration ${m.id} failed, and was rolled back: ${(e as Error).message}`);
567
+ } finally {
568
+ if (rebuilds) db.run("PRAGMA foreign_keys = ON");
569
+ }
570
+ ran.push(m.id);
571
+ }
572
+ return ran;
573
+ }
574
+
575
+ /** The id a table hands out next, without handing it out: its sequence, or the largest id it holds, then one on. */
576
+ export function peekId(db: Engine, table: string) {
577
+ const seq = db.query(`SELECT last FROM ${SEQUENCES} WHERE collection = ?`).get(table) as { last: number } | null;
578
+ const most = (db.query(`SELECT MAX(id) AS m FROM ${q(table)}`).get() as { m: number | null }).m ?? 0;
579
+ return Math.max(seq?.last ?? 0, most) + 1;
580
+ }
581
+
582
+ /** The next id for a table, handed out: never one handed out before, even when that row is gone. */
583
+ export function nextId(db: Engine, table: string) {
584
+ const next = peekId(db, table);
585
+ db.run(
586
+ `INSERT INTO ${SEQUENCES} (collection, last) VALUES (?, ?) ON CONFLICT (collection) DO UPDATE SET last = excluded.last`,
587
+ [table, next],
588
+ );
589
+ return next;
590
+ }
591
+
592
+ /** A table's last id kept at least `id`: a document brought in with ids of its own. */
593
+ export const passed = (db: Engine, table: string, id: number) =>
594
+ db.run(
595
+ `INSERT INTO ${SEQUENCES} (collection, last) VALUES (?, ?) ON CONFLICT (collection) DO UPDATE SET last = CASE WHEN excluded.last > ${SEQUENCES}.last THEN excluded.last ELSE ${SEQUENCES}.last END`,
596
+ [table, id],
597
+ );
@@ -0,0 +1,13 @@
1
+ // joined's own tables, beside every app's (which the compiler writes from their stories): each
2
+ // document's version, and every change, as it was committed (the ledger, and what a page catching up
3
+ // is sent). Written by hand, as joined's code is; never changed once it has run anywhere.
4
+ import { createTable } from "../migrate.ts";
5
+
6
+ export const changes = [
7
+ createTable("documents", { columns: { name: "text", version: "integer" }, temporal: false, unique: ["name"] }),
8
+ createTable("changes", {
9
+ columns: { doc: "text", version: "integer", ops: "json", member: "integer?", via: "text?", at: "timestamptz" },
10
+ temporal: false,
11
+ unique: [["doc", "version"]],
12
+ }),
13
+ ];
@@ -0,0 +1,16 @@
1
+ // The group's keys (src/members/keys.ts), beside the documents: each member's link, sealed with a key
2
+ // made from ROOT_TOKEN and found by its hash (a member's own id is the row's); each agent's link; the
3
+ // words left for a removed member, shown once; and a notice waiting for its member. Written by hand,
4
+ // as joined's code is; never changed once it has run anywhere.
5
+ import { createTable } from "../migrate.ts";
6
+
7
+ export const changes = [
8
+ createTable("member_keys", { columns: { hash: "text", box: "json" }, temporal: false, unique: ["hash"] }),
9
+ createTable("agents", {
10
+ columns: { member: "integer", label: "text", hash: "text", box: "json" },
11
+ temporal: false,
12
+ unique: ["hash"],
13
+ }),
14
+ createTable("farewells", { columns: { hash: "text", words: "text" }, temporal: false, unique: ["hash"] }),
15
+ createTable("notices", { columns: { kind: "text", why: "text", said_by: "text" }, temporal: false }),
16
+ ];
@@ -0,0 +1,10 @@
1
+ // A change row's inverse (the ops that put back what it did, an undo's), its context (who it concerns, from
2
+ // owns: the members told it), and the change it undoes, if it's an undo. A row from before has none of them,
3
+ // and isn't undone. Written by hand, as joined's code is; never changed once it has run anywhere.
4
+ import { addColumn } from "../migrate.ts";
5
+
6
+ export const changes = [
7
+ addColumn("changes", "inverse", "json?"),
8
+ addColumn("changes", "context", "json?"),
9
+ addColumn("changes", "undoes", "integer?"),
10
+ ];
@@ -0,0 +1,6 @@
1
+ // A change row a write didn't make, but a rule did as it followed it (a product's stock, as an order is placed): told
2
+ // as any change is, and undone only by undoing the write it followed. Written by hand, as joined's code is; never
3
+ // changed once it has run anywhere.
4
+ import { addColumn } from "../migrate.ts";
5
+
6
+ export const changes = [addColumn("changes", "followed", "boolean?")];