@blueshed/joined 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +316 -63
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +158 -37
  6. package/docs/introduction.md +27 -27
  7. package/docs/light-and-shadow.svg +2 -1
  8. package/docs/links-and-trust.svg +1 -0
  9. package/docs/stories-to-code.svg +2 -1
  10. package/docs/wire-op.svg +1 -0
  11. package/examples/README.md +20 -0
  12. package/examples/account/account.json +1 -0
  13. package/examples/account/derive.ts +41 -0
  14. package/examples/account/generated/elements.ts +52 -0
  15. package/examples/account/generated/rows.ts +22 -0
  16. package/examples/account/generated/rules.ts +32 -0
  17. package/examples/account/routes.ts +5 -0
  18. package/examples/app.css +11 -1
  19. package/examples/cafe/books.html +2 -2
  20. package/examples/cafe/cafe.css +96 -85
  21. package/examples/cafe/generated/books.rows.ts +22 -0
  22. package/examples/cafe/generated/books.rules.ts +3 -2
  23. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  24. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  25. package/examples/cafe/generated/menu.rows.ts +22 -0
  26. package/examples/cafe/generated/menu.rules.ts +3 -2
  27. package/examples/cafe/generated/order.rows.ts +27 -0
  28. package/examples/cafe/generated/order.rules.ts +11 -1
  29. package/examples/cafe/generated/staff.elements.ts +7 -2
  30. package/examples/cafe/generated/staff.rows.ts +22 -0
  31. package/examples/cafe/generated/staff.rules.ts +9 -1
  32. package/examples/cafe/generated/supplies.queries.ts +4 -2
  33. package/examples/cafe/generated/supplies.rows.ts +22 -0
  34. package/examples/cafe/generated/supplies.rules.ts +17 -1
  35. package/examples/cafe/generated/till.queries.ts +2 -0
  36. package/examples/cafe/generated/till.rows.ts +27 -0
  37. package/examples/cafe/generated/till.rules.ts +11 -1
  38. package/examples/cafe/index.html +14 -15
  39. package/examples/cafe/kitchen.css +11 -19
  40. package/examples/cafe/kitchen.ts +7 -3
  41. package/examples/cafe/look.ts +30 -0
  42. package/examples/cafe/menu.html +10 -26
  43. package/examples/cafe/menu.ts +8 -80
  44. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  45. package/examples/cafe/order.html +8 -7
  46. package/examples/cafe/order.ts +6 -2
  47. package/examples/cafe/routes.ts +0 -1
  48. package/examples/cafe/staff.json +5 -0
  49. package/examples/cafe/stories.jsonl +6 -2
  50. package/examples/cafe/supplies.html +35 -34
  51. package/examples/cafe/supplies.ts +59 -39
  52. package/examples/cafe/till.ts +19 -11
  53. package/examples/cafe/views.ts +7 -5
  54. package/examples/chart/arches.ts +150 -0
  55. package/examples/chart/chart.css +11 -0
  56. package/examples/chart/chart.json +87 -0
  57. package/examples/chart/generated/elements.ts +105 -0
  58. package/examples/chart/generated/queries.ts +36 -0
  59. package/examples/chart/generated/rows.ts +27 -0
  60. package/examples/chart/generated/rules.ts +111 -0
  61. package/examples/chart/grid.ts +118 -0
  62. package/examples/chart/index.html +78 -0
  63. package/examples/chart/migrations/001-chart.ts +6 -0
  64. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  65. package/examples/chart/page.ts +20 -0
  66. package/examples/chart/routes.ts +7 -0
  67. package/examples/chart/stories.jsonl +14 -0
  68. package/examples/chart/teeth.ts +57 -0
  69. package/examples/desk/desk.css +6 -10
  70. package/examples/desk/generated/elements.ts +1 -1
  71. package/examples/desk/generated/rows.ts +22 -0
  72. package/examples/desk/generated/rules.ts +34 -1
  73. package/examples/desk/index.html +10 -3
  74. package/examples/desk/lanes.css +21 -19
  75. package/examples/desk/routes.ts +0 -2
  76. package/examples/desk/stories.jsonl +4 -3
  77. package/examples/desk/tally.css +1 -1
  78. package/examples/desk/thumbs.ts +2 -2
  79. package/examples/docs.ts +7 -4
  80. package/examples/hello/generated/elements.ts +2 -2
  81. package/examples/hello/generated/rules.ts +3 -2
  82. package/examples/hello/hello.css +2 -4
  83. package/examples/hello/index.html +10 -3
  84. package/examples/hello/page.ts +4 -4
  85. package/examples/index.html +20 -12
  86. package/examples/notes/generated/elements.ts +112 -0
  87. package/examples/notes/generated/queries.ts +42 -0
  88. package/examples/notes/generated/rows.ts +27 -0
  89. package/examples/notes/generated/rules.ts +133 -0
  90. package/examples/notes/index.html +32 -0
  91. package/examples/notes/look.ts +41 -0
  92. package/examples/notes/migrations/001-notes.ts +7 -0
  93. package/examples/notes/notes.json +78 -0
  94. package/examples/notes/page.ts +21 -0
  95. package/examples/notes/routes.ts +6 -0
  96. package/examples/notes/stories.jsonl +24 -0
  97. package/examples/page.ts +9 -2
  98. package/examples/people/generated/rows.ts +22 -0
  99. package/examples/people/generated/rules.ts +11 -1
  100. package/examples/people/links.ts +8 -9
  101. package/examples/people/people.css +1 -1
  102. package/examples/people/routes.ts +1 -3
  103. package/examples/people/stories.jsonl +1 -0
  104. package/examples/people/view.ts +5 -2
  105. package/examples/trip/generated/elements.ts +5 -3
  106. package/examples/trip/generated/queries.ts +12 -1
  107. package/examples/trip/generated/rows.ts +27 -0
  108. package/examples/trip/generated/rules.ts +56 -2
  109. package/examples/trip/index.html +58 -12
  110. package/examples/trip/line.css +186 -0
  111. package/examples/trip/line.ts +51 -40
  112. package/examples/trip/page.ts +65 -71
  113. package/examples/trip/routes.ts +9 -5
  114. package/examples/trip/stays.css +13 -13
  115. package/examples/trip/stays.ts +15 -10
  116. package/examples/trip/stories.jsonl +2 -0
  117. package/examples/trip/told.ts +3 -26
  118. package/examples/trip/trip.css +16 -0
  119. package/examples/trips/generated/elements.ts +1 -1
  120. package/examples/trips/generated/rows.ts +22 -0
  121. package/examples/trips/generated/rules.ts +9 -1
  122. package/examples/trips/index.html +10 -10
  123. package/examples/trips/map.ts +3 -14
  124. package/examples/trips/new-trip.ts +14 -16
  125. package/examples/trips/trips.css +24 -23
  126. package/examples/weeks/generated/elements.ts +1 -1
  127. package/examples/weeks/generated/queries.ts +11 -0
  128. package/examples/weeks/generated/rows.ts +22 -0
  129. package/examples/weeks/generated/rules.ts +11 -5
  130. package/examples/weeks/routes.ts +3 -2
  131. package/examples/weeks/stories.jsonl +1 -0
  132. package/examples/welcome.css +43 -33
  133. package/package.json +8 -2
  134. package/src/attachment.ts +17 -2
  135. package/src/awesome.ts +103 -0
  136. package/src/board.css +76 -0
  137. package/src/board.ts +173 -0
  138. package/src/cli.ts +28 -3
  139. package/src/compile.ts +821 -109
  140. package/src/definitions.ts +113 -27
  141. package/src/demo.css +2 -5
  142. package/src/draft.ts +48 -27
  143. package/src/drawer.ts +248 -0
  144. package/src/engine.ts +253 -170
  145. package/src/fields.ts +341 -0
  146. package/src/file-value.ts +12 -2
  147. package/src/files.ts +113 -33
  148. package/src/ground.ts +110 -0
  149. package/src/icon-names.ts +19 -2
  150. package/src/keep.ts +16 -3
  151. package/src/kit.ts +51 -0
  152. package/src/link.ts +3 -3
  153. package/src/map.css +140 -0
  154. package/src/map.ts +200 -0
  155. package/src/mcp.ts +129 -24
  156. package/src/members/demo.ts +13 -12
  157. package/src/members/generated/rows.ts +22 -0
  158. package/src/members/generated/rules.ts +3 -2
  159. package/src/members/group.ts +105 -55
  160. package/src/members/keys.ts +95 -79
  161. package/src/members/panel.css +40 -35
  162. package/src/members/panel.ts +58 -37
  163. package/src/migrate.ts +178 -125
  164. package/src/migrations/005-change-kept.ts +7 -0
  165. package/src/month.css +129 -0
  166. package/src/month.ts +179 -0
  167. package/src/ops.ts +40 -1
  168. package/src/page.css +11 -2
  169. package/src/page.ts +68 -17
  170. package/src/parts.css +614 -230
  171. package/src/parts.ts +259 -36
  172. package/src/plane.css +61 -0
  173. package/src/plane.ts +153 -0
  174. package/src/postgres-server.ts +60 -0
  175. package/src/reading.css +73 -0
  176. package/src/reading.ts +238 -0
  177. package/src/rows.css +289 -0
  178. package/src/rows.ts +864 -0
  179. package/src/search.css +80 -0
  180. package/src/search.ts +130 -0
  181. package/src/server.ts +355 -137
  182. package/src/settings.ts +9 -4
  183. package/src/sheet.ts +116 -0
  184. package/src/skill.ts +40 -0
  185. package/src/slots.css +90 -0
  186. package/src/slots.ts +213 -0
  187. package/src/specs.ts +38 -0
  188. package/src/starter.ts +19 -2
  189. package/src/store.ts +224 -161
  190. package/src/stories.ts +43 -11
  191. package/src/surface.ts +164 -0
  192. package/src/time.ts +2 -0
  193. package/src/timeline.css +111 -0
  194. package/src/timeline.ts +235 -0
  195. package/src/toast.ts +21 -48
  196. package/src/together.ts +15 -24
  197. package/src/tokens.css +89 -3
  198. package/src/tokens.json +287 -7
  199. package/src/tool.ts +210 -0
  200. package/src/upkeep.ts +47 -22
  201. package/src/views.css +43 -0
  202. package/src/views.ts +111 -0
  203. package/src/week.css +150 -0
  204. package/src/week.ts +254 -0
  205. package/src/write.ts +326 -78
  206. package/starter/CHANGELOG.md +8 -0
  207. package/starter/CLAUDE.md +9 -3
  208. package/starter/bunfig +5 -0
  209. package/starter/githooks/pre-commit +13 -0
  210. package/starter/prettierignore +5 -0
  211. package/starter/tests/hello.test.ts +2 -0
  212. package/starter/tests/records.test.ts +40 -0
  213. package/starter/todo.jsonl +0 -0
  214. package/docs/learning.md +0 -76
  215. package/examples/cafe/trust.ts +0 -20
  216. package/examples/desk/trust.ts +0 -24
  217. package/examples/people/trust.ts +0 -14
  218. package/examples/trip/answer-rows.ts +0 -70
  219. package/examples/trip/bar.ts +0 -89
  220. package/examples/trip/calendar-map.css +0 -711
  221. package/examples/trip/calendar-map.ts +0 -249
  222. package/examples/trip/drags.ts +0 -143
  223. package/examples/trip/drawer.ts +0 -250
  224. package/examples/trip/event-form.ts +0 -200
  225. package/examples/trip/holding.ts +0 -61
  226. package/examples/trip/map.ts +0 -234
  227. package/examples/trip/month.ts +0 -87
  228. package/examples/trip/other-weeks.ts +0 -67
  229. package/examples/trip/peek.ts +0 -71
  230. package/examples/trip/people-chips.ts +0 -74
  231. package/examples/trip/shell.ts +0 -39
  232. package/examples/trip/trust.ts +0 -51
  233. package/examples/trip/week.ts +0 -237
  234. package/examples/trip/writes.ts +0 -91
  235. package/examples/trip/zones.ts +0 -16
  236. package/examples/weeks/derive.ts +0 -23
  237. package/src/scrim.ts +0 -81
