@blueshed/joined 0.3.0 → 0.3.2

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 (109) hide show
  1. package/.claude/skills/joined/reference.md +57 -18
  2. package/docs/design.md +93 -38
  3. package/docs/introduction.md +9 -9
  4. package/docs/light-and-shadow.svg +1 -0
  5. package/docs/links-and-trust.svg +1 -0
  6. package/docs/stories-to-code.svg +2 -1
  7. package/docs/wire-op.svg +1 -0
  8. package/examples/app.css +9 -0
  9. package/examples/cafe/cafe.css +87 -69
  10. package/examples/cafe/generated/staff.elements.ts +7 -2
  11. package/examples/cafe/generated/staff.rules.ts +3 -0
  12. package/examples/cafe/generated/supplies.rules.ts +5 -0
  13. package/examples/cafe/kitchen.css +11 -19
  14. package/examples/cafe/kitchen.ts +6 -2
  15. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  16. package/examples/cafe/order.html +2 -1
  17. package/examples/cafe/order.ts +1 -1
  18. package/examples/cafe/staff.json +5 -0
  19. package/examples/cafe/stories.jsonl +4 -2
  20. package/examples/cafe/supplies.html +1 -0
  21. package/examples/cafe/supplies.ts +45 -28
  22. package/examples/cafe/till.ts +14 -10
  23. package/examples/cafe/views.ts +7 -5
  24. package/examples/chart/arches.ts +5 -3
  25. package/examples/chart/chart.css +7 -2
  26. package/examples/desk/desk.css +6 -10
  27. package/examples/desk/generated/elements.ts +1 -1
  28. package/examples/desk/index.html +1 -1
  29. package/examples/desk/lanes.css +21 -19
  30. package/examples/desk/stories.jsonl +1 -1
  31. package/examples/desk/tally.css +1 -1
  32. package/examples/docs.ts +7 -4
  33. package/examples/index.html +16 -7
  34. package/examples/notes/generated/queries.ts +8 -2
  35. package/examples/notes/index.html +1 -1
  36. package/examples/notes/stories.jsonl +3 -0
  37. package/examples/page.ts +9 -2
  38. package/examples/people/links.ts +7 -9
  39. package/examples/people/people.css +1 -1
  40. package/examples/people/view.ts +1 -1
  41. package/examples/trip/generated/elements.ts +1 -1
  42. package/examples/trip/stays.css +1 -1
  43. package/examples/trip/stays.ts +1 -1
  44. package/examples/trips/generated/elements.ts +1 -1
  45. package/examples/trips/trips.css +24 -23
  46. package/examples/welcome.css +41 -33
  47. package/package.json +1 -1
  48. package/src/attachment.ts +17 -2
  49. package/src/board.css +2 -1
  50. package/src/board.ts +4 -4
  51. package/src/cli.ts +14 -2
  52. package/src/compile.ts +255 -77
  53. package/src/definitions.ts +62 -14
  54. package/src/demo.css +2 -5
  55. package/src/draft.ts +10 -4
  56. package/src/drawer.ts +30 -4
  57. package/src/engine.ts +14 -5
  58. package/src/fields.ts +88 -15
  59. package/src/file-value.ts +12 -2
  60. package/src/files.ts +113 -35
  61. package/src/icon-names.ts +4 -0
  62. package/src/keep.ts +16 -3
  63. package/src/map.css +23 -16
  64. package/src/map.ts +3 -3
  65. package/src/mcp.ts +24 -3
  66. package/src/members/group.ts +41 -17
  67. package/src/members/keys.ts +3 -3
  68. package/src/members/panel.css +17 -18
  69. package/src/members/panel.ts +9 -2
  70. package/src/migrate.ts +58 -21
  71. package/src/migrations/005-change-kept.ts +7 -0
  72. package/src/month.css +6 -2
  73. package/src/month.ts +5 -5
  74. package/src/ops.ts +40 -1
  75. package/src/page.css +3 -2
  76. package/src/page.ts +64 -16
  77. package/src/parts.css +178 -86
  78. package/src/parts.ts +60 -20
  79. package/src/plane.css +9 -4
  80. package/src/plane.ts +4 -2
  81. package/src/reading.css +1 -5
  82. package/src/rows.css +2 -21
  83. package/src/rows.ts +123 -39
  84. package/src/server.ts +157 -30
  85. package/src/sheet.ts +4 -2
  86. package/src/slots.css +0 -4
  87. package/src/specs.ts +1 -1
  88. package/src/starter.ts +15 -1
  89. package/src/store.ts +40 -18
  90. package/src/surface.ts +7 -2
  91. package/src/time.ts +2 -0
  92. package/src/timeline.ts +14 -5
  93. package/src/together.ts +15 -17
  94. package/src/tokens.css +12 -3
  95. package/src/tokens.json +38 -7
  96. package/src/tool.ts +6 -7
  97. package/src/upkeep.ts +31 -4
  98. package/src/views.css +8 -9
  99. package/src/views.ts +23 -6
  100. package/src/week.css +1 -2
  101. package/src/week.ts +11 -7
  102. package/src/write.ts +130 -15
  103. package/starter/CHANGELOG.md +8 -0
  104. package/starter/CLAUDE.md +7 -1
  105. package/starter/bunfig +2 -1
  106. package/starter/githooks/pre-commit +13 -0
  107. package/starter/prettierignore +1 -0
  108. package/starter/tests/records.test.ts +40 -0
  109. package/starter/todo.jsonl +0 -0
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,17 +99,44 @@ 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) });
100
140
 
