@blueshed/joined 0.0.0-stage → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/.claude/skills/joined/SKILL.md +17 -0
  2. package/.claude/skills/joined/reference.md +768 -0
  3. package/LICENSE +19 -0
  4. package/README.md +115 -2
  5. package/docs/design.md +148 -0
  6. package/docs/introduction.md +193 -0
  7. package/docs/learning.md +76 -0
  8. package/docs/stories.md +82 -0
  9. package/examples/app.css +27 -0
  10. package/examples/cafe/books.html +38 -0
  11. package/examples/cafe/books.json +13 -0
  12. package/examples/cafe/books.ts +64 -0
  13. package/examples/cafe/cafe.css +512 -0
  14. package/examples/cafe/front.html +115 -0
  15. package/examples/cafe/front.ts +7 -0
  16. package/examples/cafe/generated/books.elements.ts +52 -0
  17. package/examples/cafe/generated/books.queries.ts +11 -0
  18. package/examples/cafe/generated/books.rules.ts +42 -0
  19. package/examples/cafe/generated/kitchen.elements.ts +87 -0
  20. package/examples/cafe/generated/kitchen.queries.ts +47 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +98 -0
  22. package/examples/cafe/generated/menu.elements.ts +61 -0
  23. package/examples/cafe/generated/menu.queries.ts +28 -0
  24. package/examples/cafe/generated/menu.rules.ts +65 -0
  25. package/examples/cafe/generated/order.elements.ts +87 -0
  26. package/examples/cafe/generated/order.queries.ts +47 -0
  27. package/examples/cafe/generated/order.rules.ts +95 -0
  28. package/examples/cafe/generated/staff.elements.ts +55 -0
  29. package/examples/cafe/generated/staff.queries.ts +27 -0
  30. package/examples/cafe/generated/staff.rules.ts +59 -0
  31. package/examples/cafe/generated/supplies.elements.ts +62 -0
  32. package/examples/cafe/generated/supplies.queries.ts +43 -0
  33. package/examples/cafe/generated/supplies.rules.ts +84 -0
  34. package/examples/cafe/generated/till.elements.ts +93 -0
  35. package/examples/cafe/generated/till.queries.ts +57 -0
  36. package/examples/cafe/generated/till.rules.ts +113 -0
  37. package/examples/cafe/index.html +70 -0
  38. package/examples/cafe/kitchen.css +107 -0
  39. package/examples/cafe/kitchen.html +39 -0
  40. package/examples/cafe/kitchen.ts +125 -0
  41. package/examples/cafe/menu.html +55 -0
  42. package/examples/cafe/menu.json +41 -0
  43. package/examples/cafe/menu.ts +84 -0
  44. package/examples/cafe/migrations/001-cafe.ts +11 -0
  45. package/examples/cafe/order.html +37 -0
  46. package/examples/cafe/order.ts +45 -0
  47. package/examples/cafe/rail-drag.ts +30 -0
  48. package/examples/cafe/routes.ts +32 -0
  49. package/examples/cafe/staff.json +20 -0
  50. package/examples/cafe/stories.jsonl +43 -0
  51. package/examples/cafe/supplies.html +77 -0
  52. package/examples/cafe/supplies.json +33 -0
  53. package/examples/cafe/supplies.ts +170 -0
  54. package/examples/cafe/till.json +95 -0
  55. package/examples/cafe/till.ts +122 -0
  56. package/examples/cafe/trust.ts +20 -0
  57. package/examples/cafe/views.ts +171 -0
  58. package/examples/docs.ts +28 -0
  59. package/examples/film.jpg +0 -0
  60. package/examples/hello/generated/elements.ts +45 -0
  61. package/examples/hello/generated/queries.ts +24 -0
  62. package/examples/hello/generated/rules.ts +45 -0
  63. package/examples/hello/hello.css +27 -0
  64. package/examples/hello/hello.json +1 -0
  65. package/examples/hello/index.html +32 -0
  66. package/examples/hello/migrations/001-hello.ts +6 -0
  67. package/examples/hello/page.ts +49 -0
  68. package/examples/hello/routes.ts +6 -0
  69. package/examples/hello/stories.jsonl +3 -0
  70. package/examples/index.html +146 -0
  71. package/examples/page.ts +11 -0
  72. package/examples/people/adding.ts +20 -0
  73. package/examples/people/generated/elements.ts +68 -0
  74. package/examples/people/generated/queries.ts +28 -0
  75. package/examples/people/generated/rules.ts +85 -0
  76. package/examples/people/links.ts +124 -0
  77. package/examples/people/migrations/001-people.ts +6 -0
  78. package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
  79. package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
  80. package/examples/people/order.ts +61 -0
  81. package/examples/people/people.css +65 -0
  82. package/examples/people/people.json +26 -0
  83. package/examples/people/routes.ts +12 -0
  84. package/examples/people/stories.jsonl +20 -0
  85. package/examples/people/trust.ts +14 -0
  86. package/examples/people/view.ts +115 -0
  87. package/examples/routes.ts +11 -0
  88. package/examples/trip/answer-rows.ts +70 -0
  89. package/examples/trip/answers.ts +11 -0
  90. package/examples/trip/bar.ts +89 -0
  91. package/examples/trip/calendar-map.css +709 -0
  92. package/examples/trip/calendar-map.ts +249 -0
  93. package/examples/trip/drags.ts +143 -0
  94. package/examples/trip/drawer.ts +250 -0
  95. package/examples/trip/event-form.ts +199 -0
  96. package/examples/trip/generated/elements.ts +144 -0
  97. package/examples/trip/generated/queries.ts +46 -0
  98. package/examples/trip/generated/rules.ts +239 -0
  99. package/examples/trip/holding.ts +61 -0
  100. package/examples/trip/ics.ts +117 -0
  101. package/examples/trip/index.html +82 -0
  102. package/examples/trip/line-stops.ts +92 -0
  103. package/examples/trip/line-words.ts +79 -0
  104. package/examples/trip/line.ts +121 -0
  105. package/examples/trip/map.ts +234 -0
  106. package/examples/trip/mercator.ts +28 -0
  107. package/examples/trip/migrations/001-trip.ts +7 -0
  108. package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
  109. package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
  110. package/examples/trip/migrations/004-create-stays.ts +6 -0
  111. package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
  112. package/examples/trip/month.ts +87 -0
  113. package/examples/trip/other-weeks.ts +67 -0
  114. package/examples/trip/page.ts +121 -0
  115. package/examples/trip/peek.ts +71 -0
  116. package/examples/trip/people-chips.ts +74 -0
  117. package/examples/trip/place-search.ts +51 -0
  118. package/examples/trip/places.ts +34 -0
  119. package/examples/trip/routes.ts +27 -0
  120. package/examples/trip/shell.ts +39 -0
  121. package/examples/trip/stays.css +51 -0
  122. package/examples/trip/stays.ts +68 -0
  123. package/examples/trip/stories.jsonl +72 -0
  124. package/examples/trip/time.ts +46 -0
  125. package/examples/trip/told.ts +48 -0
  126. package/examples/trip/trip.json +69 -0
  127. package/examples/trip/trust.ts +51 -0
  128. package/examples/trip/week.ts +237 -0
  129. package/examples/trip/words.ts +4 -0
  130. package/examples/trip/writes.ts +91 -0
  131. package/examples/trip/zones.ts +16 -0
  132. package/examples/trips/card.ts +149 -0
  133. package/examples/trips/generated/elements.ts +60 -0
  134. package/examples/trips/generated/queries.ts +28 -0
  135. package/examples/trips/generated/rules.ts +62 -0
  136. package/examples/trips/index.html +47 -0
  137. package/examples/trips/map.ts +52 -0
  138. package/examples/trips/migrations/001-trips.ts +8 -0
  139. package/examples/trips/new-trip.ts +46 -0
  140. package/examples/trips/page.ts +9 -0
  141. package/examples/trips/routes.ts +7 -0
  142. package/examples/trips/stories.jsonl +12 -0
  143. package/examples/trips/trips.css +183 -0
  144. package/examples/trips/trips.json +7 -0
  145. package/examples/weeks/derive.ts +23 -0
  146. package/examples/weeks/generated/elements.ts +52 -0
  147. package/examples/weeks/generated/rules.ts +33 -0
  148. package/examples/weeks/routes.ts +4 -0
  149. package/examples/weeks/weeks.json +1 -0
  150. package/examples/welcome.css +299 -0
  151. package/package.json +51 -4
  152. package/src/attachment.ts +70 -0
  153. package/src/cli.ts +52 -0
  154. package/src/client.ts +98 -0
  155. package/src/compile.ts +2034 -0
  156. package/src/css.d.ts +5 -0
  157. package/src/definitions.ts +268 -0
  158. package/src/demo.css +29 -0
  159. package/src/demo.ts +42 -0
  160. package/src/draft.ts +69 -0
  161. package/src/engine.ts +288 -0
  162. package/src/file-value.ts +13 -0
  163. package/src/files.ts +187 -0
  164. package/src/follow.ts +56 -0
  165. package/src/hues.ts +3 -0
  166. package/src/icon-names.ts +77 -0
  167. package/src/icon.png +0 -0
  168. package/src/icons.ts +32 -0
  169. package/src/keep.ts +33 -0
  170. package/src/link.ts +31 -0
  171. package/src/mcp.ts +252 -0
  172. package/src/members/demo.ts +53 -0
  173. package/src/members/generated/elements.ts +68 -0
  174. package/src/members/generated/queries.ts +29 -0
  175. package/src/members/generated/rules.ts +65 -0
  176. package/src/members/group.ts +294 -0
  177. package/src/members/keys.ts +221 -0
  178. package/src/members/members.json +9 -0
  179. package/src/members/migrations/001-members.ts +6 -0
  180. package/src/members/migrations/002-guard-members.ts +11 -0
  181. package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
  182. package/src/members/panel.css +208 -0
  183. package/src/members/panel.ts +398 -0
  184. package/src/members/routes.ts +4 -0
  185. package/src/members/stories.jsonl +27 -0
  186. package/src/members/trust.ts +116 -0
  187. package/src/migrate.ts +597 -0
  188. package/src/migrations/001-joined.ts +13 -0
  189. package/src/migrations/002-group-keys.ts +16 -0
  190. package/src/migrations/003-change-inverse.ts +10 -0
  191. package/src/migrations/004-change-followed.ts +6 -0
  192. package/src/ops.ts +61 -0
  193. package/src/page.css +79 -0
  194. package/src/page.ts +413 -0
  195. package/src/parts.css +471 -0
  196. package/src/parts.ts +152 -0
  197. package/src/server.ts +862 -0
  198. package/src/settings.ts +94 -0
  199. package/src/starter.ts +89 -0
  200. package/src/store.ts +815 -0
  201. package/src/stories.ts +387 -0
  202. package/src/toast.ts +52 -0
  203. package/src/together.ts +167 -0
  204. package/src/tokens.css +85 -0
  205. package/src/tokens.json +457 -0
  206. package/src/upkeep.ts +86 -0
  207. package/src/visitors.ts +43 -0
  208. package/src/write.ts +567 -0
  209. package/starter/CLAUDE.md +37 -0
  210. package/starter/gitignore +3 -0
  211. package/starter/tests/hello-page.test.ts +14 -0
  212. package/starter/tests/hello.test.ts +8 -0
  213. package/starter/tsconfig.json +17 -0