package/src/migrate.ts CHANGED
@@ -47,7 +47,7 @@ export type Change =
47
47
  | { change: "guardTable"; key: string; table: Table };
48
48
  /** What a step does to the rows, once its changes are made, in its transaction: moves or fills them, by
49
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;
50
+ export type Up = (db: Engine, tools: { nextId: (table: string) => Promise<number> }) => unknown;
51
51
  /** One step of a history: its name (the file's), recorded once it has run, its changes, and its `up`. */
52
52
  export type Migration = { id: string; changes: Change[]; up?: Up };
53
53
 
@@ -129,8 +129,12 @@ export function applyChange(state: State, c: Change): State {
129
129
  };
130
130
  if (c.change === "createTable") (free(c.key), (next[c.key] = structuredClone(c.table)));
131
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)));
132
+ else if (c.change === "renameTable") {
133
+ (free(c.to), (next[c.to] = there(c.key)), delete next[c.key]);
134
+ // what links to it links to it by its new name
135
+ for (const t of Object.values(next))
136
+ for (const d of Object.values(t.columns)) if (d.to?.table === c.key) d.to.table = c.to;
137
+ } else if (c.change === "guardTable") (there(c.key), (next[c.key] = structuredClone(c.table)));
134
138
  else {
135
139
  const t = there(c.key);
136
140
  if ((c.change === "addColumn") === c.column in t.columns)
@@ -138,11 +142,27 @@ export function applyChange(state: State, c: Change): State {
138
142
  `${c.change}: ${c.key}.${c.column} ${c.change === "addColumn" ? "is there already" : "isn't there"}`,
139
143
  );
140
144
  if (c.change === "addColumn") t.columns[c.column] = { ...c.def };
141
- else if (c.change === "dropColumn") delete t.columns[c.column];
142
- else {
145
+ else if (c.change === "dropColumn") {
146
+ delete t.columns[c.column];
147
+ // a unique set it's in goes with it, as its index does (and the first's words, `once`, with that); an add
148
+ // needs it no longer
149
+ if (t.unique?.[0]?.includes(c.column)) delete t.once;
150
+ const unique = t.unique?.filter((u) => !u.includes(c.column));
151
+ if (unique?.length) t.unique = unique;
152
+ else delete t.unique;
153
+ const needs = t.needs?.columns.filter((x) => x !== c.column);
154
+ if (needs?.length) t.needs = { ...t.needs!, columns: needs };
155
+ else delete t.needs;
156
+ } else {
143
157
  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)));
