@blueshed/joined 0.2.0 → 0.2.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.
@@ -362,7 +362,9 @@ Working: `examples/cafe/index.html`, the till's page, holds the menu, the till's
362
362
  A write of several documents is one message, `{ id, writes: [{ doc, ops, why? }, …] }`, sent by `together(writes)`
363
363
  from `joined/page`: each part a document the page holds, or one the write makes (`board:$1`), each asked in the
364
364
  write's transaction whether its writer may hold it, and the rules a write to it is held to. It's answered as one
365
- write. A document each person sees only some of is told a write's parts on it as one change.
365
+ write. A document each person sees only some of is told a write's parts on it as one change. An undo (`undo(doc,
366
+ version)`) is one document's: a write of several lands `landed` with its first part's version, and undoing it puts
367
+ back that part alone.
366
368
 
367
369
  ## 8. Routes: pages and edges
368
370
 
@@ -535,9 +537,10 @@ Working: `src/icons.ts`; the members panel and every example.
535
537
  `via` the label, and it holds none of his keys.
536
538
  - **The MCP door** (`src/mcp.ts`): an agent's link is a custom connector for Claude in a chat (claude.ai, a
537
539
  phone), and the Agents tab copies it so: `POST /mcp/<its token>`, MCP's Streamable HTTP in plain JSON. Only an agent's token opens it. Its tools are
538
- written from the compiled rules: `read_<doc>` (as its member sees it) and `write_<doc>` (one write, ops typed as
539
- the grants allow, answered `{ done, version, ids }` or a tool error in the refusal's words); a kind's take `key`;
540
- a window isn't one (read the document). An app's `routes.ts` may export `instructions`, its words for the agent,
540
+ written from the compiled rules: `read_<doc>` (as its member sees it; whole, or a `collection`'s items, some by
541
+ `ids`) and `write_<doc>` (one write, ops typed as the grants allow, in anyOf and enum as a strict client reads
542
+ them, a link's id a number or `"$1"`, answered `{ done, version, ids }` or a tool error in the refusal's words); a
543
+ kind's take `key`; a window isn't one (read the document). An app's `routes.ts` may export `instructions`, its words for the agent,
541
544
  said as the door opens (`examples/trip/routes.ts`). Never print the token: the URL holds it. A project with no
542
545
  members (every story anonymous, hello) has no group and no agent's link: its door is anyone's, `POST /mcp` with no
543
546
  token, as a stranger's page is, each write logged "by anyone" (`tests/server.test.ts`).
package/README.md CHANGED
@@ -31,7 +31,7 @@ elements.
31
31
  hold their links and can give them again. Behind them all is a kind BDFL, who always says why.
32
32
  - **Small.** Bun, web components and one dependency (lucide, for icons), and PGlite, optional, for a
33
33
  Postgres store; the migrations are joined's own. The compiler, the server, the page's side and the store
34
- together are about 4,200 lines of code, and a change to one of 100,000 events costs at most twice one of 1,000
34
+ together are about 4,700 lines of code, and a change to one of 100,000 events costs at most twice one of 1,000
35
35
  (`bun run claims` counts the one and times the other).
36
36
 
37
37
  ## Try it
@@ -64,7 +64,8 @@ so its connector address is `…/mcp`, with no link, and Claude changes it as an
64
64
  ## Your own apps
65
65
 
66
66
  joined is a package: a project takes it as a dependency and keeps its apps in `apps/`, each a
67
- folder like those in `examples/`. Once it's published (as `@blueshed/joined`), an app begins with:
67
+ folder like those in `examples/`. It's on npm as `@blueshed/joined`; once create-joined is published too, an app
68
+ begins with:
68
69
 
69
70
  ```
70
71
  bun create joined my-app
