@blueshed/joined 0.3.3 → 0.3.5
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.
- package/.claude/skills/joined/reference.md +23 -8
- package/.claude/skills/joined-door/SKILL.md +17 -2
- package/docs/introduction.md +6 -2
- package/examples/cafe/migrations/003-guard-supplies.ts +6 -0
- package/examples/index.html +2 -2
- package/examples/trip/stories.jsonl +1 -0
- package/package.json +1 -1
- package/src/attachment.ts +2 -2
- package/src/compile.ts +45 -9
- package/src/drawer.ts +18 -2
- package/src/engine.ts +11 -2
- package/src/file-value.ts +4 -3
- package/src/files.ts +2 -7
- package/src/ics.ts +1 -1
- package/src/link.ts +11 -6
- package/src/map.ts +2 -1
- package/src/mcp.ts +102 -36
- package/src/members/demo.ts +6 -3
- package/src/members/group.ts +2 -1
- package/src/migrate.ts +125 -24
- package/src/page.ts +42 -37
- package/src/postgres-server.ts +69 -14
- package/src/proxy.ts +12 -0
- package/src/reading.ts +21 -3
- package/src/server.ts +57 -28
- package/src/skill.ts +100 -33
- package/src/store.ts +27 -18
- package/src/upkeep.ts +9 -8
- package/src/upload.ts +136 -0
- package/src/write.ts +71 -21
package/src/store.ts
CHANGED
|
@@ -194,8 +194,13 @@ const OWN = `${import.meta.dir}/migrations`;
|
|
|
194
194
|
/** How many changes a page may be behind and still catch up by them, not the whole document. */
|
|
195
195
|
const BEHIND = 500;
|
|
196
196
|
|
|
197
|
-
|
|
198
|
-
|
|
197
|
+
type Given = { name: string; dir: string; rules: Rules }[];
|
|
198
|
+
/** The store in its database: migrated, joined's own and then each app's, in the order given. On Postgres in one
|
|
199
|
+
* transaction: its triggers last, and another server on it writes before they're made again or after, never without
|
|
200
|
+
* them. (SQLite's are its connection's own; a migration of its own stands when a later one fails.) */
|
|
201
|
+
export const openStore = (db: Engine, given: Given) =>
|
|
202
|
+
db.dialect === "postgres" ? db.transaction(() => opened(db, given)) : opened(db, given);
|
|
203
|
+
async function opened(db: Engine, given: Given) {
|
|
199
204
|
/** This store's own name, on what it notifies: what it hears of its own is skipped. */
|
|
200
205
|
const self = crypto.randomUUID();
|
|
201
206
|
// each app's SQL as its engine says it
|
|
@@ -205,7 +210,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
205
210
|
}));
|
|
206
211
|
// what a write changes, noted by the database as each row was before its first change (none: added), whoever
|
|
207
212
|
// changes it, in the connection's own table; a Postgres store's triggers last, and are made again below
|
|
208
|
-
await db.
|
|
213
|
+
await db.each(
|
|
209
214
|
`CREATE TEMP TABLE IF NOT EXISTS joined_touched (n ${db.dialect === "sqlite" ? "INTEGER PRIMARY KEY" : "SERIAL PRIMARY KEY"}, tbl TEXT NOT NULL, id INTEGER NOT NULL, was INTEGER, before TEXT, UNIQUE (tbl, id))`,
|
|
210
215
|
);
|
|
211
216
|
if (db.dialect === "postgres")
|
|
@@ -448,8 +453,8 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
448
453
|
const c = collectionOf(doc, coll);
|
|
449
454
|
// one of an object's fields (/orders/1/terms/days, its column terms.days), or an object whole (/orders/1/terms)
|
|
450
455
|
const sub = field !== undefined && link !== undefined && !/^(\d+|-)$/.test(link) ? `${field}.${link}` : undefined;
|
|
451
|
-
const whole = field !== undefined && link === undefined && !(
|
|
452
|
-
if (field !== undefined && (sub ? !(
|
|
456
|
+
const whole = field !== undefined && link === undefined && !Object.hasOwn(c.fields, field) ? subsOf(c, field) : [];
|
|
457
|
+
if (field !== undefined && (sub ? !Object.hasOwn(c.fields, sub) : !Object.hasOwn(c.fields, field) && !whole.length))
|
|
453
458
|
throw new Refused(`no ${o.op} at ${o.path}`);
|
|
454
459
|
if (o.op === "add" && link === undefined) {
|
|
455
460
|
const { id: back, ...given } = (o.value ?? {}) as Record<string, unknown>,
|
|
@@ -457,7 +462,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
457
462
|
{ by } = of(doc);
|
|
458
463
|
// an id is the store's to give, but to an item an undo puts back
|
|
459
464
|
if (back !== undefined && !undoing) throw new Refused("id is the server's to give");
|
|
460
|
-
const other = Object.keys(value).find((f) => !(
|
|
465
|
+
const other = Object.keys(value).find((f) => !Object.hasOwn(c.fields, f));
|
|
461
466
|
if (other) throw new Refused(`${an(c.tag)} has no ${other}`);
|
|
462
467
|
const id = (back as number | undefined) ?? (await nextId(coll));
|
|
463
468
|
const cols = Object.keys(value).filter((f) => c.fields[f] !== "ids");
|
|
@@ -542,13 +547,17 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
542
547
|
.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${mine(doc, coll).sql}`)
|
|
543
548
|
.get(id, ...mine(doc, coll).args)),
|
|
544
549
|
/** Every row of a collection's table, each as the document has its item, whatever its where holds (an instance's:
|
|
545
|
-
* its own rows): what its definitions hold among them all (unique, noOverlap). */
|
|
546
|
-
async rowsOf(doc: string, coll: string): Promise<Item[]> {
|
|
550
|
+
* its own rows): what its definitions hold among them all (unique, noOverlap); or of some, those of these ids. */
|
|
551
|
+
async rowsOf(doc: string, coll: string, ids?: number[]): Promise<Item[]> {
|
|
547
552
|
const { sql, args } = mine(doc, coll);
|
|
548
553
|
const item = of(doc).rules!.items![coll]!;
|
|
554
|
+
// (so many asked by id that a query can't name them all: the table read, as it is)
|
|
555
|
+
if (ids && ids.length > 1000) ids = undefined;
|
|
549
556
|
const rows = await db
|
|
550
|
-
.query(
|
|
551
|
-
|
|
557
|
+
.query(
|
|
558
|
+
`SELECT CAST(${item} AS TEXT) AS item FROM ${q(coll)} t WHERE ${ids ? `t.id IN (${ids.map(() => "?").join(", ")})` : "1 = 1"}${sql}`,
|
|
559
|
+
)
|
|
560
|
+
.all(...(ids ?? []), ...args);
|
|
552
561
|
return (rows as { item: string }[]).map((r) => JSON.parse(r.item));
|
|
553
562
|
},
|
|
554
563
|
/** Whether a document can be held: one of the documents, or an instance of a kind whose root item is there. */
|
|
@@ -848,15 +857,15 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
848
857
|
|
|
849
858
|
/** Documents begun from their JSON, together, in one transaction: one's may link to another's. */
|
|
850
859
|
async takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
});
|
|
857
|
-
|
|
860
|
+
if (!docs.length) return;
|
|
861
|
+
// (the rules off and on in it too: another server on the database writes before it or after, never without them)
|
|
862
|
+
await db.transaction(async () => {
|
|
863
|
+
await rule(false);
|
|
864
|
+
await db.defer();
|
|
865
|
+
for (const { doc, json, again } of docs) await this.take(doc, json, again);
|
|
866
|
+
await db.settled();
|
|
858
867
|
await rule(true);
|
|
859
|
-
}
|
|
868
|
+
});
|
|
860
869
|
},
|
|
861
870
|
|
|
862
871
|
/** The file let go (a server stopped), once: closing it again does nothing (PGlite's would throw). */
|
package/src/upkeep.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// What a kept store needs that it never does for itself: old changes and files nothing names let go, on any store;
|
|
2
2
|
// and on SQLite, which never gives back the pages a removed row left, gathers what the planner reads, or copies the
|
|
3
|
-
// file anywhere, those too (Postgres has its own autovacuum and backups). joined does it when it's idle
|
|
4
|
-
// PRAGMA optimize once enough has been written (what's let go first: `trim`, the old
|
|
5
|
-
// (VACUUM INTO), the last seven kept. A backup is copied to a name of its own (`.part`) and given its name only once
|
|
3
|
+
// file anywhere, those too (Postgres has its own autovacuum and backups). joined does it when it's idle (or late, where
|
|
4
|
+
// it never is): a VACUUM and PRAGMA optimize once enough has been written (what's let go first: `trim`, the old
|
|
5
|
+
// changes), and a backup once a day, a copy the store's own size (VACUUM INTO), the last seven kept. A backup is copied to a name of its own (`.part`) and given its name only once
|
|
6
6
|
// it's whole, so a copy cut short (the disk full, joined killed) is never counted as one, nor lets a good one go; one a
|
|
7
7
|
// crash left is cleared as the upkeep starts. A backup is a store: to go back to one, stop joined and put it in the
|
|
8
8
|
// store's place (JOINED_DB), with no -wal or -shm beside it.
|
|
@@ -49,14 +49,15 @@ export function upkeep(
|
|
|
49
49
|
for (const part of readdirSync(backups).filter((f) => f.endsWith(PART))) unlinkSync(`${backups}/${part}`);
|
|
50
50
|
}
|
|
51
51
|
const kept = sqlite ? files(backups) : [];
|
|
52
|
-
let backedUpAt = kept.length ? statSync(`${backups}/${kept.at(-1)}`).mtimeMs :
|
|
52
|
+
let backedUpAt = kept.length ? statSync(`${backups}/${kept.at(-1)}`).mtimeMs : Date.now() - DAY - 1; // none: due now
|
|
53
53
|
|
|
54
|
-
/** Now, or when idle: vacuum if enough was written, back up if a day has passed.
|
|
54
|
+
/** Now, or when idle: vacuum if enough was written, back up if a day has passed. Never idle, each is done late: the
|
|
55
|
+
* backup an hour after it's due, the rest once a day. */
|
|
55
56
|
async function run(now = false) {
|
|
56
57
|
const at = Date.now();
|
|
57
58
|
const done: { vacuumed?: boolean; backup?: string; files?: Promise<number> } = {};
|
|
58
|
-
|
|
59
|
-
if (now ||
|
|
59
|
+
const busy = !now && at - lastWrite < IDLE;
|
|
60
|
+
if (now || (writes > 0 && at - vacuumedAt > (busy ? DAY : HOUR)) || (!busy && writes >= WRITES)) {
|
|
60
61
|
const gone = await trim();
|
|
61
62
|
if (gone) log(`let go ${gone} old changes`);
|
|
62
63
|
done.files = letGo().then(
|
|
@@ -70,7 +71,7 @@ export function upkeep(
|
|
|
70
71
|
}
|
|
71
72
|
[writes, vacuumedAt, done.vacuumed] = [0, at, true];
|
|
72
73
|
}
|
|
73
|
-
if (sqlite && (now || at - backedUpAt > DAY)) {
|
|
74
|
+
if (sqlite && (now || at - backedUpAt > (busy ? DAY + HOUR : DAY))) {
|
|
74
75
|
done.backup = `${backups}/${new Date(at).toISOString().replace(/[:.]/g, "-")}.sqlite`;
|
|
75
76
|
const part = done.backup + PART;
|
|
76
77
|
try {
|
package/src/upload.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// An upload link: a file sent for a document by an agent at the MCP door, which has no page's sign-in to send one by
|
|
2
|
+
// (its member's key is in its connector's link, which it never sees: the server does). The door's upload_<doc> asks
|
|
3
|
+
// for one: a link short-lived and used once, made for the agent's member and that document alone, so whoever has it
|
|
4
|
+
// sends one file as that member could, and nothing more. POSTed the file's bytes (by an agent that can send them,
|
|
5
|
+
// Claude Code), it's kept as a page's file is (src/files.ts) and answered its value; opened in a browser, it's a page to
|
|
6
|
+
// choose the file on, for an agent in a chat whose sandbox can't reach the site: its person opens it. Where the agent
|
|
7
|
+
// said the write it's for ("$file" in a value standing for the file), that write is made as the agent's once the file
|
|
8
|
+
// is in, so the person who chose it needn't tell the agent anything. Kept in the server's memory: a restart lets every
|
|
9
|
+
// link go, as it does whatever was being answered.
|
|
10
|
+
|
|
11
|
+
import { folderOf, MOST, TOO_BIG } from "./file-value.ts";
|
|
12
|
+
import { keep, upTo, type Files } from "./files.ts";
|
|
13
|
+
import type { Written } from "./mcp.ts";
|
|
14
|
+
import type { Who } from "./members/group.ts";
|
|
15
|
+
import type { Op } from "./ops.ts";
|
|
16
|
+
|
|
17
|
+
/** How long a link is good for, in ms. */
|
|
18
|
+
export const GOOD_FOR = 15 * 60_000;
|
|
19
|
+
/** What stands for the file in the write a link is for. */
|
|
20
|
+
export const FILE = "$file";
|
|
21
|
+
|
|
22
|
+
/** What makes the links, and is sent their files: who may put a file in a document, and how it's written (by a
|
|
23
|
+
* member's agent, or nobody, at a door that's anyone's). */
|
|
24
|
+
type Uploading = {
|
|
25
|
+
files: Files;
|
|
26
|
+
/** Why a member may not put a file in a document, or null. */
|
|
27
|
+
mayPut(doc: string, who: Who | null): Promise<string | null>;
|
|
28
|
+
/** Whether a document's kind keeps its files apart. */
|
|
29
|
+
apart(doc: string): Promise<boolean>;
|
|
30
|
+
write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
|
|
31
|
+
};
|
|
32
|
+
type Link = { doc: string; who: Who | null; name: string; until: number; ops?: Op[]; why?: string; busy?: boolean };
|
|
33
|
+
/** A link made: its address, and till when (ISO); or why not. */
|
|
34
|
+
export type Made = { url: string; until: string } | { why: string };
|
|
35
|
+
|
|
36
|
+
/** A write's ops with the file's value where "$file" stood. */
|
|
37
|
+
const filled = (ops: Op[], file: string): Op[] => JSON.parse(JSON.stringify(ops), (_, v) => (v === FILE ? file : v));
|
|
38
|
+
|
|
39
|
+
const escaped = (s: string) =>
|
|
40
|
+
s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
|
41
|
+
|
|
42
|
+
/** The page a link opens in a browser: the file chosen, sent, and what came of it said. */
|
|
43
|
+
const page = (l: Link) => `<!doctype html>
|
|
44
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
45
|
+
<meta name="color-scheme" content="light dark"><title>A file for your agent</title>
|
|
46
|
+
<style>
|
|
47
|
+
body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:0 auto;padding:2rem 1rem}
|
|
48
|
+
h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:.5rem 0}
|
|
49
|
+
label{display:block;border:2px dashed currentColor;border-radius:12px;padding:2rem 1rem;text-align:center;cursor:pointer;opacity:.8}
|
|
50
|
+
label:hover{opacity:1}input,[hidden]{display:none}#said{font-weight:600}
|
|
51
|
+
</style></head><body>
|
|
52
|
+
<h1>Your agent asked for ${escaped(l.name || "a file")}</h1>
|
|
53
|
+
<p>Choose it here${l.ops ? ", and it's put where your agent said" : ", and your agent has it"}. It goes to ${escaped(l.doc)}.</p>
|
|
54
|
+
<label>Choose the file, or drop it here<input type="file" accept="image/*,.pdf,.svg,.md"></label>
|
|
55
|
+
<p id="said" role="status"></p>
|
|
56
|
+
<script>
|
|
57
|
+
const said = document.getElementById("said"), input = document.querySelector("input");
|
|
58
|
+
async function send(file) {
|
|
59
|
+
said.textContent = "Sending " + file.name + "…";
|
|
60
|
+
const r = await fetch(location.pathname, { method: "POST", body: file }).catch(() => null);
|
|
61
|
+
const a = r && (await r.json().catch(() => null));
|
|
62
|
+
said.textContent = !a ? "That wasn't sent: try again." : a.refused ? a.refused : a.why ? "It's kept, but not put in: " + a.why : "Done: " + file.name + " is in. You can close this page.";
|
|
63
|
+
// sent: the link's used, so there's nothing more to choose
|
|
64
|
+
if (a && a.file) document.querySelector("label").hidden = true;
|
|
65
|
+
}
|
|
66
|
+
input.onchange = () => input.files[0] && send(input.files[0]);
|
|
67
|
+
document.body.ondragover = (e) => e.preventDefault();
|
|
68
|
+
document.body.ondrop = (e) => { e.preventDefault(); const f = e.dataTransfer.files[0]; f && send(f); };
|
|
69
|
+
</script></body></html>`;
|
|
70
|
+
|
|
71
|
+
/** The links: made for an agent at the door, and the route that's sent their files. */
|
|
72
|
+
export function uploads(d: Uploading, now = Date.now) {
|
|
73
|
+
const links = new Map<string, Link>();
|
|
74
|
+
/** A link still good, or none: one past its time is let go as it's asked for. */
|
|
75
|
+
const good = (nonce: string) => {
|
|
76
|
+
const l = links.get(nonce);
|
|
77
|
+
if (l && l.until > now()) return l;
|
|
78
|
+
links.delete(nonce);
|
|
79
|
+
return undefined;
|
|
80
|
+
};
|
|
81
|
+
const gone = () => Response.json({ refused: "That link has gone: ask your agent for another." }, { status: 404 });
|
|
82
|
+
return {
|
|
83
|
+
/** A link for an agent's member to send one file for a document, at the site the door was asked at. */
|
|
84
|
+
async link(origin: string, doc: string, who: Who | null, name: string, then: { ops?: Op[]; why?: string } = {}) {
|
|
85
|
+
const no = await d.mayPut(doc, who);
|
|
86
|
+
if (no) return { why: no } satisfies Made;
|
|
87
|
+
for (const [n, l] of links) if (l.until <= now()) links.delete(n);
|
|
88
|
+
const nonce = crypto.randomUUID().replaceAll("-", "") + crypto.randomUUID().replaceAll("-", ""),
|
|
89
|
+
until = now() + GOOD_FOR;
|
|
90
|
+
links.set(nonce, { doc, who, name, until, ...then });
|
|
91
|
+
return { url: `${origin}/upload/${nonce}`, until: new Date(until).toISOString() } satisfies Made;
|
|
92
|
+
},
|
|
93
|
+
routes: {
|
|
94
|
+
"/upload/:nonce": {
|
|
95
|
+
GET: (req: Request & { params: { nonce: string } }) => {
|
|
96
|
+
const l = good(req.params.nonce);
|
|
97
|
+
return l
|
|
98
|
+
? new Response(page(l), {
|
|
99
|
+
headers: {
|
|
100
|
+
"content-type": "text/html;charset=utf-8",
|
|
101
|
+
"cache-control": "no-store",
|
|
102
|
+
"content-security-policy": "frame-ancestors 'none'; base-uri 'none'; object-src 'none'",
|
|
103
|
+
"referrer-policy": "no-referrer",
|
|
104
|
+
},
|
|
105
|
+
})
|
|
106
|
+
: new Response("That link has gone: ask your agent for another.", { status: 404 });
|
|
107
|
+
},
|
|
108
|
+
async POST(req: Request & { params: { nonce: string } }) {
|
|
109
|
+
const l = good(req.params.nonce);
|
|
110
|
+
if (!l) return gone();
|
|
111
|
+
if (l.busy) return Response.json({ refused: "A file is being sent by this link already." }, { status: 409 });
|
|
112
|
+
if (Number(req.headers.get("content-length")) > MOST)
|
|
113
|
+
return Response.json({ refused: TOO_BIG }, { status: 413 });
|
|
114
|
+
l.busy = true;
|
|
115
|
+
try {
|
|
116
|
+
const bytes = await upTo(req, MOST);
|
|
117
|
+
if (!bytes) return Response.json({ refused: TOO_BIG }, { status: 413 });
|
|
118
|
+
// asked again as it's sent: what the member may do can have changed since the link was made
|
|
119
|
+
const no = await d.mayPut(l.doc, l.who);
|
|
120
|
+
if (no) return Response.json({ refused: no }, { status: 403 });
|
|
121
|
+
const kept = await keep(d.files, bytes, l.name, (await d.apart(l.doc)) ? folderOf(l.doc) : "");
|
|
122
|
+
if ("refused" in kept) return Response.json(kept, { status: 422 });
|
|
123
|
+
// used: a link sends one file
|
|
124
|
+
links.delete(req.params.nonce);
|
|
125
|
+
if (!l.ops) return Response.json(kept);
|
|
126
|
+
const w = await d.write(l.doc, filled(l.ops, kept.file), l.why, l.who);
|
|
127
|
+
return Response.json({ ...kept, ...w }, { status: "why" in w ? 422 : 200 });
|
|
128
|
+
} finally {
|
|
129
|
+
l.busy = false;
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
export type Uploads = ReturnType<typeof uploads>;
|
package/src/write.ts
CHANGED
|
@@ -27,6 +27,8 @@ import { admits, guestRole, levelled } from "./visitors.ts";
|
|
|
27
27
|
|
|
28
28
|
/** A way to read any document as it is now: whole, or as a member sees it (owns). */
|
|
29
29
|
export type Read = (doc: string, member?: number) => Doc;
|
|
30
|
+
/** An item of a document, by its id: its one row read. */
|
|
31
|
+
type Row1 = (doc: string, coll: string, id: number) => unknown;
|
|
30
32
|
/** An app's compiled rules: its grants, who someone is (rolesOf), what they see (sees: null, all of it), what its
|
|
31
33
|
* definitions hold of it (holds), and its window's test of an item (inWindow). */
|
|
32
34
|
export type Rules = StoreRules & {
|
|
@@ -36,7 +38,7 @@ export type Rules = StoreRules & {
|
|
|
36
38
|
holds?(d: Record<string, unknown>, touched: Record<string, number[]>): string | null;
|
|
37
39
|
/** What its lists hold as a write leaves them (definitions' within and apart), asked on SQLite: Postgres's triggers
|
|
38
40
|
* hold them, at the write's end (the store's settle). */
|
|
39
|
-
listsHold?(d:
|
|
41
|
+
listsHold?(d: Record<string, unknown>, touched: Record<string, number[]>): string | null;
|
|
40
42
|
/** The lists that are each member's own (definitions' mine), by collection. */
|
|
41
43
|
mine?: Record<string, string[]>;
|
|
42
44
|
/** The words a write giving or taking another's is refused in, where its mine says them, by collection and field. */
|
|
@@ -86,7 +88,8 @@ export type Told = { topic: string; change: Change & { doc: string } }[];
|
|
|
86
88
|
class Missing {
|
|
87
89
|
constructor(
|
|
88
90
|
readonly doc: string,
|
|
89
|
-
readonly
|
|
91
|
+
readonly key: string,
|
|
92
|
+
readonly load: () => Promise<unknown>,
|
|
90
93
|
) {}
|
|
91
94
|
}
|
|
92
95
|
|
|
@@ -124,7 +127,7 @@ export function writes({
|
|
|
124
127
|
/** The documents a rule reads, as they are now: each read once by the store (it waits for the database), then
|
|
125
128
|
* held while what asks it runs again; the rules themselves, the compiled ones, an app's trust.ts, its reactions and
|
|
126
129
|
* derive.ts, read as they always have, at once (settle). */
|
|
127
|
-
const reading = new AsyncLocalStorage<{ at: Read; wrote: boolean }>();
|
|
130
|
+
const reading = new AsyncLocalStorage<{ at: Read; row: Row1; wrote: boolean }>();
|
|
128
131
|
const read: Read = (doc, member) => {
|
|
129
132
|
const r = reading.getStore();
|
|
130
133
|
if (!r) throw new Error(`${doc} read outside settle`);
|
|
@@ -133,21 +136,23 @@ export function writes({
|
|
|
133
136
|
/** What asks the documents (`fn`, at once, as the rules are), run until every document it reads is here: one it
|
|
134
137
|
* hasn't is read by the store, and it's asked again (it has changed nothing yet). Each settle reads afresh. */
|
|
135
138
|
async function settle<T>(fn: () => T): Promise<T> {
|
|
136
|
-
const held = new Map<string,
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
return d;
|
|
139
|
+
const held = new Map<string, unknown>();
|
|
140
|
+
const here = <T>(doc: string, key: string, load: () => Promise<T>): T => {
|
|
141
|
+
if (!held.has(key)) throw new Missing(doc, key, load);
|
|
142
|
+
return held.get(key) as T;
|
|
141
143
|
};
|
|
144
|
+
const at: Read = (doc, member) => here(doc, `${doc}@${member ?? ""}`, () => store.read(doc, member));
|
|
145
|
+
const row: Row1 = (doc, coll, id) =>
|
|
146
|
+
here(doc, `${doc}/${coll}/${id}`, async () => (await store.rowsOf(doc, coll, [id]))[0]);
|
|
142
147
|
for (;;) {
|
|
143
|
-
const frame = { at, wrote: false };
|
|
148
|
+
const frame = { at, row, wrote: false };
|
|
144
149
|
try {
|
|
145
150
|
return await reading.run(frame, fn);
|
|
146
151
|
} catch (e) {
|
|
147
152
|
if (!(e instanceof Missing)) throw e;
|
|
148
153
|
// asked again, a route would write twice: it reads what it needs first
|
|
149
154
|
if (frame.wrote) throw new Error(`${e.doc} was read after a write: read every document before writing`);
|
|
150
|
-
held.set(
|
|
155
|
+
held.set(e.key, await e.load());
|
|
151
156
|
}
|
|
152
157
|
}
|
|
153
158
|
}
|
|
@@ -224,14 +229,14 @@ export function writes({
|
|
|
224
229
|
for (const o of ops) {
|
|
225
230
|
const { coll, key, field, link, more } = parts(o.path);
|
|
226
231
|
// a field the server fills is replaced by the server alone (a page's write of it is refused before)
|
|
227
|
-
const filled = o.op === "replace" && field !== undefined &&
|
|
232
|
+
const filled = o.op === "replace" && field !== undefined && Object.hasOwn(collections[coll]?.fills ?? {}, field);
|
|
228
233
|
const id = /^[1-9]\d*$/.test(key ?? "");
|
|
229
234
|
// a field of the document's own (/greeting)
|
|
230
235
|
const own = Object.values(collections).find((c) => c.own);
|
|
231
236
|
const formed =
|
|
232
237
|
!more?.length &&
|
|
233
238
|
(key === ""
|
|
234
|
-
? !!own && o.op !== "add" &&
|
|
239
|
+
? !!own && o.op !== "add" && Object.hasOwn(own.fields, coll)
|
|
235
240
|
: o.op === "add"
|
|
236
241
|
? field === undefined
|
|
237
242
|
? key === "-"
|
|
@@ -269,6 +274,37 @@ export function writes({
|
|
|
269
274
|
}
|
|
270
275
|
return null;
|
|
271
276
|
}
|
|
277
|
+
/** Why a write's value isn't the kind of thing its op takes (an item added is its fields; a list, ids), or null: asked
|
|
278
|
+
* before any rule reads it, so a rule may. */
|
|
279
|
+
function misshapen(doc: string, ops: Op[]) {
|
|
280
|
+
const isId = (v: unknown) => typeof v === "number" || (typeof v === "string" && /^\d+$/.test(v));
|
|
281
|
+
for (const o of ops) {
|
|
282
|
+
if (o.op === "remove" || (o.value ?? null) === null) continue;
|
|
283
|
+
const { coll, key, field, link } = parts(o.path),
|
|
284
|
+
types = rulesOf(doc).collections[coll]?.fields ?? {};
|
|
285
|
+
if (
|
|
286
|
+
o.op === "add" &&
|
|
287
|
+
key === "-" &&
|
|
288
|
+
field === undefined &&
|
|
289
|
+
(typeof o.value !== "object" || Array.isArray(o.value))
|
|
290
|
+
)
|
|
291
|
+
return `an add at ${o.path} gives an item: its fields, by name`;
|
|
292
|
+
const given: [string, unknown][] = field !== undefined ? [[field, o.value]] : Object.entries(o.value);
|
|
293
|
+
for (const [f, v] of given)
|
|
294
|
+
if (Object.hasOwn(types, f) && types[f] === "ids" && (v ?? null) !== null)
|
|
295
|
+
if (!(field !== undefined && link !== undefined ? isId(v) : Array.isArray(v) && v.every(isId)))
|
|
296
|
+
return link === undefined
|
|
297
|
+
? `${f} is a list of ids, each a whole number`
|
|
298
|
+
: `${f} takes an id, a whole number`;
|
|
299
|
+
}
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
/** Why a replace that gives no value is refused: it would clear its field, which is a remove's, granted apart; null
|
|
303
|
+
* if each gives one. */
|
|
304
|
+
function givesNothing(ops: Op[]) {
|
|
305
|
+
const o = ops.find((x) => x.op === "replace" && (x.value ?? null) === null);
|
|
306
|
+
return o ? `a replace gives a value: ${o.path} is cleared by a remove` : null;
|
|
307
|
+
}
|
|
272
308
|
/** Whether a grant's roles take in someone's: anyone's, where it's a member's and what's anyone's is theirs. */
|
|
273
309
|
const grantsTo = (to: string[], roles: () => string[], anyone: boolean) =>
|
|
274
310
|
(anyone && to.includes("member")) || to.some((r) => roles().includes(r));
|
|
@@ -350,9 +386,15 @@ export function writes({
|
|
|
350
386
|
function itemAt(doc: string, o: Op): any {
|
|
351
387
|
const { coll, key } = parts(o.path);
|
|
352
388
|
if (key === "-") return o.value;
|
|
353
|
-
// the document as a whole
|
|
354
|
-
|
|
355
|
-
|
|
389
|
+
// of the document as a whole (a window of it holds only some; a guest's, their own order): its one row, or, of a
|
|
390
|
+
// document holding only some of a table's rows, found among those
|
|
391
|
+
const { base } = docParts(doc),
|
|
392
|
+
r = rulesOf(doc),
|
|
393
|
+
id = Number(key);
|
|
394
|
+
if (!Object.hasOwn(r.collections, coll) || r.collections[coll]!.own || !Number.isSafeInteger(id)) return undefined;
|
|
395
|
+
return r.view
|
|
396
|
+
? (read(base)[coll] as { id: number }[]).find((i) => i.id === id)
|
|
397
|
+
: reading.getStore()!.row(base, coll, id);
|
|
356
398
|
}
|
|
357
399
|
/** Who someone is to an item of a collection: their roles, and its guest's (at its level: src/visitors.ts). */
|
|
358
400
|
function rolesTo(doc: string, member: number | null, coll: string, item: any, from: Read = read) {
|
|
@@ -390,11 +432,12 @@ export function writes({
|
|
|
390
432
|
for (const o of ops) {
|
|
391
433
|
const { coll, key, field } = parts(o.path);
|
|
392
434
|
const { fills = {}, copies } = rulesOf(doc).collections[coll] ?? {};
|
|
393
|
-
const given =
|
|
435
|
+
const given =
|
|
436
|
+
field ?? (o.op === "add" && key === "-" ? Object.keys(o.value ?? {}) : []).find((f) => Object.hasOwn(fills, f));
|
|
394
437
|
// (a field that moves only as the stories move it is filled as it's added, and then moved; a code, made new)
|
|
395
438
|
if (
|
|
396
439
|
given !== undefined &&
|
|
397
|
-
given
|
|
440
|
+
Object.hasOwn(fills, given) &&
|
|
398
441
|
!(o.op === "replace" && rulesOf(doc).moves?.[coll] === given) &&
|
|
399
442
|
!renews(doc, o)
|
|
400
443
|
)
|
|
@@ -417,7 +460,7 @@ export function writes({
|
|
|
417
460
|
// a field given its value, or an item given whole (an add, a replace)
|
|
418
461
|
const given: [string, unknown][] = field !== undefined ? [[field, o.value]] : Object.entries(o.value ?? {});
|
|
419
462
|
for (const [f, v] of given) {
|
|
420
|
-
const [is, refused] = r.names[f]
|
|
463
|
+
const [is, refused] = Object.hasOwn(r.names, f) ? r.names[f]! : [];
|
|
421
464
|
if (is && [v ?? []].flat().some((id) => typeof id === "number" && !is(id, read, doc))) return refused!;
|
|
422
465
|
}
|
|
423
466
|
}
|
|
@@ -625,6 +668,8 @@ export function writes({
|
|
|
625
668
|
if (r.derived) throw new Refused(`${doc} is derived from ${r.derived.join(" and ")}: write that`);
|
|
626
669
|
if (r.member) throw new Refused(`${doc} is read off ${r.reads!.join(", ")}: write those`);
|
|
627
670
|
// an anonymous document's writes are anyone's; any other's, each op's by who the writer is to its item
|
|
671
|
+
const odd = misshapen(doc, ops);
|
|
672
|
+
if (odd) throw new Refused(odd);
|
|
628
673
|
const ruled = await settle(() => {
|
|
629
674
|
const roles = who ? r.rolesOf!(who.member, read, doc) : [];
|
|
630
675
|
return (
|
|
@@ -655,6 +700,8 @@ export function writes({
|
|
|
655
700
|
if (ruled) throw new Refused(ruled);
|
|
656
701
|
// a code it makes new, the server's (whatever the page gave), before it's kept
|
|
657
702
|
ops = renewed(doc, ops);
|
|
703
|
+
const bare = givesNothing(ops);
|
|
704
|
+
if (bare) throw new Refused(bare);
|
|
658
705
|
const write = groupless(doc, who) ? { ops } : await group(docParts(doc).base, ops);
|
|
659
706
|
if ("refused" in write) throw new Refused(write.refused);
|
|
660
707
|
// of a kind's instance, or held by an item's code, it links to nothing another holds: asked of it as made, before
|
|
@@ -721,9 +768,12 @@ export function writes({
|
|
|
721
768
|
// (unique and noOverlap among every row of a collection's table, not only those its where holds)
|
|
722
769
|
const all: Record<string, Awaited<ReturnType<Store["rowsOf"]>>> = {};
|
|
723
770
|
if (r.holds) for (const c of Object.keys(touched)) all[c] = await store.rowsOf(d, c);
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
)
|
|
771
|
+
// (its lists, of the items it touched alone)
|
|
772
|
+
const lists: typeof all = {};
|
|
773
|
+
if (r.listsHold && store.db.dialect === "sqlite")
|
|
774
|
+
for (const [c, ids] of Object.entries(touched))
|
|
775
|
+
if (r.collections[c] && !r.collections[c].own) lists[c] = await store.rowsOf(d, c, ids);
|
|
776
|
+
const held = r.holds?.(all, touched) ?? r.listsHold?.(lists, touched);
|
|
727
777
|
if (held) throw new Refused(held);
|
|
728
778
|
for (const [name, r] of Object.entries(made.rows)) (rows[name] ??= []).push(...r);
|
|
729
779
|
// a document read as each member has it moves its version with what it reads
|