158
+ const renamed = (x: string) => (x === c.column ? c.to : x);
159
+ // and the words that name its value written, `{column}`
160
+ const said = (s: string) => s.replaceAll(`{${c.column}}`, `{${c.to}}`);
161
+ t.columns = Object.fromEntries(Object.entries(t.columns).map(([k, d]) => [renamed(k), d]));
162
+ for (const d of Object.values(t.columns)) if (d.to) d.to.said = said(d.to.said);
163
+ if (t.unique) t.unique = t.unique.map((u) => u.map(renamed));
164
+ if (t.needs) t.needs = { columns: t.needs.columns.map(renamed), said: said(t.needs.said) };
165
+ if (t.once) t.once = said(t.once);
146
166
  }
147
167
  }
148
168
  return next;
@@ -214,7 +234,13 @@ export function diff(state: State, want: State): { changes: Change[]; byHand: st
214
234
  if (!same(was.unique ?? [], t.unique ?? []))
215
235
  byHand.push(`${key}: unique ${JSON.stringify(t.unique ?? [])}, was ${JSON.stringify(was.unique ?? [])}`);
216
236
  }
217
- for (const key of Object.keys(state)) if (!(key in want)) changes.push({ change: "dropTable", key });
237
+ const gone = Object.keys(state).filter((key) => !(key in want)),
238
+ made = Object.keys(want).filter((key) => !(key in state));
239
+ for (const key of gone) changes.push({ change: "dropTable", key });
240
+ if (gone.length && made.length)
241
+ byHand.push(
242
+ `${gone.join(", ")} gone and ${made.join(", ")} new: if one is the other renamed, make it renameTable (a drop loses its rows)`,
243
+ );
218
244
  return { changes, byHand };