@@ -76,8 +77,9 @@ test telling hello's stories, and the scripts: `dev`, `compile` (each app's `gen
76
77
  its stories), `start` (serves `apps/`, keeping what the pages change in `.data/`), `link`, `upgrade` and `test`.
77
78
  `bun run upgrade` moves it to the newest joined and refreshes the skill.
78
79
 
79
- Until then, try it from a tarball: `bun run pack` in joined makes `.pack/blueshed-joined-<version>.tgz`, and
80
- `JOINED_FROM=<that tarball> bun <joined>/create/index.ts my-app` makes the app on it. Never take joined's folder
80
+ Until then, `bun <joined>/create/index.ts my-app` makes it, on the newest joined from npm. To try a joined not
81
+ released yet, `bun run pack` in joined makes `.pack/blueshed-joined-<version>.tgz`, and `JOINED_FROM=<that tarball>`
82
+ makes the app on it. Never take joined's folder
81
83
  itself (`file:../joined`): Bun copies a folder dependency whole, `.data/` (the store, and the members' keys)
82
84
  included.
83
85
 
@@ -187,7 +187,7 @@ Everything an app needs lives in one folder under `examples/`:
187
187
  | `index.html` & `page.ts` | The page and its controls |
188
188
  | `routes.ts` | Exports `document` and `routes` (the page and any edges like `/trip/1/trip.ics`) |
189
189
 
190
- To read deeper, see [docs/plan.md](plan.md) for `joined` as it's aimed: its architecture, what's decided
190
+ To read deeper, `docs/plan.md` in joined's repository is `joined` as it's aimed: its architecture, what's decided
191
191
  and why, every story and seed, what's built, and the phases still to build. See [docs/design.md](design.md) for how it
192
192
  looks: the rules for its surfaces, taps and drags, colour, type, icons and words, whose values and parts
193
193
  are `joined`'s design system.
package/docs/learning.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Learning joined
2
2
 
3
3
  Why joined is hard to pick up, and what would make it easier. It isn't the size: the compiler, the
4
- server, the page's side and the store are about 4,200 lines of code, and every line is tested. It's that a
4
+ server, the page's side and the store are about 4,700 lines of code, and every line is tested. It's that a
5
5
  newcomer meets several unfamiliar things at once, with nothing familiar to hold on to.
6
6
 
7
7
  ## Why it's hard
@@ -0,0 +1,119 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 360" font-family="system-ui, -apple-system, sans-serif">
2
+ <defs>
3
+ <marker id="arrow-obs" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
4
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#4e79a7"/>
5
+ </marker>
6
+ <marker id="arrow-op" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
7
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#f28e2b"/>
8
+ </marker>
9
+ </defs>
10
+
11
+ <!-- Outer Host Frame: <calendar-map> -->
12
+ <rect width="880" height="360" rx="10" fill="#fafafa" stroke="#ccc"/>
13
+ <text x="20" y="25" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="13" font-weight="600" fill="#222">&lt;calendar-map people="people"&gt;</text>
14
+ <text x="860" y="25" font-size="12" fill="#666" text-anchor="end">The light DOM is the document; the shadow DOM is the display.</text>
15
+
16
+ <!-- Left Panel: Light DOM (The Document) -->
17
+ <g transform="translate(18, 40)">
18
+ <rect width="324" height="300" rx="8" fill="#ffffff" stroke="#4e79a7" stroke-width="1.5"/>
19
+ <rect x="0.75" y="0.75" width="322.5" height="28" rx="7" fill="#eef3f8"/>
20
+ <text x="12" y="19" font-size="11.5" font-weight="600" fill="#2c5282">Light DOM — the document (hidden)</text>
21
+ <text x="312" y="19" font-size="10.5" fill="#4e79a7" text-anchor="end">no copy beside it</text>
22
+
23
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="10.2" fill="#222">
24
+ <text x="14" y="49" fill="#2c5282" font-weight="600">&lt;j-events&gt;</text>
25
+
26
+ <!-- Event 1 -->
27
+ <rect x="20" y="58" width="290" height="44" rx="5" fill="#f8f9fa" stroke="#e5e5e5"/>
28
+ <text x="28" y="75" fill="#666">&lt;j-event <tspan fill="#222">key="1" title="Land at Haneda"</tspan></text>
29
+ <text x="28" y="92" fill="#666"> start="2026-11-03T14:30:00" …&gt;</text>
30
+
31
+ <!-- Event 2 (Highlighted / Picked) -->
32
+ <rect x="20" y="112" width="290" height="86" rx="5" fill="#fdf6ec" stroke="#f28e2b" stroke-width="1.5"/>
33
+ <text x="28" y="129" font-weight="600" fill="#222">&lt;j-event <tspan fill="#d97706">key="2"</tspan></text>
34
+ <text x="38" y="146">title=<tspan fill="#59a14f">"Dinner in Shinjuku"</tspan></text>
35
+ <text x="38" y="163">start=<tspan fill="#2c5282" font-weight="600">"2026-11-04T19:00"</tspan> people=<tspan fill="#59a14f">"1 2"</tspan></text>
36
+ <text x="38" y="180">coordinates=<tspan fill="#2c5282" font-weight="600">"geo:35.6938,139.7034"</tspan>&gt;</text>
37
+
38
+ <!-- Event 3 -->
39
+ <rect x="20" y="208" width="290" height="44" rx="5" fill="#f8f9fa" stroke="#e5e5e5"/>
40
+ <text x="28" y="225" fill="#666">&lt;j-event <tspan fill="#222">key="3" title="Shinkansen"</tspan></text>
41
+ <text x="28" y="242" fill="#666"> start="2026-11-06T09:00:00" …&gt;</text>
42
+
43
+ <text x="14" y="274" fill="#2c5282" font-weight="600">&lt;/j-events&gt;</text>
44
+ </g>
45
+ </g>
46
+
47
+ <!-- Middle Bridge: MutationObserver & el.change() -->
48
+ <g transform="translate(342, 130)">
49
+ <!-- Forward arrow: MutationObserver -->
50
+ <path d="M 10 22 L 126 22" fill="none" stroke="#4e79a7" stroke-width="1.8" marker-end="url(#arrow-obs)"/>
51
+ <text x="68" y="13" font-size="10.5" font-weight="600" fill="#2c5282" text-anchor="middle">MutationObserver</text>
52
+ <text x="68" y="37" font-size="10" fill="#666" text-anchor="middle">1 attribute → 1 move</text>
53
+
54
+ <!-- Return arrow: el.change(...) -->
55
+ <path d="M 126 78 L 10 78" fill="none" stroke="#f28e2b" stroke-width="1.8" stroke-dasharray="4 3" marker-end="url(#arrow-op)"/>
56
+ <text x="68" y="69" font-family="ui-monospace, monospace" font-size="9.8" font-weight="600" fill="#d97706" text-anchor="middle">el.change({ start })</text>
57
+ <text x="68" y="93" font-size="10" fill="#666" text-anchor="middle">Save sends 1 write</text>
58
+ </g>
59
+
60
+ <!-- Right Panel: Shadow DOM (The Display) -->
61
+ <g transform="translate(478, 40)">
62
+ <rect width="384" height="300" rx="8" fill="#ffffff" stroke="#222" stroke-width="1.5"/>
63
+ <rect x="0.75" y="0.75" width="382.5" height="28" rx="7" fill="#f3f4f6"/>
64
+ <text x="14" y="19" font-size="12" font-weight="600" fill="#222">#shadow-root — drawn twice from one element</text>
65
+
66
+ <!-- Sub-view 1: Calendar Days -->
67
+ <g transform="translate(14, 42)">
68
+ <rect width="174" height="190" rx="6" fill="#ffffff" stroke="#ddd"/>
69
+ <line x1="58" y1="0" x2="58" y2="190" stroke="#eee"/>
70
+ <line x1="116" y1="0" x2="116" y2="190" stroke="#eee"/>
71
+ <line x1="0" y1="24" x2="174" y2="24" stroke="#eee"/>
72
+ <text x="29" y="16" font-size="10.5" font-weight="600" fill="#444" text-anchor="middle">Tue 3</text>
73
+ <text x="87" y="16" font-size="10.5" font-weight="600" fill="#222" text-anchor="middle">Wed 4</text>
74
+ <text x="145" y="16" font-size="10.5" font-weight="600" fill="#444" text-anchor="middle">Thu 5</text>
75
+
76
+ <!-- Hour guide lines -->
77
+ <line x1="0" y1="68" x2="174" y2="68" stroke="#f3f3f3"/>
78
+ <line x1="0" y1="112" x2="174" y2="112" stroke="#f3f3f3"/>
79
+ <line x1="0" y1="156" x2="174" y2="156" stroke="#f3f3f3"/>
80
+
81
+ <!-- Event 1 block -->
82
+ <rect x="4" y="92" width="50" height="32" rx="3" fill="#e8eff7" stroke="#4e79a7" stroke-width="1"/>
83
+ <text x="9" y="105" font-size="8.5" fill="#4e79a7" font-weight="600">14:30</text>
84
+ <text x="9" y="117" font-size="8.5" fill="#222">Land</text>
85
+
86
+ <!-- Event 2 block (Dinner, picked!) -->
87
+ <rect x="62" y="128" width="50" height="44" rx="3" fill="#fdebd6" stroke="#222" stroke-width="1.5"/>
88
+ <line x1="63" y1="128" x2="63" y2="172" stroke="#e15759" stroke-width="3"/>
89
+ <text x="69" y="140" font-size="8.5" font-weight="600" fill="#d97706">19:00</text>
90
+ <text x="69" y="152" font-size="8.5" font-weight="600" fill="#222">Dinner</text>
91
+ <circle cx="73" cy="163" r="3" fill="#f28e2b"/>
92
+ <circle cx="82" cy="163" r="3" fill="#e15759"/>
93
+ </g>
94
+
95
+ <!-- Sub-view 2: Map Tiles + Pins -->
96
+ <g transform="translate(198, 42)">
97
+ <rect width="172" height="190" rx="6" fill="#e8eef2" stroke="#ddd"/>
98
+ <!-- Stylised coastline / map grid -->
99
+ <path d="M 0 140 Q 55 120 95 85 T 172 45 L 172 190 L 0 190 Z" fill="#dbe6ec"/>
100
+ <path d="M 20 0 L 20 190 M 85 0 L 85 190 M 150 0 L 150 190 M 0 60 L 172 60 M 0 125 L 172 125" stroke="#dde5ea" stroke-width="1"/>
101
+
102
+ <!-- Pin 1 -->
103
+ <circle cx="122" cy="138" r="6" fill="#4e79a7" stroke="#fff" stroke-width="2"/>
104
+
105
+ <!-- Pin 2 (Dinner, picked!) -->
106
+ <circle cx="96" cy="88" r="8" fill="#e15759" stroke="#222" stroke-width="2"/>
107
+ <circle cx="96" cy="88" r="6" fill="none" stroke="#fff" stroke-width="1.5"/>
108
+ <rect x="40" y="56" width="112" height="22" rx="4" fill="#222"/>
109
+ <text x="96" y="71" font-size="9.5" font-weight="600" fill="#fff" text-anchor="middle">Dinner in Shinjuku</text>
110
+ </g>
111
+
112
+ <!-- Connecting callout lines inside shadow root showing both come from key="2" -->
113
+ <g transform="translate(14, 244)">
114
+ <rect width="356" height="44" rx="6" fill="#f8f9fa" stroke="#ddd"/>
115
+ <text x="12" y="18" font-size="11" font-weight="600" fill="#222">Editing “Dinner in Shinjuku”</text>
116
+ <text x="12" y="34" font-size="10.2" fill="#555">One element (<tspan font-family="ui-monospace, monospace" fill="#222">key="2"</tspan>) → one calendar block, one map pin, one form.</text>
117
+ </g>
118
+ </g>
119
+ </svg>
@@ -0,0 +1,93 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 320" font-family="system-ui, -apple-system, sans-serif">
2
+ <defs>
3
+ <marker id="l-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
4
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#e15759"/>
5
+ </marker>
6
+ <marker id="l-arrow-blue" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
7
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#4e79a7"/>
8
+ </marker>
9
+ </defs>
10
+
11
+ <rect width="880" height="320" rx="10" fill="#fafafa" stroke="#e5e5e5"/>
12
+
13
+ <!-- Left Half: Cross-Document Links via HTML IDREFS -->
14
+ <g transform="translate(20, 20)">
15
+ <rect width="410" height="280" rx="8" fill="#ffffff" stroke="#ccc"/>
16
+ <rect x="0.75" y="0.75" width="408.5" height="28" rx="7" fill="#f3f4f6"/>
17
+ <text x="14" y="19" font-size="12" font-weight="600" fill="#222">Links between documents: HTML IDREFS &amp; CSS</text>
18
+
19
+ <!-- Document 1: trip:1 -->
20
+ <g transform="translate(14, 42)">
21
+ <rect width="382" height="84" rx="6" fill="#f8f9fa" stroke="#ddd"/>
22
+ <text x="12" y="18" font-size="11" font-weight="600" fill="#4e79a7">Document: trip:1 (&lt;j-events&gt;)</text>
23
+ <text x="12" y="39" font-family="ui-monospace, monospace" font-size="9.8" fill="#222">&lt;j-event key="1" title="Land at Haneda" <tspan fill="#e15759" font-weight="600">people="1"</tspan>&gt;</text>
24
+ <text x="12" y="57" font-family="ui-monospace, monospace" font-size="9.8" fill="#222">&lt;j-event key="2" title="Dinner in Shinjuku" <tspan fill="#e15759" font-weight="600">people="1 2"</tspan>&gt;</text>
25
+ <text x="12" y="74" font-size="10.2" fill="#666">Field name = target collection name ("people")</text>
26
+ </g>
27
+
28
+ <!-- CSS Selector Query Bridge -->
29
+ <path d="M 135 168 L 135 130" fill="none" stroke="#e15759" stroke-width="1.6" marker-end="url(#l-arrow)"/>
30
+ <text x="147" y="153" font-family="ui-monospace, monospace" font-size="10.5" font-weight="600" fill="#e15759">querySelectorAll('[people~="2"]')</text>
31
+
32
+ <!-- Document 2: people -->
33
+ <g transform="translate(14, 172)">
34
+ <rect width="382" height="94" rx="6" fill="#fdf6ec" stroke="#f28e2b"/>
35
+ <text x="12" y="18" font-size="11" font-weight="600" fill="#d97706">Document: people (&lt;j-people&gt; in its popover)</text>
36
+ <text x="12" y="38" font-family="ui-monospace, monospace" font-size="10.5" fill="#222">&lt;j-person <tspan fill="#e15759" font-weight="600">key="2"</tspan> name="Kenji"&gt;</text>
37
+ <rect x="22" y="47" width="142" height="22" rx="4" fill="#ffffff" stroke="#222"/>
38
+ <text x="93" y="62" font-size="10.2" font-weight="600" fill="#222" text-anchor="middle">Dinner in Shinjuku ↗</text>
39
+ <text x="174" y="62" font-size="10.2" fill="#555">click dispatches <tspan font-family="ui-monospace, monospace" fill="#222">"pick"</tspan></text>
40
+ <text x="12" y="84" font-size="10.2" fill="#666">Server refuses removing Kenji while 1 event in trip links to him.</text>
41
+ </g>
42
+ </g>
43
+
44
+ <!-- Right Half: The Trust Network (src/members/) -->
45
+ <g transform="translate(450, 20)">
46
+ <rect width="410" height="280" rx="8" fill="#ffffff" stroke="#ccc"/>
47
+ <rect x="0.75" y="0.75" width="408.5" height="28" rx="7" fill="#f3f4f6"/>
48
+ <text x="14" y="19" font-size="12" font-weight="600" fill="#222">Sign-in by link: the trust tree (&lt;j-members&gt;)</text>
49
+
50
+ <!-- Tree Nodes -->
51
+ <!-- Root: Peter -->
52
+ <g transform="translate(20, 46)">
53
+ <rect width="246" height="34" rx="6" fill="#222"/>
54
+ <text x="12" y="21" font-size="12" font-weight="600" fill="#fff">Peter</text>
55
+ <rect x="52" y="8" width="38" height="18" rx="4" fill="#4e79a7"/>
56
+ <text x="71" y="20" font-size="9.5" font-weight="600" fill="#fff" text-anchor="middle">BDFL</text>
57
+ <text x="234" y="21" font-family="ui-monospace, monospace" font-size="10" fill="#ccc" text-anchor="end">key="1" (ROOT_TOKEN)</text>
58
+ </g>
59
+
60
+ <!-- Branch to Nick -->
61
+ <path d="M 34 80 L 34 108 L 50 108" fill="none" stroke="#888" stroke-width="1.5"/>
62
+ <g transform="translate(50, 91)">
63
+ <rect width="232" height="34" rx="6" fill="#f8f9fa" stroke="#ccc"/>
64
+ <text x="12" y="21" font-size="12" font-weight="600" fill="#222">Nick</text>
65
+ <text x="220" y="21" font-family="ui-monospace, monospace" font-size="10" fill="#666" text-anchor="end">key="2" inviter="1"</text>
66
+ </g>
67
+
68
+ <!-- Branch to Nora -->
69
+ <path d="M 64 125 L 64 153 L 80 153" fill="none" stroke="#888" stroke-width="1.5"/>
70
+ <g transform="translate(80, 136)">
71
+ <rect width="232" height="34" rx="6" fill="#f8f9fa" stroke="#ccc"/>
72
+ <text x="12" y="21" font-size="12" font-weight="600" fill="#222">Nora</text>
73
+ <text x="220" y="21" font-family="ui-monospace, monospace" font-size="10" fill="#666" text-anchor="end">key="3" inviter="2"</text>
74
+ </g>
75
+
76
+ <!-- Branch to Dev -->
77
+ <path d="M 94 170 L 94 198 L 110 198" fill="none" stroke="#888" stroke-width="1.5"/>
78
+ <g transform="translate(110, 181)">
79
+ <rect width="232" height="34" rx="6" fill="#f8f9fa" stroke="#ccc"/>
80
+ <text x="12" y="21" font-size="12" font-weight="600" fill="#222">Dev</text>
81
+ <text x="220" y="21" font-family="ui-monospace, monospace" font-size="10" fill="#666" text-anchor="end">key="4" inviter="3"</text>
82
+ </g>
83
+
84
+ <!-- Reparenting curved arrow (if Nora is removed, Dev moves up to Nick) -->
85
+ <path d="M 342 198 C 390 198, 390 108, 288 108" fill="none" stroke="#4e79a7" stroke-width="1.5" stroke-dasharray="3 2" marker-end="url(#l-arrow-blue)"/>
86
+
87
+ <!-- Rules summary at bottom -->
88
+ <g transform="translate(18, 228)" font-size="10.5" fill="#555">
89
+ <text x="0" y="14">• <tspan font-weight="600" fill="#222">Friends help friends:</tspan> your inviter holds your link to send again or replace.</text>
90
+ <text x="0" y="32">• <tspan font-weight="600" fill="#222">Remove with a reason:</tspan> if Nick removes Nora, Dev moves up to Nick.</text>
91
+ </g>
92
+ </g>
93
+ </svg>
package/docs/logo.svg ADDED
@@ -0,0 +1,47 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 180">
2
+ <!-- Warm amber right half -->
3
+ <rect x="6" y="6" width="168" height="168" fill="#e07a24"/>
4
+
5
+ <!-- Slate-blue left half (head, ear, trunk, and left block) -->
6
+ <path d="
7
+ M 6 6
8
+ H 90
9
+ V 20
10
+ A 56 56 0 0 1 146 76
11
+ V 134
12
+ A 21 21 0 0 1 104 134
13
+ H 124
14
+ V 128
15
+ A 28 28 0 0 0 68 128
16
+ V 174
17
+ H 6
18
+ Z
19
+ " fill="#46719e"/>
20
+
21
+ <!-- Top vertical join tick -->
22
+ <line x1="90" y1="6" x2="90" y2="20" stroke="#080808" stroke-width="10"/>
23
+
24
+ <!-- Continuous ear -> forehead -> outer trunk -> trunk tip -->
25
+ <path d="
26
+ M 68 100
27
+ A 40 40 0 0 1 68 20
28
+ H 90
29
+ A 56 56 0 0 1 146 76
30
+ V 134
31
+ A 21 21 0 0 1 104 134
32
+ " fill="none" stroke="#080808" stroke-width="10" stroke-linecap="butt"/>
33
+
34
+ <!-- Inner throat arch -> down into trunk curl + bottom vertical join -->
35
+ <path d="
36
+ M 68 174
37
+ V 128
38
+ A 28 28 0 0 1 124 128
39
+ V 135
40
+ " fill="none" stroke="#080808" stroke-width="10" stroke-linecap="round"/>
41
+
42
+ <!-- Outer square frame -->
43
+ <rect x="6" y="6" width="168" height="168" fill="none" stroke="#080808" stroke-width="12"/>
44
+
45
+ <!-- White dot eye -->
46
+ <circle cx="110" cy="65" r="5" fill="#fff"/>
47
+ </svg>
@@ -0,0 +1,86 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 390" font-family="system-ui, -apple-system, sans-serif">
2
+ <defs>
3
+ <marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
4
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#666"/>
5
+ </marker>
6
+ <marker id="arrow-blue" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
7
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#4e79a7"/>
8
+ </marker>
9
+ </defs>
10
+
11
+ <!-- Background -->
12
+ <rect width="880" height="390" rx="10" fill="#fafafa" stroke="#e5e5e5"/>
13
+
14
+ <!-- 1. Top Box: stories.jsonl -->
15
+ <g transform="translate(30, 22)">
16
+ <rect width="820" height="104" rx="8" fill="#ffffff" stroke="#ccc"/>
17
+ <rect width="820" height="28" rx="8" fill="#f3f4f6"/>
18
+ <path d="M 0 22 H 820" stroke="#e5e5e5" fill="none"/>
19
+ <circle cx="16" cy="14" r="4.5" fill="#e15759"/>
20
+ <circle cx="30" cy="14" r="4.5" fill="#edc948"/>
21
+ <circle cx="44" cy="14" r="4.5" fill="#59a14f"/>
22
+ <text x="62" y="18" font-size="12" font-weight="600" fill="#222">examples/trip/stories.jsonl</text>
23
+ <text x="804" y="18" font-size="11" fill="#666" text-anchor="end">the single source of truth — schema, migrations &amp; tests</text>
24
+
25
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="9.2" fill="#222">
26
+ <text x="16" y="48">
27
+ <tspan fill="#666">{"story":</tspan><tspan fill="#59a14f">"Add dinner"</tspan><tspan fill="#666">,"as":"peter","does":{"doc":</tspan><tspan fill="#4e79a7" font-weight="600">"trip:1"</tspan><tspan fill="#666">,"ops":[{"op":</tspan><tspan fill="#f28e2b" font-weight="600">"add"</tspan><tspan fill="#666">,"path":</tspan><tspan fill="#4e79a7" font-weight="600">"/events/-"</tspan><tspan fill="#666">,"value":{"people":[1,2],…}}]}}</tspan>
28
+ </text>
29
+ <text x="16" y="70">
30
+ <tspan fill="#666">{"story":</tspan><tspan fill="#59a14f">"Move train"</tspan><tspan fill="#666">,"as":"phone","does":{"doc":</tspan><tspan fill="#4e79a7" font-weight="600">"trip:1"</tspan><tspan fill="#666">,"ops":[{"op":</tspan><tspan fill="#f28e2b" font-weight="600">"replace"</tspan><tspan fill="#666">,"path":</tspan><tspan fill="#4e79a7" font-weight="600">"/events/3/start"</tspan><tspan fill="#666">,"value":"2026-11-06T10:00"}]}}</tspan>
31
+ </text>
32
+ <text x="16" y="92">
33
+ <tspan fill="#666">{"story":</tspan><tspan fill="#59a14f">"Clear place"</tspan><tspan fill="#666">,"as":"peter","does":{"doc":</tspan><tspan fill="#4e79a7" font-weight="600">"trip:1"</tspan><tspan fill="#666">,"ops":[{"op":</tspan><tspan fill="#e15759" font-weight="600">"remove"</tspan><tspan fill="#666">,"path":</tspan><tspan fill="#4e79a7" font-weight="600">"/events/2/location"</tspan><tspan fill="#666">}]}}</tspan>
34
+ </text>
35
+ </g>
36
+ </g>
37
+
38
+ <!-- Arrow down to compiler -->
39
+ <line x1="440" y1="126" x2="440" y2="156" stroke="#666" stroke-width="1.5" marker-end="url(#arrow)"/>
40
+ <text x="450" y="146" font-size="11" fill="#666">reduce stories → model</text>
41
+
42
+ <!-- 2. Middle Box: src/compile.ts -->
43
+ <g transform="translate(190, 160)">
44
+ <rect width="500" height="58" rx="8" fill="#222" stroke="#222"/>
45
+ <text x="250" y="23" font-size="13" font-weight="600" fill="#fff" text-anchor="middle">src/compile.ts — modelOf(stories)</text>
46
+ <text x="250" y="43" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="10.5" fill="#ddd" text-anchor="middle">
47
+ events → &lt;j-events&gt;&lt;j-event&gt; · tables · required · replace · clear · links
48
+ </text>
49
+ </g>
50
+
51
+ <!-- Split arrows left and right -->
52
+ <path d="M 320 218 L 320 236 L 220 236 L 220 254" fill="none" stroke="#4e79a7" stroke-width="1.5" marker-end="url(#arrow-blue)"/>
53
+ <path d="M 560 218 L 560 236 L 660 236 L 660 254" fill="none" stroke="#4e79a7" stroke-width="1.5" marker-end="url(#arrow-blue)"/>
54
+ <text x="260" y="231" font-size="11" fill="#4e79a7" text-anchor="end">for the server &amp; store</text>
55
+ <text x="620" y="231" font-size="11" fill="#4e79a7">for the page</text>
56
+
57
+ <!-- 3A. Left Box: generated/rules.ts & migrations/ -->
58
+ <g transform="translate(30, 258)">
59
+ <rect width="395" height="112" rx="8" fill="#ffffff" stroke="#4e79a7" stroke-width="1.5"/>
60
+ <rect x="0.75" y="0.75" width="393.5" height="26" rx="7" fill="#eef3f8"/>
61
+ <text x="14" y="18" font-size="12" font-weight="600" fill="#2c5282">generated/rules.ts &amp; migrations/</text>
62
+ <text x="382" y="18" font-size="11" fill="#4e79a7" text-anchor="end">guards &amp; SQLite tables</text>
63
+
64
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="10.5" fill="#222">
65
+ <text x="14" y="47"><tspan fill="#666">export function</tspan> <tspan fill="#2c5282" font-weight="600">check</tspan>(o: Op, has: Has): string | null</text>
66
+ <text x="14" y="66" font-family="system-ui, sans-serif" font-size="10.5" fill="#555">• Refuses any collection, field, or op no story did</text>
67
+ <text x="14" y="84" font-family="system-ui, sans-serif" font-size="10.5" fill="#555">• Checks every id in <tspan font-family="ui-monospace, monospace" fill="#222">people: [1, 2]</tspan> exists in <tspan font-family="ui-monospace, monospace" fill="#222">people</tspan></text>
68
+ <text x="14" y="102" font-family="system-ui, sans-serif" font-size="10.5" fill="#555">• Writes SQLite migrations (<tspan font-family="ui-monospace, monospace" fill="#222">events</tspan>, <tspan font-family="ui-monospace, monospace" fill="#222">events_people</tspan>)</text>
69
+ </g>
70
+ </g>
71
+
72
+ <!-- 3B. Right Box: generated/elements.ts -->
73
+ <g transform="translate(455, 258)">
74
+ <rect width="395" height="112" rx="8" fill="#ffffff" stroke="#4e79a7" stroke-width="1.5"/>
75
+ <rect x="0.75" y="0.75" width="393.5" height="26" rx="7" fill="#eef3f8"/>
76
+ <text x="14" y="18" font-size="12" font-weight="600" fill="#2c5282">generated/elements.ts</text>
77
+ <text x="382" y="18" font-size="11" fill="#4e79a7" text-anchor="end">web components in the DOM</text>
78
+
79
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="10.5" fill="#222">
80
+ <text x="14" y="47"><tspan fill="#2c5282" font-weight="600">&lt;j-events&gt;</tspan> → <tspan fill="#666">hold("trip:1?week=…"), items, add(...events)</tspan></text>
81
+ <text x="14" y="67"><tspan fill="#2c5282" font-weight="600">&lt;j-event&gt;</tspan> → <tspan fill="#666">key, data (cached &amp; frozen)</tspan></text>
82
+ <text x="14" y="86" font-family="system-ui, sans-serif" font-size="10.5" fill="#555">• Only the ops stories do: <tspan font-family="ui-monospace, monospace" fill="#222">change({…}), clear(…), drop()</tspan></text>
83
+ <text x="14" y="103" font-family="system-ui, sans-serif" font-size="10.5" fill="#555">• No story removes a title → <tspan font-family="ui-monospace, monospace" fill="#222">clear("title")</tspan> does not exist</text>
84
+ </g>
85
+ </g>
86
+ </svg>
@@ -0,0 +1,99 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 310" font-family="system-ui, -apple-system, sans-serif">
2
+ <defs>
3
+ <marker id="w-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
4
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#4e79a7"/>
5
+ </marker>
6
+ <marker id="w-arrow-green" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
7
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#59a14f"/>
8
+ </marker>
9
+ </defs>
10
+
11
+ <rect width="880" height="310" rx="10" fill="#fafafa" stroke="#e5e5e5"/>
12
+
13
+ <!-- Column 1: Peter's Laptop -->
14
+ <g transform="translate(16, 24)">
15
+ <rect width="214" height="262" rx="8" fill="#ffffff" stroke="#ccc"/>
16
+ <rect x="0.75" y="0.75" width="212.5" height="28" rx="7" fill="#f3f4f6"/>
17
+ <text x="12" y="19" font-size="11.5" font-weight="600" fill="#222">1. Peter’s laptop</text>
18
+ <text x="202" y="19" font-size="10.5" fill="#666" text-anchor="end">one /ws per tab</text>
19
+
20
+ <text x="12" y="50" font-size="11" fill="#555">Drags the shinkansen to 10:00</text>
21
+ <text x="12" y="66" font-size="11" fill="#555">and presses <tspan font-weight="600" fill="#222">Save</tspan>:</text>
22
+
23
+ <rect x="12" y="78" width="190" height="52" rx="5" fill="#eef3f8" stroke="#4e79a7"/>
24
+ <text x="20" y="94" font-family="ui-monospace, monospace" font-size="10" fill="#2c5282" font-weight="600">el.change({</text>
25
+ <text x="20" y="109" font-family="ui-monospace, monospace" font-size="9.5" fill="#222"> start: "2026-11-06T10:00"</text>
26
+ <text x="20" y="123" font-family="ui-monospace, monospace" font-size="10" fill="#2c5282" font-weight="600">})</text>
27
+
28
+ <line x1="12" y1="146" x2="202" y2="146" stroke="#eee"/>
29
+
30
+ <text x="12" y="168" font-size="11" font-weight="600" fill="#59a14f">4a. On broadcast:</text>
31
+ <text x="12" y="187" font-family="ui-monospace, monospace" font-size="10" fill="#222">items.get("3")</text>
32
+ <text x="12" y="203" font-family="ui-monospace, monospace" font-size="10" fill="#222"> .setAttribute("start", …)</text>
33
+ <text x="12" y="226" font-size="10.5" fill="#555">Only <tspan font-family="ui-monospace, monospace" fill="#222">key="3"</tspan> moves; Save resets.</text>
34
+ <text x="12" y="246" font-family="ui-monospace, monospace" font-size="10" fill="#666">body[data-trip_1_week_…="2"]</text>
35
+ </g>
36
+
37
+ <!-- Arrow 1 -> 2 (Send Op) -->
38
+ <path d="M 236 96 L 342 96" fill="none" stroke="#4e79a7" stroke-width="1.8" marker-end="url(#w-arrow)"/>
39
+ <text x="289" y="75" font-family="ui-monospace, monospace" font-size="9.5" fill="#2c5282" text-anchor="middle">replace</text>
40
+ <text x="289" y="88" font-family="ui-monospace, monospace" font-size="9" fill="#4e79a7" text-anchor="middle">/events/3/start</text>
41
+
42
+ <!-- Arrow 2 -> 1 (Broadcast back) -->
43
+ <path d="M 342 188 L 236 188" fill="none" stroke="#59a14f" stroke-width="1.8" marker-end="url(#w-arrow-green)"/>
44
+ <text x="289" y="179" font-family="ui-monospace, monospace" font-size="9" fill="#59a14f" text-anchor="middle">{ version: 2, ops }</text>
45
+
46
+ <!-- Column 2: The Server -->
47
+ <g transform="translate(348, 24)">
48
+ <rect width="218" height="262" rx="8" fill="#ffffff" stroke="#222" stroke-width="1.5"/>
49
+ <rect x="0.75" y="0.75" width="216.5" height="28" rx="7" fill="#222"/>
50
+ <text x="109" y="19" font-size="11.5" font-weight="600" fill="#fff" text-anchor="middle">2. src/server.ts &amp; store.ts</text>
51
+
52
+ <g transform="translate(12, 44)" font-size="11" fill="#222">
53
+ <rect width="194" height="36" rx="5" fill="#f8f9fa" stroke="#e5e5e5"/>
54
+ <text x="10" y="15" font-weight="600">1. rules.check(op, has)</text>
55
+ <text x="10" y="29" font-size="10" fill="#666">Allowed by stories? Links valid?</text>
56
+
57
+ <rect y="44" width="194" height="36" rx="5" fill="#f8f9fa" stroke="#e5e5e5"/>
58
+ <text x="10" y="59" font-weight="600">2. group.mayWrite(doc, ops, …)</text>
59
+ <text x="10" y="73" font-size="10" fill="#666">Signed in? Not read-only? Trust ok?</text>
60
+
61
+ <rect y="88" width="194" height="36" rx="5" fill="#f8f9fa" stroke="#e5e5e5"/>
62
+ <text x="10" y="103" font-weight="600">3. store.write(doc, ops, …)</text>
63
+ <text x="10" y="117" font-size="10" fill="#666">1 SQLite transaction + changes row</text>
64
+
65
+ <rect y="132" width="194" height="44" rx="5" fill="#eef7ec" stroke="#59a14f"/>
66
+ <text x="10" y="149" font-weight="600" fill="#2b6e22">4. told(change) — pub/sub</text>
67
+ <text x="10" y="166" font-family="ui-monospace, monospace" font-size="9.2" fill="#222">{ doc, version: 2, ops, by: 1 }</text>
68
+ </g>
69
+
70
+ <text x="109" y="246" font-size="10" fill="#a33" text-anchor="middle">Refused? Tells sender "refused" + why</text>
71
+ </g>
72
+
73
+ <!-- Arrow 2 -> 3 (Broadcast to phone) -->
74
+ <path d="M 572 188 L 644 188" fill="none" stroke="#59a14f" stroke-width="1.8" marker-end="url(#w-arrow-green)"/>
75
+ <text x="608" y="179" font-family="ui-monospace, monospace" font-size="9.5" fill="#59a14f" text-anchor="middle">~25 ms</text>
76
+
77
+ <!-- Column 3: Peter's Phone -->
78
+ <g transform="translate(650, 24)">
79
+ <rect width="214" height="262" rx="8" fill="#ffffff" stroke="#ccc"/>
80
+ <rect x="0.75" y="0.75" width="212.5" height="28" rx="7" fill="#f3f4f6"/>
81
+ <text x="12" y="19" font-size="11.5" font-weight="600" fill="#222">3. Peter’s phone</text>
82
+ <text x="202" y="19" font-size="10.5" fill="#666" text-anchor="end">the same week</text>
83
+
84
+ <text x="12" y="52" font-size="11" fill="#555">Hears the same op on its socket:</text>
85
+
86
+ <rect x="12" y="64" width="190" height="58" rx="5" fill="#f8f9fa" stroke="#ddd"/>
87
+ <text x="20" y="82" font-family="ui-monospace, monospace" font-size="9.8" fill="#666">&lt;j-event <tspan fill="#222">key="3"</tspan></text>
88
+ <text x="20" y="98" font-family="ui-monospace, monospace" font-size="9.8" fill="#59a14f" font-weight="600"> start="2026-11-06T10:00"</text>
89
+ <text x="20" y="113" font-family="ui-monospace, monospace" font-size="9.8" fill="#666"> title="Shinkansen to Kyoto"&gt;</text>
90
+
91
+ <line x1="12" y1="146" x2="202" y2="146" stroke="#eee"/>
92
+
93
+ <text x="12" y="168" font-size="11" font-weight="600" fill="#59a14f">4b. Surgical update:</text>
94
+ <text x="12" y="188" font-size="10.2" fill="#555">• <tspan font-family="ui-monospace, monospace" fill="#222">MutationObserver</tspan> sees <tspan font-family="ui-monospace, monospace" fill="#222">key="3"</tspan></text>
95
+ <text x="12" y="207" font-size="10.5" fill="#555">• Moves only the Shinkansen block</text>
96
+ <text x="12" y="226" font-size="10.5" fill="#555">• Every other node stays untouched</text>
97
+ <text x="12" y="246" font-family="ui-monospace, monospace" font-size="10" fill="#666">body[data-trip_1_week_…="2"]</text>
98
+ </g>
99
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueshed/joined",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Compiled documents, talking to web components as elements in the DOM.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,7 +52,8 @@
52
52
  "docs/introduction.md",
53
53
  "docs/stories.md",
54
54
  "docs/design.md",
55
- "docs/learning.md"
55
+ "docs/learning.md",
56
+ "docs/*.svg"
56
57
  ],
57
58
  "dependencies": {
58
59
  "lucide": "^1.62.0"
package/src/attachment.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  // A file field on the page (Attachment, joined/attachment): what an item holds in it shown, a photo as its picture and
2
- // a PDF as a link, each opening the file; and, where its person may, a way to choose one, and to take it off. A file
3
- // chosen is sent to the server for the item's document (/files, src/files.ts), which keeps it and answers its value;
4
- // that's put in the field by the view's own op (`put`: the item's replace, or an add form's field), never written to
5
- // the element. Drawn again as the item is, only what changed moves: the picture stays while its file does.
2
+ // a PDF or a Markdown file as a link, each opening the file; and, where its person may, a way to choose one, and to
3
+ // take it off. A file chosen is sent to the server for the item's document (/files, src/files.ts), which keeps it and
4
+ // answers its value; that's put in the field by the view's own op (`put`: the item's replace, or an add form's field),
5
+ // never written to the element. Drawn again as the item is, only what changed moves: the picture stays while its file
6
+ // does.
6
7
 
7
8
  import { fileUrl, MOST, TOO_BIG } from "./file-value.ts";
8
9
  import { icon, iconButton } from "./icons.ts";
@@ -60,11 +61,12 @@ export function attachment(doc: () => string, put: (file: string) => Promise<Ans
60
61
  draw(value: string | undefined, may: { put?: boolean; take?: boolean } = {}) {
61
62
  const url = value && fileUrl(value);
62
63
  if (url && shown.getAttribute("href") !== url) {
63
- const pdf = url.endsWith(".pdf");
64
- Object.assign(shown, { href: url, className: pdf ? "act small" : "j-file-picture" });
65
- shown.ariaLabel = pdf ? "Open the PDF" : "Open the picture";
66
- if (!pdf) picture.src = url;
67
- shown.replaceChildren(...(pdf ? [icon("download"), "PDF"] : [picture]));
64
+ // a PDF or a Markdown file, a link to it, named; a photo or an SVG, its picture
65
+ const linked = url.endsWith(".pdf") ? "PDF" : url.endsWith(".md") ? "Markdown" : undefined;
66
+ Object.assign(shown, { href: url, className: linked ? "act small" : "j-file-picture" });
67
+ shown.ariaLabel = linked ? `Open the ${linked}` : "Open the picture";
68
+ if (!linked) picture.src = url;
69
+ shown.replaceChildren(...(linked ? [icon("download"), linked] : [picture]));
68
70
  }
69
71
  shown.hidden = !url;
70
72
  words.textContent = value ? "Another file" : "Add a file";
package/src/client.ts CHANGED
@@ -26,6 +26,13 @@ export function applied(doc: Record<string, any>, o: Op): Record<string, any> {
26
26
  [coll]: items.flatMap((i) => (String(i.id) === key ? (f(i) ?? []) : [i])),
27
27
  });
28
28
  if (field === undefined) return o.op === "remove" ? changed(() => null) : changed((i) => ({ ...i, ...o.value }));
29
+ // one of an object's fields (/orders/1/terms/days): made where there's none; the object gone once it's empty
30
+ if (link !== undefined && !/^(\d+|-)$/.test(link))
31
+ return changed((i) => {
32
+ const { [link]: _, ...rest } = i[field] ?? {};
33
+ const now = o.op === "remove" ? rest : { ...rest, [link]: o.value };
34
+ return Object.keys(now).length ? { ...i, [field]: now } : (({ [field]: _, ...others }) => others)(i);
35
+ });
29
36
  // an id added to a list, or taken from it: the rest as it was
30
37
  if (link !== undefined)
31
38
  return changed((i) => {
package/src/files.ts CHANGED
@@ -1,4 +1,4 @@
1
- // A file a document names: a photo, an SVG or a PDF, its field's value `file:<its SHA-256>.<ext>` (the compiler's file form),
1
+ // A file a document names: a photo, an SVG, a PDF or a Markdown file, its field's value `file:<its SHA-256>.<ext>` (the compiler's file form),
2
2
  // kept in a folder, files/ beside the store, or a bucket (JOINED_FILES: `s3://<bucket>/<prefix>`), and served at