package/src/stories.ts ADDED
@@ -0,0 +1,387 @@
1
+ // The stories, told (joined/stories): an app's stories are its tests, here or in a project using joined.
2
+ // A server on a store of its own, begun from the seeds; a page's socket for each name a story names,
3
+ // signed in by their own link; the story's write sent; and what didn't go as the story says, said.
4
+
5
+ import { rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { APPS, ENGINE, OWN, type Story } from "./compile.ts";
8
+ import type { Dialect } from "./engine.ts";
9
+ import { start } from "./server.ts";
10
+ import type { Member } from "./members/trust.ts";
11
+ import type { Op } from "./ops.ts";
12
+ import { madeBy, partsOf, type Part, type Told } from "./together.ts";
13
+
14
+ const folderOf = (doc: string, dir: string) => (doc === "members" ? OWN : `${dir}/${doc}`);
15
+ const lines = async (doc: string, dir: string) =>
16
+ (await Bun.file(`${folderOf(doc, dir)}/stories.jsonl`).text())
17
+ .split("\n")
18
+ .filter((l) => l.trim())
19
+ .map((l) => JSON.parse(l));
20
+
21
+ /** A document's stories, from its app's folder (the members': joined's own). */
22
+ export const storiesOf = async (doc: string, dir = APPS) => (await lines(doc, dir)).filter((l) => l.story) as Story[];
23
+ /** A document's stories as they're written: a does (or cannot) of one write, or of several (src/together.ts). */
24
+ const toldOf = async (doc: string, dir: string) => (await lines(doc, dir)).filter((l) => l.story) as Told[];
25
+ /** Who each name in a document's stories is: a member's name, or as its cast line says (null: nobody). */
26
+ export const castOf = async (doc: string, dir = APPS) =>
27
+ ((await lines(doc, dir)).find((l) => l.cast)?.cast ?? {}) as Record<string, string | null>;
28
+
29
+ /** A server on a store of its own, each document begun from its seed: invite-only by `root`, unless open; on either
30
+ * engine. */
31
+ export async function fresh({
32
+ dir = APPS,
33
+ open = false,
34
+ root = crypto.randomUUID(),
35
+ engine = ENGINE,
36
+ }: { dir?: string; open?: boolean; root?: string; engine?: Dialect } = {}) {
37
+ // a file of its own (a test may restart its server on it), so no two servers share one; Postgres's in memory
38
+ const db = engine === "postgres" ? ":memory:" : `${tmpdir()}/joined-${crypto.randomUUID()}.sqlite`;
39
+ const keys = `${tmpdir()}/joined-${crypto.randomUUID()}.keys.json`;
40
+ // and the files its documents name, a folder of its own
41
+ const files = `${tmpdir()}/joined-${crypto.randomUUID()}-files`;
42
+ const gone = () =>
43
+ Promise.all(
44
+ [db, `${db}-wal`, `${db}-shm`, keys].map((f) =>
45
+ Bun.file(f)
46
+ .delete()
47
+ .catch(() => {}),
48
+ ),
49
+ );
50
+ const server = await start({ port: 0, dir, db, engine, keys, files, rootToken: open ? "" : root });
51
+ /** A name's token: a member's, by their name (or the cast's), or undefined for nobody. */
52
+ const tokenFor = async (name: string, cast: Record<string, string | null> = {}) => {
53
+ const as = name in cast ? cast[name] : name;
54
+ if (as === null) return undefined;
55
+ const m = (server.read("members").members as Member[]).find((x) => x.name.toLowerCase() === as!.toLowerCase());
56
+ if (!m) throw new Error(`no member named ${as}`);
57
+ return (await server.tokenOf(m.id))!;
58
+ };
59
+ return {
60
+ server,
61
+ db,
62
+ keys,
63
+ files,
64
+ root,
65
+ tokenFor,
66
+ stop: async () => {
67
+ server.stop(true);
68
+ server.store.close();
69
+ rmSync(files, { recursive: true, force: true });
70
+ await gone();
71
+ },
72
+ };
73
+ }
74
+
75
+ /** A page's socket, signed in by a token (or as nobody), with a document joined to it: every message
76
+ * it's sent (but the build, told first, left out), a wait for the next that matches, a way to
77
+ * subscribe to another, and whether the server refused it at the door. */
78
+ export async function page(url: URL, doc: string, token?: string) {
79
+ // Bun's WebSocket takes headers (the cookie a browser would send), which the DOM's types don't know
80
+ const ws = new WebSocket(
81
+ `${url.href.replace(/^http/, "ws")}ws`,
82
+ (token ? { headers: { cookie: `joined=${token}` } } : undefined) as any,
83
+ );
84
+ ws.onopen = () => ws.send(JSON.stringify({ subscribe: doc }));
85
+ const heard: any[] = [];
86
+ const waiting: [(m: any) => boolean, (m: any) => void][] = [];
87
+ ws.onmessage = (e) => {
88
+ const m = JSON.parse(String(e.data));
89
+ if (m.build) return;
90
+ heard.push(m);
91
+ for (const w of waiting.splice(0)) w[0](m) ? w[1](m) : waiting.push(w);
92
+ };
93
+ const next = (match: (m: any) => boolean) => new Promise<any>((done) => waiting.push([match, done]));
94
+ const closed = new Promise<number>((done) => ws.addEventListener("close", (e) => done(e.code)));
95
+ const whole = (d: string) => next((m) => m.doc === d && m.ops?.[0]?.path === "");
96
+ // refused: at the door (the socket closed), or the document isn't one to hold
97
+ const denied = next((m) => m.doc === doc && m.refused === true);
98
+ const refused = await Promise.race([whole(doc).then(() => false), closed.then(() => true), denied.then(() => true)]);
99
+ /** Another document this page's socket subscribes to: the whole of it, as sent. */
100
+ const subscribe = (d: string) => (ws.send(JSON.stringify({ subscribe: d })), whole(d));
101
+ return { ws, doc, heard, next, subscribe, refused, closed };
102
+ }
103
+
104
+ /** What a document holds at a path (`/orders/6/total`): in a collection, the item of that id; else the field. */
105
+ const atPath = (doc: unknown, path: string) =>
106
+ path
107
+ .split("/")
108
+ .slice(1)
109
+ .reduce<any>((v, k) => (Array.isArray(v) ? v.find((x) => String(x?.id) === k) : v?.[k]), doc);
110
+
111
+ /** The page of an anonymous story: signed in as nobody, on a server that's open. */
112
+ const ANYONE = "";
113
+
114
+ /** How long a page that mustn't hear a write (unseen) is given to hear it anyway, and one that must (seen). */
115
+ const QUIET = 100,
116
+ HEARD = 2000;
117
+
118
+ /** Each of a document's stories told, by who it says, on a server of its own: what didn't go as it says,
119
+ * a line each (none: every story did). Its premise first, each name's writes in order, each done. A story
120
+ * that does is done, every page it names as seeing it hears its ops (those its person sees, where the
121
+ * document has owns), by its writer, no page it names as unseen hears anything of it, and each path in its then
122
+ * holds its value as the teller's page holds the document after (another document's, named before it); one that cannot
123
+ * is refused, in its refused words where it has them, at the door when its teller is nobody, and the document
124
+ * is as it was. A story with no `as` is anonymous: told on a server that's open, by a page signed in as nobody,
125
+ * its premise a list of writes. */
126
+ export async function tell(doc: string, dir = APPS, engine = ENGINE) {
127
+ const cast = await castOf(doc, dir);
128
+ // whether a story's document is sent as each person sees it: its own rules, of an app of one document or several
129
+ // (of a write of several documents, another app's: its own)
130
+ const sees = async (d: string) => {
131
+ const name = d.split(/[:?]/)[0]!,
132
+ several = `${folderOf(doc, dir)}/generated/${name}.rules.ts`,
133
+ another = `${folderOf(name, dir)}/generated/rules.ts`;
134
+ const r = await import(
135
+ (await Bun.file(several).exists())
136
+ ? several
137
+ : name !== doc && (await Bun.file(another).exists())
138
+ ? another
139
+ : `${folderOf(doc, dir)}/generated/rules.ts`
140
+ );
141
+ return r.sees ? "some" : r.view ? "whole" : null;
142
+ };
143
+ const wrong: string[] = [];
144
+ for (const s of await toldOf(doc, dir)) {
145
+ const anonymous = s.as === undefined,
146
+ as = s.as ?? ANYONE;
147
+ const { server, tokenFor, stop } = await fresh({ dir, open: anonymous, engine });
148
+ // the story's own document: of a kind, its instance (shelf:1); of several writes, its first's (src/together.ts),
149
+ // and each other's there is before it (not one the write makes, board:$1)
150
+ const write = s.does ?? s.cannot!,
151
+ writes = partsOf(write),
152
+ at = writes[0]!.doc,
153
+ docs = [...new Set(writes.map((w) => w.doc).filter((d) => !madeBy(d)))];
154
+ try {
155
+ const premise = Array.isArray(s.premise)
156
+ ? s.premise.map((w) => [ANYONE, w] as const)
157
+ : Object.entries(s.premise ?? {}).flatMap(([n, ws]) => ws.map((w) => [n, w] as const));
158
+ const names = [...new Set([...premise.map(([n]) => n), as, ...(s.seen ?? []), ...(s.unseen ?? [])])];
159
+ const tokenOf = (n: string) => (n === ANYONE ? undefined : tokenFor(n, cast));
160
+ // the premise's pages first; the story's own once the premise has run, so it may be someone the premise made
161
+ const pages: Record<string, Awaited<ReturnType<typeof page>>> = {};
162
+ const open = async (ns: string[]) => {
163
+ for (const [n, p] of await Promise.all(
164
+ ns.filter((n) => !(n in pages)).map(async (n) => [n, await page(server.url, at, await tokenOf(n))] as const),
165
+ ))
166
+ pages[n] = p;
167
+ };
168
+ await open([...new Set(premise.map(([n]) => n))]);
169
+ let id = 0;
170
+ /** A write sent on a name's page (of several documents, its parts), and the server's answer to it. */
171
+ const send = (n: string, w: Part | Part[]) => {
172
+ const sent = ++id;
173
+ const answer = pages[n]!.next((m) => m.done === sent || m.refused === sent);
174
+ pages[n]!.ws.send(
175
+ JSON.stringify(Array.isArray(w) ? { id: sent, writes: w } : { id: sent, doc: w.doc, ops: w.ops, why: w.why }),
176
+ );
177
+ return answer as Promise<{ done?: number; refused?: number; why?: string }>;
178
+ };
179
+ // each page holds the story's document; a premise's other document is subscribed to once
180
+ const joined = new Set(names.map((n) => `${n} ${at}`));
181
+ let refused: string | undefined;
182
+ for (const [n, w] of premise) {
183
+ if (!joined.has(`${n} ${w.doc}`)) (joined.add(`${n} ${w.doc}`), await pages[n]!.subscribe(w.doc));
184
+ const said = await send(n, w);
185
+ if (said.done) continue;
186
+ refused = `${s.story}: ${n}'s premise was refused: ${said.why}`;
187
+ break;
188
+ }
189
+ if (!refused) await open(names);
190
+ if (refused) {
191
+ wrong.push(refused);
192
+ continue;
193
+ }
194
+ // each page holds every document the write is to that's there before it
195
+ for (const n of names)
196
+ for (const d of docs)
197
+ if (!pages[n]!.refused && !joined.has(`${n} ${d}`)) (joined.add(`${n} ${d}`), await pages[n]!.subscribe(d));
198
+ const before = new Map(docs.map((d) => [d, server.read(d).version]));
199
+ const unchanged = () => docs.every((d) => server.read(d).version === before.get(d));
200
+ if (pages[as]!.refused) {
201
+ if (!s.cannot) wrong.push(`${s.story}: refused at the door`);
202
+ if (!unchanged()) wrong.push(`${s.story}: refused at the door, and the document changed`);
203
+ // in the words it's refused in there, where the server says them (No access)
204
+ const why = pages[as]!.heard.find((m) => m.doc === at && m.refused === true)?.why;
205
+ if (s.refused && why !== s.refused)
206
+ wrong.push(`${s.story}: refused at the door as "${why}", not "${s.refused}"`);
207
+ continue;
208
+ }
209
+ // the member it's by: an anonymous story's is nobody's
210
+ const writer = anonymous
211
+ ? null
212
+ : (server.read("members").members as Member[]).find(
213
+ (x) => x.name.toLowerCase() === (cast[as] ?? as).toLowerCase(),
214
+ )!.id;
215
+ // each part a page hears: its document's change, at the version it makes there or later (a document told as each
216
+ // person sees it is told a write's parts on it as one change); one the write makes, none
217
+ const parts = writes.flatMap((w, k) =>
218
+ madeBy(w.doc)
219
+ ? []
220
+ : [
221
+ {
222
+ doc: w.doc,
223
+ ops: w.ops.map((o) => `${o.op} ${o.path}`),
224
+ version: before.get(w.doc)! + writes.slice(0, k + 1).filter((x) => x.doc === w.doc).length,
225
+ },
226
+ ],
227
+ );
228
+ const hears = (n: string, p: (typeof parts)[number]) =>
229
+ pages[n]!.next((m) => m.doc === p.doc && m.ops && m.version >= p.version);
230
+ const told = (s.seen ?? []).flatMap((n) =>
231
+ parts.map((p) =>
232
+ Promise.race([hears(n, p), Bun.sleep(HEARD).then(() => null)]).then((m) => [n, p, m] as const),
233
+ ),
234
+ );
235
+ const unseen = (s.unseen ?? []).map((n) =>
236
+ Promise.race([Promise.any(parts.map((p) => hears(n, p))).then(() => n), Bun.sleep(QUIET).then(() => null)]),
237
+ );
238
+ const said = await send(as, write);
239
+ if (s.cannot && !said.refused) wrong.push(`${s.story}: let through`);
240
+ if (s.cannot && !unchanged()) wrong.push(`${s.story}: refused, and the document changed`);
241
+ if (s.cannot && said.refused && s.refused && said.why !== s.refused)
242
+ wrong.push(`${s.story}: refused as "${said.why}", not "${s.refused}"`);
243
+ if (s.does && !said.done) wrong.push(`${s.story}: refused: ${said.why}`);
244
+ // every page it names hears the story's ops (a removal brings those who move up before it; with owns, those
245
+ // its person sees), and who wrote them; none it names as unseen hears it
246
+ if (s.does && said.done) {
247
+ for (const [n, { doc: d, ops }, m] of await Promise.all(told)) {
248
+ if (!m) {
249
+ wrong.push(`${s.story}: ${n} didn't hear it`);
250
+ continue;
251
+ }
252
+ // (as its person sees it, a list is told whole, replaced, for an id the story adds to it or takes from it; or,
253
+ // its last id taken, the list gone)
254
+ const heard = m.ops.flatMap((o: Op) =>
255
+ ops.includes(`${o.op} ${o.path}`)
256
+ ? [`${o.op} ${o.path}`]
257
+ : ops.filter(
258
+ (w) => (o.op === "replace" || o.op === "remove") && w.split(" ")[1]!.startsWith(`${o.path}/`),
259
+ ),
260
+ );
261
+ // as its person sees it, some of the ops; as a part of it, what changed of it (an order leaving the kitchen)
262
+ const told = await sees(d);
263
+ const short = told === "whole" ? !m.ops.length : told ? !heard.length : heard.join() !== ops.join();
264
+ if (short) wrong.push(`${s.story}: ${n} heard only ${heard.join(", ")}`);
265
+ if (m.by !== writer) wrong.push(`${s.story}: ${n} heard it as by ${m.by}, not ${writer}`);
266
+ }
267
+ for (const n of (await Promise.all(unseen)).filter(Boolean)) wrong.push(`${s.story}: ${n} heard it, unseen`);
268
+ // what it leaves: each path as its teller holds it, on a page of theirs that holds the document anew
269
+ const held = new Map<string, unknown>();
270
+ for (const [key, want] of Object.entries(s.then ?? {})) {
271
+ const d = key.slice(0, key.indexOf("/")) || at,
272
+ path = key.slice(key.indexOf("/"));
273
+ if (!held.has(d)) {
274
+ const p = await page(server.url, d, await tokenOf(as));
275
+ held.set(d, p.heard.find((m) => m.doc === d && m.ops?.[0]?.path === "")?.ops[0].value);
276
+ p.ws.close();
277
+ }
278
+ const got = atPath(held.get(d), path);
279
+ if (!Bun.deepEquals(got, want))
280
+ wrong.push(`${s.story}: ${key} holds ${JSON.stringify(got) ?? "nothing"}, not ${JSON.stringify(want)}`);
281
+ }
282
+ }
283
+ for (const p of Object.values(pages)) p.ws.close();
284
+ } finally {
285
+ await stop();
286
+ }
287
+ }
288
+ return wrong;
289
+ }
290
+
291
+ /** An op as the page offers it (its element's `may`, src/write.ts): where it goes, as a selector of the element whose
292
+ * `may` says it, and the word it says. A collection's element offers what's added to it, and a document's own fields;
293
+ * an item's element what's done to it, a field or an id of a list. */
294
+ function offered(
295
+ o: Op,
296
+ collections: Record<string, { place: string; tag: string; own?: boolean; fields: Record<string, string> }>,
297
+ ) {
298
+ const [, coll = "", key, field, link] = o.path.split("/");
299
+ const own = Object.values(collections).find((c) => c.own);
300
+ // a document's own field (/greeting): its own element's
301
+ if (own && !(coll in collections))
302
+ return { at: own.place, word: `${o.op}:${[coll, key, field].filter(Boolean).join(".")}` };
303
+ const c = collections[coll];
304
+ if (!c) return null;
305
+ if (key === "-") return { at: c.place, word: "add" };
306
+ const at = `${c.place} > ${c.tag}[key="${key}"]`;
307
+ if (field === undefined) return { at, word: o.op };
308
+ // an id of a list: its own word; a move: the step, as a URL writes it; else the field (an object's, dotted)
309
+ if (c.fields[field] === "ids" && link !== undefined) return { at, word: `${o.op}:${field}[]` };
310
+ const dotted = [field, link].filter(Boolean).join(".");
311
+ return {
312
+ at,
313
+ word: `${o.op}:${dotted}`,
314
+ step:
315
+ o.op === "replace" && typeof o.value === "string"
316
+ ? `${o.op}:${dotted}>${encodeURIComponent(o.value)}`
317
+ : undefined,
318
+ };
319
+ }
320
+
321
+ /** Each of an app's stories that does something, told in a browser as its member, on the page that holds its document
322
+ * (`path`; none, the story isn't a page's): the element each op is to is there, and its `may` offers it (every control
323
+ * the story needs, reachable); then its ops go up as the page's own do, the element's "ops" event, and are done. What
324
+ * didn't, in words. */
325
+ export async function inBrowser(app: string, path: (doc: string) => string | null, view: Bun.WebView, dir = APPS) {
326
+ const cast = await castOf(app, dir);
327
+ const wrong: string[] = [];
328
+ for (const s of await toldOf(app, dir)) {
329
+ // (a write of several documents is no one element's: a page sends it by together(), joined/page)
330
+ const write = Array.isArray(s.does) ? undefined : s.does;
331
+ const at = write && path(write.doc);
332
+ if (!write || at === null || at === undefined) continue;
333
+ const name = write.doc.split(/[:?]/)[0]!;
334
+ const several = `${folderOf(app, dir)}/generated/${name}.rules.ts`;
335
+ const { collections } = await import(
336
+ (await Bun.file(several).exists()) ? several : `${folderOf(app, dir)}/generated/rules.ts`
337
+ );
338
+ const { server, tokenFor, stop } = await fresh({ dir, open: s.as === undefined });
339
+ try {
340
+ // its premise, written as each of its people
341
+ for (const [n, ws] of Array.isArray(s.premise) ? [[ANYONE, s.premise] as const] : Object.entries(s.premise ?? {}))
342
+ for (const w of ws) {
343
+ const p = await page(server.url, w.doc, n === ANYONE ? undefined : await tokenFor(n, cast));
344
+ const answer = p.next((m) => m.done === 1 || m.refused === 1);
345
+ p.ws.send(JSON.stringify({ id: 1, doc: w.doc, ops: w.ops, why: w.why }));
346
+ await answer;
347
+ p.ws.close();
348
+ }
349
+ // its member's page: signed in by their link, at the page holding the story's document, live
350
+ if (s.as !== undefined) await view.navigate(`${server.url.href}auth/${await tokenFor(s.as, cast)}`);
351
+ await view.navigate(new URL(at, server.url).href);
352
+ const offers = write.ops.map((o) => [o, offered(o, collections)] as const);
353
+ const first = offers.find(([, x]) => x)?.[1];
354
+ const ready = `document.body.dataset.members !== undefined${first ? ` && document.querySelector(${JSON.stringify(first.at)})?.hasAttribute("may")` : ""}`;
355
+ for (
356
+ let i = 0;
357
+ i < 150 && !(await view.evaluate(`(() => { try { return !!(${ready}); } catch { return false; } })()`));
358
+ i++
359
+ )
360
+ await Bun.sleep(20);
361
+ // every op the story needs, offered where it goes
362
+ for (const [o, x] of offers) {
363
+ if (!x) continue;
364
+ const may = await view.evaluate<string | null>(
365
+ `document.querySelector(${JSON.stringify(x.at)})?.getAttribute("may") ?? null`,
366
+ );
367
+ const words = (may ?? "").split(" ");
368
+ if (!words.includes(x.word) && !(x.step && words.includes(x.step)))
369
+ wrong.push(`${s.story}: ${o.op} ${o.path} isn't offered (${x.at} may "${may ?? "(not there)"}")`);
370
+ }
371
+ // sent as the page sends its own, from the element it's to: done
372
+ const from = first?.at ?? "body";
373
+ if (!(await view.evaluate<boolean>(`!!document.querySelector(${JSON.stringify(from)})`))) {
374
+ wrong.push(`${s.story}: no ${from} on ${at}`);
375
+ continue;
376
+ }
377
+ const why = await view.evaluate<string>(`new Promise((answer) => {
378
+ const el = document.querySelector(${JSON.stringify(from)}), held = el.closest("[doc]");
379
+ el.dispatchEvent(new CustomEvent("ops", { bubbles: true, composed: true, detail: { doc: held?.getAttribute("doc") ?? ${JSON.stringify(write.doc.split("?")[0])}, ops: ${JSON.stringify(write.ops)}, why: ${JSON.stringify(write.why ?? null)} ?? undefined, answer: (why) => answer(why ?? "") } }));
380
+ })`);
381
+ if (why) wrong.push(`${s.story}: refused on the page: ${why}`);
382
+ } finally {
383
+ await stop();
384
+ }
385
+ }
386
+ return wrong;
387
+ }
package/src/toast.ts ADDED
@@ -0,0 +1,52 @@
1
+ // A toast: a page's own words, for a moment, with toast(): an icon before them, and held until the next
2
+ // toast rather than fading (a walk-through saying each step as it's made). A page that wants it imports
3
+ // this. It's drawn in a shadow of its own, at the foot of the page, and said politely to a screen reader;
4
+ // words in quick succession keep it up, not flicker it. A write that lands isn't toasted (what it did shows
5
+ // as its change), nor a refusal (whoever sent it says why, beside what sent it).
6
+
7
+ const host = Object.assign(document.createElement("div"), { className: "toast" });
8
+ const root = host.attachShadow({ mode: "open" });
9
+ root.innerHTML = `<style>
10
+ p {
11
+ position: fixed;
12
+ left: 50%;
13
+ bottom: calc(var(--space-16) + env(safe-area-inset-bottom));
14
+ z-index: 20;
15
+ display: flex;
16
+ gap: var(--space-10);
17
+ align-items: center;
18
+ box-sizing: border-box;
19
+ /* as wide as its words, as the screen allows: fixed at the middle, it would fit only the half to its right */
20
+ width: max-content;
21
+ max-width: min(36rem, calc(100vw - 2rem));
22
+ margin: 0;
23
+ padding: var(--space-6) var(--space-16);
24
+ border-radius: 4px;
25
+ background: var(--ink);
26
+ color: var(--card);
27
+ font: var(--font-small);
28
+ translate: -50% 0;
29
+ opacity: 0;
30
+ transition: opacity 0.2s;
31
+ pointer-events: none;
32
+ }
33
+ p.shown { opacity: 1; }
34
+ svg { flex: none; }
35
+ @media (prefers-reduced-motion: reduce) { p { transition: none; } }
36
+ </style><p role="status" aria-live="polite"></p>`;
37
+ const said = root.querySelector("p")!;
38
+ let hide: ReturnType<typeof setTimeout> | undefined;
39
+
40
+ /** Words in the toast, an icon before them if given: for 1.5s, or held until the next toast. The words
41
+ * are text, or a node of the page's own (a name in bold); empty words take it away. */
42
+ export function toast(words: string | Node, { icon, hold = false }: { icon?: Element; hold?: boolean } = {}) {
43
+ clearTimeout(hide);
44
+ if (!words) return said.classList.remove("shown");
45
+ const text = document.createElement("span");
46
+ text.append(words);
47
+ said.replaceChildren(...(icon ? [icon] : []), text);
48
+ said.classList.add("shown");
49
+ if (!hold) hide = setTimeout(() => said.classList.remove("shown"), 1500);
50
+ }
51
+
52
+ document.body.append(host);
@@ -0,0 +1,167 @@
1
+ // A write of several documents: Padlet's template, a board made with its first sections and posts at once. It's one
2
+ // write all the same: its parts land in turn, in one transaction, all of them or none, each held to its own document's
3
+ // rules (its trust.ts, the grants, the group's) and told to its own document's pages. On the wire it's
4
+ // `{ id, writes: [{ doc, ops, why? }, …] }`, each part a write's shape; in a story, a does (or cannot) that's a list of
5
+ // writes. "$n" is the write's nth add, whichever part made it: in a value, the id that add was given; as a part's
6
+ // document, the instance of a kind it made (`board:$1`, the board the first part adds), since nothing else can name a
7
+ // document that isn't there until the write is.
8
+ //
9
+ // The compiler tells each part as a story of its own, of its own document, the parts before it written first: so each
10
+ // part's ops are granted, and typed, as one write's are.
11
+
12
+ import type { Story } from "./compile.ts";
13
+ import { Refused } from "./engine.ts";
14
+ import { docParts, parts, type Op } from "./ops.ts";
15
+
16
+ /** One document's part of a write: its ops, and why, as a write of one document is. */
17
+ export type Part = { doc: string; ops: Op[]; why?: string };
18
+ /** An add a write made: its collection, and the id it was given. */
19
+ type Added = { coll: string; id: number };
20
+ /** A line of stories.jsonl telling a story: its does (or cannot) one write, or several. */
21
+ export type Told = Omit<Story, "does" | "cannot"> & { does?: Part | Part[]; cannot?: Part | Part[] };
22
+ /** The documents as the compiler holds a story's state: each by its name (a kind's, every instance's rows). */
23
+ type State = Record<string, Record<string, unknown>>;
24
+
25
+ /** "$n": the write's nth add. */
26
+ const NTH = /^\$([1-9]\d*)$/;
27
+
28
+ /** A story's does or cannot, as its parts: one write, or several. */
29
+ export const partsOf = (w: Part | Part[]) => (Array.isArray(w) ? w : [w]);
30
+
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 ?? "");
33
+
34
+ /** Each add of an item, in order: what a later "$n" counts. */
35
+ const addsOf = (ops: Op[]) =>
36
+ ops.filter((o) => o.op === "add" && parts(o.path).key === "-" && parts(o.path).field === undefined);
37
+
38
+ /** A part as its write names it, after the adds before it (`adds`): "$n" naming one of those, its id in a value, and as
39
+ * its document the instance it made, where it's an add to its kind's root (`rootOf` a kind's root, by its name); naming
40
+ * one of the part's own, numbered from its first, as a write of one document numbers them. Refused: a document no add
41
+ * before it makes. */
42
+ export function named(w: Part, adds: Added[], rootOf: (name: string) => string | undefined): Part {
43
+ const value = (v: unknown): unknown => {
44
+ const n = typeof v === "string" ? NTH.exec(v)?.[1] : undefined;
45
+ if (n) return Number(n) <= adds.length ? adds[Number(n) - 1]!.id : `$${Number(n) - adds.length}`;
46
+ return Array.isArray(v)
47
+ ? v.map(value)
48
+ : v && typeof v === "object"
49
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, value(x)]))
50
+ : v;
51
+ };
52
+ const { name, key = "" } = docParts(w.doc),
53
+ n = NTH.exec(key)?.[1];
54
+ const made = n === undefined ? undefined : adds[Number(n) - 1];
55
+ // (a document that's no kind's has no instance to name)
56
+ if (n !== undefined && (!made || made.coll !== rootOf(name)))
57
+ throw new Refused(`no add before it in this write makes ${w.doc}`);
58
+ return {
59
+ ...w,
60
+ doc: made ? w.doc.replace(`:${key}`, `:${made.id}`) : w.doc,
61
+ ops: w.ops.map((o) => ("value" in o ? { ...o, value: value(o.value) } : o)),
62
+ };
63
+ }
64
+
65
+ /** A write's parts, each named as the write names it (named) and landed in turn (`land`: its ops as they were made). */
66
+ export function inTurn(writes: Part[], rootOf: (name: string) => string | undefined, land: (part: Part) => Op[]) {
67
+ const adds: Added[] = [];
68
+ for (const w of writes)
69
+ adds.push(...addsOf(land(named(w, adds, rootOf))).map((o) => ({ coll: parts(o.path).coll, id: o.value.id })));
70
+ }
71
+
72
+ /** Why a list of writes, a story's does or cannot (or a write of one), isn't one, or null: each a write, and a part's
73
+ * document named by an add (`board:$1`) only by one a part before it makes. */
74
+ export function unwritten(writes: unknown[]): string | null {
75
+ let adds = 0;
76
+ for (const w of writes) {
77
+ if (typeof w !== "object" || w === null || Array.isArray(w)) return "a write is its doc and its ops";
78
+ const { doc, ops } = w as Part;
79
+ const n = NTH.exec(docParts(String(doc)).key ?? "")?.[1];
80
+ if (n !== undefined && Number(n) > adds)
81
+ return `${doc} names the write's add ${n}, but the writes before it make ${adds}`;
82
+ adds += addsOf(Array.isArray(ops) ? ops : []).length;
83
+ }
84
+ return writes.length ? null : "a list of writes has its writes";
85
+ }
86
+
87
+ /** The parts before a part of a story of several writes (none: it's the first, or a story of one write). */
88
+ const BEFORE = new WeakMap<Story, Part[]>();
89
+
90
+ /** Each app's stories as the compiler tells them, one write each: a story of several writes told as a story for each
91
+ * part, of its own document's app (the app whose stories of one write are told of it: one app's, never two), the parts
92
+ * before it written first. An app's own come first, then those of others' stories, by app.
93
+ *
94
+ * A part checks only what's told of it alone. A cannot of several writes is refused whole, at one part or another, so
95
+ * none of its parts is a cannot of its own: it checks no definition (a role, owns, a rule over values), and is told
96
+ * only as the whole write. Nor does a part of a document the write makes (`board:$1`) say who mustn't hear it: no page
97
+ * held it to hear. */
98
+ export function told(apps: Record<string, Told[]>): Record<string, Story[]> {
99
+ const home = new Map<string, string>();
100
+ for (const app of Object.keys(apps).sort())
101
+ for (const s of apps[app]!) {
102
+ const said = (s.does ?? s.cannot)!;
103
+ if (Array.isArray(said)) continue;
104
+ const name = docParts(said.doc).name,
105
+ other = home.get(name);
106
+ if (other && other !== app)
107
+ throw new Error(`${other}'s stories and ${app}'s are both told of ${name}: one app's`);
108
+ home.set(name, app);
109
+ }
110
+ const own: Record<string, Story[]> = {},
111
+ others: Record<string, Story[]> = {};
112
+ for (const app of Object.keys(apps)) ((own[app] = []), (others[app] = []));
113
+ for (const app of Object.keys(apps).sort())
114
+ for (const s of apps[app]!) {
115
+ const word = s.does ? "does" : "cannot",
116
+ writes = partsOf(s[word]!);
117
+ writes.forEach((w, k) => {
118
+ const to = home.get(docParts(w.doc).name);
119
+ if (!to) throw new Error(`${app}'s stories: "${s.story}" writes ${w.doc}, which no app's stories are told of`);
120
+ if (to === "members" && app !== "members")
121
+ throw new Error(`${app}'s stories: "${s.story}" writes the group's document with its own: write it alone`);
122
+ if (word === "cannot" && Array.isArray(s.cannot)) return;
123
+ const { unseen, ...rest } = s;
124
+ const part = { ...(madeBy(w.doc) ? rest : s), [word]: w } as Story;
125
+ if (k) BEFORE.set(part, writes.slice(0, k));
126
+ (to === app ? own : others)[to]!.push(part);
127
+ });
128
+ }
129
+ return Object.fromEntries(Object.keys(apps).map((app) => [app, [...own[app]!, ...others[app]!]]));
130
+ }
131
+
132
+ /** A part of a story of several writes as it's written: on the state its premise leaves (`state`), the parts before it
133
+ * written in turn (`write`: a write made on a state, as a premise's is, the state it leaves), each named as the write
134
+ * names it; the state it's written on, and its document as the write names it (`name`). A story of one write: as it
135
+ * is. */
136
+ export function writtenBefore(
137
+ s: Story,
138
+ state: State,
139
+ write: (state: State, w: Part) => State,
140
+ rootOf: (name: string) => string | undefined,
141
+ ) {
142
+ const adds: Added[] = [];
143
+ const nameOf = (w: Part) => {
144
+ try {
145
+ return named(w, adds, rootOf);
146
+ } catch (e) {
147
+ throw new Error(`"${s.story}": ${(e as Error).message}`);
148
+ }
149
+ };
150
+ for (const w of BEFORE.get(s) ?? []) {
151
+ const part = nameOf(w),
152
+ name = docParts(part.doc).name,
153
+ now = write(state, part);
154
+ // each add, the id the state gave it: of its collection's rows, those that weren't there, in order
155
+ const taken = new Map<string, number>();
156
+ for (const { path } of addsOf(part.ops)) {
157
+ const { coll } = parts(path);
158
+ const had = new Set(((state[name]?.[coll] ?? []) as { id: number }[]).map((r) => r.id));
159
+ const fresh = ((now[name]![coll] ?? []) as { id: number }[]).filter((r) => !had.has(r.id));
160
+ const i = taken.get(coll) ?? 0;
161
+ taken.set(coll, i + 1);
162
+ adds.push({ coll, id: fresh[i]!.id });
163
+ }
164
+ state = now;
165
+ }
166
+ return { state, name: (doc: string) => nameOf({ doc, ops: [] }).doc };
167
+ }