219
245
  }
220
246
 
@@ -279,26 +305,32 @@ const SQL: Record<ColumnType, Record<Dialect, string> & { empty: string }> = {
279
305
  /** Where joined records what has run, and keeps each table's last id. */
280
306
  const RAN = "joined_migrations",
281
307
  SEQUENCES = "joined_sequences";
282
- const has = (db: Engine, table: string) => db.columns(table).length > 0;
308
+ const has = async (db: Engine, table: string) => (await db.columns(table)).length > 0;
283
309
  const uniqueName = (table: string, columns: string[]) => `idx_${table}_unique_${columns.join("_")}`;
284
310
  /** 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
311
+ async function uniquesOf(db: Engine, table: string): Promise<{ name: string; columns: string[] }[]> {
312
+ if (db.dialect === "sqlite") {
313
+ const made = (
314
+ (await db.query(`PRAGMA index_list(${q(table)})`).all()) as { name: string; origin: string }[]
315
+ ).filter((i) => i.origin === "c");
316
+ const out = [];
317
+ for (const i of made)
318
+ out.push({
319
+ name: i.name,
320
+ columns: ((await db.query(`PRAGMA index_info(${q(i.name)})`).all()) as { name: string }[]).map((c) => c.name),
321
+ });
322
+ return out;
323
+ }
324
+ return (
325
+ (await db
326
+ .query(
327
+ `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
328
  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
329
  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) }));
330
+ )
331
+ .all(q(table))) as { name: string; columns: string }[]
332
+ ).map((i) => ({ name: i.name, columns: JSON.parse(i.columns) }));
333
+ }
302
334
  const makeUnique = (db: Engine, table: string, columns: string[]) =>
303
335
  db.run(
304
336
  `CREATE UNIQUE INDEX IF NOT EXISTS ${q(uniqueName(table, columns))} ON ${q(table)} (${columns.map(q).join(", ")})`,
@@ -351,32 +383,34 @@ const tableSql = (db: Engine, key: string, t: Table) =>
351
383
  "PRIMARY KEY (id)",
352
384
  ].join(", ")})${t.strict && db.dialect === "sqlite" ? " STRICT" : ""}`;
353
385
  /** The triggers named so, whatever table each is on, dropped. */
354
- export const dropTriggers = (db: Engine, like: string) => {
355
- const found = db
386
+ export const dropTriggers = async (db: Engine, like: string) => {
387
+ const found = (await db
356
388
  .query(
357
389
  db.dialect === "sqlite"
358
390
  ? "SELECT name, tbl_name AS tbl FROM sqlite_master WHERE type = 'trigger' AND name LIKE ?"
359
391
  : "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
392
  )
361
- .all(like) as { name: string; tbl: string }[];
393
+ .all(like)) as { name: string; tbl: string }[];
362
394
  for (const { name, tbl } of found)
363
- db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
395
+ await db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
364
396
  };
397
+ /** Whether a row being inserted is an add, the one its table's sequence has just given out: a document brought in (a
398
+ * seed) has its own, and an item an undo puts back the one it had. */
399
+ export const isAdd = (table: string) => `NEW.id = (SELECT last FROM ${SEQUENCES} WHERE collection = '${table}')`;
365
400
  /** 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
401
  * sequence has just given out); a link to a row that
367
402
  * 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);
403
+ async function guardWith(db: Engine, key: string, t: Table | undefined) {
404
+ for (const when of ["insert", "update"]) await dropTriggers(db, `joined_${key}_${when}`);
405
+ await guardHeld(db, key, t);
371
406
  if (!t) return;
372
407
  const links = Object.entries(t.columns).flatMap(([c, d]): [string, string][] =>
373
408
  d.to
374
409
  ? [[`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
410
  : [],
376
411
  );
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}')`;
412
+ // (what isn't an add is held to its links by the foreign keys, at commit)
413
+ const add = isAdd(key);
380
414
  const insert: [string, string][] = [];
381
415
  if (t.needs)
382
416
  insert.push([`${add} AND (${t.needs.columns.map((c) => `NEW.${q(c)} IS NULL`).join(" OR ")})`, t.needs.said]);
@@ -386,9 +420,9 @@ function guardWith(db: Engine, key: string, t: Table | undefined) {
386
420
  `EXISTS (SELECT 1 FROM ${q(key)} WHERE ${t.unique[0].map((c) => `${q(c)} = NEW.${q(c)}`).join(" AND ")})`,
387
421
  t.once,
388
422
  ]);
389
- const trigger = (when: string, cases: [string, string][]) =>
423
+ const trigger = async (when: string, cases: [string, string][]) =>
390
424
  cases.length &&
391
- db.run(
425
+ (await db.run(
392
426
  triggerSql(db.dialect, {
393
427
  name: `joined_${key}_${when}`,
394
428
  at: "BEFORE",
@@ -396,36 +430,36 @@ function guardWith(db: Engine, key: string, t: Table | undefined) {
396
430
  table: key,
397
431
  body: cases.map(([cond, said]) => refuseSql(db.dialect, cond, words(said))).join(" "),
398
432
  }),
399
- );
400
- trigger("insert", insert);
401
- trigger("update", links);
433
+ ));
434
+ await trigger("insert", insert);
435
+ await trigger("update", links);
402
436
  }
403
437
 
404
438
  /** A Postgres table's links made its foreign keys, each once the table it links to is there (another app's may come
405
439
  * later: the store makes them, once every app's have run). */
406
- export function linked(db: Engine, key: string, t: Table | undefined) {
440
+ export async function linked(db: Engine, key: string, t: Table | undefined) {
407
441
  if (db.dialect === "sqlite") return;
408
442
  for (const [c, d] of Object.entries(t?.columns ?? {})) {
409
443
  const name = `${key}_${c}_fkey`;
410
444
  if (
411
445
  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)
446
+ (await has(db, d.to.table)) &&
447
+ !(await db.query("SELECT 1 FROM pg_constraint WHERE conrelid = to_regclass(?) AND conname = ?").get(q(key), name))
414
448
  )
415
- db.run(`ALTER TABLE ${q(key)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(c)})${references(db, d, true)}`);
449
+ await db.run(`ALTER TABLE ${q(key)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(c)})${references(db, d, true)}`);
416
450
  }
417
451
  }
418
452
 
419
453
  /** A table's links guarded where they point: a row linked to, removed, is refused before its foreign key would, in
420
454
  * words saying how many link to it. A trigger on the table linked to, made once that's there (another app's may
421
455
  * 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_%`);
456
+ export async function guardHeld(db: Engine, key: string, t: Table | undefined) {
457
+ await dropTriggers(db, `joined_${key}_held_%`);
424
458
  for (const [c, d] of Object.entries(t?.columns ?? {}))
425
- if (d.to?.held && has(db, d.to.table)) {
459
+ if (d.to?.held && (await has(db, d.to.table))) {
426
460
  const n = `(SELECT COUNT(*) FROM ${q(key)} WHERE ${q(c)} = OLD.id)`;
427
461
  const [one, many] = d.to.held.map((w) => `'${w.replaceAll("'", "''")}'`);
428
- db.run(
462
+ await db.run(
429
463
  triggerSql(db.dialect, {
430
464
  name: `joined_${key}_held_${c}`,
431
465
  at: "BEFORE",
@@ -442,97 +476,106 @@ export function guardHeld(db: Engine, key: string, t: Table | undefined) {
442
476
  }
443
477
 
444
478
  /** 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. */
479
+ * empty, and the table it links to; its columns in no order, as neither the CHECKs nor the keys have one. */
446
480
  const checks = (t: Table) => [
447
481
  !!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
- ]),
482
+ Object.entries(t.columns)
483
+ .map(([c, d]) => [
484
+ c,
485
+ d.is ? [d.is.type, d.is.form ?? null, d.is.said] : null,
486
+ !!d.nullable,
487
+ d.to?.table ?? null,
488
+ d.to?.onDelete ?? null,
489
+ ])
490
+ .sort(([a], [b]) => (String(a) < String(b) ? -1 : 1)),
455
491
  ];