3
3
  // /files/<its name>. Its name is its content's hash, so
4
4
  // it never changes and is cached for good; the same file sent twice is kept once. A photo is kept as a WebP at most
package/src/mcp.ts CHANGED
@@ -5,12 +5,12 @@
5
5
  // page does: each write its member's, via the agent, under the same rules (the app's trust.ts, the grants, the
6
6
  // group's), whole or not at all, and told to every page at once. Its tools are written from each document's compiled
7
7
  // rules, never the stories: read_<doc>, the document as its member sees it, and write_<doc>, one write, its ops typed
8
- // as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read whole,
9
- // as its member sees it. Each app may give the agent its own words (its routes.ts's `instructions`), said as it opens.
8
+ // as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read as its
9
+ // member sees it, whole or one collection's items (some, by id). Each app may give the agent its own words (its routes.ts's `instructions`), said as it opens.
10
10
 
11
11
  import { FORMS, SAID } from "./compile.ts";
12
12
  import type { Who } from "./members/group.ts";
13
- import type { Op, Type } from "./ops.ts";
13
+ import { NTH, parts, type Op, type Type } from "./ops.ts";
14
14
  import type { Doc } from "./store.ts";
15
15
  import type { Rules } from "./write.ts";
16
16
 
@@ -42,10 +42,19 @@ const ID = "[1-9]\\d*";
42
42
  const answered = (value: unknown): Result => ({ content: [{ type: "text", text: JSON.stringify(value) }] });
