@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/server.ts CHANGED
@@ -24,19 +24,32 @@ import { groupOf, say, type Data, type Who } from "./members/group.ts";
24
24
  import { fromHere } from "./members/demo.ts";
25
25
  import { door, type Written } from "./mcp.ts";
26
26
  import { bdflOf, type Asked, type Member } from "./members/trust.ts";
27
- import { attribute, docParts, parts, valueAt, versionKey, type Change, type Op, type Type } from "./ops.ts";
27
+ import {
28
+ attribute,
29
+ docParts,
30
+ isOp,
31
+ MESSAGE,
32
+ OPS,
33
+ parts,
34
+ valueAt,
35
+ versionKey,
36
+ type Change,
37
+ type Op,
38
+ type Type,
39
+ } from "./ops.ts";
28
40
  import { openStore, Refused, type Doc } from "./store.ts";
29
41
  import { madeBy, type Part } from "./together.ts";
30
- import { writes, type Held, type Reactions, type Read, type Rules, type Told, type Trust } from "./write.ts";
42
+ import { Made, writes, type Held, type Reactions, type Read, type Rules, type Told, type Trust } from "./write.ts";
31
43
  /** A write refused, and why, in words a page shows as they are: a reaction or a route throws it. */
32
44
  export { Refused };
33
45
  export type { Reactions, Read, Trust };
34
46
  import { upkeep, KEEP } from "./upkeep.ts";
47
+ import { folderOf } from "./file-value.ts";
35
48
  import { filesAt, letGo, named, putsFile, routes as fileRoutes, type Files } from "./files.ts";
36
49
  import { version } from "../package.json";
37
50
 
38
- /** The most a page's message may be, in bytes. */
39
- const MESSAGE = 1 << 20;
51
+ /** How many documents a page holds at once (each write views every one held): past it, one is let go first. */
52
+ const HELD = 64;
40
53
  /** A timed field's clearing that failed is tried again a minute on; a timer waits at most what setTimeout can. */
41
54
  const MINUTE = 60_000,
42
55
  DAY = 1440 * MINUTE,
@@ -54,6 +67,8 @@ type Message = {
54
67
  writes?: Part[];
55
68
  /** A change of the document to undo, by its version: the page's own. */
56
69
  undo?: number;
70
+ /** A write kept while away, its own id (src/outbox.ts): sent again, it's answered done, not made twice. */
71
+ kept?: string;
57
72
  } & Asked;
58
73
 
59
74
  /** A page's message, read; or why it isn't one joined reads. */
@@ -65,16 +80,14 @@ export function messageOf(text: string): Message | string {
65
80
  return "that isn't JSON";
66
81
  }
67
82
  if (typeof m !== "object" || m === null || Array.isArray(m)) return "a message is a JSON object";
68
- const { id, subscribe, since, unsubscribe, doc, ops, why, writes, undo } = m as Record<string, unknown>;
69
- const op = (o: any) =>
70
- typeof o === "object" && o !== null && ["add", "replace", "remove"].includes(o.op) && typeof o.path === "string";
83
+ const { id, subscribe, since, unsubscribe, doc, ops, why, writes, undo, kept } = m as Record<string, unknown>;
71
84
  const part = (w: any) =>
72
85
  typeof w === "object" &&
73
86
  w !== null &&
74
87
  typeof w.doc === "string" &&
75
88
  (w.why === undefined || typeof w.why === "string") &&
76
89
  Array.isArray(w.ops) &&
77
- w.ops.every(op);
90
+ w.ops.every(isOp);
78
91
  if (writes !== undefined && [doc, ops, why].some((x) => x !== undefined))
79
92
  return "a write is a doc and its ops, or writes, each its own: not both";
80
93
  if (writes !== undefined && !(Array.isArray(writes) && writes.length && writes.every(part)))
@@ -86,24 +99,55 @@ export function messageOf(text: string): Message | string {
86
99
  if (since !== undefined && !Number.isInteger(since)) return "since is a version";
87
100
  if (undo !== undefined && !(Number.isInteger(undo) && typeof doc === "string"))
88
101
  return "an undo is a document's version";
89
- if (ops !== undefined && !(Array.isArray(ops) && ops.every(op)))
90
- return "ops are each an add, a replace or a remove, at a path";
102
+ if (ops !== undefined && !(Array.isArray(ops) && ops.every(isOp))) return OPS;
103
+ if (kept !== undefined && !(typeof kept === "string" && kept)) return "kept is a kept write's own id, in words";
104
+ if (kept !== undefined && ops === undefined && writes === undefined) return "only a write is kept";
91
105
  return m as Message;
92
106
  }
93
107
 