456
492
 
457
493
  /** One change made on the database, the tables before it and after: its table's triggers made again from what it
458
494
  * is. */
459
- function make(db: Engine, c: Change, before: State, after: State) {
460
- guardWith(db, c.key, undefined);
495
+ async function make(db: Engine, c: Change, before: State, after: State) {
496
+ await guardWith(db, c.key, undefined);
461
497
  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);
498
+ if (!(await has(db, c.key))) await db.run(tableSql(db, c.key, c.table));
499
+ for (const u of c.table.unique ?? []) await makeUnique(db, c.key, u);
464
500
  } else if (c.change === "guardTable") {
465
501
  // its triggers alone, unless what a CHECK says changed: then
466
502
  if (same(checks(before[c.key]!), checks(c.table))) return guardWith(db, c.key, after[c.key]);
467
503
  // Postgres changes a table's CHECKs and foreign keys in place: each dropped, and made again from what it is
468
504
  if (db.dialect === "postgres") {
469
- for (const { name } of db
505
+ for (const { name } of (await db
470
506
  .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)}`);
507
+ .all(q(c.key))) as { name: string }[])
508
+ await db.run(`ALTER TABLE ${q(c.key)} DROP CONSTRAINT ${q(name)}`);
473
509
  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)}`);
510
+ if (d.is) await db.run(`ALTER TABLE ${q(c.key)} ADD${checkSql(db, col, d)}`);
475
511
  // 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`);
512
+ if (d.nullable) await db.run(`ALTER TABLE ${q(c.key)} ALTER COLUMN ${q(col)} DROP NOT NULL`);
477
513
  }
478
- linked(db, c.key, c.table);
514
+ await linked(db, c.key, c.table);
479
515
  return guardWith(db, c.key, after[c.key]);
480
516
  }