43
43
  const refused = (why: string): Result => ({ content: [{ type: "text", text: why }], isError: true });
44
44
 
45
- /** A field's value, as its type says it: its JSON type, and a string's form and words, as the database holds it to. */
45
+ /** An id of a collection's: a number, or "$n", the nth add of the same write (anyOf, as a strict client's schema
46
+ * says either, never a list of types). */
47
+ const idOf = (of: string | undefined, said = `an id of ${of}`): Schema => ({
48
+ anyOf: [{ type: "integer" }, { type: "string", pattern: NTH.source, description: "$1: this write's first add" }],
49
+ description: said,
50
+ });
51
+
52
+ /** A field's value, as its type says it: its JSON type, and a string's form and words, as the database holds it to; a
53
+ * link, an id of what it links to. */
46
54
  function formOf(c: Collection, field: string): Schema {
47
55
  const t = c.fields[field] as Type;
48
- if (t === "ids") return { type: "array", items: { type: "integer" }, description: `ids of ${c.links[field]}` };
56
+ if (t === "ids") return { type: "array", items: idOf(c.links[field]), description: `ids of ${c.links[field]}` };
57
+ if (c.links?.[field]) return idOf(c.links[field]);
49
58
  const json = t === "boolean" ? "boolean" : t === "integer" ? "integer" : t === "decimal" ? "number" : "string";
50
59
  const form = FORMS[t as keyof typeof FORMS];
51
60
  return { type: json, description: SAID[t], ...(form ? { pattern: form.source } : {}) };
@@ -66,6 +75,9 @@ function itemOf(c: Collection): Schema {
66
75
  return { type: "object", properties, required: (c.needs ?? []).filter((f) => !filled.includes(f)) };
67
76
  }
68
77
 
78
+ /** A document's own fields, as a collection's. */
79
+ const ownOf = (r: Rules) => Object.values(r.collections).find((c) => c.own) as Collection;
80
+
69
81
  /** Each op a write may hold, read off a document's grants: the op on its path's form (`replace /events/{id}/title`), the
70
82
  * pattern its path matches, and the value it takes; an add by a first step (`add posts.status:>waiting`), what it
71
83
  * gives (`status waiting`). */
@@ -78,10 +90,7 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
78
90
  [coll, rest] = dot < 0 ? [of, ""] : [of.slice(0, dot), of.slice(dot + 1)];
79
91
  const c = r.collections[coll] as Collection | undefined;
80
92
  // a document's own field, at its top (/greeting)
81
- if (!c) {
82
- const own = Object.values(r.collections).find((c) => c.own) as Collection;
83
- return { op, path: `/${of}`, pattern: `^/${of}$`, value: formOf(own, of) };
84
- }
93
+ if (!c) return { op, path: `/${of}`, pattern: `^/${of}$`, value: formOf(ownOf(r), of) };
85
94
  if (!rest)
86
95
  return op === "add"
87
96
  ? { op, path: `/${coll}/-`, pattern: `^/${coll}/-$`, value: itemOf(c) }
@@ -94,7 +103,7 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
94
103
  op,
95
104
  path: `/${coll}/{id}/${f}/-`,
96
105
  pattern: `^/${coll}/${ID}/${f}/-$`,
97
- value: { type: "integer", description: `an id of ${c.links[f]}` },
106
+ value: idOf(c.links[f]),
98
107
  }