101
141
  /** What fails in the background (a change told, the clock, another server's change heard), said, and the server goes on. */
102
142
  const failed = (what: string) => (e: unknown) => console.error(`${what} failed:`, e);
@@ -344,13 +384,15 @@ export async function start({
344
384
  async function toldAll({ changes, told }: { changes: Change[]; told: Told }) {
345
385
  const written = new Set(changes.map((change) => docParts(change.doc).name));
346
386
  // a page holding a document by a root item's code (an instance, or the root's own), where the root's document
347
- // changed (its level, its code), asked again whether it may hold it, and refused as at the door if not, before
348
- // 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
349
389
  for (const ws of pages)
350
390
  for (const doc of ws.data.docs) {
351
- const root = !derives.has(doc) && byCode(doc);
391
+ const root = !derives.has(doc) && byCode(doc),
392
+ gated = !derives.has(doc) && !!rulesOf(doc).mayHold;
352
393
  const no =
353
- root && written.has(root) && (await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken)));
394
+ ((root && written.has(root)) || gated) &&
395
+ (await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken)));
354
396
  if (no)
355
397
  (ws.data.docs.delete(doc),
356
398
  ws.unsubscribe(topicOf(ws, doc)),
@@ -519,13 +561,37 @@ export async function start({
519
561
  : `you may not put a file in ${docParts(doc).base}`)
520
562
  );
521
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;
570
+ return (
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}`)
575
+ );
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";
522
580
  const routes: Routes = {
523
581
  "/health": () => new Response("ok"),
524
582
  "/version": () => Response.json({ joined: version, build }),
525
583
  "/favicon.ico": icon,
526
584
  "/apple-touch-icon.png": icon,
527
585
  "/apple-touch-icon-precomposed.png": icon,
528
- ...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
+ ),
529
595
  // everything a member can see, as JSON: each document as they see it, each kind's instances by their key; theirs
530
596
  // to keep, or to take elsewhere
531
597
  "/export": group.edge(async (_req, who) => {
@@ -541,12 +607,39 @@ export async function start({
541
607
  }
542
608
  return Response.json(everything, { headers: { "content-disposition": 'attachment; filename="joined.json"' } });
543
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
+ }),
544
637
  // the MCP door: an agent's link, for Claude in a chat, reading and writing as a page does (src/mcp.ts)
545
- "/mcp/:token": door(agents),
638
+ "/mcp/:token": mine(door(agents)),
546
639
  // and where nobody's a member, anyone's, with no link, as a stranger's page is: its writes are anyone's
547
- ...(members ? {} : { "/mcp": door({ ...agents, anyone: true }) }),
640
+ ...(members ? {} : { "/mcp": mine(door({ ...agents, anyone: true })) }),
548
641
  // a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
549
- ...fileRoutes(filesKept, mayPut),
642
+ ...fileRoutes(filesKept, mayPut, mayHoldFiles, apart),
550
643
  };
551
644
  // an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
552
645
  // document it reads is here (src/write.ts)
@@ -565,11 +658,11 @@ export async function start({
565
658
  }
566
659
  routes[path] =
567
660
  typeof answer === "function"
568
- ? group.edge(settled(answer))
661
+ ? ownSite(group.edge(settled(answer)))
569
662
  : answer instanceof Response
570
663
  ? answer
571
664
  : Object.fromEntries(
572
- Object.entries(answer).map(([method, fn]) => [method, group.edge(settled(fn as Handler))]),
665
+ Object.entries(answer).map(([method, fn]) => [method, ownSite(group.edge(settled(fn as Handler)))]),
573
666
  );
574
667
  }
575
668
  // an app's open routes, anyone's and never guarded: each document read as nobody (owns and sees apply, the group's
@@ -623,9 +716,21 @@ export async function start({
623
716
  return a === null ? "" : a === "" ? ` ${f}` : ` ${f}="${escaped(a)}"`;
624
717
  })
625
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";
626
722
  async function rendered(req: Request, path: string) {
627
723
  const { html, docs } = await shell(path);
628
- 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
+ };
629
734
  const signed = await group.at(req),
630
735
  who = signed instanceof Response ? null : signed;
631
736
  // a stranger is served the page as it is, but for what's anonymous, which is anyone's; and anyone, only what
@@ -680,9 +785,11 @@ export async function start({
680
785
  if (!derives.has(doc) && !(await exists(doc)))
681
786
  return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
682
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;
683
- // a document only some may hold (its where's), those its roles name; a derived one too
788
+ // a document only some may hold (its where's), those its roles name. A derived one too, before it's derived
684
789
  const no = await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
685
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` });
686
793
  // a derived document is derived for the page, and sent whole, subscribed again or not