481
517
  // made anew beside it, its rows copied, and put in its place; what else names it (another's trigger) isn't
482
518
  // rewritten as it's renamed, so it names this one
483
- const there = db.columns(c.key),
519
+ const there = await db.columns(c.key),
484
520
  was = Object.keys(c.table.columns).filter((col) => there.includes(col));
485
- db.run(tableSql(db, `${c.key}__new`, c.table));
486
- db.run(
521
+ await db.run(tableSql(db, `${c.key}__new`, c.table));
522
+ await db.run(
487
523
  `INSERT INTO ${q(`${c.key}__new`)} (${["id", ...was].map(q).join(", ")}) SELECT ${["id", ...was].map(q).join(", ")} FROM ${q(c.key)}`,
488
524
  );
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);
525
+ await db.run(`DROP TABLE ${q(c.key)}`);
526
+ await db.run("PRAGMA legacy_alter_table = ON");
527
+ await db.run(`ALTER TABLE ${q(`${c.key}__new`)} RENAME TO ${q(c.key)}`);
528
+ await db.run("PRAGMA legacy_alter_table = OFF");
529
+ for (const u of c.table.unique ?? []) await makeUnique(db, c.key, u);
494
530
  } 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]);
531
+ await db.run(`DROP TABLE IF EXISTS ${q(c.key)}`);
532
+ await db.run(`DELETE FROM ${SEQUENCES} WHERE collection = ?`, [c.key]);
497
533
  } 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]);