99
108
  : { op, path: `/${coll}/{id}/${f}/{its id}`, pattern: `^/${coll}/${ID}/${f}/${ID}$` };
100
109
  }
@@ -105,11 +114,11 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
105
114
  // an add by its field's first step: an item, giving that step
106
115
  if (op === "add") {
107
116
  const item = itemOf(c);
108
- const value = { ...item, properties: { ...(item.properties as object), [field]: { const: to } } };
117
+ const value = { ...item, properties: { ...(item.properties as object), [field]: { enum: [to] } } };
109
118
  return { op, path: `/${coll}/-`, pattern: `^/${coll}/-$`, value, gives: `${field} ${to}` };
110
119
  }
111
120
  const value =
112
- op === "remove" ? undefined : step ? { const: to, description: `only from ${from}` } : formOf(c, field);
121
+ op === "remove" ? undefined : step ? { enum: [to], description: `only from ${from}` } : formOf(c, field);
113
122
  return { op, path: `/${coll}/{id}/${at}`, pattern: `^/${coll}/${ID}/${at}$`, ...(value ? { value } : {}) };
114
123
  });
115
124
  }
@@ -125,6 +134,36 @@ const described = (r: Rules) =>
125
134
  )
126
135
  .join("; ");
127
136
 
137
+ /** A write's ops as a small model sends them: an object or a list given for a string field (a bag of pairs) is said as
138
+ * its JSON text, as the field holds it; anything else is left for the write to refuse in its words. */
139
+ function texted(r: Rules, ops: Op[]): Op[] {
140
+ const text = (c: Collection | undefined, f: string, v: unknown) =>
141
+ c?.fields[f] === "string" && v !== null && typeof v === "object" ? JSON.stringify(v) : v;
142
+ return ops.map((o) => {
143
+ if (!o || typeof o !== "object" || !("value" in o) || typeof o.path !== "string") return o;
144
+ const { coll, key, field, link } = parts(o.path),
145
+ c = r.collections[coll] as Collection | undefined;
146
+ // a document's own field, at its top (/greeting)
147
+ if (!c) return { ...o, value: text(ownOf(r), coll, o.value) } as Op;
148
+ if (key === "-" && field === undefined && o.value && typeof o.value === "object" && !Array.isArray(o.value))
149
+ return {
150
+ ...o,
151
+ value: Object.fromEntries(Object.entries(o.value).map(([f, v]) => [f, text(c, f, v)])),
152
+ } as Op;
153
+ return field !== undefined && link === undefined ? ({ ...o, value: text(c, field, o.value) } as Op) : o;
154
+ });
155
+ }
156
+
157
+ /** What a read asks for: a collection's items alone, and of those only the ids named; else the whole document. */
158
+ function readOf(doc: Doc, args: { collection?: unknown; ids?: unknown }): Doc | string {
159
+ if (args.collection === undefined) return doc;
160
+ const coll = String(args.collection),
161
+ items = (doc as Record<string, unknown>)[coll];
162
+ if (!Array.isArray(items)) return `it has no ${coll}`;
163
+ const ids = Array.isArray(args.ids) ? new Set(args.ids.map(Number)) : null;
164
+ return { version: doc.version, [coll]: ids ? items.filter((i) => ids.has(i.id)) : items } as Doc;
165
+ }
166
+
128
167
  /** Who comes to a door that's anyone's: nobody, as a stranger's page is. */