687
794
  if (derives.has(doc)) {
688
795
  ws.data.docs.add(doc);
@@ -742,7 +849,7 @@ export async function start({
742
849
  let w: Written;
743
850
  try {
744
851
  if (no) throw new Refused(no);
745
- w = await written([{ doc, ops: await store.undoing(base, m.undo) }], who, m.undo);
852
+ w = await written([{ doc, ops: await store.undoing(base, m.undo) }], who, { undoes: m.undo });
746
853
  } catch (e) {
747
854
  if (!(e instanceof Refused)) throw e;
748
855
  log?.(`undo ${base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
@@ -768,6 +875,7 @@ export async function start({
768
875
  const w = await written(
769
876
  writes.map((w) => ({ ...w, why: w.why?.trim() || undefined })),
770
877
  who,
878
+ { kept: m.kept },
771
879
  );
772
880
  // a stranger's change, which only this page undoes
773
881
  if (!("why" in w) && who === null)
@@ -786,8 +894,15 @@ export async function start({
786
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
787
895
  * it (a window's write is its document's), by who, landed whole or not at all, told, and answered: done, with the
788
896
  * version its first part made and the id each item added was given, in order, so the writer needn't match them; or
789
- * refused, why. Each logs one line. `undoes`: a page's undo, of the version it puts back (src/write.ts, ask). */
790
- 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> {
791
906
  const doc = writes.map((w) => docParts(w.doc).base).join(" and "),
792
907
  by = byOf(who),
793
908
  act = undoes === undefined ? "write" : `undo ${undoes}`;
@@ -818,8 +933,17 @@ export async function start({
818
933
  // a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
819
934
  let landed: Awaited<ReturnType<typeof land>>;
820
935
  try {
821
- landed = await 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
+ });
822
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
+ }
823
947
  // refused in words; anything else is the server's, logged, and the writer told it wasn't saved
824
948
  if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
825
949
  const why = e instanceof Refused ? e.message : "That wasn't saved: the server had a problem with it.";
@@ -880,7 +1004,8 @@ export async function start({
880
1004
  message(ws, text) {
881
1005
  const queue = (ws.data.queue = (ws.data.queue ?? Promise.resolve()).then(async () => {
882
1006
  const m = messageOf(String(text));
883
- if (typeof m === "string") return say(ws, { refused: null, why: m });
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 });
884
1009
  try {
885
1010
  await answer(ws, m);
886
1011
  // a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
@@ -957,7 +1082,8 @@ export async function start({
957
1082
  }
958
1083
  await store.heard((doc, version) => void heard(doc, version).catch(failed(`hearing ${doc}`)));
959
1084
 
960
- // stopped, its clock stops too: a time it was waiting for comes to a store that may be closed
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)
961
1087
  const stop = server.stop.bind(server);
962
1088
  return Object.assign(server, {
963
1089
  stop: async (closeActive?: boolean) => {
@@ -967,6 +1093,7 @@ export async function start({
967
1093
  await Promise.all(answering);
968
1094
  await ticking;
969
1095
  await telling;
1096
+ await store.close();
970
1097
  },
971
1098
  apps: apps.map((a) => a.app).filter(Boolean),
972
1099
  members,
package/src/sheet.ts CHANGED
@@ -84,9 +84,11 @@ export class JSheet extends HTMLElement {
84
84
  choices: (f) =>
85
85
  [...document.querySelectorAll(f.to!.tag)].map((t) => [Number(t.getAttribute("key")), titled(t, f.to!.title)]),
86
86
  add: (s, value) => send(document.querySelector(s.place)!, s.doc, [{ op: "add", path: `/${s.name}/-`, value }]),
87
+ doc: () => document.querySelector(s.place)?.closest("[doc]")?.getAttribute("doc") ?? s.doc,
87
88
  said: (request) => void said(this.#line, request),
88
- // a drawer docked at the screen's side: the page keeps clear of it (src/page.css), said only as it changes
89
- shown: () => docked(!!this.#drawer?.open),
89
+ // a drawer docked at the screen's side: the page keeps clear of it (src/page.css), said only as it changes. A
90
+ // new one is asked in a modal, over the page: it moves nothing
91
+ shown: () => docked(!!this.#drawer?.open && this.#drawer.open !== "new"),
90
92
  },
91
93
  s,
92
94
  asks,
package/src/slots.css CHANGED
@@ -79,10 +79,6 @@
79
79
  min-height: var(--size-finger);
80
80
  }
81
81
  }
82
- .tools[hidden],
83
- .tabs[hidden] {
84
- display: none;
85
- }
86
82
  /* its parts one above another, a space between each, as joined's page spaces what it holds; none where one is empty */
87
83
  :host {
88
84
  display: grid;
package/src/specs.ts CHANGED
@@ -31,7 +31,7 @@ export function kindOf(collection: string, field: string): Kind {
31
31
  const f = document.querySelector(`j-sheet[for="${collection}"] > j-field[name="${field}"]`);
32
32
  if (!f) return {};
33
33
  return Object.fromEntries(
34
- (["label", "as", "currency", "readonly"] as const).flatMap((k) =>
34
+ (["label", "as", "currency", "readonly", "hint", "not"] as const).flatMap((k) =>
35
35
  f.hasAttribute(k) ? [[k, k === "readonly" ? true : f.getAttribute(k)!]] : [],
36
36
  ),
37
37
  ) as Kind;
package/src/starter.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  // An app's folder, begun and kept up: `joined init` puts in a folder (a project taking joined as its dependency) what
2
2
  // an app on joined starts from, never over what's there, and `joined upgrade` moves joined to another version.
3
3
  // init hello (examples/hello, anyone's, no sign-in) in apps/, the apps' look, the skill, a CLAUDE.md, a
4
- // .gitignore, bun fmt's settings (never what the compiler writes), a tsconfig, tests telling hello's stories (and its page's, in a browser), the scripts; then
4
+ // .gitignore, bun fmt's settings (never what the compiler writes), a tsconfig, tests telling hello's stories (and its page's, in a browser), the scripts; the
5
+ // record (a CHANGELOG.md, a todo.jsonl, the hook refusing a commit without them, and their test); then
5
6
  // compiled
6
7
  // upgrade joined at another version (the newest, a version, or any spec Bun takes: a tarball), the skill
7
8
  // refreshed from it, and the apps compiled by it
8
9
  // `bun create joined <dir>` (create/, the package create-joined) makes the folder and runs init in it.
9
10
 
11
+ import { chmodSync } from "node:fs";
10
12
  import { basename } from "node:path";
11
13
  import { writeAll } from "./compile.ts";
12
14
 
@@ -36,14 +38,25 @@ const STARTER: [string | { text: string }, string][] = [
36
38
  [".claude/skills/joined/reference.md", ".claude/skills/joined/reference.md"],
37
39
  ["starter/CLAUDE.md", "CLAUDE.md"],
38
40
  ["starter/gitignore", ".gitignore"],
41
+ // bun fmt's settings (bunfig, as packing leaves out a bunfig.toml): what the compiler writes left as it is, or the
42
+ // next compile can't read it back
39
43
  ["starter/bunfig", "bunfig.toml"],
40
44
  ["starter/prettierignore", ".prettierignore"],
41
45
  ["starter/tsconfig.json", "tsconfig.json"],
42
46
  ["starter/tests/hello.test.ts", "tests/hello.test.ts"],
43
47
  ["starter/tests/hello-page.test.ts", "tests/hello-page.test.ts"],
48
+ // the record: where it's been, what's open, and the hook that holds every commit to them (CLAUDE.md, The record)
49
+ ["starter/CHANGELOG.md", "CHANGELOG.md"],
50
+ ["starter/todo.jsonl", "todo.jsonl"],
51
+ ["starter/githooks/pre-commit", ".githooks/pre-commit"],
52
+ ["starter/tests/records.test.ts", "tests/records.test.ts"],
44
53
  ];
54
+ /** The hook, run by git: a program. */
55
+ const HOOK = ".githooks/pre-commit";
45
56
  /** The scripts an app runs, by joined's command. */
46
57
  const SCRIPTS = {
58
+ // `bun install` wires the record's hook, where the folder is its repository's own (never a repository it's in)
59
+ prepare: `[ "$(git rev-parse --show-toplevel 2>/dev/null)" = "$PWD" ] && git config core.hooksPath .githooks || true`,
47
60
  // a demo on this machine: <joined-demo> offers to be anyone in the group (never live)
48
61
  dev: "joined compile && JOINED_DEMO=1 joined start",
49
62
  compile: "joined compile",
@@ -61,6 +74,7 @@ export async function init(dir: string) {
61
74
  // written by its path: a file Bun's asked exists() of takes a copy of another as nothing (Bun 1.4.4)
62
75
  else
63
76
  (await Bun.write(`${dir}/${to}`, typeof from === "string" ? Bun.file(`${JOINED}/${from}`) : from.text),
77
+ to === HOOK && chmodSync(`${dir}/${to}`, 0o755),
64
78
  said.push(`made ${to}`));
65
79
  const pkg = Bun.file(`${dir}/package.json`),
66
80
  was = (await pkg.exists()) ? await pkg.json() : { name: basename(dir), private: true, type: "module" };
package/src/store.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  stateOf,
23
23
  type State,
24
24
  } from "./migrate.ts";
25
- import { docParts, parts, valueAt, type Change, type Op, type Type } from "./ops.ts";
25
+ import { docParts, linksNamed, parts, valueAt, type Change, type Op, type Type } from "./ops.ts";
26
26
 
27
27
  /** An app's compiled rules, as the store reads them: its document, each collection's tag, fields and links (the
28
28
  * collection each is to), and its kind: a document for each item of another's collection (doc:root), its rows
@@ -39,12 +39,13 @@ export type Rules = {
39
39
  /** Its links that go with what they point at: that item removed, this one is removed first. */
40
40
  goes?: string[];
41
41
  fills?: Record<string, unknown>;
42
+ clock?: readonly ("item" | "root" | "document")[];
42
43
  timed?: string;
43
44
  own?: boolean;
44
45
  copies?: { from: string; fields: string[]; to: string; at: string };
45
46
  }
46
47
  >;
47
- kind: { root: string; doc: string; column: string } | null;
48
+ kind: { root: string; doc: string; column: string; files?: "apart" } | null;
48
49
  /** The field holding an item's own code (definitions' guests); of a kind, its root's: a board's secret link. */
49
50
  guests?: Record<string, string>;
50
51
  /** The document as one statement over its tables (generated/queries.ts): $doc, $key of a kind's instance, and
@@ -366,6 +367,10 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
366
367
  * text): what it was given is asked first, in the words its CHECK has. */
367
368
  const cell = (coll: string, f: string, t: Type, v: unknown) => {
368
369
  const out = v === undefined ? null : t === "boolean" && typeof v === "boolean" ? +v : v;
370
+ // a list or an object for a column of one value: no table can be asked of it, so it's refused here, in the words
371
+ // the column's CHECK has
372
+ if (out !== null && typeof out === "object")
373
+ throw new Refused(tables[coll]?.columns[f]?.is?.said ?? `${f} is one value, not a list or an object`);
369
374
  const is = db.dialect === "postgres" && out !== null ? tables[coll]?.columns[f]?.is : undefined;
370
375
  if (
371
376
  is &&
@@ -527,6 +532,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
527
532
  return 1;
528
533
  }
529
534
 
535
+ let closed = false;
530
536
  return {
531
537
  db,
532
538
  /** Whether a document holds an item: what a link may point at. */
@@ -535,6 +541,16 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
535
541
  !!(await db
536
542
  .query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${mine(doc, coll).sql}`)
537
543
  .get(id, ...mine(doc, coll).args)),
544
+ /** Every row of a collection's table, each as the document has its item, whatever its where holds (an instance's:
545
+ * its own rows): what its definitions hold among them all (unique, noOverlap). */
546
+ async rowsOf(doc: string, coll: string): Promise<Item[]> {
547
+ const { sql, args } = mine(doc, coll);
548
+ const item = of(doc).rules!.items![coll]!;
549
+ const rows = await db
550
+ .query(`SELECT CAST(${item} AS TEXT) AS item FROM ${q(coll)} t WHERE 1 = 1${sql}`)
551
+ .all(...args);
552
+ return (rows as { item: string }[]).map((r) => JSON.parse(r.item));
553
+ },
538
554
  /** Whether a document can be held: one of the documents, or an instance of a kind whose root item is there. */
539
555
  async exists(doc: string): Promise<boolean> {
540
556
  const { base, params } = docParts(doc);
@@ -568,35 +584,29 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
568
584
  * (`within`: the group's keys), and what the rules over values do as they follow. Then each document holding a row
569
585
  * it changed is told it in its own paths, at its next version, in a row of its change: the document written always
570
586
  * (first, its ops as they leave it), and every other a rule reached (`followed`). `undoes`, the version an undo
571
- * puts back. Its changes, with the ops as they were made (what an add was given), and the rows it changed; or a
572
- * refusal, with why. */
587
+ * puts back; `kept`, the id a page gave a write it kept while away (src/outbox.ts), on the document written's row.
588
+ * Its changes, with the ops as they were made (what an add was given), and the rows it changed; or a refusal, with
589
+ * why. */
573
590
  async write(
574
591
  name: string,
575
592
  ops: Op[],
576
593
  by: number | null,
577
594
  via: string | null,
578
595
  within?: (applied: Op[]) => unknown,
579
- { undoes }: { undoes?: number } = {},
596
+ { undoes, kept }: { undoes?: number; kept?: string } = {},
580
597
  ): Promise<{ changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] }> {
581
598
  // a window's write is its document's
582
599
  const doc = docParts(name).base;
583
600
  return db.transaction(async () => {
584
601
  await db.run(`DELETE FROM ${noted}`);
585
- // a value naming an add before it in this write ("$1", the first add's) is the id that add was given
602
+ // a link naming an add before it in this write ("$1", the first add's) is the id that add was given
586
603
  const done: Awaited<ReturnType<typeof apply>>[] = [];
587
604
  const minted: number[] = [];
588
- const named = (v: unknown): unknown =>
589
- typeof v === "string" && /^\$[1-9]\d*$/.test(v)
590
- ? (minted[Number(v.slice(1)) - 1] ?? v)
591
- : Array.isArray(v)
592
- ? v.map(named)
593
- : v && typeof v === "object"
594
- ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, named(x)]))
595
- : v;
605
+ const collections = of(doc).rules?.collections;
596
606
  for (const o of ops) {
597
607
  const d = await apply(
598
608
  doc,
599
- inward(doc, { ...o, ...("value" in o ? { value: named(o.value) } : {}) }),
609
+ linksNamed(inward(doc, o), collections, (n, v) => minted[n - 1] ?? v),
600
610
  undoes !== undefined,
601
611
  );
602
612
  if (d.applied.op === "add" && parts(d.applied.path).key === "-") minted.push(d.applied.value.id);
@@ -635,7 +645,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
635
645
  const { ops, inverse } = names.get(name)!,
636
646
  version = await moved(name);
637
647
  await db.run(
638
- "INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
648
+ "INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, kept, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
639
649
  [
640
650
  await nextId("changes"),
641
651
  name,
@@ -644,6 +654,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
644
654
  JSON.stringify(inverse),
645
655
  name === doc ? (undoes ?? null) : null,
646
656
  name === doc ? null : 1,
657
+ name === doc ? (kept ?? null) : null,
647
658
  by,
648
659
  via,
649
660
  new Date().toISOString(),
@@ -667,6 +678,13 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
667
678
  * rows a write changed): its new version. */
668
679
  moved,
669
680
 
681
+ /** The version a write kept while away made (src/outbox.ts), by the id its page gave it; undefined, if it hasn't
682
+ * been made (or its change has been let go). */
683
+ async keptAs(kept: string): Promise<number | undefined> {
684
+ const row = await db.query("SELECT version FROM changes WHERE kept = ?").get(kept);
685
+ return (row as { version: number } | null)?.version;
686
+ },
687
+
670
688
  /** A change as its row keeps it: its ops, their inverse, what it undoes, and whether a rule made it;
671
689
  * or undefined, if it isn't kept (let go, or from before inverses were). */
672
690
  async change(doc: string, version: number): Promise<Kept | undefined> {
@@ -841,8 +859,12 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
841
859
  }
842
860
  },
843
861
 
844
- /** The file let go (a server stopped). */
845
- close: () => db.close(),
862
+ /** The file let go (a server stopped), once: closing it again does nothing (PGlite's would throw). */
863
+ async close() {
864
+ if (closed) return;
865
+ closed = true;
866
+ await db.close();
867
+ },
846
868
  /** Each change committed by another server on the database, heard as its document and version (Postgres's
847
869
  * LISTEN): this one's own it tells as it writes. */
848
870
  heard: (fn: (doc: string, version: number) => void) =>
package/src/surface.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  // docked at the right with the page beside it as it was (nothing dimmed; a row still tapped beside it), or a sheet
3
3
  // popped beside the page; on a phone, Web Awesome's wa-drawer risen from the foot, the page dimmed behind it, a tap
4
4
  // there closing it. Its title, what it holds and its foot are moved between the two as the screen changes, so a
5
- // display builds them once. Its ×, Escape (wherever you are, unless a modal or something before it took it) and,
5
+ // display builds them once. Its ×, Escape (wherever you are, unless a modal, in any shadow, or something before it
6
+ // took it) and,
6
7
  // on a phone, a tap on the dimmed page close it, each told to `closed`.
7
8
 
8
9
  import { iconButton } from "./icons.ts";
@@ -12,8 +13,12 @@ type Wa = HTMLElement & { open: boolean };
12
13
 
13
14
  /** The docked drawers open, in the order they opened: Escape closes the last. */
14
15
  const docked: Surface[] = [];
16
+ /** Whether a modal is open anywhere: in the page, or in a display's shadow (the drawer's ask, the group's). */
17
+ const modal = (root: Document | ShadowRoot): boolean =>
18
+ !!root.querySelector("wa-dialog[open]") ||
19
+ [...root.querySelectorAll("*")].some((el) => !!el.shadowRoot && modal(el.shadowRoot));
15
20
  document.addEventListener("keydown", (e) => {
16
- if (e.key !== "Escape" || e.defaultPrevented || document.querySelector("wa-dialog[open]")) return;
21
+ if (e.key !== "Escape" || e.defaultPrevented || modal(document)) return;
17
22
  const top = docked.at(-1);
18
23
  if (top) (e.preventDefault(), top.closed());
19
24
  });
package/src/time.ts CHANGED
@@ -18,6 +18,8 @@ export const dated = (day: number, how: Intl.DateTimeFormatOptions) =>
18
18
  new Date(day * DAY).toLocaleDateString("en-GB", { ...how, timeZone: "UTC" });
19
19
  /** The wall clock where the person is, now: 2026-11-03T14:05:00 (its date, today: now().slice(0, 10)). */
20
20
  export const now = () => new Date().toLocaleString("sv").replace(" ", "T");
21
+ /** The wall clock in a zone (Asia/Tokyo), now; a RangeError where the world names no such zone. */
22
+ export const wallIn = (zone: string) => new Date().toLocaleString("sv", { timeZone: zone }).replace(" ", "T");
21
23
  /** A stay's nights in words: 3–6 Nov, 3 nights. */
22
24
  export const stayed = (s: { from: string; until: string }) => {
23
25
  const n = dayOf(s.until) - dayOf(s.from);