534
+ await db.run(`ALTER TABLE ${q(c.key)} RENAME TO ${q(c.to)}`);
535
+ await guardWith(db, c.to, after[c.to]);
536
+ // the guards of what links to it made again, naming it by its new name (Postgres's triggers named it as it was)
537
+ for (const [key, t] of Object.entries(after))
538
+ if (key !== c.to && Object.values(t.columns).some((d) => d.to?.table === c.to)) await guardWith(db, key, t);
539
+ for (const u of await uniquesOf(db, c.to))
540
+ (await db.run(`DROP INDEX ${q(u.name)}`), await makeUnique(db, c.to, u.columns));
541
+ await db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
502
542
  } else if (c.change === "addColumn") {
503
543
  // every row takes the column's empty value; one with none (json, a time) is left to be empty
504
544
  const { empty } = SQL[c.def.type];
505
545
  const fill = c.def.nullable || empty === "NULL" ? "" : ` NOT NULL DEFAULT ${empty}`;
506
- db.run(
546
+ await db.run(
507
547
  `ALTER TABLE ${q(c.key)} ADD COLUMN ${columnSql(db, c.column, { ...c.def, nullable: true }, after[c.key]!.strict)}${fill}`,
508
548
  );
509
549
  } 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)}`);
550
+ for (const u of await uniquesOf(db, c.key))
551
+ if (u.columns.includes(c.column)) await db.run(`DROP INDEX ${q(u.name)}`);
552
+ await db.run(`ALTER TABLE ${q(c.key)} DROP COLUMN ${q(c.column)}`);
512
553
  } 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);
554
+ await db.run(`ALTER TABLE ${q(c.key)} RENAME COLUMN ${q(c.column)} TO ${q(c.to)}`);
555
+ for (const u of await uniquesOf(db, c.key)) await db.run(`DROP INDEX ${q(u.name)}`);
556
+ for (const u of after[c.key]!.unique ?? []) await makeUnique(db, c.key, u);
516
557
  }
517
- guardWith(db, c.key, after[c.key]);
558
+ await guardWith(db, c.key, after[c.key]);
518
559
  }
519
560
 
520
561
  /** 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(() => {
562
+ * ids it ran. Another process migrating the store at once waits for it, and finds what it ran done. A database
563
+ * from before 0.8 has delta's names for joined's two tables: they're renamed, and what they hold is kept. */
564
+ export async function migrate(db: Engine, app: string, list: Migration[]): Promise<string[]> {
565
+ await db.transaction(async () => {
525
566
  for (const [was, now] of [
526
567
  ["delta_migrations", RAN],
527
568
  ["_delta_sequences", SEQUENCES],
528
569
  ] as const)
529
- if (has(db, was) && !has(db, now)) db.run(`ALTER TABLE ${q(was)} RENAME TO ${now}`);
530
- db.run(
570
+ if ((await has(db, was)) && !(await has(db, now))) await db.run(`ALTER TABLE ${q(was)} RENAME TO ${now}`);
571
+ await db.run(
531
572
  `CREATE TABLE IF NOT EXISTS ${RAN} (app TEXT NOT NULL, id TEXT NOT NULL, ran_at TEXT NOT NULL, PRIMARY KEY (app, id))`,
532
573
  );
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));
574
+ await db.run(`CREATE TABLE IF NOT EXISTS ${SEQUENCES} (collection TEXT PRIMARY KEY, last INTEGER NOT NULL)`);
575
+ });
576
+ const done = new Set(
577
+ ((await db.query(`SELECT id FROM ${RAN} WHERE app = ?`).all(app)) as { id: string }[]).map((r) => r.id),
578
+ );
536
579
  const ran: string[] = [];
537
580
  let state: State = {};
538
581
  for (const m of list) {
@@ -543,50 +586,60 @@ export function migrate(db: Engine, app: string, list: Migration[]): string[] {
543
586
  // link to it (or refused by them): its foreign keys are off while it runs (they can't be turned off inside its
544
587
  // transaction), and checked whole before it commits
545
588
  const rebuilds = db.dialect === "sqlite" && m.changes.some((c) => c.change === "guardTable");
546
- if (rebuilds) db.run("PRAGMA foreign_keys = OFF");
589
+ if (rebuilds) await db.run("PRAGMA foreign_keys = OFF");
590
+ let made = false;
547
591
  try {
548
- db.transaction(() => {
592
+ await db.transaction(async () => {
593
+ // another process may have run it since this one looked (one transaction at a time, whoever's: src/engine.ts)
594
+ if (await db.query(`SELECT 1 FROM ${RAN} WHERE app = ? AND id = ?`).get(app, m.id)) return;
549
595
  // 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) => {
596
+ await db.defer();
597
+ let s = before;
598
+ for (const c of m.changes) {
552
599
  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");
600
+ await make(db, c, s, after);
601
+ s = after;
602
+ }
603
+ // an up's statements, each waited for (one written before joined was async runs them without waiting)
604
+ const asked: Promise<unknown>[] = [];
605
+ const said = <T>(p: Promise<T>) => (asked.push(p), p);
606
+ const its: Engine = {
607
+ ...db,
608
+ run: (sql, args) => said(db.run(sql, args)),
609
+ query: (sql) => ({
610
+ get: (...args) => said(db.query(sql).get(...args)),
611
+ all: (...args) => said(db.query(sql).all(...args)),
612
+ }),
613
+ };
614
+ await m.up?.(its, { nextId: (table) => said(nextId(db, table)) });
615
+ await Promise.all(asked);
559
616
  if (rebuilds) {
560
- const loose = db.query("PRAGMA foreign_key_check").get() as { table: string; parent: string } | null;
617
+ const loose = (await db.query("PRAGMA foreign_key_check").get()) as { table: string; parent: string } | null;
561
618
  if (loose) throw new Error(`${loose.table} links to no row of ${loose.parent}`);
562
619
  }
563
- db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
564
- }).immediate();
620
+ await db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
621
+ made = true;
622
+ });
565
623
  } catch (e) {
566
624
  throw new Error(`${app}'s migration ${m.id} failed, and was rolled back: ${(e as Error).message}`);
567
625
  } finally {
568
- if (rebuilds) db.run("PRAGMA foreign_keys = ON");
626
+ if (rebuilds) await db.run("PRAGMA foreign_keys = ON");
569
627
  }
570
- ran.push(m.id);
628
+ if (made) ran.push(m.id);
571
629
  }
572
630
  return ran;
573
631
  }
574
632
 
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;
633
+ /** The next id for a table, handed out in one statement (two servers on one database never take the same): never
634
+ * one handed out before, even when that row is gone. */
635
+ export async function nextId(db: Engine, table: string) {
636
+ const most = `(SELECT COALESCE(MAX(id), 0) + 1 FROM ${q(table)})`;
637
+ const r = (await db
638
+ .query(
639
+ `INSERT INTO ${SEQUENCES} (collection, last) VALUES (?, ${most}) ON CONFLICT (collection) DO UPDATE SET last = ${db.dialect === "sqlite" ? "MAX" : "GREATEST"}(${SEQUENCES}.last + 1, ${most}) RETURNING last`,
640
+ )
641
+ .get(table)) as { last: number };
642
+ return r.last;
590
643
  }