129
168
  const ANYONE: Who = { member: 0, token: "" };
130
169
 
@@ -148,13 +187,28 @@ export function door(d: Door) {
148
187
  const key = r.kind
149
188
  ? { key: { type: "integer", description: `which ${r.doc}: the id of one of ${r.kind.doc}'s ${r.kind.root}` } }
150
189
  : {};
190
+ const colls = Object.entries(r.collections)
191
+ .filter(([, c]) => !c.own)
192
+ .map(([n]) => n);
193
+ const part = colls.length
194
+ ? {
195
+ collection: { type: "string", enum: colls, description: "only this collection's items (a big document)" },
196
+ ids: {
197
+ type: "array",
198
+ items: { type: "integer" },
199
+ description: "only these of the collection's items, by id",
200
+ },
201
+ }
202
+ : {};
151
203
  tools.push({
152
204
  name: `read_${r.doc}`,
153
- description: `Read ${r.doc}, as you see it, with its version. It holds ${described(r)}.`,
154
- inputSchema: { type: "object", properties: key, required: Object.keys(key) },
205
+ description: `Read ${r.doc}, as you see it, with its version${colls.length ? `: whole, or one collection's items, or some of them by id` : ""}. It holds ${described(r)}.`,
206
+ inputSchema: { type: "object", properties: { ...key, ...part }, required: Object.keys(key) },
155
207
  run: (args) => {
156
208
  const no = d.holds(name(args), who.member);
157
- return no ? refused(no) : answered(d.read(name(args), who.member));
209
+ if (no) return refused(no);
210
+ const read = readOf(d.read(name(args), who.member), args);
211
+ return typeof read === "string" ? refused(read) : answered(read);
158
212
  },
159
213
  });
160
214
  const ops = opsOf(r);
@@ -172,10 +226,10 @@ export function door(d: Door) {
172
226
  type: "array",
173
227
  minItems: 1,
174
228
  items: {
175
- oneOf: ops.map((o) => ({
229
+ anyOf: ops.map((o) => ({
176
230
  type: "object",
177
231
  properties: {
178
- op: { const: o.op },
232
+ op: { type: "string", enum: [o.op] },
179
233
  path: { type: "string", pattern: o.pattern, description: said(o) },
180
234
  ...(o.value ? { value: o.value } : {}),
181
235
  },
@@ -194,7 +248,7 @@ export function door(d: Door) {
194
248
  if (no) return refused(no);
195
249
  const w = await d.write(
196
250
  name(args),
197
- args.ops,
251
+ texted(r, args.ops),
198
252
  typeof args.why === "string" ? args.why.trim() || undefined : undefined,
199
253
  d.anyone ? null : who,
200
254
  );
@@ -22,7 +22,9 @@ type Handler = (req: Request, who?: Who) => Response | Promise<Response>;
22
22
  /** Who a request or a socket is: a member, by the token it came with, and the agent's link if it came by one. */
23
23
  export type Who = { member: number; token: string; agent?: Agent };
24
24
  /** A page's socket, as the server keeps it: the documents it subscribes to, who it is, and the site it came from. */
25
- export type Data = { docs: Set<string>; who: Who | null; origin: string };
25
+ /** A page's socket's own: the documents it holds, who it is, where it's from, and the changes a stranger's page made
26
+ * (`<doc> <version>`), which only it may undo. */
27
+ export type Data = { docs: Set<string>; who: Who | null; origin: string; made?: Set<string> };
26
28
  type Socket = Bun.ServerWebSocket<Data>;
27
29
  /** A write the group lets go: its ops, with what they bring, and what follows them. */
28
30
  /** A write the group lets go: its ops, with what they bring; what must land with them, in the write's own
package/src/ops.ts CHANGED
@@ -54,6 +54,11 @@ export function docParts(doc: string) {
54
54
  return { base, name, key, params: Object.fromEntries(new URLSearchParams(query ?? "")) as Record<string, string> };
55
55
  }
56
56
 
57
+ /** "$n": a write of several's nth add (src/together.ts). */
58
+ export const NTH = /^\$([1-9]\d*)$/;
59
+ /** Whether a part's document is named by an add before it in its write (`board:$1`): no page holds it yet. */
60
+ export const madeBy = (doc: string) => NTH.test(docParts(doc).key ?? "");
61
+
57
62
  /** An op's path, in its parts; `link` is an id in a list of ids, and `more` anything past it, which no op may have. */
58
63
  export function parts(path: string) {
59
64
  const [, coll = "", key = "", field, link, ...more] = path.split("/");
package/src/page.ts CHANGED
@@ -18,7 +18,8 @@
18
18
  // What the page's person may do in a document, by the grants and their roles (the server's word, as the write is
19
19
  // held to it), is a `may` attribute, the applier's to write as every attribute of a document's elements is: on a
20
20
  // collection's element what may be added ("add"), on an item's what may be done to it ("remove replace:price",
21
- // "replace:status>being%20made"), so a view, or CSS (`[may~="add"]`), offers only that. None: nothing.
21
+ // "replace:status>being%20made"), so a view, or CSS (`[may~="add"]`), offers only that. None: nothing. What's
22
+ // the same for every item of a collection is said once, by "*".
22
23
  //
23
24
  // A socket drops: a phone sleeps, the wifi changes, the server is deployed again. Then the page is
24
25
  // away (body[data-away]): a write that only adds (a cost, a person) is kept on this device, the page told it's
@@ -34,7 +35,7 @@
34
35
  // person has typed is waiting (a write unanswered, a draft's changes), saying so in the toast meanwhile.
35
36
 
36
37
  import { unsaved } from "./draft.ts";
37
- import { attribute, parts, valueAt, versionKey, type Op, type Type } from "./ops.ts";
38
+ import { attribute, madeBy, parts, valueAt, versionKey, type Op, type Type } from "./ops.ts";
38
39
  import { adds, keep, sent, waiting, type Kept } from "./outbox.ts";
39
40
  import { toast } from "./toast.ts";
40
41
  // a display's list kept by key: its own module (joined/keep), here too for what imported it from here
@@ -148,6 +149,7 @@ export function letGo(el: HTMLElement) {
148
149
  docs.delete(doc);
149
150
  mays.delete(doc);
150
151
  socket.behind.delete(doc);
152
+ socket.ready.delete(doc);
151
153
  delete document.body.dataset[versionKey(doc)];
152
154
  if (isOpen()) socket.ws!.send(JSON.stringify({ unsubscribe: doc }));
153
155
  return;
@@ -167,6 +169,9 @@ document.addEventListener("ops", (e) => {
167
169
  const { doc, ops, why, writes, answer } = (
168
170
  e as CustomEvent<{ doc: string; ops: Op[]; why?: string; writes?: Part[]; answer?: Answered }>
169
171
  ).detail;
172
+ // a write of several: each part a document the page holds, or one the write makes (board:$1)
173
+ const off = writes?.find((p) => !docs.has(p.doc) && !madeBy(p.doc));
174
+ if (writes && (!writes.length || off)) return answer?.(off ? `${off.doc} isn't on this page` : "a write of nothing");
170
175
  if (!isOpen() && (writes ?? [{ ops }]).every((p) => adds(p.ops)) && (writes || docs.has(doc)))
171
176
  return (keep(writes ? { writes } : { doc, ops, why }), answer?.());
172
177
  // landed, its sender is told the version it made, from the write's own answer (a page's undo keeps it: `undo`)
@@ -195,7 +200,8 @@ export const ask = (doc: string, asked: object) =>
195
200
 
196
201
  /** Undo a change of a document the page holds, its own, by the version it made (a write's `landed` says it): the
197
202
  * server puts back what it changed, unless something it changed has changed since. Its answer: why it was refused,
198
- * or the version the undo made, which undone in turn is a redo. What it did comes as the document's change. */
203
+ * or the version the undo made, which undone in turn is a redo. What it did comes as the document's change. One
204
+ * document's: a write of several (together) is undone by each part's own version, its first's alone told as landed. */
199
205
  export const undo = (doc: string, version: number) =>
200
206
  new Promise<{ why?: string; version?: number }>((done) =>
201
207
  docs.has(doc)
@@ -224,7 +230,8 @@ const subscribe = (s: WebSocket, doc: string) => {
224
230
  /** What was kept while the page was away, sent now it's back: oldest first, each once its documents are held again;
225
231
  * the signal gone again, the rest wait. One refused is let go, and said. */
226
232
  async function flush() {
227
- const ready = (k: Kept) => (k.writes?.map((p) => p.doc) ?? [k.doc!]).every((d) => socket.ready.has(d));
233
+ // (a document the write makes, board:$1, is held by no page until it's made)
234
+ const ready = (k: Kept) => (k.writes?.map((p) => p.doc) ?? [k.doc!]).every((d) => socket.ready.has(d) || madeBy(d));
228
235
  if (socket.sending) return;
229
236
  socket.sending = true;
230
237
  try {
@@ -455,7 +462,7 @@ function whole(h: Held, items: Record<string, unknown>[]) {
455
462
  function element({ tag, fields, items, may }: Held, item: Record<string, unknown>) {
456
463
  const el = document.createElement(tag);
457
464
  el.setAttribute("key", String(item.id));
458
- set(el, "string", "may", may[String(item.id)]);
465
+ set(el, "string", "may", may[String(item.id)] ?? may["*"]);
459
466
  for (const [field, type] of Object.entries(fields)) set(el, type, field, valueAt(item, field));
460
467
  items.set(String(item.id), el);
461
468
  return el;
@@ -465,7 +472,7 @@ function element({ tag, fields, items, may }: Held, item: Record<string, unknown
465
472
  * its one item, and says it as the collection's). */
466
473
  function allow(h: Held) {
467
474
  set(h.el, "string", "may", h.may[""]);
468
- if (!h.own) for (const [key, el] of h.items) set(el, "string", "may", h.may[key]);
475
+ if (!h.own) for (const [key, el] of h.items) set(el, "string", "may", h.may[key] ?? h.may["*"]);
469
476
  }
470
477
 
471
478
  /** A field as an attribute, by the rule the server writes a page by (attribute(), src/ops.ts), set only if it
package/src/server.ts CHANGED
@@ -351,8 +351,10 @@ export async function start({
351
351
  for (const doc of derives.keys())
352
352
  if (rulesOf(doc).derived!.some((d) => written.has(d)))
353
353
  for (const ws of pages) if (ws.data.docs.has(doc)) derivedTo(ws, doc);
354
- // what each page's person may do, where the write changed it (an item come or moved, a role gained)
355
- for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) mayTo(ws, doc);
354
+ // what each page's person may do, where the write changed it (an item come or moved, a role gained): worked out
355
+ // once for each person and document, however many pages they have open
356
+ 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);
356
358
  };
357
359
  /** What each page was last sent of each derived document (by its name) and told it may do in each it holds
358
360
  * (`may <doc>`): each sent again only when it's changed. */
@@ -383,8 +385,10 @@ export async function start({
383
385
  ? mayOf(doc, who?.member ?? null)
384
386
  : {};
385
387
  /** 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. */
386
- function mayTo(ws: ServerWebSocket<Data>, doc: string) {
387
- const may = mayIn(doc, ws.data.who);
388
+ function mayTo(ws: ServerWebSocket<Data>, doc: string, asked?: Map<string, ReturnType<typeof mayIn>>) {
389
+ 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);
388
392
  if (fresh(ws, `may ${doc}`, JSON.stringify(may))) say(ws, { doc, may });
389
393
  }
390
394
  const write: Write = (doc, ops) => {
@@ -406,7 +410,7 @@ export async function start({
406
410
  if (docParts(doc).name === GROUP) throw new Refused("the group's changes aren't undone");
407
411
  const ops = store.undoing(doc, version);
408
412
  // held to the stories as any write is
409
- const why = ungranted(doc, ops, null);
413
+ const why = ungranted(doc, ops, null, true, true);
410
414
  if (why) throw new Refused(why);
411
415
  const landed = land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
412
416
  tell(landed);
@@ -668,23 +672,31 @@ export async function start({
668
672
  // in turn (a redo)
669
673
  if (m.undo !== undefined) {
670
674
  const doc = m.doc!,
675
+ base = docParts(doc).base,
671
676
  by = who?.member ?? null;
672
- const made = store.change(docParts(doc).base, m.undo);
677
+ const made = store.change(base, m.undo);
678
+ // 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
673
679
  const no = !ws.data.docs.has(doc)
674
- ? `this page isn't subscribed to ${docParts(doc).base}`
675
- : made && made.by !== by
680
+ ? `this page isn't subscribed to ${base}`
681
+ : made && (made.by !== by || (by === null && !ws.data.made?.has(`${base} ${m.undo}`)))
676
682
  ? "a change is undone by whoever made it"
677
- : null;
683
+ : docParts(base).name === GROUP
684
+ ? "the group's changes aren't undone"
685
+ : null;
686
+ // held as the page's own write is: who they are now (read-only, a role gone, a guest's level), the app's
687
+ // rules, and its settings (frozen); then guarded as the server's undo is
688
+ let w: Written;
678
689
  try {
679
690
  if (no) throw new Refused(no);
680
- const { version } = undo(doc, m.undo, by);
681
- log?.(`undo ${docParts(doc).base} ${m.undo} by ${byOf(who)}: done, version ${version}`);
682
- return say(ws, { done: m.id, version });
691
+ w = await written([{ doc, ops: store.undoing(base, m.undo) }], who, m.undo);
683
692
  } catch (e) {
684
693
  if (!(e instanceof Refused)) throw e;
685
- log?.(`undo ${docParts(doc).base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
694
+ log?.(`undo ${base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
686
695
  return say(ws, { refused: m.id, why: e.message });
687
696
  }
697
+ if ("why" in w) return say(ws, { refused: m.id, why: w.why });
698
+ if (by === null) (ws.data.made ??= new Set()).add(`${base} ${w.version}`);
699
+ return say(ws, { done: m.id, version: w.version });
688
700
  }
689
701
  if (!m.ops && !m.writes) {
690
702
  return say(ws, await group.asked(ws, m as Message & { id: number }));
@@ -703,6 +715,9 @@ export async function start({
703
715
  writes.map((w) => ({ ...w, why: w.why?.trim() || undefined })),
704
716
  who,
705
717
  );
718
+ // a stranger's change, which only this page undoes
719
+ if (!("why" in w) && who === null)
720
+ (ws.data.made ??= new Set()).add(`${docParts(writes[0]!.doc).base} ${w.version}`);
706
721
  say(
707
722
  ws,
708
723
  "why" in w
@@ -717,10 +732,11 @@ export async function start({
717
732
  /** 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
718
733
  * it (a window's write is its document's), by who, landed whole or not at all, told, and answered: done, with the
719
734
  * version its first part made and the id each item added was given, in order, so the writer needn't match them; or
720
- * refused, why. Each logs one line. */
721
- async function written(writes: Part[], who: Who | null): Promise<Written> {
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> {
722
737
  const doc = writes.map((w) => docParts(w.doc).base).join(" and "),
723
- by = byOf(who);
738
+ by = byOf(who),
739
+ act = undoes === undefined ? "write" : `undo ${undoes}`;
724
740
  // In the write's transaction, in order, refused at the first that says no: the app's own rules, the grants, and
725
741
  // the group's rules (src/write.ts), and, as its rows are written, the tables' constraints; each part's.
726
742
  const afters: ((applied: Op[]) => Promise<void>)[] = [];
@@ -730,23 +746,30 @@ export async function start({
730
746
  const no = mayHold(name, who?.member ?? null, !(members && rootToken));
731
747
  if (no) throw new Refused(no);
732
748
  let after: (applied: Op[]) => Promise<void> = async () => {};
733
- const asking = ask(name, ops, why, who, (doc, ops) => {
734
- const write = group.write(doc, ops, who, why);
735
- if (!("refused" in write)) after = write.after;
736
- return write;
737
- });
749
+ const asking = ask(
750
+ name,
751
+ ops,
752
+ why,
753
+ who,
754
+ (doc, ops) => {
755
+ const write = group.write(doc, ops, who, why);
756
+ if (!("refused" in write)) after = write.after;
757
+ return write;
758
+ },
759
+ undoes !== undefined,
760
+ );
738
761
  afters.push(after);
739
762
  return asking;
740
763
  };
741
764
  // a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
742
765
  let landed: ReturnType<typeof land>;
743
766
  try {
744
- landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { asked, held: pagesHold() });
767
+ landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { undoes, asked, held: pagesHold() });
745
768
  } catch (e) {
746
769
  // refused in words; anything else is the server's, logged, and the writer told it wasn't saved
747
770
  if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
748
771
  const why = e instanceof Refused ? e.message : "That wasn't saved: the server had a problem with it.";
749
- log?.(`write ${doc} by ${by}: refused, ${why}`);
772
+ log?.(`${act} ${doc} by ${by}: refused, ${why}`);
750
773
  return { why };
751
774
  }
752
775
  tell(landed);
@@ -755,7 +778,7 @@ export async function start({
755
778
  // what follows each part (the group's pages told, a new member's link made), and then the writer's answer:
756
779
  // done is all of it done
757
780
  for (const [i, after] of afters.entries()) await after(landed.parts[i]!.ops);
758
- log?.(`write ${doc} by ${by}: done, version ${change.version}`);
781
+ log?.(`${act} ${doc} by ${by}: done, version ${change.version}`);
759
782
  const ids = landed.applied
760
783
  .filter((o) => o.op === "add" && parts(o.path).key === "-" && parts(o.path).field === undefined)
761
784
  .map((o) => o.value.id as number);
@@ -785,6 +808,8 @@ export async function start({
785
808
  data: {} as Data,
786
809
  // a message is a write, a subscribe or an ask: a megabyte is thousands of events; more closes the socket
787
810
  maxPayloadLength: MESSAGE,
811
+ // each message deflated where the browser takes it (they all do): a document sent whole is mostly its names
812
+ perMessageDeflate: true,
788
813
  // the page is told the build first, each time it connects: a page served by another reloads
789
814
  open(ws) {
790
815
  say(ws, { build });
package/src/together.ts CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import type { Story } from "./compile.ts";
13
13
  import { Refused } from "./engine.ts";
14
- import { docParts, parts, type Op } from "./ops.ts";
14
+ import { docParts, madeBy, NTH, parts, type Op } from "./ops.ts";
15
15
 
16
16
  /** One document's part of a write: its ops, and why, as a write of one document is. */
17
17
  export type Part = { doc: string; ops: Op[]; why?: string };
@@ -22,14 +22,10 @@ export type Told = Omit<Story, "does" | "cannot"> & { does?: Part | Part[]; cann
22
22
  /** The documents as the compiler holds a story's state: each by its name (a kind's, every instance's rows). */
23
23
  type State = Record<string, Record<string, unknown>>;
24
24
 
25
- /** "$n": the write's nth add. */
26
- const NTH = /^\$([1-9]\d*)$/;
27
-
28
25
  /** A story's does or cannot, as its parts: one write, or several. */
29
26
  export const partsOf = (w: Part | Part[]) => (Array.isArray(w) ? w : [w]);
30
27
 
31
- /** Whether a part's document is named by an add before it in its write (`board:$1`): no page holds it yet. */
32
- export const madeBy = (doc: string) => NTH.test(docParts(doc).key ?? "");
28
+ export { madeBy };
33
29
 
34
30
  /** Each add of an item, in order: what a later "$n" counts. */
35
31
  const addsOf = (ops: Op[]) =>
package/src/write.ts CHANGED
@@ -140,8 +140,9 @@ export function writes({
140
140
  /** Why a write does what no story does (an op of a form no path has, or one no story grants), or what the
141
141
  * writer's roles may not; null if neither. `roles` null: the server's own write, or nobody's on an open group,
142
142
  * asked only whether a story does it; `anyone`, whether what's granted anyone is the writer's. Asked in the write's
143
- * transaction: the values are the tables' to refuse. */
144
- function ungranted(doc: string, ops: Op[], roles: ((o: Op) => string[]) | null, anyone = true) {
143
+ * transaction: the values are the tables' to refuse. `undoing`: an undo's inverse, where an item removed is put back
144
+ * as it was, at whatever step it had come to, by anyone a story lets add one at any step. */
145
+ function ungranted(doc: string, ops: Op[], roles: ((o: Op) => string[]) | null, anyone = true, undoing = false) {
145
146
  const { grants, collections, moves } = rulesOf(doc);
146
147
  for (const o of ops) {
147
148
  const { coll, key, field, link, more } = parts(o.path);
@@ -169,15 +170,23 @@ export function writes({
169
170
  // an add giving a field that moves: its first step, from nothing
170
171
  const first =
171
172
  formed && o.op === "add" && field === undefined && moves?.[coll] ? (o.value as any)?.[moves[coll]] : undefined;
172
- const to = formed
173
- ? (grants[
174
- moved
175
- ? `${grantOf(o)}:${itemAt(doc, o)?.[field!]}>${o.value}`
176
- : first !== undefined
177
- ? `${grantOf(o)}.${moves![coll]}:>${first}`
178
- : grantOf(o)
179
- ] ?? (filled && !moved ? [] : undefined))
180
- : undefined;
173
+ const back =
174
+ undoing && first !== undefined
175
+ ? Object.entries(grants)
176
+ .filter(([g]) => g === grantOf(o) || g.startsWith(`${grantOf(o)}.${moves![coll]}:>`))
177
+ .flatMap(([, to]) => to)
178
+ : [];
179
+ const to = back.length
180
+ ? back
181
+ : formed
182
+ ? (grants[
183
+ moved
184
+ ? `${grantOf(o)}:${itemAt(doc, o)?.[field!]}>${o.value}`
185
+ : first !== undefined
186
+ ? `${grantOf(o)}.${moves![coll]}:>${first}`
187
+ : grantOf(o)
188
+ ] ?? (filled && !moved ? [] : undefined))
189
+ : undefined;
181
190
  if (!to) return moved || first !== undefined ? "that isn't a move you can make" : `no ${o.op} at ${o.path}`;
182
191
  if (roles && !grantsTo(to, () => roles(o), anyone)) return `you may not ${o.op} at ${o.path}`;
183
192
  }
@@ -204,14 +213,18 @@ export function writes({
204
213
  // (a document no page writes has no grants; one kept as it is, frozen, is written by none)
205
214
  if (!Object.keys(r.grants ?? {}).length || now.frozen) return may;
206
215
  const anyone = member === null && !!r.anonymous,
207
- seen = view(doc, member ?? 0);
216
+ everyone = anyoneIs(doc, member);
217
+ // the document as they see it, read only where an item's own say is asked (a whole read for each page and each
218
+ // write cost the desk's server a second a write at 30 pages: sandbox, 16 Nov)
219
+ let seen: Doc | undefined;
208
220
  /** What someone may do to one element: each grant it takes (`token`), if their roles to its item do; once (an add
209
221
  * by either of two first steps is one add). */
210
222
  const tokens = (coll: string, item: any, token: (grant: string) => string | undefined) => {
211
- const roles = anyone ? [] : rolesTo(doc, member, coll, item, readOnce);
223
+ let roles: string[] | undefined; // asked only where a grant isn't any member's
224
+ const theirs = () => (roles ??= anyone ? [] : rolesTo(doc, member, coll, item, readOnce));
212
225
  const words = Object.entries(r.grants).flatMap(([g, to]) => {
213
226
  const t = token(g);
214
- return t !== undefined && (anyone || grantsTo(to, () => roles, anyoneIs(doc, member))) ? [t] : [];
227
+ return t !== undefined && (anyone || grantsTo(to, theirs, everyone)) ? [t] : [];
215
228
  });
216
229
  return [...new Set(words)].join(" ");
217
230
  };
@@ -235,8 +248,17 @@ export function writes({
235
248
  ? "add"
236
249
  : undefined,
237
250
  );
238
- for (const item of (seen[coll] ?? []) as Record<string, unknown>[])
239
- at[String(item.id)] = tokens(coll, item, (g) => itemToken(g, coll, item, r.moves?.[coll]));
251
+ // what may be done to an item is the same for every item where no grant to one asks who they are to it (each
252
+ // granted any member, or anyone) and none moves it a step from where it is: said once, as "*"
253
+ const moved = r.moves?.[coll],
254
+ toItems = Object.entries(r.grants).filter(([g]) => itemToken(g, coll, {}, undefined) !== undefined);
255
+ const same =
256
+ (anyone || (everyone && toItems.every(([, to]) => to.includes("member")))) &&
257
+ !toItems.some(([g]) => moved && g.startsWith(`replace ${coll}.${moved}:`));
258
+ if (same) at["*"] = tokens(coll, {}, (g) => itemToken(g, coll, {}, moved));
259
+ else
260
+ for (const item of ((seen ??= view(doc, member ?? 0))[coll] ?? []) as Record<string, unknown>[])
261
+ at[String(item.id)] = tokens(coll, item, (g) => itemToken(g, coll, item, moved));
240
262
  }
241
263
  const said = Object.entries(at).filter(([, t]) => t);
242
264
  if (said.length) may[coll] = Object.fromEntries(said);
@@ -412,6 +434,7 @@ export function writes({
412
434
  why: string | undefined,
413
435
  who: { member: number } | null,
414
436
  group: (doc: string, ops: Op[]) => { ops: Op[]; within?: (applied: Op[]) => void } | { refused: string },
437
+ undoing = false,
415
438
  ) {
416
439
  const r = rulesOf(doc);
417
440
  if (r.derived) throw new Refused(`${doc} is derived from ${r.derived.join(" and ")}: write that`);
@@ -420,7 +443,8 @@ export function writes({
420
443
  // an anonymous document's writes are anyone's; any other's, each op's by who the writer is to its item
421
444
  const ruled =
422
445
  trusts[r.doc]?.({ doc: docParts(doc).base, ops, why }, { member: who?.member ?? 0, roles }, read) ??
423
- serversIn(doc, ops) ??
446
+ // (an undo puts back what the server filled, as it was)
447
+ (undoing ? null : serversIn(doc, ops)) ??
424
448
  // who the writer is to the item each op is to: a member's roles, and a guest's (a page holding the document by
425
449
  // the item's own code: definitions' guests)
426
450
  ungranted(
@@ -428,11 +452,13 @@ export function writes({
428
452
  ops,
429
453
  !who && r.anonymous ? null : (o) => rolesTo(doc, who?.member ?? null, parts(o.path).coll, itemAt(doc, o)),
430
454
  anyoneIs(doc, who?.member ?? null),
455
+ undoing,
431
456
  ) ??
432
457
  // of a kind, what its root item's settings say of a write the grants allow (a frozen board, one held for approval)
433
458
  settled(
434
459
  r,
435
- settingsNow(r, () => rootItem(r, doc, read)),
460
+ // (an undo puts an item back at the step it had come to: frozen alone refuses it)
461
+ ((now) => (undoing ? { ...now, first: {} } : now))(settingsNow(r, () => rootItem(r, doc, read))),
436
462
  ops,
437
463
  );
438
464
  if (ruled) throw new Refused(ruled);
@@ -472,7 +498,9 @@ export function writes({
472
498
  applied: Op[] = [],
473
499
  own: Change[] = [];
474
500
  const one = (d: string, o: Op[], b: number | null, v: string | null, w?: (applied: Op[]) => void, u?: number) => {
475
- const made = store.write(d, fill(d, withGone(d, o), b), b, v, w, { undoes: u });
501
+ // (an undo puts back what was, filled as it was then: a field cleared since stays clear)
502
+ const gone = withGone(d, o);
503
+ const made = store.write(d, u === undefined ? fill(d, gone, b) : gone, b, v, w, { undoes: u });
476
504
  // what the definitions hold of it (unique, noOverlap), once the write is done: refused whole if not
477
505
  const held = rulesOf(d).holds?.(read(d), touchedBy(made.applied));
478
506
  if (held) throw new Refused(held);