@blueshed/joined 0.2.1 → 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.
@@ -537,9 +537,10 @@ Working: `src/icons.ts`; the members panel and every example.
537
537
  `via` the label, and it holds none of his keys.
538
538
  - **The MCP door** (`src/mcp.ts`): an agent's link is a custom connector for Claude in a chat (claude.ai, a
539
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
540
- written from the compiled rules: `read_<doc>` (as its member sees it) and `write_<doc>` (one write, ops typed as
541
- the grants allow, answered `{ done, version, ids }` or a tool error in the refusal's words); a kind's take `key`;
542
- 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,
543
544
  said as the door opens (`examples/trip/routes.ts`). Never print the token: the URL holds it. A project with no
544
545
  members (every story anonymous, hello) has no group and no agent's link: its door is anyone's, `POST /mcp` with no
545
546
  token, as a stranger's page is, each write logged "by anyone" (`tests/server.test.ts`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueshed/joined",
3
- "version": "0.2.1",
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": {
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
  );
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
@@ -461,7 +462,7 @@ function whole(h: Held, items: Record<string, unknown>[]) {
461
462
  function element({ tag, fields, items, may }: Held, item: Record<string, unknown>) {
462
463
  const el = document.createElement(tag);
463
464
  el.setAttribute("key", String(item.id));
464
- set(el, "string", "may", may[String(item.id)]);
465
+ set(el, "string", "may", may[String(item.id)] ?? may["*"]);
465
466
  for (const [field, type] of Object.entries(fields)) set(el, type, field, valueAt(item, field));
466
467
  items.set(String(item.id), el);
467
468
  return el;
@@ -471,7 +472,7 @@ function element({ tag, fields, items, may }: Held, item: Record<string, unknown
471
472
  * its one item, and says it as the collection's). */
472
473
  function allow(h: Held) {
473
474
  set(h.el, "string", "may", h.may[""]);
474
- 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["*"]);
475
476
  }
476
477
 
477
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) => {
@@ -804,6 +808,8 @@ export async function start({
804
808
  data: {} as Data,
805
809
  // a message is a write, a subscribe or an ask: a megabyte is thousands of events; more closes the socket
806
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,
807
813
  // the page is told the build first, each time it connects: a page served by another reloads
808
814
  open(ws) {
809
815
  say(ws, { build });
package/src/write.ts CHANGED
@@ -213,14 +213,18 @@ export function writes({
213
213
  // (a document no page writes has no grants; one kept as it is, frozen, is written by none)
214
214
  if (!Object.keys(r.grants ?? {}).length || now.frozen) return may;
215
215
  const anyone = member === null && !!r.anonymous,
216
- 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;
217
220
  /** What someone may do to one element: each grant it takes (`token`), if their roles to its item do; once (an add
218
221
  * by either of two first steps is one add). */
219
222
  const tokens = (coll: string, item: any, token: (grant: string) => string | undefined) => {
220
- 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));
221
225
  const words = Object.entries(r.grants).flatMap(([g, to]) => {
222
226
  const t = token(g);
223
- return t !== undefined && (anyone || grantsTo(to, () => roles, anyoneIs(doc, member))) ? [t] : [];
227
+ return t !== undefined && (anyone || grantsTo(to, theirs, everyone)) ? [t] : [];
224
228
  });
225
229
  return [...new Set(words)].join(" ");
226
230
  };
@@ -244,8 +248,17 @@ export function writes({
244
248
  ? "add"
245
249
  : undefined,
246
250
  );
247
- for (const item of (seen[coll] ?? []) as Record<string, unknown>[])
248
- 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));
249
262
  }
250
263
  const said = Object.entries(at).filter(([, t]) => t);
251
264
  if (said.length) may[coll] = Object.fromEntries(said);