108
+ /** A message's id, where it's JSON with a number for one, though it's no message joined takes; else null. */
109
+ const idIn = (text: string): number | null => {
110
+ try {
111
+ const id = JSON.parse(text)?.id;
112
+ return typeof id === "number" ? id : null;
113
+ } catch {
114
+ return null;
115
+ }
116
+ };
117
+
94
118
  /** Whether a request comes from another site's page, which would send it with this one's cookie (a socket opened, a
95
- * file sent); a sandboxed frame's says "null". None said: a program's, not a page's. */
119
+ * file sent, a sign-out); a sandboxed frame's says "null". None said: a program's, not a page's. This site is its
120
+ * host and its scheme, as the request came: over https where a proxy in front (Railway's) says it took it so. */
96
121
  const anotherSite = (req: Request) => {
97
122
  const origin = req.headers.get("origin");
98
- return !!origin && (!URL.canParse(origin) || new URL(origin).host !== new URL(req.url).host);
123
+ if (!origin) return false;
124
+ if (!URL.canParse(origin)) return true;
125
+ const from = new URL(origin),
126
+ to = new URL(req.url),
127
+ scheme = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
128
+ return from.host !== to.host || from.protocol !== (scheme ? `${scheme}:` : to.protocol);
99
129
  };
130
+ /** A route's answer, but to another site's page sending what isn't a read (a sign-out, a post to an edge). */
131
+ const ownSite =
132
+ (answer: Handler): Handler =>
133
+ (req: Request) =>
134
+ req.method !== "GET" && req.method !== "HEAD" && anotherSite(req)
135
+ ? new Response("another site", { status: 403 })
136
+ : answer(req);
137
+
138
+ /** The MCP door, but to another site's page posting to it (a DNS rebinding, MCP's transport says, refused 403). */
139
+ const mine = (d: ReturnType<typeof door>) => ({ ...d, POST: ownSite(d.POST) });
140
+
141
+ /** What fails in the background (a change told, the clock, another server's change heard), said, and the server goes on. */
142
+ const failed = (what: string) => (e: unknown) => console.error(`${what} failed:`, e);
100
143
 
101
144
  /** joined's icon (an elephant in wood joinery, its trunk a j), 180 square. */
102
145
  const ICON = `${import.meta.dir}/icon.png`;
103
146
 
104
147
  /** A write by the server itself, a route's or a job's: shaped as the stories say, but asked of no roles and no
105
- * trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused. */
106
- export type Write = (doc: string, ops: Op[]) => Change;
148
+ * trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused, once it
149
+ * has (await it). A route reads what it needs before it writes. */
150
+ export type Write = (doc: string, ops: Op[]) => Promise<Change>;
107
151
  /** A derived document (its app's derive.ts, exported from its routes.ts): what it is now, for a member (nobody, 0),
108
152
  * read off the documents it's derived from. Read-only: its pages write the documents it's read from. */
109
153
  export type Derive = (read: Read, member: number) => Record<string, { id: number }[]>;
@@ -228,7 +272,18 @@ export async function start({
228
272
  : [],
229
273
  );
230
274
  for (const { rules: r } of held) rules[r.doc] = r;
231
- const trusts = Object.fromEntries(apps.flatMap((a) => (a.trust ? docsOf(a).map((d) => [d.doc, a.trust!]) : [])));
275
+ // each app's own rules, and how many writes each has refused: its stories, told, hold it to one (src/stories.ts)
276
+ const ruled = new Map(apps.flatMap((a) => (a.trust ? [[a.app, 0] as [string, number]] : [])));
277
+ const noting =
278
+ (app: string, trust: Trust): Trust =>
279
+ (...asked) => {
280
+ const why = trust(...asked);
281
+ if (why) ruled.set(app, ruled.get(app)! + 1);
282
+ return why;
283
+ };
284
+ const trusts = Object.fromEntries(
285
+ apps.flatMap((a) => (a.trust ? docsOf(a).map((d) => [d.doc, noting(a.app, a.trust!)]) : [])),
286
+ );
232
287
  const reacts = Object.fromEntries(
233
288
  apps.flatMap((a) => (a.reactions ? docsOf(a).map((d) => [d.doc, a.reactions!]) : [])),
234
289
  );
@@ -258,12 +313,12 @@ export async function start({
258
313
  // a static document is its seed: a release's, past the store's version, is taken in place of what was
259
314
  if (r.type === "static") {
260
315
  const seed = await Bun.file(await seedOf(at, r.doc)).json();
261
- if (!store.holds(r.doc) || seed.version > store.read(r.doc).version)
262
- taken.push({ doc: r.doc, json: seed, again: store.holds(r.doc) });
316
+ const had = await store.holds(r.doc);
317
+ if (!had || seed.version > (await store.read(r.doc)).version) taken.push({ doc: r.doc, json: seed, again: had });
263
318
  continue;
264
319
  }
265
320
  // a document read by member is a query over others' rows: there's nothing of its own to begin
266
- if (r.derived || r.member || store.holds(r.doc)) continue;
321
+ if (r.derived || r.member || (await store.holds(r.doc))) continue;
267
322
  const before = data[r.doc] ?? `${DATA}/${r.doc}.json`;
268
323
  const kept = await Bun.file(before).exists();
269
324
  const seed = await seedOf(at, r.doc);
@@ -272,26 +327,28 @@ export async function start({
272
327
  const json = (await from.exists()) ? await from.json() : { version: 1 };
273
328
  taken.push({ doc: r.doc, json, ...(kept ? { kept: before } : {}) });
274
329
  }
275
- store.takeAll(taken);
330
+ await store.takeAll(taken);
276
331
  for (const { kept } of taken) if (kept && lasts) renameSync(kept, `${kept}.imported`);
277
- // (a SQLite file's: a Postgres store's vacuum and backups aren't joined's, nor letting its files go); a file nothing
278
- // names is let go once it's older than the history, and than a week's backups, which may name it still
332
+ // (old changes and files on any store; vacuum and backups a SQLite file's alone, Postgres keeping its own); a file
333
+ // nothing names is let go once it's older than the history, and than a week's backups, which may name it still
279
334
  const tables = held.filter((h) => !h.rules.derived && !h.rules.member).map((h) => h.rules),
280
335
  filesKept = typeof files === "string" ? filesAt(files) : files;
281
- const kept =
282
- lasts && engine === "sqlite"
283
- ? upkeep(store.db, backups, console.log, {
284
- trim: () => store.trim(Date.now() - history * DAY),
285
- letGo: () => letGo(filesKept, named(store.db, tables), Date.now() - Math.max(history, KEEP) * DAY),
286
- })
287
- : null;
288
- const { land, view, ungranted, ask, read, rulesOf, mayHold, mayOf, groupless, byCode, exists } = writes({
289
- store,
290
- rules,
291
- group: GROUP,
292
- trusts,
293
- reacts,
294
- });
336
+ const kept = lasts
337
+ ? upkeep(store.db, backups, console.log, {
338
+ sqlite: engine === "sqlite",
339
+ trim: () => store.trim(Date.now() - history * DAY),
340
+ letGo: async () => letGo(filesKept, await named(store.db, tables), Date.now() - Math.max(history, KEEP) * DAY),
341
+ })
342
+ : null;
343
+ const { land, view, ungranted, ask, read, settle, now, wrote, rulesOf, mayHold, mayOf, groupless, byCode, exists } =
344
+ writes({
345
+ store,
346
+ rules,
347
+ group: GROUP,
348
+ trusts,
349
+ reacts,
350
+ open: !(members && rootToken),
351
+ });
295
352
 
296
353
  // What each page holds beside whole documents, by its topic: a window of one (trip?week=2026-11-02), or a document as
297
354
  // a person sees it (`<doc>@<member>`, nobody 0), where that's only some of it (owns) or it's read as each has it;
@@ -320,17 +377,22 @@ export async function start({
320
377
  };
321
378
  /** What landed, published once it has committed: each change to its document's topic (a document seen whole), and
322
379
  * what's told to each window and view; and each document derived from one of them, derived again for each page
323
- * holding it. The one place anything is published: here, once the store's write commits; on Postgres, as each
324
- * commit is notified. */
325
- const tell = ({ changes, told }: { changes: Change[]; told: Told }) => {
380
+ * holding it. The one place anything is published: here, once the store's write commits. */
381
+ let telling = Promise.resolve();
382
+ const tell = (landed: { changes: Change[]; told: Told }) =>
383
+ (telling = telling.then(() => toldAll(landed)).catch(failed("telling a change")));
384
+ async function toldAll({ changes, told }: { changes: Change[]; told: Told }) {
326
385
  const written = new Set(changes.map((change) => docParts(change.doc).name));
327
386
  // a page holding a document by a root item's code (an instance, or the root's own), where the root's document
328
- // changed (its level, its code), asked again whether it may hold it, and refused as at the door if not, before
329
- // anything's told: told no more
387
+ // changed (its level, its code), or one only some roles may hold (its where's: a role lost, a post taken away),
388
+ // asked again whether it may hold it, and refused as at the door if not, before anything's told: told no more
330
389
  for (const ws of pages)
331
390
  for (const doc of ws.data.docs) {
332
- const root = !derives.has(doc) && byCode(doc);
333
- const no = root && written.has(root) && mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
391
+ const root = !derives.has(doc) && byCode(doc),
392
+ gated = !derives.has(doc) && !!rulesOf(doc).mayHold;
393
+ const no =
394
+ ((root && written.has(root)) || gated) &&
395
+ (await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken)));
334
396
  if (no)
335
397
  (ws.data.docs.delete(doc),
336
398
  ws.unsubscribe(topicOf(ws, doc)),
@@ -350,12 +412,12 @@ export async function start({
350
412
  }
351
413
  for (const doc of derives.keys())
352
414
  if (rulesOf(doc).derived!.some((d) => written.has(d)))
353
- for (const ws of pages) if (ws.data.docs.has(doc)) derivedTo(ws, doc);
415
+ for (const ws of pages) if (ws.data.docs.has(doc)) await derivedTo(ws, doc);
354
416
  // what each page's person may do, where the write changed it (an item come or moved, a role gained): worked out
355
417
  // once for each person and document, however many pages they have open
356
418
  const asked = new Map<string, ReturnType<typeof mayIn>>();
357
- for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) mayTo(ws, doc, asked);
358
- };
419
+ for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) await mayTo(ws, doc, asked);
420
+ }
359
421
  /** What each page was last sent of each derived document (by its name) and told it may do in each it holds
360
422
  * (`may <doc>`): each sent again only when it's changed. */
361
423
  const last = new WeakMap<ServerWebSocket<Data>, Map<string, string>>();
@@ -371,32 +433,40 @@ export async function start({
371
433
  );
372
434
  /** A derived document, as a page's member has it now, sent to the page if it isn't what it was sent last; its
373
435
  * version, the sum of the versions of the documents it's derived from. */
374
- function derivedTo(ws: ServerWebSocket<Data>, doc: string) {
375
- const value = derives.get(doc)!(read, ws.data.who?.member ?? 0);
436
+ async function derivedTo(ws: ServerWebSocket<Data>, doc: string) {
437
+ const value = await settle((read) => derives.get(doc)!(read, ws.data.who?.member ?? 0));
376
438
  if (!fresh(ws, doc, JSON.stringify(value))) return;
377
- const version = rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0);
439
+ const version = await versionsOf(doc);
378
440
  say(ws, { doc, version, ops: [{ op: "replace", path: "", value }] });
379
441
  }
380
442
  /** What a person may do in a document they hold (src/write.ts, mayOf): nothing, where the group would refuse them any
381
443
  * write (removed, read-only, not signed in), but in a document that's anonymous, which is anyone's, or as a
382
444
  * stranger its guest. */
383
- const mayIn = (doc: string, who: Data["who"]) =>
384
- groupless(doc, who) || !("refused" in group.write(docParts(doc).base, [], who))
445
+ const mayIn = async (doc: string, who: Data["who"]): ReturnType<typeof mayOf> =>
446
+ groupless(doc, who) || !("refused" in (await group.write(docParts(doc).base, [], who)))
385
447
  ? mayOf(doc, who?.member ?? null)
386
448
  : {};
449
+ /** A derived document's version: the sum of the versions of the documents it's derived from. */
450
+ const versionsOf = async (doc: string) => {
451
+ let n = 0;
452
+ for (const d of rulesOf(doc).derived!) n += await store.versions(d);
453
+ return n;
454
+ };
387
455
  /** What a page's person may do in a document, told to the page (`{ doc, may }`) if it isn't what it was told last. */
388
- function mayTo(ws: ServerWebSocket<Data>, doc: string, asked?: Map<string, ReturnType<typeof mayIn>>) {
456
+ async function mayTo(ws: ServerWebSocket<Data>, doc: string, asked?: Map<string, ReturnType<typeof mayIn>>) {
389
457
  const key = `${doc} ${ws.data.who?.member ?? ""} ${ws.data.who?.agent?.id ?? ""}`;
390
- const may = asked?.get(key) ?? mayIn(doc, ws.data.who);
391
- asked?.set(key, may);
458
+ const asking = asked?.get(key) ?? mayIn(doc, ws.data.who);
459
+ asked?.set(key, asking);
460
+ const may = await asking;
392
461
  if (fresh(ws, `may ${doc}`, JSON.stringify(may))) say(ws, { doc, may });
393
462
  }
394
- const write: Write = (doc, ops) => {
395
- if (docParts(doc).name === GROUP || !store.exists(doc)) throw new Refused(`the server can't write ${doc}`);
396
- const why = ungranted(doc, ops, null);
463
+ const write: Write = async (doc, ops) => {
464
+ wrote();
465
+ if (docParts(doc).name === GROUP || !(await store.exists(doc))) throw new Refused(`the server can't write ${doc}`);
466
+ const why = await ungranted(doc, ops, null);
397
467
  if (why) throw new Refused(why);
398
- const landed = land([{ doc, ops }], null, null, { held: pagesHold() });
399
- tell(landed);
468
+ const landed = await land([{ doc, ops }], null, null, { held: pagesHold() });
469
+ await tell(landed);
400
470
  retime();
401
471
  return landed.changes[0]!;
402
472
  };
@@ -404,16 +474,16 @@ export async function start({
404
474
  * since), written as the server's own write, by whoever undoes it, and told as any change is; what the rules
405
475
  * over values did as it was made, they undo as it's undone. An undo undone is a redo. Never the group's: its links
406
476
  * and its keys aren't put back. */
407
- const undo = (name: string, version: number, by: number | null = null) => {
477
+ const undo = async (name: string, version: number, by: number | null = null) => {
408
478
  // a window's change is its document's
409
479
  const doc = docParts(name).base;
410
480
  if (docParts(doc).name === GROUP) throw new Refused("the group's changes aren't undone");
411
- const ops = store.undoing(doc, version);
481
+ const ops = await store.undoing(doc, version);
412
482
  // held to the stories as any write is
413
- const why = ungranted(doc, ops, null, true, true);
483
+ const why = await ungranted(doc, ops, null, true, true);
414
484
  if (why) throw new Refused(why);
415
- const landed = land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
416
- tell(landed);
485
+ const landed = await land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
486
+ await tell(landed);
417
487
  retime();
418
488
  return landed.changes[0]!;
419
489
  };
@@ -431,12 +501,16 @@ export async function start({
431
501
  lasts,
432
502
  read,
433
503
  // what each member may hold (asked once the server's made, as each page is told who it is)
434
- holds: (member) => Object.keys(rules).filter((doc) => doc !== GROUP && !mayRead(doc, member)),
504
+ holds: async (member) => {
505
+ const docs: string[] = [];
506
+ for (const doc of Object.keys(rules)) if (doc !== GROUP && !(await mayRead(doc, member))) docs.push(doc);
507
+ return docs;
508
+ },
435
509
  // a demo's, from this machine alone: asked once the server listens, of each request
436
510
  demo: demo ? (req) => fromHere(req, server.requestIP(req)?.address) : undefined,
437
511
  // in by their link: the act their invitation names, done for them as them, once, then gone
438
512
  accepted: async (who) => {
439
- const act = (read(GROUP).members as Member[]).find((m) => m.id === who.member)?.act;
513
+ const act = ((await read(GROUP)).members as Member[]).find((m) => m.id === who.member)?.act;
440
514
  if (!act) return;
441
515
  const [name = "", word = ""] = act.split(" ");
442
516
  const w = acts[name]?.(who.member, word);
@@ -453,14 +527,14 @@ export async function start({
453
527
  // group's, then every app's, and no path answered by two; an app's edge is guarded by the group
454
528
  const icon = () => new Response(Bun.file(ICON));
455
529
  /** Whether a member may read a document: why not, or nothing (as the door and /export ask it). */
456
- const mayRead = (doc: string, member: number) =>
457
- derives.has(doc) || exists(doc) ? mayHold(doc, member, false) : `there's no document called ${doc}`;
530
+ const mayRead = async (doc: string, member: number) =>
531
+ derives.has(doc) || (await exists(doc)) ? mayHold(doc, member, false) : `there's no document called ${doc}`;
458
532
  /** A document as a member sees it, with its version (a derived one's, the sum of what it's derived from). */
459
- const asMember = (doc: string, member: number) =>
533
+ const asMember = async (doc: string, member: number): Promise<Doc> =>
460
534
  derives.has(doc)
461
535
  ? {
462
- version: rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0),
463
- ...derives.get(doc)!(read, member),
536
+ version: await versionsOf(doc),
537
+ ...(await settle((read) => derives.get(doc)!(read, member))),
464
538
  }
465
539
  : view(doc, member);
466
540
  /** The MCP door, for an agent's link (src/mcp.ts): the documents' rules, read and written as a page does. */
@@ -479,41 +553,102 @@ export async function start({
479
553
  if (anotherSite(req)) return "another site";
480
554
  const signed = await group.at(req),
481
555
  who = signed instanceof Response ? null : signed;
482
- if (!store.exists(doc)) return `there's no document called ${doc}`;
556
+ if (!(await store.exists(doc))) return `there's no document called ${doc}`;
557
+ return (
558
+ (await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
559
+ (putsFile(rulesOf(doc).collections, await mayIn(doc, who))
560
+ ? null
561
+ : `you may not put a file in ${docParts(doc).base}`)
562
+ );
563
+ };
564
+ /** Why someone may not be sent an instance's file (src/files.ts), or null: they may hold it, as a member by their
565
+ * link or a guest by its code, and see an item naming it. */
566
+ const mayHoldFiles = async (req: Request, doc: string, name: string) => {
567
+ if (!(await store.exists(docParts(doc).base))) return `there's no document called ${docParts(doc).base}`;
568
+ const signed = await group.at(req),
569
+ who = signed instanceof Response ? null : signed;
483
570
  return (
484
- mayHold(doc, who?.member ?? null, !(members && rootToken)) ??
485
- (putsFile(rulesOf(doc).collections, mayIn(doc, who)) ? null : `you may not put a file in ${docParts(doc).base}`)
571
+ (await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
572
+ (JSON.stringify(await view(doc, who?.member ?? 0)).includes(`file:${name}`)
573
+ ? null
574
+ : `no item you see names ${name}`)
486
575
  );
487
576
  };
577
+ /** Whether a document's kind keeps its files apart, each instance's in a folder of its own. */
578
+ const apart = async (doc: string) =>
579
+ ((await exists(doc)) || (await store.exists(doc))) && rulesOf(doc).kind?.files === "apart";
488
580
  const routes: Routes = {
489
581
  "/health": () => new Response("ok"),
490
582
  "/version": () => Response.json({ joined: version, build }),
491
583
  "/favicon.ico": icon,
492
584
  "/apple-touch-icon.png": icon,
493
585
  "/apple-touch-icon-precomposed.png": icon,
494
- ...group.routes,
586
+ // the group's, each of them but a read refused to another site's page
587
+ ...Object.fromEntries(
588
+ Object.entries(group.routes).map(([path, r]) => [
589
+ path,
590
+ typeof r === "function"
591
+ ? ownSite(r as Handler)
592
+ : Object.fromEntries(Object.entries(r).map(([method, fn]) => [method, ownSite(fn as Handler)])),
593
+ ]),
594
+ ),
495
595
  // everything a member can see, as JSON: each document as they see it, each kind's instances by their key; theirs
496
596
  // to keep, or to take elsewhere
497
- "/export": group.edge((_req, who) => {
597
+ "/export": group.edge(async (_req, who) => {
498
598
  const member = who?.member ?? 0,
499
599
  everything: Record<string, unknown> = {};
500
600
  for (const r of Object.values(rules)) {
501
601
  const docs = r.kind
502
- ? ((asMember(r.kind.doc, member)[r.kind.root] ?? []) as { id: number }[]).map((i) => `${r.doc}:${i.id}`)
602
+ ? (((await asMember(r.kind.doc, member))[r.kind.root] ?? []) as { id: number }[]).map(
603
+ (i) => `${r.doc}:${i.id}`,
604
+ )
503
605
  : [r.doc];
504
- for (const doc of docs) if (!mayRead(doc, member)) everything[doc] = asMember(doc, member);
606
+ for (const doc of docs) if (!(await mayRead(doc, member))) everything[doc] = await asMember(doc, member);
505
607
  }
506
608
  return Response.json(everything, { headers: { "content-disposition": 'attachment; filename="joined.json"' } });
507
609
  }),
610
+ // one instance whole, handed back: its document as the member sees it, its root item, and every file it names, in
611
+ // a folder named for it (book-1/book-1.json, book-1/files/<name>), a tar; theirs to keep, or to take elsewhere
612
+ "/export/:folder": group.edge(async (req, who) => {
613
+ const at = /^([a-z][a-z0-9-]*)-(\d+)$/.exec((req as Request & { params: { folder: string } }).params.folder),
614
+ doc = at ? `${at[1]}:${at[2]}` : "",
615
+ member = who?.member ?? 0;
616
+ if (!at || !rulesOf(doc)?.kind || !(await store.exists(doc))) return new Response("Not found", { status: 404 });
617
+ const r = rulesOf(doc),
618
+ root = (((await asMember(r.kind!.doc, member))[r.kind!.root] ?? []) as { id: number }[]).find(
619
+ (i) => i.id === Number(at[2]),
620
+ ),
621
+ why = (await mayRead(doc, member)) ?? (root ? null : `you don't see ${doc}`);
622
+ if (why) return Response.json({ refused: why }, { status: 403 });
623
+ const folder = folderOf(doc),
624
+ held = await asMember(doc, member),
625
+ entries: Record<string, Blob | string> = {
626
+ [`${folder}/${folder}.json`]: `${JSON.stringify({ [doc]: held, [r.kind!.root]: [root] }, null, 2)}\n`,
627
+ };
628
+ for (const [, name] of JSON.stringify(held).matchAll(/file:([0-9a-f]{64}\.[a-z0-9]{1,8})/g)) {
629
+ const own = filesKept.file(`${folder}/${name}`),
630
+ file = (await own.exists()) ? own : filesKept.file(name!);
631
+ if (await file.exists()) entries[`${folder}/files/${name}`] = new Blob([await file.arrayBuffer()]);
632
+ }
633
+ return new Response(await new Bun.Archive(entries).bytes(), {
634
+ headers: { "content-type": "application/x-tar", "content-disposition": `attachment; filename="${folder}.tar"` },
635
+ });
636
+ }),
508
637
  // the MCP door: an agent's link, for Claude in a chat, reading and writing as a page does (src/mcp.ts)
509
- "/mcp/:token": door(agents),
638
+ "/mcp/:token": mine(door(agents)),
510
639
  // and where nobody's a member, anyone's, with no link, as a stranger's page is: its writes are anyone's
511
- ...(members ? {} : { "/mcp": door({ ...agents, anyone: true }) }),
640
+ ...(members ? {} : { "/mcp": mine(door({ ...agents, anyone: true })) }),
512
641
  // a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
513
- ...fileRoutes(filesKept, mayPut),
642
+ ...fileRoutes(filesKept, mayPut, mayHoldFiles, apart),
514
643
  };
644
+ // an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
645
+ // document it reads is here (src/write.ts)
646
+ const settled =
647
+ <A extends unknown[]>(fn: (...a: A) => Response | Promise<Response>) =>
648
+ async (...a: A): Promise<Response> =>
649
+ await settle(async () => await fn(...a));
515
650
  for (const { app, routes: of = {} } of apps)
516
- for (const [path, answer] of Object.entries(typeof of === "function" ? of(read, write) : of)) {
651
+ for (const [path, answer] of Object.entries(typeof of === "function" ? of(now, write) : of)) {
517
652
  if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
518
653
  // a page (Bun's bundle of its index.html) is kept at /_page<path>, and served at its own path rendered
519
654
  if (typeof answer === "object" && "index" in answer) {
@@ -523,21 +658,25 @@ export async function start({
523
658
  }
524
659
  routes[path] =
525
660
  typeof answer === "function"
526
- ? group.edge(answer)
661
+ ? ownSite(group.edge(settled(answer)))
527
662
  : answer instanceof Response
528
663
  ? answer
529
- : Object.fromEntries(Object.entries(answer).map(([method, fn]) => [method, group.edge(fn as Handler)]));
664
+ : Object.fromEntries(
665
+ Object.entries(answer).map(([method, fn]) => [method, ownSite(group.edge(settled(fn as Handler)))]),
666
+ );
530
667
  }
531
668
  // an app's open routes, anyone's and never guarded: each document read as nobody (owns and sees apply, the group's
532
669
  // door doesn't), so each shows only what it picks
533
- const nobody: Read = (doc) => read(doc, 0);
670
+ const nobody: Read = (doc) => now(doc, 0);
534
671
  for (const { app, open: of = {} } of apps)
535
672
  for (const [path, answer] of Object.entries(typeof of === "function" ? of(nobody) : of)) {
536
673
  if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
537
- routes[path] = answer;
674
+ routes[path] = typeof answer === "function" ? settled(answer) : answer;
538
675
  }
539
676
 
540
677
  const pages = new Set<ServerWebSocket<Data>>();
678
+ /** The messages a page sent that are being answered, waited for as the server stops. */
679
+ const answering = new Set<Promise<unknown>>();
541
680
 
542
681
  // A page served with its documents in it: each collection element it holds filled with its items, as the
543
682
  // person asking sees them, and each document's version on <body>, so the page subscribes since it and is sent only
@@ -562,7 +701,9 @@ export async function start({
562
701
  for (const [place, { doc }] of places)
563
702
  finding.on(place, { element: (el) => void docs.add(el.getAttribute("doc") ?? doc) });
564
703
  await finding.transform(new Response(html)).text();
565
- const page = { html, docs: [...docs].filter((d) => exists(d)) };
704
+ const held: string[] = [];
705
+ for (const d of docs) if (await exists(d)) held.push(d);
706
+ const page = { html, docs: held };
566
707
  if (production) shells.set(path, page);
567
708
  return page;
568
709
  }
@@ -575,18 +716,35 @@ export async function start({
575
716
  return a === null ? "" : a === "" ? ` ${f}` : ` ${f}="${escaped(a)}"`;
576
717
  })
577
718
  .join("")}></${tag}>`;
719
+ /** Whether a request came over https: its own URL's, or a proxy's in front (Railway's) saying so. */
720
+ const secure = (req: Request) =>
721
+ new URL(req.url).protocol === "https:" || req.headers.get("x-forwarded-proto") === "https";
578
722
  async function rendered(req: Request, path: string) {
579
723
  const { html, docs } = await shell(path);
580
- const headers = { "content-type": "text/html;charset=utf-8", "cache-control": "private, no-store" };
724
+ const headers = {
725
+ "content-type": "text/html;charset=utf-8",
726
+ "cache-control": "private, no-store",
727
+ // never framed by another site (a click taken over), nor sniffed as anything else; and, served over https,
728
+ // asked for over https only
729
+ "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'",
730
+ "x-frame-options": "SAMEORIGIN",
731
+ "x-content-type-options": "nosniff",
732
+ ...(secure(req) ? { "strict-transport-security": "max-age=31536000" } : {}),
733
+ };
581
734
  const signed = await group.at(req),
582
735
  who = signed instanceof Response ? null : signed;
583
736
  // a stranger is served the page as it is, but for what's anonymous, which is anyone's; and anyone, only what
584
737
  // they may hold (a cook, none of the till's orders)
585
- const held = docs.filter(
586
- (d) => (who || !members || rulesOf(d).anonymous) && !mayHold(d, who?.member ?? null, !(members && rootToken)),
587
- );
588
- const seen = new Map(held.map((d) => [d, view(d, who?.member ?? 0)]));
589
- const may = new Map(held.map((d) => [d, mayIn(d, who)]));
738
+ const seen = new Map<string, Doc>(),
739
+ may = new Map<string, Awaited<ReturnType<typeof mayIn>>>();
740
+ for (const d of docs)
741
+ if (
742
+ (who || !members || rulesOf(d).anonymous) &&
743
+ !(await mayHold(d, who?.member ?? null, !(members && rootToken)))
744
+ ) {
745
+ seen.set(d, await view(d, who?.member ?? 0));
746
+ may.set(d, await mayIn(d, who));
747
+ }
590
748
  const filling = new HTMLRewriter().on("body", {
591
749
  element(el) {
592
750
  el.setAttribute("data-build", build);
@@ -624,17 +782,20 @@ export async function start({
624
782
  // or without, a collection of it put back on the page (another kept it held meanwhile): it's sent whole.
625
783
  if (m.subscribe !== undefined) {
626
784
  const doc = m.subscribe;
785
+ if (!derives.has(doc) && !(await exists(doc)))
786
+ return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
787
+ // a stranger's page, on a group that's invite-only, holds what's anonymous alone, or an item's own as its guest;
788
+ // a document only some may hold (its where's), those its roles name. A derived one too, before it's derived
789
+ const no = await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
790
+ if (no) return say(ws, { doc, refused: true, why: no });
791
+ if (!ws.data.docs.has(doc) && ws.data.docs.size >= HELD)
792
+ return say(ws, { doc, refused: true, why: `a page holds ${HELD} documents at most: let one go first` });
627
793
  // a derived document is derived for the page, and sent whole, subscribed again or not
628
794
  if (derives.has(doc)) {
629
795
  ws.data.docs.add(doc);
630
796
  forget(ws, doc);
631
- return derivedTo(ws, doc);
797
+ return await derivedTo(ws, doc);
632
798
  }
633
- if (!exists(doc)) return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
634
- // a stranger's page, on a group that's invite-only, holds what's anonymous alone, or an item's own as its guest;
635
- // a document only some may hold (its where's), those its roles name
636
- const no = mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
637
- if (no) return say(ws, { doc, refused: true, why: no });
638
799
  // a static document is read with its page, and changes only with a release: there's nothing to be told
639
800
  if (rulesOf(doc).type === "static")
640
801
  return say(ws, { doc, refused: true, why: `${doc} is static: it changes only with a release` });
@@ -644,11 +805,11 @@ export async function start({
644
805
  const topic = topicOf(ws, doc),
645
806
  part = isPart(doc, topic);
646
807
  ws.subscribe(topic);
647
- const missed = m.since === undefined || part ? null : store.since(doc, m.since);
808
+ const missed = m.since === undefined || part ? null : await store.since(doc, m.since);
648
809
  if (missed) for (const c of missed) say(ws, c);
649
810
  else {
650
811
  const member = ws.data.who?.member ?? 0;
651
- const { version, ...value } = view(doc, member);
812
+ const { version, ...value } = await view(doc, member);
652
813
  const t = part
653
814
  ? (topics.get(topic) ??
654
815
  topics
@@ -659,7 +820,7 @@ export async function start({
659
820
  }
660
821
  // and what its person may do there, told afresh
661
822
  forget(ws, doc);
662
- mayTo(ws, doc);
823
+ await mayTo(ws, doc);
663
824
  return again ? undefined : group.opened(ws, doc);
664
825
  }
665
826
  // a page unsubscribes from a document (its elements taken off it): it's told it no more
@@ -674,7 +835,7 @@ export async function start({
674
835
  const doc = m.doc!,
675
836
  base = docParts(doc).base,
676
837
  by = who?.member ?? null;
677
- const made = store.change(base, m.undo);
838
+ const made = await store.change(base, m.undo);
678
839
  // nobody's change (a stranger's, the server's own, a rule's, a reaction's) is undone only by the page that made it
679
840
  const no = !ws.data.docs.has(doc)
680
841
  ? `this page isn't subscribed to ${base}`
@@ -688,7 +849,7 @@ export async function start({
688
849
  let w: Written;
689
850
  try {
690
851
  if (no) throw new Refused(no);
691
- w = await written([{ doc, ops: store.undoing(base, m.undo) }], who, m.undo);
852
+ w = await written([{ doc, ops: await store.undoing(base, m.undo) }], who, { undoes: m.undo });
692
853
  } catch (e) {
693
854
  if (!(e instanceof Refused)) throw e;
694
855
  log?.(`undo ${base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
@@ -714,6 +875,7 @@ export async function start({
714
875
  const w = await written(
715
876
  writes.map((w) => ({ ...w, why: w.why?.trim() || undefined })),
716
877
  who,
878
+ { kept: m.kept },
717
879
  );
718
880
  // a stranger's change, which only this page undoes
719
881
  if (!("why" in w) && who === null)
@@ -732,27 +894,34 @@ export async function start({
732
894
  /** A write, a page's or an agent's at the MCP door: of one document or several (src/together.ts), each as it names
733
895
  * it (a window's write is its document's), by who, landed whole or not at all, told, and answered: done, with the
734
896
  * version its first part made and the id each item added was given, in order, so the writer needn't match them; or
735
- * refused, why. Each logs one line. `undoes`: a page's undo, of the version it puts back (src/write.ts, ask). */
736
- async function written(writes: Part[], who: Who | null, undoes?: number): Promise<Written> {
897
+ * refused, why. Each logs one line. `undoes`: a page's undo, of the version it puts back (src/write.ts, ask).
898
+ * `kept`: a write a page kept while away, by the id it gave it (src/outbox.ts); one made already (its answer lost on
899
+ * the way, or sent by two tabs from the one device's storage) is answered done, with the version it made, and not
900
+ * made again (src/write.ts looks for it in the write's own transaction). */
901
+ async function written(
902
+ writes: Part[],
903
+ who: Who | null,
904
+ { undoes, kept }: { undoes?: number; kept?: string } = {},
905
+ ): Promise<Written> {
737
906
  const doc = writes.map((w) => docParts(w.doc).base).join(" and "),
738
907
  by = byOf(who),
739
908
  act = undoes === undefined ? "write" : `undo ${undoes}`;
740
909
  // In the write's transaction, in order, refused at the first that says no: the app's own rules, the grants, and
741
910
  // the group's rules (src/write.ts), and, as its rows are written, the tables' constraints; each part's.
742
911
  const afters: ((applied: Op[]) => Promise<void>)[] = [];
743
- const asked = (name: string, ops: Op[], why?: string) => {
912
+ const asked = async (name: string, ops: Op[], why?: string) => {
744
913
  // each part's document one its writer may hold (a where's holds, a visitor's level): one the write makes
745
914
  // (board:$1) no page has held
746
- const no = mayHold(name, who?.member ?? null, !(members && rootToken));
915
+ const no = await mayHold(name, who?.member ?? null, !(members && rootToken));
747
916
  if (no) throw new Refused(no);
748
917
  let after: (applied: Op[]) => Promise<void> = async () => {};
749
- const asking = ask(
918
+ const asking = await ask(
750
919
  name,
751
920
  ops,
752
921
  why,
753
922
  who,
754
- (doc, ops) => {
755
- const write = group.write(doc, ops, who, why);
923
+ async (doc, ops) => {
924
+ const write = await group.write(doc, ops, who, why);
756
925
  if (!("refused" in write)) after = write.after;
757
926
  return write;
758
927
  },
@@ -762,17 +931,26 @@ export async function start({
762
931
  return asking;
763
932
  };
764
933
  // a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
765
- let landed: ReturnType<typeof land>;
934
+ let landed: Awaited<ReturnType<typeof land>>;
766
935
  try {
767
- landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { undoes, asked, held: pagesHold() });
936
+ landed = await land(writes, who?.member ?? null, who?.agent?.label ?? null, {
937
+ undoes,
938
+ kept,
939
+ asked,
940
+ held: pagesHold(),
941
+ });
768
942
  } catch (e) {
943
+ if (e instanceof Made) {
944
+ log?.(`${act} ${doc} by ${by}: done already, version ${e.version}`);
945
+ return { done: true, version: e.version, ids: [] };
946
+ }
769
947
  // refused in words; anything else is the server's, logged, and the writer told it wasn't saved
770
948
  if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
771
949
  const why = e instanceof Refused ? e.message : "That wasn't saved: the server had a problem with it.";
772
950
  log?.(`${act} ${doc} by ${by}: refused, ${why}`);
773
951
  return { why };
774
952
  }
775
- tell(landed);
953
+ await tell(landed);
776
954
  retime();
777
955
  const change = landed.parts[0]!;
778
956
  // what follows each part (the group's pages told, a new member's link made), and then the writer's answer:
@@ -814,7 +992,7 @@ export async function start({
814
992
  open(ws) {
815
993
  say(ws, { build });
816
994
  pages.add(ws);
817
- group.admit(ws);
995
+ void group.admit(ws);
818
996
  },
819
997
  close(ws) {
820
998
  pages.delete(ws);
@@ -822,17 +1000,24 @@ export async function start({
822
1000
  },
823
1001
  // a message that isn't one joined reads is refused; one the server fails on is logged and answered, and
824
1002
  // the server goes on
825
- async message(ws, text) {
826
- const m = messageOf(String(text));
827
- if (typeof m === "string") return say(ws, { refused: null, why: m });
828
- try {
829
- await answer(ws, m);
830
- // a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
831
- if (m.subscribe !== undefined && m.id !== undefined) say(ws, { done: m.id });
832
- } catch (e) {
833
- console.error("a message failed:", e);
834
- say(ws, { refused: m.id ?? null, why: "The server had a problem with that." });
835
- }
1003
+ // a page's messages are answered one at a time, in the order it sent them
1004
+ message(ws, text) {
1005
+ const queue = (ws.data.queue = (ws.data.queue ?? Promise.resolve()).then(async () => {
1006
+ const m = messageOf(String(text));
1007
+ // refused, to the write it's about where its id can be read (a copy, a move: no op of joined's), else to none
1008
+ if (typeof m === "string") return say(ws, { refused: idIn(String(text)), why: m });
1009
+ try {
1010
+ await answer(ws, m);
1011
+ // a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
1012
+ if (m.subscribe !== undefined && m.id !== undefined) say(ws, { done: m.id });
1013
+ } catch (e) {
1014
+ console.error("a message failed:", e);
1015
+ say(ws, { refused: m.id ?? null, why: "The server had a problem with that." });
1016
+ }
1017
+ }));
1018
+ // what's being answered is finished before the server stops, and its store closes
1019
+ answering.add(queue);
1020
+ void queue.finally(() => answering.delete(queue));
836
1021
  },
837
1022
  },
838
1023
  });
@@ -842,21 +1027,22 @@ export async function start({
842
1027
  const timed = held.flatMap(({ rules: r }) =>
843
1028
  Object.entries(r.collections).flatMap(([coll, c]) => (c.timed ? [{ doc: r.doc, coll, field: c.timed }] : [])),
844
1029
  );
845
- let clock: ReturnType<typeof setTimeout> | undefined;
846
- function tick() {
1030
+ let clock: ReturnType<typeof setTimeout> | undefined,
1031
+ ticking = Promise.resolve();
1032
+ async function tick(): Promise<void> {
847
1033
  clearTimeout(clock);
848
1034
  let soonest = Infinity,
849
1035
  cleared = false;
850
1036
  for (const { doc, coll, field } of timed)
851
- for (const item of read(doc)[coll] as Record<string, any>[]) {
1037
+ for (const item of (await read(doc))[coll] as Record<string, any>[]) {
852
1038
  const at = Date.parse(item[field] ?? "");
853
1039
  if (!(at <= Date.now())) {
854
1040
  if (at < soonest) soonest = at;
855
1041
  continue;
856
1042
  }
857
1043
  try {
858
- tell(
859
- land([{ doc, ops: [{ op: "remove", path: `/${coll}/${item.id}/${field}` }] }], null, null, {
1044
+ await tell(
1045
+ await land([{ doc, ops: [{ op: "remove", path: `/${coll}/${item.id}/${field}` }] }], null, null, {
860
1046
  held: pagesHold(),
861
1047
  }),
862
1048
  );
@@ -867,24 +1053,56 @@ export async function start({
867
1053
  }
868
1054
  }
869
1055
  if (cleared) return tick();
870
- if (soonest < Infinity) (clock = setTimeout(tick, Math.min(soonest - Date.now(), LONGEST))).unref();
1056
+ if (soonest < Infinity) (clock = setTimeout(retime, Math.min(soonest - Date.now(), LONGEST))).unref();
871
1057
  }
872
- /** The clock set again, after a write that may have changed a time. */
1058
+ /** The clock set again, after a write that may have changed a time: one look at a time. */
873
1059
  function retime() {
874
- if (timed.length) tick();
1060
+ if (timed.length) ticking = ticking.then(tick).catch(failed("the clock"));
875
1061
  }
876
1062
  retime();
877
1063
 
878
- // stopped, its clock stops too: a time it was waiting for comes to a store that may be closed
1064
+ // A change another server on the database made (Postgres: each server hears every commit), told here as this server
1065
+ // tells its own: the change to each page holding its document whole, and each part a page holds (a window, what a
1066
+ // person sees, a document read off others) sent whole again, as it is now; and where the members changed, every page
1067
+ // whose link no longer opens (removed, replaced, taken back) closed.
1068
+ async function heard(doc: string, version: number) {
1069
+ const c = await store.change(doc, version);
1070
+ const by = c?.by ?? null,
1071
+ via = c?.via ?? null;
1072
+ const told: Told = [];
1073
+ for (const [topic, t] of topics) {
1074
+ const r = rulesOf(t.doc);
1075
+ if (docParts(t.doc).base !== doc && !r.member && !r.view) continue;
1076
+ const { version: now, ...value } = await view(t.doc, t.member ?? 0);
1077
+ told.push({ topic, change: { doc: t.doc, version: now, ops: [{ op: "replace", path: "", value }], by, via } });
1078
+ }
1079
+ await tell({ changes: c ? [{ doc, version, ops: c.ops, by, via }] : [], told });
1080
+ if (docParts(doc).name === GROUP) await group.heard();
1081
+ retime();
1082
+ }
1083
+ await store.heard((doc, version) => void heard(doc, version).catch(failed(`hearing ${doc}`)));
1084
+
1085
+ // stopped, its clock and its upkeep stop too, what's being answered is finished, and its store is closed (a SQLite
1086
+ // file whole, its -wal folded in): a caller that closes the store itself as well does no harm (src/store.ts)
879
1087
  const stop = server.stop.bind(server);
880
1088
  return Object.assign(server, {
881
- stop: (closeActive?: boolean) => (clearTimeout(clock), stop(closeActive)),
1089
+ stop: async (closeActive?: boolean) => {
1090
+ clearTimeout(clock);
1091
+ kept?.stop();
1092
+ await stop(closeActive);
1093
+ await Promise.all(answering);
1094
+ await ticking;
1095
+ await telling;
1096
+ await store.close();
1097
+ },
882
1098
  apps: apps.map((a) => a.app).filter(Boolean),
883
1099
  members,
884
1100
  build,
885
1101
  // what's answered, without the bundles the pages are rendered from
886
1102
  paths: Object.keys(routes).filter((p) => !p.startsWith("/_page")),
887
1103
  tokenOf: group.tokenOf,
1104
+ /** Each app with rules of its own (a trust.ts), and how many writes they've refused. */
1105
+ ruled,
888
1106
  read,
889
1107
  write,
890
1108
  undo,
@@ -896,7 +1114,7 @@ export async function start({
896
1114
  /** What a server says as it starts: where it is, and the BDFL's link, or that it's open, or has no members. A ROOT_TOKEN
897
1115
  * long enough to be a secret is never printed (on Railway, what's printed is in the logs); a short
898
1116
  * one, fine on this machine alone, is, with a warning. */
899
- export function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.env.ROOT_TOKEN) {
1117
+ export async function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.env.ROOT_TOKEN) {
900
1118
  const said = [`joined on ${server.url}: ${server.apps.join(", ")}; ${server.paths.join(" ")}`];
901
1119
  if (!server.members)
902
1120
  return [
@@ -904,7 +1122,7 @@ export function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.en
904
1122
  "no members: no story is told as one, so anyone who reaches it may read and write, an agent too, at /mcp",
905
1123
  ];
906
1124
  if (!root) return [...said, "open: no ROOT_TOKEN, so anyone who reaches it may read and write"];
907
- const bdfl = `${bdflOf(server.read(GROUP).members as Member[])?.name ?? "The BDFL"}'s link (the BDFL's)`;
1125
+ const bdfl = `${bdflOf((await server.read(GROUP)).members as Member[])?.name ?? "The BDFL"}'s link (the BDFL's)`;
908
1126
  if (root.length >= 32) return [...said, `${bdfl} isn't printed: bun run link <name>, or .railway/root-link`];
909
1127
  return [
910
1128
  ...said,