591
644
 
592
645
  /** A table's last id kept at least `id`: a document brought in with ids of its own. */
@@ -0,0 +1,7 @@
1
+ // A change row's kept write: the id a page gave a write it kept while away (src/outbox.ts), on the row of the change
2
+ // it made, so the same write sent again (its answer lost, or two tabs sending what one device kept) is answered done
3
+ // and not made twice. A row from before has none. Written by hand, as joined's code is; never changed once it has run
4
+ // anywhere.
5
+ import { addColumn } from "../migrate.ts";
6
+
7
+ export const changes = [addColumn("changes", "kept", "text?")];
package/src/month.css ADDED
@@ -0,0 +1,129 @@
1
+ /* <j-month> (./month.ts), in its shadow: its head, the days' names, six weeks of days, and under them the marked
2
+ day's items with Add. Wide, each day says its items; on a phone, a mark, and the marked day's are listed. */
3
+ .names,
4
+ .days {
5
+ display: grid;
6
+ grid-template-columns: repeat(7, minmax(0, 1fr));
7
+ }
8
+ .names {
9
+ padding: 0 0 var(--space-4);
10
+ color: var(--muted);
11
+ font: var(--font-tiny);
12
+ text-align: center;
13
+ }
14
+ .days {
15
+ border-top: 1px solid var(--line);
16
+ }
17
+ .day {
18
+ position: relative;
19
+ box-sizing: border-box;
20
+ min-width: 0;
21
+ min-height: calc(var(--space-64) + var(--space-24));
22
+ display: flex;
23
+ flex-direction: column;
24
+ align-items: stretch;
25
+ gap: var(--space-4);
26
+ padding: var(--space-4);
27
+ border-bottom: 1px solid var(--line);
28
+ border-left: 1px solid var(--line);
29
+ }
30
+ .day:nth-child(7n + 1) {
31
+ border-left: 0;
32
+ }
33
+ .day[away] > .n {
34
+ color: var(--muted);
35
+ }
36
+ .day[over] {
37
+ background: var(--card-hover);
38
+ outline: 1px solid var(--accent);
39
+ outline-offset: -1px;
40
+ }
41
+ /* a day's number: a tap marks the day. Today's is ringed; the marked day's filled */
42
+ .n {
43
+ align-self: flex-start;
44
+ box-sizing: border-box;
45
+ min-width: var(--space-24);
46
+ height: var(--space-24);
47
+ padding: 0 var(--space-4);
48
+ border: 1px solid transparent;
49
+ border-radius: var(--radius-pill);
50
+ background: none;
51
+ color: var(--ink);
52
+ font: var(--font-small);
53
+ font-variant-numeric: tabular-nums;
54
+ cursor: pointer;
55
+ }
56
+ .n:hover {
57
+ border-color: var(--control-edge);
58
+ }
59
+ .n[today] {
60
+ border-color: var(--ink);
61
+ }
62
+ .n[aria-current] {
63
+ border-color: var(--accent);
64
+ background: var(--accent);
65
+ color: var(--card);
66
+ }
67
+ /* the mark that a day has items: shown where their words aren't (on a phone) */
68
+ .mark {
69
+ display: none;
70
+ align-self: center;
71
+ width: var(--space-6);
72
+ height: var(--space-6);
73
+ border-radius: var(--radius-dot);
74
+ background: var(--accent);
75
+ }
76
+ /* the marked day, under the month: its name, Add, and its items, each a row */
77
+ .that-day {
78
+ padding: var(--space-8) var(--space-16) var(--space-12);
79
+ }
80
+ .that-day > header {
81
+ display: flex;
82
+ align-items: center;
83
+ gap: var(--space-8);
84
+ min-height: var(--size-touch);
85
+ }
86
+ .that-day h4 {
87
+ flex: 1;
88
+ margin: 0;
89
+ font: var(--font-label);
90
+ }
91
+ .that-day ul {
92
+ display: grid;
93
+ gap: var(--space-6);
94
+ margin: var(--space-8) 0 0;
95
+ padding: 0;
96
+ list-style: none;
97
+ }
98
+ .that-day ul:empty {
99
+ display: none;
100
+ }
101
+ .that-day .item {
102
+ width: 100%;
103
+ min-height: var(--size-touch);
104
+ padding: 0 var(--space-12);
105
+ font: var(--font-row);
106
+ }
107
+ @media (max-width: 40rem) {
108
+ .day {
109
+ min-height: var(--size-finger);
110
+ align-items: center;
111
+ padding: var(--space-4) 0;
112
+ }
113
+ /* the day's number is what's tapped: a finger, as tall as the day */
114
+ .n {
115
+ align-self: center;
116
+ min-width: var(--size-finger);
117
+ height: var(--size-finger);
118
+ }
119
+ .day > .item {
120
+ display: none;
121
+ }
122
+ .mark {
123
+ display: block;
124
+ }
125
+ .that-day .item,
126
+ .that-day .adding {
127
+ min-height: var(--size-finger);
128
+ }
129
+ }