@blueshed/joined 0.3.3 → 0.3.4
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 +13 -5
- 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 +5 -2
- 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 +32 -25
- package/src/store.ts +27 -18
- package/src/upkeep.ts +9 -8
- package/src/write.ts +71 -21
package/src/server.ts
CHANGED
|
@@ -37,7 +37,8 @@ import {
|
|
|
37
37
|
type Op,
|
|
38
38
|
type Type,
|
|
39
39
|
} from "./ops.ts";
|
|
40
|
-
import {
|
|
40
|
+
import { schemeOf } from "./proxy.ts";
|
|
41
|
+
import { openStore, Refused, rootCode, type Doc } from "./store.ts";
|
|
41
42
|
import { madeBy, type Part } from "./together.ts";
|
|
42
43
|
import { Made, writes, type Held, type Reactions, type Read, type Rules, type Told, type Trust } from "./write.ts";
|
|
43
44
|
/** A write refused, and why, in words a page shows as they are: a reaction or a route throws it. */
|
|
@@ -122,10 +123,8 @@ const anotherSite = (req: Request) => {
|
|
|
122
123
|
const origin = req.headers.get("origin");
|
|
123
124
|
if (!origin) return false;
|
|
124
125
|
if (!URL.canParse(origin)) return true;
|
|
125
|
-
const from = new URL(origin)
|
|
126
|
-
|
|
127
|
-
scheme = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
128
|
-
return from.host !== to.host || from.protocol !== (scheme ? `${scheme}:` : to.protocol);
|
|
126
|
+
const from = new URL(origin);
|
|
127
|
+
return from.host !== new URL(req.url).host || from.protocol !== `${schemeOf(req)}:`;
|
|
129
128
|
};
|
|
130
129
|
/** A route's answer, but to another site's page sending what isn't a read (a sign-out, a post to an edge). */
|
|
131
130
|
const ownSite =
|
|
@@ -135,7 +134,9 @@ const ownSite =
|
|
|
135
134
|
? new Response("another site", { status: 403 })
|
|
136
135
|
: answer(req);
|
|
137
136
|
|
|
138
|
-
/** The MCP door, but to another site's page posting to it
|
|
137
|
+
/** The MCP door, but to another site's page posting to it, refused 403. A DNS rebinding (a site's name pointed at this
|
|
138
|
+
* machine) is this site by its host, so it isn't refused: it has no member's link, so it reaches an open group alone
|
|
139
|
+
* (#233). */
|
|
139
140
|
const mine = (d: ReturnType<typeof door>) => ({ ...d, POST: ownSite(d.POST) });
|
|
140
141
|
|
|
141
142
|
/** What fails in the background (a change told, the clock, another server's change heard), said, and the server goes on. */
|
|
@@ -563,8 +564,12 @@ export async function start({
|
|
|
563
564
|
};
|
|
564
565
|
/** Why someone may not be sent an instance's file (src/files.ts), or null: they may hold it, as a member by their
|
|
565
566
|
* link or a guest by its code, and see an item naming it. */
|
|
566
|
-
const mayHoldFiles = async (req: Request,
|
|
567
|
-
|
|
567
|
+
const mayHoldFiles = async (req: Request, asked: string, name: string) => {
|
|
568
|
+
const { base, params } = docParts(asked);
|
|
569
|
+
if (!(await store.exists(base))) return `there's no document called ${base}`;
|
|
570
|
+
// held by its root's code, whatever the kind's guests call it; the page's window, if it holds one, says nothing here
|
|
571
|
+
const by = rootCode(rulesOf(base)),
|
|
572
|
+
doc = by && params[by] !== undefined ? `${base}?${by}=${encodeURIComponent(params[by])}` : base;
|
|
568
573
|
const signed = await group.at(req),
|
|
569
574
|
who = signed instanceof Response ? null : signed;
|
|
570
575
|
return (
|
|
@@ -641,6 +646,7 @@ export async function start({
|
|
|
641
646
|
// a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
|
|
642
647
|
...fileRoutes(filesKept, mayPut, mayHoldFiles, apart),
|
|
643
648
|
};
|
|
649
|
+
const bundles = `/_page-${crypto.randomUUID()}`;
|
|
644
650
|
// an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
|
|
645
651
|
// document it reads is here (src/write.ts)
|
|
646
652
|
const settled =
|
|
@@ -650,9 +656,10 @@ export async function start({
|
|
|
650
656
|
for (const { app, routes: of = {} } of apps)
|
|
651
657
|
for (const [path, answer] of Object.entries(typeof of === "function" ? of(now, write) : of)) {
|
|
652
658
|
if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
|
|
653
|
-
// a page (Bun's bundle of its index.html) is kept at
|
|
659
|
+
// a page (Bun's bundle of its index.html) is kept at a path no one is told, as it has none of the page's headers,
|
|
660
|
+
// and served at its own path rendered
|
|
654
661
|
if (typeof answer === "object" && "index" in answer) {
|
|
655
|
-
routes[
|
|
662
|
+
routes[`${bundles}${path}`] = answer;
|
|
656
663
|
routes[path] = (req: Request) => rendered(req, path);
|
|
657
664
|
continue;
|
|
658
665
|
}
|
|
@@ -689,13 +696,13 @@ export async function start({
|
|
|
689
696
|
.filter((r) => !r.derived)
|
|
690
697
|
.flatMap((r) => Object.entries(r.collections).map(([coll, c]) => [c.place, { doc: r.doc, coll, ...c }] as const)),
|
|
691
698
|
);
|
|
692
|
-
/** A page as Bun bundles it (kept at
|
|
699
|
+
/** A page as Bun bundles it (kept at `bundles`), and the documents it holds: read once live, and each time in
|
|
693
700
|
* development, where it's bundled afresh. */
|
|
694
701
|
const shells = new Map<string, { html: string; docs: string[] }>();
|
|
695
702
|
async function shell(path: string) {
|
|
696
703
|
const kept = shells.get(path);
|
|
697
704
|
if (kept) return kept;
|
|
698
|
-
const html = await (await fetch(new URL(
|
|
705
|
+
const html = await (await fetch(new URL(`${bundles}${path}`, server.url))).text();
|
|
699
706
|
const docs = new Set<string>();
|
|
700
707
|
const finding = new HTMLRewriter();
|
|
701
708
|
for (const [place, { doc }] of places)
|
|
@@ -716,9 +723,6 @@ export async function start({
|
|
|
716
723
|
return a === null ? "" : a === "" ? ` ${f}` : ` ${f}="${escaped(a)}"`;
|
|
717
724
|
})
|
|
718
725
|
.join("")}></${tag}>`;
|
|
719
|
-
/** Whether a request came over https: its own URL's, or a proxy's in front (Railway's) saying so. */
|
|
720
|
-
const secure = (req: Request) =>
|
|
721
|
-
new URL(req.url).protocol === "https:" || req.headers.get("x-forwarded-proto") === "https";
|
|
722
726
|
async function rendered(req: Request, path: string) {
|
|
723
727
|
const { html, docs } = await shell(path);
|
|
724
728
|
const headers = {
|
|
@@ -729,7 +733,7 @@ export async function start({
|
|
|
729
733
|
"content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'",
|
|
730
734
|
"x-frame-options": "SAMEORIGIN",
|
|
731
735
|
"x-content-type-options": "nosniff",
|
|
732
|
-
...(
|
|
736
|
+
...(schemeOf(req) === "https" ? { "strict-transport-security": "max-age=31536000" } : {}),
|
|
733
737
|
};
|
|
734
738
|
const signed = await group.at(req),
|
|
735
739
|
who = signed instanceof Response ? null : signed;
|
|
@@ -808,14 +812,17 @@ export async function start({
|
|
|
808
812
|
const missed = m.since === undefined || part ? null : await store.since(doc, m.since);
|
|
809
813
|
if (missed) for (const c of missed) say(ws, c);
|
|
810
814
|
else {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const
|
|
814
|
-
?
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
815
|
+
// a part's topic is here before it's read, so a write landing meanwhile is told to it; and read again, where one
|
|
816
|
+
// told was newer than what was read
|
|
817
|
+
const member = ws.data.who?.member ?? 0,
|
|
818
|
+
asWho = topic !== doc || r.view ? { member: topic === doc ? 0 : member } : {},
|
|
819
|
+
t = part ? (topics.get(topic) ?? topics.set(topic, { doc, ...asWho, version: 0 }).get(topic)!) : null;
|
|
820
|
+
let seen: Doc;
|
|
821
|
+
do seen = await view(doc, member);
|
|
822
|
+
while (t && seen.version < t.version);
|
|
823
|
+
const { version, ...value } = seen;
|
|
824
|
+
// (the first to hold it: what it's told next follows what it's sent)
|
|
825
|
+
if (t && !t.version) t.version = version;
|
|
819
826
|
say(ws, { doc, version: t?.version ?? version, ops: [{ op: "replace", path: "", value }] });
|
|
820
827
|
}
|
|
821
828
|
// and what its person may do there, told afresh
|
|
@@ -1099,7 +1106,7 @@ export async function start({
|
|
|
1099
1106
|
members,
|
|
1100
1107
|
build,
|
|
1101
1108
|
// what's answered, without the bundles the pages are rendered from
|
|
1102
|
-
paths: Object.keys(routes).filter((p) => !p.startsWith(
|
|
1109
|
+
paths: Object.keys(routes).filter((p) => !p.startsWith(bundles)),
|
|
1103
1110
|
tokenOf: group.tokenOf,
|
|
1104
1111
|
/** Each app with rules of its own (a trust.ts), and how many writes they've refused. */
|
|
1105
1112
|
ruled,
|
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/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
|