@niscorp/moss 0.4.0 → 0.5.0
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/CHANGELOG.md +481 -0
- package/DESIGN.md +265 -49
- package/DOCS.md +1524 -341
- package/README.md +37 -20
- package/dist/app-BoVB0_0j.d.ts +143 -0
- package/dist/app-Cc8VnOz8.d.cts +143 -0
- package/dist/chunk-3RIWTXGI.cjs +174 -0
- package/dist/chunk-3RIWTXGI.cjs.map +1 -0
- package/dist/chunk-4ZGAFZGS.js +152 -0
- package/dist/chunk-4ZGAFZGS.js.map +1 -0
- package/dist/chunk-5U2ZZUI5.cjs +137 -0
- package/dist/chunk-5U2ZZUI5.cjs.map +1 -0
- package/dist/chunk-6QPTMKRE.cjs +53 -0
- package/dist/chunk-6QPTMKRE.cjs.map +1 -0
- package/dist/chunk-BQRPR2F7.js +2704 -0
- package/dist/chunk-BQRPR2F7.js.map +1 -0
- package/dist/chunk-BZK37HR3.cjs +2716 -0
- package/dist/chunk-BZK37HR3.cjs.map +1 -0
- package/dist/chunk-FTFME3HS.cjs +383 -0
- package/dist/chunk-FTFME3HS.cjs.map +1 -0
- package/dist/{chunk-U3UR5AOQ.js → chunk-FTZ6NFKZ.js} +43 -16
- package/dist/chunk-FTZ6NFKZ.js.map +1 -0
- package/dist/chunk-IUJ2TRNB.cjs +57 -0
- package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
- package/dist/chunk-IW3A2YIC.js +49 -0
- package/dist/chunk-IW3A2YIC.js.map +1 -0
- package/dist/chunk-JYBHJDT7.cjs +30 -0
- package/dist/chunk-JYBHJDT7.cjs.map +1 -0
- package/dist/chunk-NRZ3Z2FF.js +61 -0
- package/dist/chunk-NRZ3Z2FF.js.map +1 -0
- package/dist/chunk-PCPQMC7A.js +26 -0
- package/dist/chunk-PCPQMC7A.js.map +1 -0
- package/dist/chunk-T5BRTFKP.js +53 -0
- package/dist/chunk-T5BRTFKP.js.map +1 -0
- package/dist/chunk-TGKDS2T7.cjs +330 -0
- package/dist/chunk-TGKDS2T7.cjs.map +1 -0
- package/dist/chunk-TLNRFAQ6.js +326 -0
- package/dist/chunk-TLNRFAQ6.js.map +1 -0
- package/dist/chunk-VKQPOZDJ.cjs +72 -0
- package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
- package/dist/chunk-ZWB6QDGF.js +374 -0
- package/dist/chunk-ZWB6QDGF.js.map +1 -0
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.d.cts +3 -1
- package/dist/client/node.d.ts +3 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +14 -302
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +9 -33
- package/dist/client.d.ts +9 -33
- package/dist/client.js +2 -2
- package/dist/document-CU3muGbz.d.cts +169 -0
- package/dist/document-UFbAd-Ka.d.ts +169 -0
- package/dist/env-CY8EGWnD.d.cts +24 -0
- package/dist/env-DEPqqHEb.d.ts +24 -0
- package/dist/index-BuDuOSyx.d.cts +130 -0
- package/dist/index-BuDuOSyx.d.ts +130 -0
- package/dist/index.cjs +45 -3916
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -100
- package/dist/index.d.ts +46 -100
- package/dist/index.js +4 -94
- package/dist/index.js.map +1 -1
- package/dist/integrations.cjs +975 -0
- package/dist/integrations.cjs.map +1 -0
- package/dist/integrations.d.cts +63 -0
- package/dist/integrations.d.ts +63 -0
- package/dist/integrations.js +972 -0
- package/dist/integrations.js.map +1 -0
- package/dist/messages-CSwCJgH3.d.cts +51 -0
- package/dist/messages-CSwCJgH3.d.ts +51 -0
- package/dist/node.cjs +17 -3455
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +13 -10
- package/dist/node.d.ts +13 -10
- package/dist/node.js +5 -3
- package/dist/protocol.cjs +24 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +11 -0
- package/dist/protocol.d.ts +11 -0
- package/dist/protocol.js +3 -0
- package/dist/protocol.js.map +1 -0
- package/dist/slots-96gNc9uH.d.cts +12 -0
- package/dist/slots-BX5N0Juv.d.ts +14 -0
- package/dist/slots-CU-AbnJg.d.cts +14 -0
- package/dist/slots-sLXDrlbG.d.ts +12 -0
- package/dist/socket-D90h1xSV.d.cts +24 -0
- package/dist/socket-D90h1xSV.d.ts +24 -0
- package/dist/targets-DInbLzff.d.cts +9 -0
- package/dist/targets-DInbLzff.d.ts +9 -0
- package/dist/terminal/dom/index.cjs +8 -3
- package/dist/terminal/dom/index.cjs.map +1 -1
- package/dist/terminal/dom/index.d.cts +3 -0
- package/dist/terminal/dom/index.d.ts +3 -0
- package/dist/terminal/dom/index.js +8 -3
- package/dist/terminal/dom/index.js.map +1 -1
- package/dist/terminal/dom/server.cjs +2 -7
- package/dist/terminal/dom/server.cjs.map +1 -1
- package/dist/terminal/dom/server.d.cts +3 -5
- package/dist/terminal/dom/server.d.ts +3 -5
- package/dist/terminal/dom/server.js +2 -7
- package/dist/terminal/dom/server.js.map +1 -1
- package/dist/terminal/index.cjs +22 -300
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.d.cts +7 -2
- package/dist/terminal/index.d.ts +7 -2
- package/dist/terminal/index.js +21 -22
- package/dist/terminal/index.js.map +1 -1
- package/dist/terminal/ink/index.d.ts +3 -2
- package/dist/terminal/ink/index.js +149 -106
- package/dist/terminal/ink/index.js.map +1 -1
- package/dist/terminal/react/index.cjs +21 -71
- package/dist/terminal/react/index.cjs.map +1 -1
- package/dist/terminal/react/index.d.cts +5 -2
- package/dist/terminal/react/index.d.ts +5 -2
- package/dist/terminal/react/index.js +17 -20
- package/dist/terminal/react/index.js.map +1 -1
- package/dist/terminal/react/server.cjs +4 -68
- package/dist/terminal/react/server.cjs.map +1 -1
- package/dist/terminal/react/server.d.cts +9 -6
- package/dist/terminal/react/server.d.ts +9 -6
- package/dist/terminal/react/server.js +3 -18
- package/dist/terminal/react/server.js.map +1 -1
- package/dist/terminal/tty/index.cjs +147 -130
- package/dist/terminal/tty/index.cjs.map +1 -1
- package/dist/terminal/tty/index.d.cts +4 -2
- package/dist/terminal/tty/index.d.ts +4 -2
- package/dist/terminal/tty/index.js +147 -130
- package/dist/terminal/tty/index.js.map +1 -1
- package/dist/terminal/vue/index.cjs +20 -72
- package/dist/terminal/vue/index.cjs.map +1 -1
- package/dist/terminal/vue/index.d.cts +8 -12
- package/dist/terminal/vue/index.d.ts +8 -12
- package/dist/terminal/vue/index.js +45 -1
- package/dist/terminal/vue/index.js.map +1 -1
- package/dist/terminal/vue/server.cjs +4 -76
- package/dist/terminal/vue/server.cjs.map +1 -1
- package/dist/terminal/vue/server.d.cts +7 -6
- package/dist/terminal/vue/server.d.ts +7 -6
- package/dist/terminal/vue/server.js +3 -10
- package/dist/terminal/vue/server.js.map +1 -1
- package/dist/tide.cjs +41 -0
- package/dist/tide.cjs.map +1 -0
- package/dist/tide.d.cts +25 -0
- package/dist/tide.d.ts +25 -0
- package/dist/tide.js +39 -0
- package/dist/tide.js.map +1 -0
- package/dist/unverified.cjs +12 -0
- package/dist/unverified.cjs.map +1 -0
- package/dist/unverified.d.cts +7 -0
- package/dist/unverified.d.ts +7 -0
- package/dist/unverified.js +10 -0
- package/dist/unverified.js.map +1 -0
- package/dist/vite.cjs +96 -232
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +6 -8
- package/dist/vite.d.ts +6 -8
- package/dist/vite.js +97 -71
- package/dist/vite.js.map +1 -1
- package/package.json +51 -8
- package/dist/chunk-4T6KAXBP.js +0 -256
- package/dist/chunk-4T6KAXBP.js.map +0 -1
- package/dist/chunk-EMRDIZLY.js +0 -99
- package/dist/chunk-EMRDIZLY.js.map +0 -1
- package/dist/chunk-HOZID4EM.js +0 -366
- package/dist/chunk-HOZID4EM.js.map +0 -1
- package/dist/chunk-R3QMJ3JF.js +0 -3404
- package/dist/chunk-R3QMJ3JF.js.map +0 -1
- package/dist/chunk-SK4PDGEE.js +0 -55
- package/dist/chunk-SK4PDGEE.js.map +0 -1
- package/dist/chunk-U3UR5AOQ.js.map +0 -1
- package/dist/document-DhWxieUc.d.cts +0 -1024
- package/dist/document-DhWxieUc.d.ts +0 -1024
- package/dist/slots-Do9ScG7v.d.cts +0 -37
- package/dist/slots-Do9ScG7v.d.ts +0 -37
|
@@ -0,0 +1,2716 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkFTFME3HS_cjs = require('./chunk-FTFME3HS.cjs');
|
|
4
|
+
var chunkJYBHJDT7_cjs = require('./chunk-JYBHJDT7.cjs');
|
|
5
|
+
var chunk3RIWTXGI_cjs = require('./chunk-3RIWTXGI.cjs');
|
|
6
|
+
var zod = require('zod');
|
|
7
|
+
var crypto$1 = require('crypto');
|
|
8
|
+
var charter = require('@niscorp/charter');
|
|
9
|
+
var nova = require('@niscorp/nova');
|
|
10
|
+
var reflect = require('@niscorp/nova/reflect');
|
|
11
|
+
var strata = require('@niscorp/strata');
|
|
12
|
+
var vex = require('@niscorp/vex');
|
|
13
|
+
var i18n = require('@niscorp/nova/i18n');
|
|
14
|
+
var prism = require('@niscorp/prism');
|
|
15
|
+
var postgres = require('@niscorp/strata/postgres');
|
|
16
|
+
var migrations = require('@niscorp/nova/migrations');
|
|
17
|
+
var migrations$1 = require('@niscorp/prism/migrations');
|
|
18
|
+
var hono = require('hono');
|
|
19
|
+
var hono$1 = require('@niscorp/vex/hono');
|
|
20
|
+
var async_hooks = require('async_hooks');
|
|
21
|
+
var document = require('@niscorp/nova/document');
|
|
22
|
+
|
|
23
|
+
// src/manifest/app.ts
|
|
24
|
+
var defineApp = (app) => app;
|
|
25
|
+
var tokenFromCookie = (header, name = chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY) => {
|
|
26
|
+
if (header === void 0 || header === null) return null;
|
|
27
|
+
const wanted = encodeURIComponent(name);
|
|
28
|
+
for (const part of header.split(";")) {
|
|
29
|
+
const at = part.indexOf("=");
|
|
30
|
+
if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
|
|
31
|
+
try {
|
|
32
|
+
const value = decodeURIComponent(part.slice(at + 1).trim());
|
|
33
|
+
return value === "" ? null : value;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
var ownOriginOf = (origin, host, listed = []) => {
|
|
41
|
+
if (origin === void 0 || origin === null || !URL.canParse(origin)) return void 0;
|
|
42
|
+
const asked = new URL(origin);
|
|
43
|
+
const own = asked.host === host?.toLowerCase() || listed.some((entry2) => URL.canParse(entry2) && new URL(entry2).origin === asked.origin);
|
|
44
|
+
return own ? asked : void 0;
|
|
45
|
+
};
|
|
46
|
+
var cookiesAt = (where, key, token, lastsMs) => {
|
|
47
|
+
const name = encodeURIComponent(chunk3RIWTXGI_cjs.sessionNameOf(key, where.port));
|
|
48
|
+
const life = token === null ? "; Max-Age=0" : typeof lastsMs === "number" ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1e3))}` : "";
|
|
49
|
+
const kept = `Path=/; SameSite=Lax${where.secure ? "; Secure" : ""}${life}`;
|
|
50
|
+
return [`${where.secure ? "__Host-" : ""}${name}=${encodeURIComponent(token ?? "")}; HttpOnly; ${kept}`, `${name}.held=${token === null ? "" : "1"}; ${kept}`];
|
|
51
|
+
};
|
|
52
|
+
var originOf = (request) => {
|
|
53
|
+
const said = request.headers.get("origin");
|
|
54
|
+
if (said !== null && URL.canParse(said)) return said;
|
|
55
|
+
const here = new URL(request.url);
|
|
56
|
+
const scheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || here.protocol.slice(0, -1);
|
|
57
|
+
return `${scheme}://${request.headers.get("host") ?? here.host}`;
|
|
58
|
+
};
|
|
59
|
+
var sessionCookies = (page, token, options = {}) => {
|
|
60
|
+
const at = new URL(typeof page === "string" ? page : originOf(page));
|
|
61
|
+
return cookiesAt({ port: at.port, secure: at.protocol === "https:" }, options.key ?? chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY, token, options.lastsMs);
|
|
62
|
+
};
|
|
63
|
+
var sessionTokenOf = (cookies, where, key = chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY) => {
|
|
64
|
+
const name = chunk3RIWTXGI_cjs.sessionNameOf(key, where.port);
|
|
65
|
+
for (const secure of where.secure === void 0 ? [true, false] : [where.secure]) {
|
|
66
|
+
const token = tokenFromCookie(cookies, `${secure ? "__Host-" : ""}${name}`);
|
|
67
|
+
if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
};
|
|
71
|
+
var SEALED_FOR_MS = 6e4;
|
|
72
|
+
var SealedSchema = zod.z.object({ token: zod.z.string(), until: zod.z.number() });
|
|
73
|
+
var sealName = (secure) => `${secure ? "__Http-" : ""}nisc.seal`;
|
|
74
|
+
var toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
75
|
+
var fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
|
|
76
|
+
var keyOf = async (seal) => crypto.subtle.importKey("raw", await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seal)), "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
77
|
+
var newSeal = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
78
|
+
var sealOf = (cookies, secure) => tokenFromCookie(cookies, sealName(secure));
|
|
79
|
+
var sealCookie = (seal, where) => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? "; Secure" : ""}`;
|
|
80
|
+
var sealSession = async (seal, token, forMs = SEALED_FOR_MS) => {
|
|
81
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
82
|
+
const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));
|
|
83
|
+
return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));
|
|
84
|
+
};
|
|
85
|
+
var openSealed = async (seal, sealed) => {
|
|
86
|
+
try {
|
|
87
|
+
const bytes = fromBase64Url(sealed);
|
|
88
|
+
const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));
|
|
89
|
+
const inside = SealedSchema.safeParse(JSON.parse(new TextDecoder().decode(opened)));
|
|
90
|
+
return inside.success && inside.data.until > Date.now() ? inside.data.token : null;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var hashSessionToken = (token) => crypto$1.createHash("sha256").update(token).digest("hex");
|
|
96
|
+
var SESSION_TOKEN_PREFIX = "st_";
|
|
97
|
+
var PrincipalRowSchema = zod.z.object({ principal: zod.z.string() });
|
|
98
|
+
var RemainingRowSchema = zod.z.object({ remaining: zod.z.coerce.number() });
|
|
99
|
+
var SESSIONS_SEQUENCE = {
|
|
100
|
+
id: "nisc.moss.sessions",
|
|
101
|
+
migrations: [
|
|
102
|
+
{
|
|
103
|
+
description: "The sessions table: a token is stored only as its hash",
|
|
104
|
+
steps: [
|
|
105
|
+
{
|
|
106
|
+
kind: "sql",
|
|
107
|
+
sql: `CREATE TABLE IF NOT EXISTS sessions (
|
|
108
|
+
token_hash text PRIMARY KEY,
|
|
109
|
+
principal text NOT NULL,
|
|
110
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
111
|
+
expires_at timestamptz NOT NULL
|
|
112
|
+
)`
|
|
113
|
+
}
|
|
114
|
+
]
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
};
|
|
118
|
+
var mintSession = async (pool, principal, ttlMs) => {
|
|
119
|
+
await pool.query("DELETE FROM sessions WHERE expires_at < now()");
|
|
120
|
+
const token = `${SESSION_TOKEN_PREFIX}${crypto$1.randomBytes(32).toString("base64url")}`;
|
|
121
|
+
await pool.query("INSERT INTO sessions (token_hash, principal, expires_at) VALUES ($1, $2, $3)", [hashSessionToken(token), principal, new Date(Date.now() + ttlMs)]);
|
|
122
|
+
return token;
|
|
123
|
+
};
|
|
124
|
+
var sessionOf = async (pool, token) => {
|
|
125
|
+
const res = await pool.query("SELECT principal FROM sessions WHERE token_hash = $1 AND expires_at > now()", [hashSessionToken(token)]);
|
|
126
|
+
const row = PrincipalRowSchema.safeParse(res.rows[0]);
|
|
127
|
+
return row.success ? row.data.principal : null;
|
|
128
|
+
};
|
|
129
|
+
var sessionRemainingMs = async (pool, token) => {
|
|
130
|
+
const res = await pool.query("SELECT extract(epoch from expires_at - now()) * 1000 AS remaining FROM sessions WHERE token_hash = $1 AND expires_at > now()", [hashSessionToken(token)]);
|
|
131
|
+
const row = RemainingRowSchema.safeParse(res.rows[0]);
|
|
132
|
+
return row.success ? row.data.remaining : null;
|
|
133
|
+
};
|
|
134
|
+
var revokeAllFor = async (pool, principal) => {
|
|
135
|
+
await pool.query("DELETE FROM sessions WHERE principal = $1", [principal]);
|
|
136
|
+
};
|
|
137
|
+
var sessionVerifierOf = (runtime) => {
|
|
138
|
+
const chosen = runtime.session;
|
|
139
|
+
if (chosen === void 0) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
"moss: `runtime.session` is unset \u2014 authentication is the one door that must not default open. Choose: 'sessions' (moss's stored credential: mintSession, revokeAllFor), 'dev-open' (every token is trusted; development only), or your own verifier function."
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
if (chosen === "sessions") return (token) => sessionOf(runtime.pool, token);
|
|
145
|
+
if (chosen === "dev-open") {
|
|
146
|
+
console.error("[moss] session: dev-open \u2014 every well-formed token is trusted, and a forged principal walks in. Development only.");
|
|
147
|
+
return devSession;
|
|
148
|
+
}
|
|
149
|
+
console.info(`[moss] session: a function the app supplied${chosen.name === "" ? "" : ` (\`${chosen.name}\`)`} decides who a token is.`);
|
|
150
|
+
return chosen;
|
|
151
|
+
};
|
|
152
|
+
var sessionRevokerOf = (runtime) => runtime.session === "sessions" ? (principal) => revokeAllFor(runtime.pool, principal) : void 0;
|
|
153
|
+
var mintDevToken = (sub, claims = {}) => btoa(JSON.stringify({ sub, ...claims, iat: Date.now() })).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
154
|
+
var DevTokenSchema = zod.z.object({ sub: zod.z.string() });
|
|
155
|
+
var devSession = (token) => {
|
|
156
|
+
try {
|
|
157
|
+
const parsed = DevTokenSchema.safeParse(JSON.parse(atob(token.replace(/-/g, "+").replace(/_/g, "/"))));
|
|
158
|
+
return parsed.success ? parsed.data.sub : null;
|
|
159
|
+
} catch {
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// src/identity/cache.ts
|
|
165
|
+
var DEFAULT_IDENTITY_MAX = 1e4;
|
|
166
|
+
var DEFAULT_IDENTITY_IDLE_MS = 30 * 60 * 1e3;
|
|
167
|
+
var SWEEP_EVERY_MS = 60 * 1e3;
|
|
168
|
+
var createHeldRecords = (max) => {
|
|
169
|
+
const held = /* @__PURE__ */ new Map();
|
|
170
|
+
const tagged = /* @__PURE__ */ new Map();
|
|
171
|
+
let evicted = 0;
|
|
172
|
+
const untag = (principal, record2) => {
|
|
173
|
+
const tag = record2.tag;
|
|
174
|
+
if (tag === void 0) return;
|
|
175
|
+
const group = tagged.get(tag);
|
|
176
|
+
if (group === void 0) return;
|
|
177
|
+
group.delete(principal);
|
|
178
|
+
if (group.size === 0) tagged.delete(tag);
|
|
179
|
+
};
|
|
180
|
+
const forget = (principal) => {
|
|
181
|
+
const entry2 = held.get(principal);
|
|
182
|
+
if (entry2 === void 0) return false;
|
|
183
|
+
untag(principal, entry2.record);
|
|
184
|
+
held.delete(principal);
|
|
185
|
+
return true;
|
|
186
|
+
};
|
|
187
|
+
const evictOldest = () => {
|
|
188
|
+
const oldest = held.keys().next();
|
|
189
|
+
if (oldest.done === true) return;
|
|
190
|
+
forget(oldest.value);
|
|
191
|
+
evicted += 1;
|
|
192
|
+
};
|
|
193
|
+
const remember = (principal, record2, at) => {
|
|
194
|
+
forget(principal);
|
|
195
|
+
while (held.size >= max) evictOldest();
|
|
196
|
+
held.set(principal, { record: record2, since: at, lastSeen: at });
|
|
197
|
+
if (record2.tag !== void 0) {
|
|
198
|
+
const group = tagged.get(record2.tag) ?? /* @__PURE__ */ new Set();
|
|
199
|
+
group.add(principal);
|
|
200
|
+
tagged.set(record2.tag, group);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
return {
|
|
204
|
+
of: (principal) => held.get(principal),
|
|
205
|
+
touch: (principal, entry2, at) => {
|
|
206
|
+
held.delete(principal);
|
|
207
|
+
entry2.lastSeen = at;
|
|
208
|
+
held.set(principal, entry2);
|
|
209
|
+
},
|
|
210
|
+
forget,
|
|
211
|
+
remember,
|
|
212
|
+
forgetAll: () => {
|
|
213
|
+
held.clear();
|
|
214
|
+
tagged.clear();
|
|
215
|
+
},
|
|
216
|
+
forgetTag: (tag) => {
|
|
217
|
+
const principals = [...tagged.get(tag) ?? []];
|
|
218
|
+
for (const principal of principals) forget(principal);
|
|
219
|
+
return principals;
|
|
220
|
+
},
|
|
221
|
+
forgetIdle: (at, idleMs) => {
|
|
222
|
+
for (const [principal, entry2] of [...held]) {
|
|
223
|
+
if (at - entry2.lastSeen >= idleMs) {
|
|
224
|
+
forget(principal);
|
|
225
|
+
evicted += 1;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
list: () => [...held].map(([principal, entry2]) => ({ principal, since: entry2.since, lastSeen: entry2.lastSeen })),
|
|
230
|
+
size: () => held.size,
|
|
231
|
+
evicted: () => evicted
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
var createIdentityCache = (ctx) => {
|
|
235
|
+
const max = ctx.max ?? DEFAULT_IDENTITY_MAX;
|
|
236
|
+
if (max <= 0) {
|
|
237
|
+
throw new Error(`moss: \`runtime.identityMax\` is ${max}, and the identity cache needs room for at least one record. Give it 1 or more, or leave it unset for ${DEFAULT_IDENTITY_MAX}.`);
|
|
238
|
+
}
|
|
239
|
+
const idleMs = ctx.idleMs ?? DEFAULT_IDENTITY_IDLE_MS;
|
|
240
|
+
const revalidateMs = ctx.revalidateMs ?? 0;
|
|
241
|
+
const now = ctx.now ?? Date.now;
|
|
242
|
+
const held = createHeldRecords(max);
|
|
243
|
+
const pending = /* @__PURE__ */ new Map();
|
|
244
|
+
let resolved = 0;
|
|
245
|
+
let expired = 0;
|
|
246
|
+
const get = async (principal) => {
|
|
247
|
+
const at = now();
|
|
248
|
+
const hit = held.of(principal);
|
|
249
|
+
if (hit !== void 0) {
|
|
250
|
+
const stale = revalidateMs > 0 && at - hit.since >= revalidateMs;
|
|
251
|
+
if (!stale) {
|
|
252
|
+
held.touch(principal, hit, at);
|
|
253
|
+
return hit.record;
|
|
254
|
+
}
|
|
255
|
+
expired += 1;
|
|
256
|
+
}
|
|
257
|
+
const inFlight = pending.get(principal);
|
|
258
|
+
if (inFlight !== void 0) return inFlight.work;
|
|
259
|
+
const forgotten = /* @__PURE__ */ new Set();
|
|
260
|
+
const isStillOut = () => pending.get(principal)?.work === work;
|
|
261
|
+
const work = ctx.resolve(principal).then((record2) => {
|
|
262
|
+
resolved += 1;
|
|
263
|
+
const wearsForgottenTag = record2.tag !== void 0 && forgotten.has(record2.tag);
|
|
264
|
+
if (isStillOut() && !wearsForgottenTag) held.remember(principal, record2, now());
|
|
265
|
+
return record2;
|
|
266
|
+
}).finally(() => {
|
|
267
|
+
if (isStillOut()) pending.delete(principal);
|
|
268
|
+
});
|
|
269
|
+
pending.set(principal, { work, forgotten });
|
|
270
|
+
return work;
|
|
271
|
+
};
|
|
272
|
+
const sweep2 = idleMs > 0 ? setInterval(() => held.forgetIdle(now(), idleMs), Math.min(SWEEP_EVERY_MS, idleMs)) : void 0;
|
|
273
|
+
sweep2?.unref?.();
|
|
274
|
+
return {
|
|
275
|
+
get,
|
|
276
|
+
invalidate: (principal) => {
|
|
277
|
+
pending.delete(principal);
|
|
278
|
+
return held.forget(principal);
|
|
279
|
+
},
|
|
280
|
+
invalidateAll: () => {
|
|
281
|
+
held.forgetAll();
|
|
282
|
+
pending.clear();
|
|
283
|
+
},
|
|
284
|
+
invalidateTag: (tag) => {
|
|
285
|
+
const principals = held.forgetTag(tag);
|
|
286
|
+
for (const principal of principals) pending.delete(principal);
|
|
287
|
+
for (const flight of pending.values()) flight.forgotten.add(tag);
|
|
288
|
+
return principals;
|
|
289
|
+
},
|
|
290
|
+
list: held.list,
|
|
291
|
+
meter: () => ({ size: held.size(), max, resolved, evicted: held.evicted(), expired }),
|
|
292
|
+
stop: () => {
|
|
293
|
+
if (sweep2 !== void 0) clearInterval(sweep2);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
};
|
|
297
|
+
var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
|
|
298
|
+
var assignedRoles = (assignments, principal) => principal === null ? ["public"] : assignments?.[principal] ?? ["public"];
|
|
299
|
+
var IdentityRecordSchema = zod.z.looseObject({
|
|
300
|
+
roles: zod.z.array(zod.z.string()),
|
|
301
|
+
scope: zod.z.record(zod.z.string(), zod.z.unknown()),
|
|
302
|
+
installed: zod.z.array(zod.z.string()).optional(),
|
|
303
|
+
tag: zod.z.string().optional()
|
|
304
|
+
});
|
|
305
|
+
var recordRefusal = (issues) => new Error(
|
|
306
|
+
`moss: \`identity.resolve\` did not answer an identity record (${issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")}). A record is { roles: string[], scope: {\u2026}, installed?: string[], tag?: string }.`
|
|
307
|
+
);
|
|
308
|
+
var resolveThrough = (seam2, readAs) => async (principal) => {
|
|
309
|
+
const role = seam2.as;
|
|
310
|
+
const read2 = async (fingerprint, scope) => {
|
|
311
|
+
if (role === void 0) throw new Error("moss: identity.read needs identity.as \u2014 name the charter role the reader executes as");
|
|
312
|
+
return readAs(role, fingerprint, scope);
|
|
313
|
+
};
|
|
314
|
+
const answered = IdentityRecordSchema.safeParse(await seam2.resolve(principal, read2));
|
|
315
|
+
if (!answered.success) throw recordRefusal(answered.error.issues);
|
|
316
|
+
return answered.data;
|
|
317
|
+
};
|
|
318
|
+
var createIdentity = (config) => {
|
|
319
|
+
const seam2 = config.seam;
|
|
320
|
+
const cache = seam2 === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam2, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
|
|
321
|
+
const keys = /* @__PURE__ */ new WeakMap();
|
|
322
|
+
const keyOf2 = (record2) => {
|
|
323
|
+
const hit = keys.get(record2);
|
|
324
|
+
if (hit !== void 0) return hit;
|
|
325
|
+
const key = memoKey(record2.roles, record2.installed);
|
|
326
|
+
keys.set(record2, key);
|
|
327
|
+
return key;
|
|
328
|
+
};
|
|
329
|
+
const fromAssignments = (principal) => {
|
|
330
|
+
const roles = assignedRoles(config.assignments, principal);
|
|
331
|
+
return { roles, scope: {}, installed: void 0, memoKey: memoKey(roles, void 0) };
|
|
332
|
+
};
|
|
333
|
+
const resolve2 = async (principal) => {
|
|
334
|
+
if (cache !== void 0 && principal !== null) {
|
|
335
|
+
const record2 = await cache.get(principal);
|
|
336
|
+
return { roles: record2.roles, scope: record2.scope, installed: record2.installed, memoKey: keyOf2(record2), record: record2 };
|
|
337
|
+
}
|
|
338
|
+
return fromAssignments(principal);
|
|
339
|
+
};
|
|
340
|
+
const composeScope = (principal, resolved) => ({
|
|
341
|
+
userId: principal ?? "anonymous",
|
|
342
|
+
...resolved.scope,
|
|
343
|
+
...config.scope?.(principal, resolved.record) ?? {}
|
|
344
|
+
});
|
|
345
|
+
return {
|
|
346
|
+
resolve: resolve2,
|
|
347
|
+
composeScope,
|
|
348
|
+
scopeValuesFor: async (principal) => composeScope(principal, await resolve2(principal)),
|
|
349
|
+
invalidate: (principal) => cache?.invalidate(principal) ?? false,
|
|
350
|
+
invalidateTag: (tag) => cache?.invalidateTag(tag) ?? [],
|
|
351
|
+
invalidateAll: () => cache?.invalidateAll(),
|
|
352
|
+
...cache !== void 0 ? { roster: { list: cache.list, meter: cache.meter } } : {},
|
|
353
|
+
stop: () => cache?.stop()
|
|
354
|
+
};
|
|
355
|
+
};
|
|
356
|
+
var entriesOf = (app) => app.entries ?? [];
|
|
357
|
+
var shellComponents = (manifest, shell2) => {
|
|
358
|
+
const names = /* @__PURE__ */ new Set([nova.CANVAS_SLOT_NAME, nova.ACTION_SLOT_NAME]);
|
|
359
|
+
for (const source of [manifest.actions, manifest.layouts ?? {}, shell2.canvases, shell2.layout ?? {}, shell2.layoutStore ?? {}, shell2.fragments ?? {}]) {
|
|
360
|
+
for (const name of reflect.componentsOf(source)) names.add(name);
|
|
361
|
+
}
|
|
362
|
+
const contracts = shell2.components ?? {};
|
|
363
|
+
for (const name of Object.keys(contracts)) names.add(name);
|
|
364
|
+
return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
|
|
365
|
+
};
|
|
366
|
+
var wearableOf = (app) => {
|
|
367
|
+
const declared = app.wearable;
|
|
368
|
+
const source = declared ?? Object.values(app.assignments ?? {});
|
|
369
|
+
const seen = /* @__PURE__ */ new Map();
|
|
370
|
+
for (const roles of source) {
|
|
371
|
+
const key = [...roles].sort().join("\0");
|
|
372
|
+
if (!seen.has(key)) seen.set(key, roles);
|
|
373
|
+
}
|
|
374
|
+
return [...seen.values()];
|
|
375
|
+
};
|
|
376
|
+
var narrowedBy = (filter, ids, installed) => {
|
|
377
|
+
const answered = new Set(filter(ids, installed));
|
|
378
|
+
return ids.filter((id) => answered.has(id));
|
|
379
|
+
};
|
|
380
|
+
var catalogFor = (app, roles, installed, installedOnly) => {
|
|
381
|
+
const granted = [...charter.resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
|
|
382
|
+
const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
|
|
383
|
+
return { ids, hash: versionToken(ids) };
|
|
384
|
+
};
|
|
385
|
+
var variantLayouts = (variants, held) => {
|
|
386
|
+
const layouts = /* @__PURE__ */ new Map();
|
|
387
|
+
for (const id of held) {
|
|
388
|
+
const variant = variants[id];
|
|
389
|
+
if (variant !== void 0) layouts.set(variant.action, variant.layout);
|
|
390
|
+
}
|
|
391
|
+
return layouts;
|
|
392
|
+
};
|
|
393
|
+
var resolveVariantsForRoles = (app, roles) => {
|
|
394
|
+
const variants = app.layouts ?? {};
|
|
395
|
+
return variantLayouts(variants, charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
|
|
396
|
+
};
|
|
397
|
+
var withVariants = (actions, ids, layouts) => ids.flatMap((id) => {
|
|
398
|
+
const definition = actions[id];
|
|
399
|
+
if (definition === void 0) return [];
|
|
400
|
+
const layout2 = layouts.get(id);
|
|
401
|
+
return [[id, layout2 === void 0 ? definition : { ...definition, layout: layout2 }]];
|
|
402
|
+
});
|
|
403
|
+
var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
|
|
404
|
+
var createRoleMemo = (config) => {
|
|
405
|
+
const catalogs = /* @__PURE__ */ new Map();
|
|
406
|
+
const variants = /* @__PURE__ */ new Map();
|
|
407
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
408
|
+
const kept = (memo, key, resolve2) => {
|
|
409
|
+
const hit = memo.get(key);
|
|
410
|
+
if (hit !== void 0) return hit;
|
|
411
|
+
const resolved = resolve2();
|
|
412
|
+
memo.set(key, resolved);
|
|
413
|
+
return resolved;
|
|
414
|
+
};
|
|
415
|
+
const roleMemo = {
|
|
416
|
+
catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
|
|
417
|
+
variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
|
|
418
|
+
definitionsFor: (roles, installed) => kept(definitions, memoKey(roles, installed), () => definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles))),
|
|
419
|
+
drop: () => {
|
|
420
|
+
catalogs.clear();
|
|
421
|
+
variants.clear();
|
|
422
|
+
definitions.clear();
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
return roleMemo;
|
|
426
|
+
};
|
|
427
|
+
var versionToken = (ids) => {
|
|
428
|
+
const s = ids.join("\n");
|
|
429
|
+
let h = 2166136261;
|
|
430
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
431
|
+
h ^= s.charCodeAt(i);
|
|
432
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
433
|
+
}
|
|
434
|
+
return h.toString(16).padStart(8, "0");
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
// src/manifest/verify.ts
|
|
438
|
+
var candidateOf = (shipped, inForce, grants) => ({
|
|
439
|
+
charter: shipped.charter,
|
|
440
|
+
actions: inForce.actions,
|
|
441
|
+
layouts: shipped.layouts ?? {},
|
|
442
|
+
wearable: wearableOf(shipped),
|
|
443
|
+
grants,
|
|
444
|
+
entries: inForce.entries,
|
|
445
|
+
profiles: vex.scopeProfiles(shipped.behaviors ?? {})
|
|
446
|
+
});
|
|
447
|
+
var unreadActions = (actions) => Object.entries(actions).flatMap(([id, definition]) => {
|
|
448
|
+
if (strata.exceedsDepth(definition)) return [{ id, why: strata.depthRefusal() }];
|
|
449
|
+
const parsed = nova.ActionDefinitionSchema.safeParse(definition);
|
|
450
|
+
if (parsed.success) return [];
|
|
451
|
+
const first = parsed.error.issues[0];
|
|
452
|
+
return [{ id, why: first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}` }];
|
|
453
|
+
});
|
|
454
|
+
var reachErrors = (entries, profiles) => {
|
|
455
|
+
const unknown = entries.flatMap((entry2) => entry2.reach !== void 0 && !profiles.has(entry2.reach) ? [`${entry2.fingerprint} declares reach "${entry2.reach}"`] : []);
|
|
456
|
+
return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(", ") || "(none)"}`];
|
|
457
|
+
};
|
|
458
|
+
var endlessChains = (actions) => reflect.chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));
|
|
459
|
+
var verifyManifest = (candidate) => {
|
|
460
|
+
const unread = unreadActions(candidate.actions);
|
|
461
|
+
const refused = new Set(unread.map((action) => action.id));
|
|
462
|
+
const read2 = refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };
|
|
463
|
+
const charter$1 = charter.verifyCharter(
|
|
464
|
+
read2.charter,
|
|
465
|
+
{ actions: Object.keys(read2.actions), data: read2.grants, layouts: Object.keys(read2.layouts) },
|
|
466
|
+
read2.wearable,
|
|
467
|
+
auditClosure(read2.actions, read2.layouts)
|
|
468
|
+
);
|
|
469
|
+
const found = (check, details) => details.map((detail) => ({ check, detail }));
|
|
470
|
+
return {
|
|
471
|
+
errors: [
|
|
472
|
+
...found("actions", unread.map((action) => `"${action.id}" is not an action nova reads: ${action.why}`)),
|
|
473
|
+
...found("charter", charter$1.errors.map((error) => `${error.rule}: ${error.detail}`)),
|
|
474
|
+
...found("reach", reachErrors(read2.entries, read2.profiles)),
|
|
475
|
+
...found("variants", verifyVariants(read2))
|
|
476
|
+
],
|
|
477
|
+
said: endlessChains(read2.actions).map((chain) => `a chain of steps that never ends: ${chain.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),
|
|
478
|
+
charter: charter$1
|
|
479
|
+
};
|
|
480
|
+
};
|
|
481
|
+
var verifyApp = (app, grants) => verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));
|
|
482
|
+
var HEADLINES = {
|
|
483
|
+
boot: {
|
|
484
|
+
actions: "Actions are not ones nova reads \u2014 refusing to serve:",
|
|
485
|
+
charter: "Charter is incoherent \u2014 refusing to serve:",
|
|
486
|
+
reach: "Entries declare a reach no table offers \u2014 refusing to serve:",
|
|
487
|
+
variants: "Layout variants are incoherent \u2014 refusing to serve:"
|
|
488
|
+
},
|
|
489
|
+
refresh: {
|
|
490
|
+
actions: "Refresh refused \u2014 actions nova does not read:",
|
|
491
|
+
charter: "Refresh refused \u2014 charter incoherent over the new artifacts:",
|
|
492
|
+
reach: "Refresh refused \u2014 entries declare a reach no table offers:",
|
|
493
|
+
variants: "Refresh refused \u2014 layout variants incoherent:"
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
var refusalOf = (report, moment) => {
|
|
497
|
+
const first = report.errors[0];
|
|
498
|
+
if (first === void 0) return void 0;
|
|
499
|
+
const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);
|
|
500
|
+
return [HEADLINES[moment][first.check], ...findings].join("\n");
|
|
501
|
+
};
|
|
502
|
+
var verifyVariants = (app) => {
|
|
503
|
+
const variants = app.layouts ?? {};
|
|
504
|
+
const ids = Object.keys(variants);
|
|
505
|
+
if (ids.length === 0) return [];
|
|
506
|
+
const errors = [];
|
|
507
|
+
for (const [id, variant] of Object.entries(variants)) {
|
|
508
|
+
if (app.actions[variant.action] === void 0) {
|
|
509
|
+
errors.push(`layout variant "${id}" reshapes unknown action "${variant.action}"`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const wearers = /* @__PURE__ */ new Map();
|
|
513
|
+
for (const role of Object.keys(app.charter)) wearers.set(`role "${role}"`, [role]);
|
|
514
|
+
for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(", ")}]`, roles);
|
|
515
|
+
wearers.set("the anonymous principal", ["public"]);
|
|
516
|
+
for (const [who, roles] of wearers) {
|
|
517
|
+
let granted;
|
|
518
|
+
try {
|
|
519
|
+
granted = charter.resolvePrincipal(app.charter, ids, roles, "layouts");
|
|
520
|
+
} catch {
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
const byAction = /* @__PURE__ */ new Map();
|
|
524
|
+
for (const id of granted) {
|
|
525
|
+
const variant = variants[id];
|
|
526
|
+
if (variant !== void 0) byAction.set(variant.action, [...byAction.get(variant.action) ?? [], id]);
|
|
527
|
+
}
|
|
528
|
+
for (const [action, held] of byAction) {
|
|
529
|
+
if (held.length > 1) {
|
|
530
|
+
errors.push(`${who} holds ${held.length} variants of "${action}" (${held.sort().join(", ")}) \u2014 one variant per action per principal`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return errors;
|
|
535
|
+
};
|
|
536
|
+
var auditClosure = (definitions, variants = {}) => {
|
|
537
|
+
return (grantedIds, layoutIds = []) => {
|
|
538
|
+
const granted = withVariants(definitions, grantedIds, variantLayouts(variants, layoutIds)).map(([, definition]) => definition);
|
|
539
|
+
const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));
|
|
540
|
+
const channels = [
|
|
541
|
+
...new Set(
|
|
542
|
+
granted.flatMap((definition) => {
|
|
543
|
+
const found = nova.collectChannels(definition);
|
|
544
|
+
return [...found.emits, ...found.listens];
|
|
545
|
+
})
|
|
546
|
+
)
|
|
547
|
+
];
|
|
548
|
+
const issues = [];
|
|
549
|
+
for (const definition of granted) {
|
|
550
|
+
const audit = nova.auditAction(definition, { catalog, channels });
|
|
551
|
+
if (audit.ok) continue;
|
|
552
|
+
for (const issue of audit.issues) {
|
|
553
|
+
if (issue.includes("which is not in the catalog") && !issue.includes("{{")) issues.push(`${definition.id}: ${issue}`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return issues;
|
|
557
|
+
};
|
|
558
|
+
};
|
|
559
|
+
var isDeferred = (value) => typeof value === "string" && i18n.isBinding(value) || reflect.isRecord(value) && Object.keys(value).some((key) => key.startsWith("$"));
|
|
560
|
+
var layoutMisfits = (layout2, components) => {
|
|
561
|
+
const found = /* @__PURE__ */ new Set();
|
|
562
|
+
reflect.walkNodes(layout2, (record2) => {
|
|
563
|
+
const name = record2["component"];
|
|
564
|
+
if (typeof name !== "string") return;
|
|
565
|
+
const spec = components.get(name);
|
|
566
|
+
if (spec === void 0) {
|
|
567
|
+
found.add(`layout uses "${name}", which this app has no component for`);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const schema = spec.propsSchema;
|
|
571
|
+
const props = record2["props"];
|
|
572
|
+
if (!(schema instanceof zod.z.ZodObject) || !reflect.isRecord(props)) return;
|
|
573
|
+
const shape = schema.shape;
|
|
574
|
+
for (const [key, value] of Object.entries(props)) {
|
|
575
|
+
const prop = shape[key];
|
|
576
|
+
if (prop === void 0) {
|
|
577
|
+
found.add(`"${name}" has no prop "${key}"`);
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (isDeferred(value)) continue;
|
|
581
|
+
const check = zod.z.safeParse(prop, value);
|
|
582
|
+
if (!check.success) found.add(`"${name}" prop "${key}" \u2014 ${check.error.issues[0]?.message ?? "invalid"}`);
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
return [...found];
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
// src/manifest/generation.ts
|
|
589
|
+
var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
|
|
590
|
+
var MAX_INTERVAL_MS = 2 ** 31 - 1;
|
|
591
|
+
var MOVE_ATTEMPTS = 5;
|
|
592
|
+
var createGeneration = (pointer, ctx) => {
|
|
593
|
+
const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
|
|
594
|
+
let seen = -1;
|
|
595
|
+
let checking = false;
|
|
596
|
+
const poll = async () => {
|
|
597
|
+
if (checking) return;
|
|
598
|
+
checking = true;
|
|
599
|
+
try {
|
|
600
|
+
const n = await readPointer();
|
|
601
|
+
if (n === void 0 || n === seen) return;
|
|
602
|
+
if (seen !== -1 && !await follow(n)) return;
|
|
603
|
+
seen = n;
|
|
604
|
+
} finally {
|
|
605
|
+
checking = false;
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
const readPointer = async () => {
|
|
609
|
+
try {
|
|
610
|
+
return await pointer.read();
|
|
611
|
+
} catch (err) {
|
|
612
|
+
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
613
|
+
return void 0;
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
let unfollowed;
|
|
617
|
+
const follow = async (n) => {
|
|
618
|
+
try {
|
|
619
|
+
await ctx.onMoved();
|
|
620
|
+
} catch (err) {
|
|
621
|
+
const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
|
|
622
|
+
if (unfollowed?.said !== what) {
|
|
623
|
+
console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
|
|
624
|
+
}
|
|
625
|
+
unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
if (unfollowed !== void 0) {
|
|
629
|
+
console.log(
|
|
630
|
+
`[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
|
|
631
|
+
);
|
|
632
|
+
unfollowed = void 0;
|
|
633
|
+
}
|
|
634
|
+
return true;
|
|
635
|
+
};
|
|
636
|
+
const move = async () => {
|
|
637
|
+
for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
|
|
638
|
+
const n = await pointer.read();
|
|
639
|
+
if (await pointer.move(n)) {
|
|
640
|
+
if (seen === n || seen === -1) seen = n + 1;
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
|
|
645
|
+
};
|
|
646
|
+
void poll();
|
|
647
|
+
const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
|
|
648
|
+
timer?.unref?.();
|
|
649
|
+
return {
|
|
650
|
+
bump: () => {
|
|
651
|
+
void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
|
|
652
|
+
},
|
|
653
|
+
current: () => seen,
|
|
654
|
+
stop: () => {
|
|
655
|
+
if (timer !== void 0) clearInterval(timer);
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
};
|
|
659
|
+
var seam = zod.z.custom((value) => typeof value === "function", "expected a function");
|
|
660
|
+
var depthChecked = (schema) => zod.z.unknown().refine((value) => !strata.exceedsDepth(value), { message: strata.depthRefusal(), abort: true }).pipe(schema);
|
|
661
|
+
var strings = zod.z.array(zod.z.string()).readonly();
|
|
662
|
+
var record = zod.z.record(zod.z.string(), zod.z.unknown());
|
|
663
|
+
var layout = depthChecked(nova.LayoutNodeSchema);
|
|
664
|
+
var LayoutVariantSchema = zod.z.object({ action: zod.z.string(), layout }).strict();
|
|
665
|
+
var CanvasSeedSchema = zod.z.union([zod.z.string(), zod.z.object({ action: zod.z.string(), input: record.optional(), with: strings.optional() }).strict()]);
|
|
666
|
+
var CanvasSchema = zod.z.object({
|
|
667
|
+
id: zod.z.string(),
|
|
668
|
+
mode: zod.z.enum(["stack", "list"]).optional(),
|
|
669
|
+
actionLayout: zod.z.union([zod.z.string(), layout]).optional(),
|
|
670
|
+
initial: zod.z.union([CanvasSeedSchema, zod.z.array(CanvasSeedSchema)]).optional()
|
|
671
|
+
}).strict();
|
|
672
|
+
var ComponentContractSchema = zod.z.looseObject({ meta: zod.z.looseObject({ description: zod.z.string().optional() }).optional() });
|
|
673
|
+
var shell = {
|
|
674
|
+
canvases: zod.z.array(CanvasSchema),
|
|
675
|
+
layout: layout.optional(),
|
|
676
|
+
layoutStore: zod.z.record(zod.z.string(), layout).optional(),
|
|
677
|
+
fragments: zod.z.record(zod.z.string(), depthChecked(nova.ActionFragmentSchema)).optional(),
|
|
678
|
+
seeds: seam.optional(),
|
|
679
|
+
components: zod.z.record(zod.z.string(), ComponentContractSchema).optional(),
|
|
680
|
+
inputs: seam.optional()
|
|
681
|
+
};
|
|
682
|
+
var ShellManifestSchema = zod.z.object(shell).strict();
|
|
683
|
+
var PageManifestSchema = zod.z.object({ ...shell, path: zod.z.string(), params: zod.z.string().optional() }).strict();
|
|
684
|
+
var entry = { fingerprint: zod.z.string(), intent: zod.z.string().optional(), reach: zod.z.string().optional() };
|
|
685
|
+
var ReadEntrySchema = zod.z.object({
|
|
686
|
+
...entry,
|
|
687
|
+
shape: zod.z.unknown().optional(),
|
|
688
|
+
dsl: depthChecked(vex.QuerySchema),
|
|
689
|
+
mapping: depthChecked(prism.ConfigSchema).optional(),
|
|
690
|
+
refresh: zod.z.enum(vex.REFRESH_MODES).optional()
|
|
691
|
+
}).strict();
|
|
692
|
+
var WriteEntrySchema = zod.z.object({ ...entry, mutation: depthChecked(vex.MutationDefinitionSchema) }).strict();
|
|
693
|
+
var FeatureSchema = zod.z.looseObject({
|
|
694
|
+
name: zod.z.string(),
|
|
695
|
+
tables: zod.z.object({ names: strings, sequences: zod.z.array(strata.SequenceSchema).readonly().optional() }).strict().optional(),
|
|
696
|
+
start: seam
|
|
697
|
+
});
|
|
698
|
+
var ReactionSchema = zod.z.object({ table: zod.z.string(), op: zod.z.enum(["insert", "update", "delete"]).optional(), run: seam }).strict();
|
|
699
|
+
var fields = {
|
|
700
|
+
charter: record,
|
|
701
|
+
assignments: zod.z.record(zod.z.string(), strings).optional(),
|
|
702
|
+
wearable: zod.z.array(strings).readonly().optional(),
|
|
703
|
+
actions: zod.z.record(zod.z.string(), depthChecked(nova.ActionDefinitionSchema)),
|
|
704
|
+
layouts: zod.z.record(zod.z.string(), LayoutVariantSchema).optional(),
|
|
705
|
+
behaviors: zod.z.record(zod.z.string(), record).optional(),
|
|
706
|
+
scope: seam.optional(),
|
|
707
|
+
identity: zod.z.object({ as: zod.z.string().optional(), resolve: seam }).strict().optional(),
|
|
708
|
+
phrases: seam.optional(),
|
|
709
|
+
phraseKeys: zod.z.object({ props: strings.optional(), suffixes: strings.optional(), text: zod.z.boolean().optional() }).strict().optional(),
|
|
710
|
+
features: zod.z.array(FeatureSchema).readonly().optional(),
|
|
711
|
+
entries: zod.z.array(zod.z.union([ReadEntrySchema, WriteEntrySchema])).readonly().optional(),
|
|
712
|
+
resources: zod.z.record(zod.z.string(), zod.z.union([strings, zod.z.looseObject({ entities: strings })])).optional(),
|
|
713
|
+
shell: ShellManifestSchema.optional(),
|
|
714
|
+
pages: zod.z.record(zod.z.string(), PageManifestSchema).optional(),
|
|
715
|
+
grammars: zod.z.array(strata.SequenceSchema).readonly().optional(),
|
|
716
|
+
functions: seam.optional(),
|
|
717
|
+
onSession: seam.optional(),
|
|
718
|
+
runs: seam.optional(),
|
|
719
|
+
reactions: zod.z.array(ReactionSchema).readonly().optional()
|
|
720
|
+
};
|
|
721
|
+
var ManifestSchema = zod.z.object(fields).strict();
|
|
722
|
+
var placesOf = (issue, under) => {
|
|
723
|
+
const path = [...under, ...issue.path];
|
|
724
|
+
if (issue.code !== "invalid_union") return [{ path, message: issue.message }];
|
|
725
|
+
const branches = issue.errors.map((branch) => branch.flatMap((inner) => placesOf(inner, path))).filter((branch) => branch.length > 0);
|
|
726
|
+
const reach = (places) => Math.max(...places.map((place) => place.path.length));
|
|
727
|
+
const closer = (best, branch) => reach(branch) > reach(best) || reach(branch) === reach(best) && branch.length < best.length ? branch : best;
|
|
728
|
+
const [first, ...others] = branches;
|
|
729
|
+
return first === void 0 ? [{ path, message: issue.message }] : others.reduce(closer, first);
|
|
730
|
+
};
|
|
731
|
+
var manifestMisfits = (app) => {
|
|
732
|
+
const parsed = ManifestSchema.safeParse(app);
|
|
733
|
+
if (parsed.success) return [];
|
|
734
|
+
return parsed.error.issues.flatMap((issue) => placesOf(issue, [])).map((place) => `${place.path.map(String).join(".") || "(the manifest)"}: ${place.message}`);
|
|
735
|
+
};
|
|
736
|
+
var isData = (value) => {
|
|
737
|
+
if (Array.isArray(value)) return true;
|
|
738
|
+
const made = Object.getPrototypeOf(value);
|
|
739
|
+
return made === Object.prototype || made === null;
|
|
740
|
+
};
|
|
741
|
+
var freezeDeep = (data) => {
|
|
742
|
+
const seen = /* @__PURE__ */ new Set();
|
|
743
|
+
const pending = [data];
|
|
744
|
+
while (pending.length > 0) {
|
|
745
|
+
const value = pending.pop();
|
|
746
|
+
if (typeof value !== "object" || value === null || !isData(value) || seen.has(value)) continue;
|
|
747
|
+
seen.add(value);
|
|
748
|
+
Object.freeze(value);
|
|
749
|
+
for (const inner of Object.values(value)) pending.push(inner);
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
var receiveManifest = (app) => {
|
|
753
|
+
const misfits = manifestMisfits(app);
|
|
754
|
+
if (misfits.length > 0) throw new Error(["The manifest does not parse \u2014 refusing to serve:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
|
|
755
|
+
freezeDeep(app);
|
|
756
|
+
};
|
|
757
|
+
|
|
758
|
+
// src/manifest/running.ts
|
|
759
|
+
var mergedActions = (own, sets) => Object.freeze([...sets.values()].reduce((all, set) => ({ ...all, ...set }), { ...own }));
|
|
760
|
+
var tell = (listener) => {
|
|
761
|
+
try {
|
|
762
|
+
listener();
|
|
763
|
+
} catch (error) {
|
|
764
|
+
console.error("[moss:manifest] a listener to a manifest change threw:", error);
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
var createSetOwners = () => {
|
|
768
|
+
const owners = /* @__PURE__ */ new Map();
|
|
769
|
+
const ownerRefusalOf = (source) => {
|
|
770
|
+
const owner = owners.get(source);
|
|
771
|
+
return owner === void 0 ? void 0 : `the set of actions "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
|
|
772
|
+
};
|
|
773
|
+
return {
|
|
774
|
+
ownerRefusalOf,
|
|
775
|
+
claim: (source, owner, handedOver) => {
|
|
776
|
+
const held = owners.get(source);
|
|
777
|
+
if (held !== void 0) throw new Error(`moss: the set of actions "${source}" is ${held}'s, and ${owner} claims it too. A set of actions has one writer.`);
|
|
778
|
+
if (handedOver) throw new Error(`moss: the set of actions "${source}" was handed over by the app, and ${owner} claims it. A set of actions has one writer.`);
|
|
779
|
+
owners.set(source, owner);
|
|
780
|
+
},
|
|
781
|
+
assertAppOwned: (source) => {
|
|
782
|
+
const refusal = ownerRefusalOf(source);
|
|
783
|
+
if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
|
|
784
|
+
return source;
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
};
|
|
788
|
+
var verifiedAtBoot = (candidate) => {
|
|
789
|
+
const report = verifyManifest(candidate);
|
|
790
|
+
for (const line of report.said) console.error(`[moss] ${line}`);
|
|
791
|
+
const refused = refusalOf(report, "boot");
|
|
792
|
+
if (refused !== void 0) throw new Error(refused);
|
|
793
|
+
return report;
|
|
794
|
+
};
|
|
795
|
+
var createComponentNames = (read2) => {
|
|
796
|
+
let components = /* @__PURE__ */ new WeakMap();
|
|
797
|
+
return {
|
|
798
|
+
of: (shell2) => {
|
|
799
|
+
const kept = components.get(shell2);
|
|
800
|
+
if (kept !== void 0) return kept;
|
|
801
|
+
const names = read2(shell2);
|
|
802
|
+
components.set(shell2, names);
|
|
803
|
+
return names;
|
|
804
|
+
},
|
|
805
|
+
drop: () => {
|
|
806
|
+
components = /* @__PURE__ */ new WeakMap();
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
};
|
|
810
|
+
var createRunningManifest = (config) => {
|
|
811
|
+
const { shipped } = config;
|
|
812
|
+
const entries = entriesOf(shipped);
|
|
813
|
+
const candidate = (actions) => candidateOf(shipped, { actions, entries }, config.grants);
|
|
814
|
+
const own = shipped.actions;
|
|
815
|
+
const loaders = /* @__PURE__ */ new Map();
|
|
816
|
+
const owners = createSetOwners();
|
|
817
|
+
let sets = /* @__PURE__ */ new Map();
|
|
818
|
+
let inForce = mergedActions(own, sets);
|
|
819
|
+
let report = verifiedAtBoot(candidate(inForce));
|
|
820
|
+
const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
|
|
821
|
+
const roleMemo = createRoleMemo({
|
|
822
|
+
manifest: () => ({ charter: shipped.charter, actions: inForce, layouts: shipped.layouts }),
|
|
823
|
+
installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
|
|
824
|
+
});
|
|
825
|
+
const components = createComponentNames((shell2) => shellComponents({ actions: inForce, layouts: shipped.layouts }, shell2));
|
|
826
|
+
const byFingerprint = new Map(entries.map((entry2) => [entry2.fingerprint, entry2]));
|
|
827
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
828
|
+
let pointer;
|
|
829
|
+
const applySets = (arrived, announce) => {
|
|
830
|
+
const next = new Map([...sets, ...arrived]);
|
|
831
|
+
const actions = mergedActions(own, next);
|
|
832
|
+
const verified = verifyManifest(candidate(actions));
|
|
833
|
+
const refusal = refusalOf(verified, "refresh");
|
|
834
|
+
if (refusal !== void 0) throw new Error(refusal);
|
|
835
|
+
for (const set of arrived.values()) freezeDeep(set);
|
|
836
|
+
sets = next;
|
|
837
|
+
inForce = actions;
|
|
838
|
+
report = verified;
|
|
839
|
+
roleMemo.drop();
|
|
840
|
+
components.drop();
|
|
841
|
+
for (const listener of [...listeners]) tell(listener);
|
|
842
|
+
if (announce) pointer?.bump();
|
|
843
|
+
};
|
|
844
|
+
const reload = async () => {
|
|
845
|
+
const read2 = [];
|
|
846
|
+
for (const [source, load] of loaders) read2.push([source, await load()]);
|
|
847
|
+
applySets(new Map(read2), false);
|
|
848
|
+
};
|
|
849
|
+
return {
|
|
850
|
+
actions: () => inForce,
|
|
851
|
+
entries: () => entries,
|
|
852
|
+
verify: (actions) => verifyManifest(candidate(actions)),
|
|
853
|
+
report: () => report,
|
|
854
|
+
replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
|
|
855
|
+
claim: (source, owner) => {
|
|
856
|
+
owners.claim(source, owner, sets.has(source));
|
|
857
|
+
return {
|
|
858
|
+
replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
|
|
859
|
+
setLoader: (load) => {
|
|
860
|
+
loaders.set(source, load);
|
|
861
|
+
if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
},
|
|
865
|
+
refresh: () => applySets(/* @__PURE__ */ new Map(), true),
|
|
866
|
+
watch: () => {
|
|
867
|
+
const where = config.pointer;
|
|
868
|
+
if (pointer !== void 0 || where === void 0) return;
|
|
869
|
+
pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
|
|
870
|
+
},
|
|
871
|
+
onChange: (listener) => {
|
|
872
|
+
listeners.add(listener);
|
|
873
|
+
return () => {
|
|
874
|
+
listeners.delete(listener);
|
|
875
|
+
};
|
|
876
|
+
},
|
|
877
|
+
addCatalogFilter: (filter) => {
|
|
878
|
+
catalogFilters.push(filter);
|
|
879
|
+
roleMemo.drop();
|
|
880
|
+
},
|
|
881
|
+
catalogFor: roleMemo.catalogFor,
|
|
882
|
+
artifactsFor: (shell2, roles, installed) => ({
|
|
883
|
+
actions: roleMemo.definitionsFor(roles, installed),
|
|
884
|
+
canvases: shell2.canvases,
|
|
885
|
+
...shell2.layout !== void 0 ? { frame: shell2.layout } : {},
|
|
886
|
+
...shell2.layoutStore !== void 0 ? { layoutStore: shell2.layoutStore } : {},
|
|
887
|
+
...shell2.fragments !== void 0 ? { fragments: shell2.fragments } : {},
|
|
888
|
+
entries: byFingerprint,
|
|
889
|
+
components: components.of(shell2)
|
|
890
|
+
}),
|
|
891
|
+
generation: () => pointer?.current() ?? -1,
|
|
892
|
+
stop: () => pointer?.stop()
|
|
893
|
+
};
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
// src/data/tables.ts
|
|
897
|
+
var GENERATION_DDL = [
|
|
898
|
+
/* sql */
|
|
899
|
+
`CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
|
|
900
|
+
/* sql */
|
|
901
|
+
`INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
|
|
902
|
+
];
|
|
903
|
+
var MOSS_SEQUENCE = {
|
|
904
|
+
id: "nisc.moss",
|
|
905
|
+
migrations: [
|
|
906
|
+
{
|
|
907
|
+
description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
|
|
908
|
+
steps: [
|
|
909
|
+
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
|
|
910
|
+
id text PRIMARY KEY,
|
|
911
|
+
url text NOT NULL,
|
|
912
|
+
-- THE HASH, NEVER THE KEY. The integration key is minted at registration
|
|
913
|
+
-- (see assert.ts for the credential rule), returned once in that response,
|
|
914
|
+
-- and this is all that remains of it here. Presenting the key is the only
|
|
915
|
+
-- way to produce this value again, so a stolen database does not hold a
|
|
916
|
+
-- credential \u2014 and a lost key is re-registered, not recovered.
|
|
917
|
+
key_hash text,
|
|
918
|
+
status text NOT NULL DEFAULT 'pending',
|
|
919
|
+
-- The store card's words, straight from the bundle's meta. Columns
|
|
920
|
+
-- rather than jsonb so an app's vex read can select them like anything
|
|
921
|
+
-- else on this table.
|
|
922
|
+
title text NOT NULL DEFAULT '',
|
|
923
|
+
tagline text NOT NULL DEFAULT '',
|
|
924
|
+
description text NOT NULL DEFAULT '',
|
|
925
|
+
-- The listing page's long form, re-imported whole like everything else
|
|
926
|
+
-- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
|
|
927
|
+
-- intake (copyPress), never the paths the bundle declared \u2014 the listing
|
|
928
|
+
-- composes from host ground alone.
|
|
929
|
+
story jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
930
|
+
highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
931
|
+
press jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
932
|
+
-- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
|
|
933
|
+
-- printed by the approval card and the store tile from this one place.
|
|
934
|
+
adds text NOT NULL DEFAULT '',
|
|
935
|
+
-- The one integration action the store may open: its settings screen.
|
|
936
|
+
settings_action text NOT NULL DEFAULT '',
|
|
937
|
+
requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
938
|
+
requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
939
|
+
approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
940
|
+
-- What it tells and hears (bundle offers/needs), beside the grants
|
|
941
|
+
-- because they are the same kind of thing: the integration's declared
|
|
942
|
+
-- statement, written at import, replaced on re-registration. moss
|
|
943
|
+
-- never reads them; the host's bus does.
|
|
944
|
+
offers jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
945
|
+
needs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
946
|
+
-- The verbs the integration gates on ({id, title}), for the host's role
|
|
947
|
+
-- editor to grant. Beside offers/needs because it is the same kind of
|
|
948
|
+
-- thing: a declaration written at import, replaced on re-registration,
|
|
949
|
+
-- that moss never reads \u2014 the host does.
|
|
950
|
+
capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
951
|
+
-- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
|
|
952
|
+
-- beside capabilities because it is the same kind of thing: a declaration
|
|
953
|
+
-- written at import, replaced on re-registration, that moss never reads.
|
|
954
|
+
-- The host renders a settings form from it and stores the values itself.
|
|
955
|
+
configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
956
|
+
-- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
|
|
957
|
+
-- and a section model the host's editor renders. Beside configuration
|
|
958
|
+
-- because it is the same kind of thing: a declaration written at import,
|
|
959
|
+
-- replaced on re-registration, that moss never reads \u2014 the host does.
|
|
960
|
+
documents jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
961
|
+
-- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
|
|
962
|
+
-- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
|
|
963
|
+
-- the host's assistant is the consumer.
|
|
964
|
+
assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
965
|
+
-- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
|
|
966
|
+
-- (reachOf). Beside the grants because it is one: a grant of reach, held
|
|
967
|
+
-- by the same row, revoked by the same delete.
|
|
968
|
+
reach jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
969
|
+
-- Pages this integration serves and the host frames. Kept apart from reach
|
|
970
|
+
-- because they are spent differently: reach is a screen's call carrying a
|
|
971
|
+
-- session, a frame is a document GET carrying a grant.
|
|
972
|
+
frames jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
973
|
+
last_import_at timestamptz,
|
|
974
|
+
last_error text
|
|
975
|
+
)
|
|
976
|
+
` },
|
|
977
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
978
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
979
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
|
|
980
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
981
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
982
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
983
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
984
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
985
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
986
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
987
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
988
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
989
|
+
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
|
|
990
|
+
integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
|
|
991
|
+
action_id text NOT NULL,
|
|
992
|
+
definition jsonb NOT NULL,
|
|
993
|
+
-- The bindings, beside the artifact and never inside it: which host
|
|
994
|
+
-- action this one rides (a panel), or which menu hub lists it. Empty
|
|
995
|
+
-- means neither \u2014 reachable only through whatever else names it.
|
|
996
|
+
-- preview is the rider's display endpoint (own-prefix, validated at
|
|
997
|
+
-- intake): the host calls it with the offered ids to paint the strip.
|
|
998
|
+
attach_to text NOT NULL DEFAULT '',
|
|
999
|
+
preview text NOT NULL DEFAULT '',
|
|
1000
|
+
place_in text NOT NULL DEFAULT '',
|
|
1001
|
+
PRIMARY KEY (integration_id, action_id)
|
|
1002
|
+
)
|
|
1003
|
+
` },
|
|
1004
|
+
...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
|
|
1005
|
+
]
|
|
1006
|
+
},
|
|
1007
|
+
{
|
|
1008
|
+
description: "Stored integration actions carry the grammar stamp their definition is written in",
|
|
1009
|
+
steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
|
|
1010
|
+
},
|
|
1011
|
+
{
|
|
1012
|
+
description: "No two integrations hold the hash of one key",
|
|
1013
|
+
steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
|
|
1014
|
+
},
|
|
1015
|
+
{
|
|
1016
|
+
description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
|
|
1017
|
+
steps: [
|
|
1018
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
|
|
1019
|
+
{
|
|
1020
|
+
kind: "sql",
|
|
1021
|
+
sql: `ALTER TABLE integrations
|
|
1022
|
+
DROP COLUMN IF EXISTS title,
|
|
1023
|
+
DROP COLUMN IF EXISTS tagline,
|
|
1024
|
+
DROP COLUMN IF EXISTS description,
|
|
1025
|
+
DROP COLUMN IF EXISTS story,
|
|
1026
|
+
DROP COLUMN IF EXISTS highlights,
|
|
1027
|
+
DROP COLUMN IF EXISTS press,
|
|
1028
|
+
DROP COLUMN IF EXISTS adds,
|
|
1029
|
+
DROP COLUMN IF EXISTS settings_action,
|
|
1030
|
+
DROP COLUMN IF EXISTS offers,
|
|
1031
|
+
DROP COLUMN IF EXISTS needs,
|
|
1032
|
+
DROP COLUMN IF EXISTS capabilities,
|
|
1033
|
+
DROP COLUMN IF EXISTS configuration,
|
|
1034
|
+
DROP COLUMN IF EXISTS documents,
|
|
1035
|
+
DROP COLUMN IF EXISTS assistants,
|
|
1036
|
+
DROP COLUMN IF EXISTS frames`
|
|
1037
|
+
},
|
|
1038
|
+
{
|
|
1039
|
+
kind: "sql",
|
|
1040
|
+
sql: `ALTER TABLE integration_actions
|
|
1041
|
+
DROP COLUMN IF EXISTS attach_to,
|
|
1042
|
+
DROP COLUMN IF EXISTS preview,
|
|
1043
|
+
DROP COLUMN IF EXISTS place_in`
|
|
1044
|
+
}
|
|
1045
|
+
]
|
|
1046
|
+
}
|
|
1047
|
+
]
|
|
1048
|
+
};
|
|
1049
|
+
var tableSequencesOf = (owners) => {
|
|
1050
|
+
const cacheSequence = (owners.cache ?? vex.createPostgresCache({ pool: owners.pool })).sequence;
|
|
1051
|
+
return [
|
|
1052
|
+
MOSS_SEQUENCE,
|
|
1053
|
+
...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
|
|
1054
|
+
...cacheSequence === void 0 ? [] : [cacheSequence],
|
|
1055
|
+
...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
|
|
1056
|
+
...owners.tables ?? []
|
|
1057
|
+
];
|
|
1058
|
+
};
|
|
1059
|
+
var misfitOf = (entry2, schema) => {
|
|
1060
|
+
if (!("mutation" in entry2)) {
|
|
1061
|
+
try {
|
|
1062
|
+
vex.resolve(vex.pruneOptional(entry2.dsl, "all"), schema);
|
|
1063
|
+
return void 0;
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
return error instanceof Error ? error.message : String(error);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return vex.mutationMisfits(entry2.mutation, schema)[0];
|
|
1069
|
+
};
|
|
1070
|
+
var misfitsOf = (entries, schema) => {
|
|
1071
|
+
const misfits = /* @__PURE__ */ new Map();
|
|
1072
|
+
for (const entry2 of entries) {
|
|
1073
|
+
const why = misfitOf(entry2, schema);
|
|
1074
|
+
if (why !== void 0) misfits.set(entry2.fingerprint, why);
|
|
1075
|
+
}
|
|
1076
|
+
return misfits;
|
|
1077
|
+
};
|
|
1078
|
+
var canonical = (value) => {
|
|
1079
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
1080
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1081
|
+
const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
|
|
1082
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
|
|
1083
|
+
};
|
|
1084
|
+
var isSeededAs = async (cache, entry2) => {
|
|
1085
|
+
const held = await cache.get(entry2.fingerprint);
|
|
1086
|
+
if (held === void 0 || held.protected !== true) return false;
|
|
1087
|
+
if ("mutation" in entry2) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry2.mutation);
|
|
1088
|
+
return held.kind === "ok" && canonical(held.dsl) === canonical(entry2.dsl);
|
|
1089
|
+
};
|
|
1090
|
+
var changesBetween = (before, after) => {
|
|
1091
|
+
const removed = [];
|
|
1092
|
+
const retyped = [];
|
|
1093
|
+
for (const was of before.entities) {
|
|
1094
|
+
const now = after.entities.find((entity) => entity.table === was.table);
|
|
1095
|
+
if (now === void 0) {
|
|
1096
|
+
removed.push(was.table);
|
|
1097
|
+
continue;
|
|
1098
|
+
}
|
|
1099
|
+
for (const field of was.fields) {
|
|
1100
|
+
const kept = now.fields.find((f) => f.name === field.name);
|
|
1101
|
+
if (kept === void 0) removed.push(`${was.table}.${field.name}`);
|
|
1102
|
+
else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
return { removed, retyped };
|
|
1106
|
+
};
|
|
1107
|
+
var oneAtATime = (query) => {
|
|
1108
|
+
let last = Promise.resolve();
|
|
1109
|
+
return (text, values) => {
|
|
1110
|
+
const next = last.then(() => query(text, values));
|
|
1111
|
+
last = next.catch(() => void 0);
|
|
1112
|
+
return next;
|
|
1113
|
+
};
|
|
1114
|
+
};
|
|
1115
|
+
var migrateTables = async (runtime, app, options = {}) => {
|
|
1116
|
+
const entries = entriesOf(app);
|
|
1117
|
+
const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
|
|
1118
|
+
const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
|
|
1119
|
+
const misfitsBefore = misfitsOf(entries, before);
|
|
1120
|
+
const excused = /* @__PURE__ */ new Set();
|
|
1121
|
+
for (const entry2 of entries) {
|
|
1122
|
+
if (misfitsBefore.has(entry2.fingerprint) && await isSeededAs(cache, entry2).catch(() => false)) excused.add(entry2.fingerprint);
|
|
1123
|
+
}
|
|
1124
|
+
let found = { removed: [], retyped: [], alreadyBroken: [] };
|
|
1125
|
+
const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
|
|
1126
|
+
const report = await postgres.migrate(runtime.pool, tableSequencesOf(owners), {
|
|
1127
|
+
...options.dryRun === true ? { dryRun: true } : {},
|
|
1128
|
+
guard: async (tx) => {
|
|
1129
|
+
const after = await vex.createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
|
|
1130
|
+
const refused = [];
|
|
1131
|
+
const alreadyBroken = [];
|
|
1132
|
+
for (const [fingerprint, why] of misfitsOf(entries, after)) {
|
|
1133
|
+
if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
|
|
1134
|
+
else refused.push(`${fingerprint}: ${why}`);
|
|
1135
|
+
}
|
|
1136
|
+
found = { ...changesBetween(before, after), alreadyBroken };
|
|
1137
|
+
return refused;
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
|
|
1141
|
+
};
|
|
1142
|
+
var featureTablesOf = (app) => {
|
|
1143
|
+
const features = /* @__PURE__ */ new Set();
|
|
1144
|
+
return (app.features ?? []).map((feature) => {
|
|
1145
|
+
if (features.has(feature.name)) {
|
|
1146
|
+
throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
|
|
1147
|
+
}
|
|
1148
|
+
features.add(feature.name);
|
|
1149
|
+
const names = feature.tables?.names ?? [];
|
|
1150
|
+
return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
|
|
1151
|
+
});
|
|
1152
|
+
};
|
|
1153
|
+
var createDataLayer = async (deps) => {
|
|
1154
|
+
const adapter = vex.createPostgresAdapter({ pool: deps.pool });
|
|
1155
|
+
const cache = deps.cache ?? vex.createPostgresCache({ pool: deps.pool });
|
|
1156
|
+
await cache.init?.();
|
|
1157
|
+
const engine = vex.createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
|
|
1158
|
+
const schema = await engine.introspect();
|
|
1159
|
+
return { engine, adapter, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)) };
|
|
1160
|
+
};
|
|
1161
|
+
var grammarsOf = (app) => [
|
|
1162
|
+
migrations.NOVA_SEQUENCE,
|
|
1163
|
+
migrations$1.PRISM_SEQUENCE,
|
|
1164
|
+
...app.grammars ?? []
|
|
1165
|
+
];
|
|
1166
|
+
var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
|
|
1167
|
+
var vexRecordToSpan = (rec) => ({
|
|
1168
|
+
name: "vex.execute",
|
|
1169
|
+
startUnixNano: rec.startUnixNano,
|
|
1170
|
+
endUnixNano: rec.endUnixNano,
|
|
1171
|
+
status: rec.status,
|
|
1172
|
+
attributes: {
|
|
1173
|
+
op: rec.kind,
|
|
1174
|
+
hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
|
|
1175
|
+
...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
|
|
1176
|
+
...rec.reach !== void 0 ? { reach: rec.reach } : {},
|
|
1177
|
+
...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
|
|
1178
|
+
...rec.rows !== void 0 ? { rows: rec.rows } : {}
|
|
1179
|
+
}
|
|
1180
|
+
});
|
|
1181
|
+
var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
1182
|
+
var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
|
|
1183
|
+
var createOwnEntries = (deps) => async (own) => {
|
|
1184
|
+
const cache = vex.createMemoryCache();
|
|
1185
|
+
await vex.seedCache(cache, own.entries);
|
|
1186
|
+
const schema = await deps.adapter.introspect({ entities: [...own.tables] });
|
|
1187
|
+
const engine = vex.createQueryEngine({
|
|
1188
|
+
adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
|
|
1189
|
+
cache
|
|
1190
|
+
});
|
|
1191
|
+
await engine.introspect();
|
|
1192
|
+
const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, { public: true }])) };
|
|
1193
|
+
const reachable = new Set((await vex.handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed) => listed.fingerprint));
|
|
1194
|
+
const outside = own.entries.map((entry2) => entry2.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
|
|
1195
|
+
if (outside.length > 0) {
|
|
1196
|
+
throw new Error(
|
|
1197
|
+
`moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
return async (fingerprint, context) => {
|
|
1201
|
+
const outcome = await vex.handleQuery(
|
|
1202
|
+
{
|
|
1203
|
+
engine,
|
|
1204
|
+
locked: true,
|
|
1205
|
+
scopePolicy: policy,
|
|
1206
|
+
mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(vex.tablesChangedBy(event.writes, schema)) },
|
|
1207
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
1208
|
+
},
|
|
1209
|
+
{ fingerprint, context },
|
|
1210
|
+
{}
|
|
1211
|
+
);
|
|
1212
|
+
if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
|
|
1213
|
+
return resultOf(outcome.body);
|
|
1214
|
+
};
|
|
1215
|
+
};
|
|
1216
|
+
var TABLE = "moss_generation";
|
|
1217
|
+
var THE_ROW = { eq: [`${TABLE}.id`, 1] };
|
|
1218
|
+
var readPointerEntry = {
|
|
1219
|
+
fingerprint: "moss/generation",
|
|
1220
|
+
intent: "Where the generation pointer is",
|
|
1221
|
+
dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
|
|
1222
|
+
};
|
|
1223
|
+
var movePointerEntry = {
|
|
1224
|
+
fingerprint: "moss/generation-move",
|
|
1225
|
+
intent: "Move the generation pointer to the next number, if it is still where it was read",
|
|
1226
|
+
mutation: {
|
|
1227
|
+
op: "update",
|
|
1228
|
+
table: TABLE,
|
|
1229
|
+
set: { n: { $context: "next" } },
|
|
1230
|
+
where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
|
|
1234
|
+
var RowSchema = zod.z.object({ n: zod.z.coerce.number() });
|
|
1235
|
+
var RowsSchema = zod.z.array(zod.z.unknown());
|
|
1236
|
+
var createPointer = (replay) => ({
|
|
1237
|
+
read: async () => {
|
|
1238
|
+
const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
|
|
1239
|
+
return RowSchema.parse(rows[0] ?? { n: 0 }).n;
|
|
1240
|
+
},
|
|
1241
|
+
// A write that changed one row answers that row; one that changed none
|
|
1242
|
+
// answers no row, which does not parse: the counter moved since it was read.
|
|
1243
|
+
move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
|
|
1244
|
+
});
|
|
1245
|
+
var resolvePolicyForRoles = (app, grants, roles) => {
|
|
1246
|
+
const behaviors = app.behaviors ?? {};
|
|
1247
|
+
return vex.mergeScopePolicies(
|
|
1248
|
+
roles.map(
|
|
1249
|
+
(role) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, [role], "data"), behaviors, charter.resolveScoping(app.charter, role))
|
|
1250
|
+
)
|
|
1251
|
+
);
|
|
1252
|
+
};
|
|
1253
|
+
var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
|
|
1254
|
+
var createPolicies = (config) => {
|
|
1255
|
+
const { grants } = config;
|
|
1256
|
+
const governed = { charter: config.charter, behaviors: config.behaviors };
|
|
1257
|
+
const policies = /* @__PURE__ */ new Map();
|
|
1258
|
+
const reachPolicies = /* @__PURE__ */ new Map();
|
|
1259
|
+
return {
|
|
1260
|
+
of: (who) => {
|
|
1261
|
+
const hit = policies.get(who.memoKey);
|
|
1262
|
+
if (hit !== void 0) return hit;
|
|
1263
|
+
const compiled = resolvePolicyForRoles(governed, grants, who.roles);
|
|
1264
|
+
policies.set(who.memoKey, compiled);
|
|
1265
|
+
return compiled;
|
|
1266
|
+
},
|
|
1267
|
+
atReach: (who, reach) => {
|
|
1268
|
+
const key = `${who.memoKey}\0${reach}`;
|
|
1269
|
+
const hit = reachPolicies.get(key);
|
|
1270
|
+
if (hit !== void 0) return hit;
|
|
1271
|
+
const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
|
|
1272
|
+
reachPolicies.set(key, compiled);
|
|
1273
|
+
return compiled;
|
|
1274
|
+
},
|
|
1275
|
+
drop: () => {
|
|
1276
|
+
policies.clear();
|
|
1277
|
+
reachPolicies.clear();
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
};
|
|
1281
|
+
var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
|
|
1282
|
+
const roles = [role];
|
|
1283
|
+
const policy = deps.policyFor(roles);
|
|
1284
|
+
const outcome = await vex.handleQuery(
|
|
1285
|
+
{
|
|
1286
|
+
engine: deps.engine,
|
|
1287
|
+
locked: true,
|
|
1288
|
+
scopePolicy: policy,
|
|
1289
|
+
policyForReach: (reach) => deps.policyAtReach(roles, reach),
|
|
1290
|
+
mutations: { client: deps.db, policy },
|
|
1291
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
1292
|
+
},
|
|
1293
|
+
{ fingerprint, context },
|
|
1294
|
+
scope
|
|
1295
|
+
);
|
|
1296
|
+
if (outcome.status !== 200) {
|
|
1297
|
+
console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
|
|
1298
|
+
return void 0;
|
|
1299
|
+
}
|
|
1300
|
+
const body = outcome.body;
|
|
1301
|
+
return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
1302
|
+
};
|
|
1303
|
+
var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
|
|
1304
|
+
var writeRequestOf = (header) => ({
|
|
1305
|
+
header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
|
|
1306
|
+
});
|
|
1307
|
+
var SAID_NOTHING = { header: () => void 0 };
|
|
1308
|
+
var createWriteNotifier = () => {
|
|
1309
|
+
const requests = new async_hooks.AsyncLocalStorage();
|
|
1310
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1311
|
+
return {
|
|
1312
|
+
subscribe: (listener) => {
|
|
1313
|
+
listeners.add(listener);
|
|
1314
|
+
return () => {
|
|
1315
|
+
listeners.delete(listener);
|
|
1316
|
+
};
|
|
1317
|
+
},
|
|
1318
|
+
within: (request, run) => requests.run(request, run),
|
|
1319
|
+
report: (event) => {
|
|
1320
|
+
const request = requests.getStore() ?? SAID_NOTHING;
|
|
1321
|
+
for (const listener of [...listeners]) {
|
|
1322
|
+
try {
|
|
1323
|
+
listener(event, request);
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
};
|
|
1330
|
+
};
|
|
1331
|
+
var createWireFollower = (callSignal) => {
|
|
1332
|
+
const controller = new AbortController();
|
|
1333
|
+
const end = () => {
|
|
1334
|
+
controller.abort();
|
|
1335
|
+
};
|
|
1336
|
+
if (callSignal.aborted) end();
|
|
1337
|
+
else callSignal.addEventListener("abort", end, { once: true });
|
|
1338
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
1339
|
+
let missed;
|
|
1340
|
+
const live = {
|
|
1341
|
+
signal: controller.signal,
|
|
1342
|
+
onChange: (response) => {
|
|
1343
|
+
if (handlers.size === 0) {
|
|
1344
|
+
missed = { body: response.result };
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
for (const handler of [...handlers]) handler(response.result);
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
const onChange = (handler) => {
|
|
1351
|
+
if (controller.signal.aborted) return () => {
|
|
1352
|
+
};
|
|
1353
|
+
handlers.add(handler);
|
|
1354
|
+
if (missed !== void 0) {
|
|
1355
|
+
const { body } = missed;
|
|
1356
|
+
missed = void 0;
|
|
1357
|
+
handler(body);
|
|
1358
|
+
}
|
|
1359
|
+
return () => {
|
|
1360
|
+
handlers.delete(handler);
|
|
1361
|
+
if (handlers.size === 0) end();
|
|
1362
|
+
};
|
|
1363
|
+
};
|
|
1364
|
+
const handedOver = () => {
|
|
1365
|
+
setTimeout(() => {
|
|
1366
|
+
if (handlers.size === 0) end();
|
|
1367
|
+
}, 0);
|
|
1368
|
+
};
|
|
1369
|
+
return { live, onChange, handedOver, end };
|
|
1370
|
+
};
|
|
1371
|
+
|
|
1372
|
+
// src/data/routes.ts
|
|
1373
|
+
var createVexRoutes = (deps) => {
|
|
1374
|
+
const routes = new hono.Hono();
|
|
1375
|
+
routes.use(
|
|
1376
|
+
"/api/*",
|
|
1377
|
+
(c, next) => deps.writes.within(
|
|
1378
|
+
writeRequestOf((name) => c.req.header(name)),
|
|
1379
|
+
() => next()
|
|
1380
|
+
)
|
|
1381
|
+
);
|
|
1382
|
+
const mount = (path, entities) => {
|
|
1383
|
+
routes.route(
|
|
1384
|
+
path,
|
|
1385
|
+
hono$1.vex({
|
|
1386
|
+
engine: deps.engine,
|
|
1387
|
+
...entities !== void 0 ? { entities: [...entities] } : {},
|
|
1388
|
+
locked: true,
|
|
1389
|
+
getScope: deps.scope,
|
|
1390
|
+
getPolicy: deps.policy,
|
|
1391
|
+
getPolicyForReach: deps.policyAtReach,
|
|
1392
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
|
|
1393
|
+
mutations: { client: deps.db, onWrite: deps.writes.report }
|
|
1394
|
+
})
|
|
1395
|
+
);
|
|
1396
|
+
};
|
|
1397
|
+
mount("/api/vex");
|
|
1398
|
+
for (const [name, resource] of Object.entries(deps.resources ?? {})) {
|
|
1399
|
+
mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
|
|
1400
|
+
}
|
|
1401
|
+
return routes;
|
|
1402
|
+
};
|
|
1403
|
+
var createIntentAnswers = (deps) => {
|
|
1404
|
+
const engines = /* @__PURE__ */ new WeakMap();
|
|
1405
|
+
const engineFor = (writers) => {
|
|
1406
|
+
const kept = engines.get(writers);
|
|
1407
|
+
if (kept !== void 0) return kept;
|
|
1408
|
+
const { adapter, schema } = deps;
|
|
1409
|
+
const created = (async () => {
|
|
1410
|
+
const engine = vex.createQueryEngine({
|
|
1411
|
+
adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
|
|
1412
|
+
cache: deps.cache,
|
|
1413
|
+
generateDsl: writers.generateDsl,
|
|
1414
|
+
mapToShape: writers.mapToShape,
|
|
1415
|
+
...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
|
|
1416
|
+
...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
|
|
1417
|
+
});
|
|
1418
|
+
await engine.introspect();
|
|
1419
|
+
return engine;
|
|
1420
|
+
})();
|
|
1421
|
+
engines.set(writers, created);
|
|
1422
|
+
return created;
|
|
1423
|
+
};
|
|
1424
|
+
return async (writers, asked, caller) => (await engineFor(writers)).execute({ intent: asked.intent, shape: asked.shape, context: asked.context ?? {} }, { scope: caller.scope, scopePolicy: caller.policy });
|
|
1425
|
+
};
|
|
1426
|
+
|
|
1427
|
+
// src/data/data.ts
|
|
1428
|
+
var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
|
|
1429
|
+
var prepareEngine = async (config) => {
|
|
1430
|
+
await postgres.migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
|
|
1431
|
+
const grammars = await createGrammarUpgrader({ grammars: config.grammars });
|
|
1432
|
+
const layer = await createDataLayer(config);
|
|
1433
|
+
return {
|
|
1434
|
+
grammars,
|
|
1435
|
+
engine: layer.engine,
|
|
1436
|
+
grants: layer.grants,
|
|
1437
|
+
adapter: layer.adapter,
|
|
1438
|
+
upgradeStore: async (store) => {
|
|
1439
|
+
await postgres.upgradeStore(config.pool, store, grammars);
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
};
|
|
1443
|
+
var lazyIntentAnswers = (prepared, config) => {
|
|
1444
|
+
const { engine } = prepared;
|
|
1445
|
+
let answers;
|
|
1446
|
+
const answering = () => {
|
|
1447
|
+
if (answers !== void 0) return answers;
|
|
1448
|
+
const schema = engine.getSchema();
|
|
1449
|
+
if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
|
|
1450
|
+
answers = createIntentAnswers({
|
|
1451
|
+
adapter: prepared.adapter,
|
|
1452
|
+
schema,
|
|
1453
|
+
cache: engine.cache,
|
|
1454
|
+
...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
|
|
1455
|
+
...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
|
|
1456
|
+
});
|
|
1457
|
+
return answers;
|
|
1458
|
+
};
|
|
1459
|
+
return answering;
|
|
1460
|
+
};
|
|
1461
|
+
var tablesByFeature = (config) => (feature) => {
|
|
1462
|
+
const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
|
|
1463
|
+
if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
|
|
1464
|
+
return kept.names;
|
|
1465
|
+
};
|
|
1466
|
+
var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
|
|
1467
|
+
const own = tablesOf(feature);
|
|
1468
|
+
if (store.schema !== void 0) {
|
|
1469
|
+
throw new Error(
|
|
1470
|
+
`moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
|
|
1471
|
+
);
|
|
1472
|
+
}
|
|
1473
|
+
if (!own.includes(store.table)) {
|
|
1474
|
+
throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
|
|
1475
|
+
}
|
|
1476
|
+
await prepared.upgradeStore(store);
|
|
1477
|
+
};
|
|
1478
|
+
var createDataWith = (prepared, config) => {
|
|
1479
|
+
const { grammars, engine, grants } = prepared;
|
|
1480
|
+
const governed = { charter: config.charter, behaviors: config.behaviors };
|
|
1481
|
+
const policies = createPolicies({ ...governed, grants });
|
|
1482
|
+
const emit = chunkJYBHJDT7_cjs.emitterOf(config.telemetry);
|
|
1483
|
+
const onExecute = emit === void 0 ? void 0 : (record2) => emit(vexRecordToSpan(record2));
|
|
1484
|
+
const writes = createWriteNotifier();
|
|
1485
|
+
const answering = lazyIntentAnswers(prepared, config);
|
|
1486
|
+
const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
|
|
1487
|
+
const tablesOf = tablesByFeature(config);
|
|
1488
|
+
let pointerEntries;
|
|
1489
|
+
const pointerReplay = () => {
|
|
1490
|
+
pointerEntries ??= ownEntries(POINTER, void 0);
|
|
1491
|
+
return pointerEntries;
|
|
1492
|
+
};
|
|
1493
|
+
return {
|
|
1494
|
+
grants,
|
|
1495
|
+
grammars,
|
|
1496
|
+
seed: (entries) => vex.seedCache(engine.cache, entries),
|
|
1497
|
+
fingerprints: async () => await engine.cache.keys?.() ?? [],
|
|
1498
|
+
policyOf: policies.of,
|
|
1499
|
+
// Compiled afresh and not taken from the kept ones: the caller owns its
|
|
1500
|
+
// copy, and nothing it does to it reaches a policy a request is served under.
|
|
1501
|
+
policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
|
|
1502
|
+
fingerprintsFor: async (who) => (await vex.handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry2) => entry2.fingerprint).sort(),
|
|
1503
|
+
executeAs: createExecuteAs({
|
|
1504
|
+
engine,
|
|
1505
|
+
db: config.db,
|
|
1506
|
+
policyFor: (roles) => policies.of(callerOfRoles(roles)),
|
|
1507
|
+
policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
|
|
1508
|
+
...onExecute !== void 0 ? { onExecute } : {}
|
|
1509
|
+
}),
|
|
1510
|
+
answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
|
|
1511
|
+
ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
|
|
1512
|
+
routes: (routing) => createVexRoutes({
|
|
1513
|
+
engine,
|
|
1514
|
+
db: config.db,
|
|
1515
|
+
resources: routing.resources,
|
|
1516
|
+
scope: routing.scope,
|
|
1517
|
+
policy: (c) => policies.of(routing.caller(c)),
|
|
1518
|
+
policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
|
|
1519
|
+
...onExecute !== void 0 ? { onExecute } : {},
|
|
1520
|
+
writes
|
|
1521
|
+
}),
|
|
1522
|
+
upgradeStore: createUpgradeStore(prepared, tablesOf),
|
|
1523
|
+
onWrite: writes.subscribe,
|
|
1524
|
+
pointer: createPointer(pointerReplay),
|
|
1525
|
+
dropOnChange: (changed) => {
|
|
1526
|
+
changed(policies.drop);
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
};
|
|
1530
|
+
var createData = async (config) => createDataWith(await prepareEngine(config), config);
|
|
1531
|
+
var DEFAULT_ROOT = '<div id="root"></div>';
|
|
1532
|
+
var embedSnapshot = (snapshot, principal, path) => {
|
|
1533
|
+
const { frame, trees, seed, live } = snapshot;
|
|
1534
|
+
const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
|
|
1535
|
+
const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1536
|
+
return `<script type="application/json" id="${chunk3RIWTXGI_cjs.SNAPSHOT_ELEMENT_ID}">${text}</script>`;
|
|
1537
|
+
};
|
|
1538
|
+
var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
|
|
1539
|
+
var rootHolding = (root) => {
|
|
1540
|
+
const closing = root.lastIndexOf("</");
|
|
1541
|
+
if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
|
|
1542
|
+
return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
|
|
1543
|
+
};
|
|
1544
|
+
var escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
1545
|
+
var renderDocument = async (config) => {
|
|
1546
|
+
const { server, template, request, draw } = config;
|
|
1547
|
+
const tokenKey = config.tokenKey ?? chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY;
|
|
1548
|
+
const root = config.root ?? DEFAULT_ROOT;
|
|
1549
|
+
const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
|
|
1550
|
+
if (!template.includes(root)) return undrawn;
|
|
1551
|
+
const holding = rootHolding(root);
|
|
1552
|
+
if (holding === void 0) {
|
|
1553
|
+
console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
|
|
1554
|
+
return undrawn;
|
|
1555
|
+
}
|
|
1556
|
+
try {
|
|
1557
|
+
const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
|
|
1558
|
+
const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
|
|
1559
|
+
const principal = token === null ? null : await server.principalOf(token);
|
|
1560
|
+
const route = server.page(request.path);
|
|
1561
|
+
const host = route?.host ?? server.shells;
|
|
1562
|
+
if (host === void 0) return undrawn;
|
|
1563
|
+
const snapshot = await host.snapshot(principal === null ? null : token, principal, {
|
|
1564
|
+
...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
|
|
1565
|
+
...route !== void 0 ? { inputs: route.inputs } : {}
|
|
1566
|
+
});
|
|
1567
|
+
const screen = await draw(snapshot);
|
|
1568
|
+
const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
|
|
1569
|
+
const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
|
|
1570
|
+
const head = document.headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
|
|
1571
|
+
for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
|
|
1572
|
+
const html = document.placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
|
|
1573
|
+
return {
|
|
1574
|
+
html,
|
|
1575
|
+
...head !== void 0 ? { head } : {},
|
|
1576
|
+
headers: documentHeaders(principal),
|
|
1577
|
+
drawn: true,
|
|
1578
|
+
principal,
|
|
1579
|
+
...route !== void 0 ? { page: route.name } : {},
|
|
1580
|
+
live: snapshot.live,
|
|
1581
|
+
why: snapshot.why,
|
|
1582
|
+
drawnWith: snapshot.drawnWith,
|
|
1583
|
+
settled: snapshot.settled
|
|
1584
|
+
};
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
|
|
1587
|
+
return undrawn;
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
|
|
1591
|
+
// src/documents/pages.ts
|
|
1592
|
+
var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
|
|
1593
|
+
var compile = (name, page) => {
|
|
1594
|
+
if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
|
|
1595
|
+
const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
|
|
1596
|
+
for (const segment of segments) {
|
|
1597
|
+
if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
|
|
1598
|
+
throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
|
|
1602
|
+
const twice = named.find((param, index) => named.indexOf(param) !== index);
|
|
1603
|
+
if (twice !== void 0) {
|
|
1604
|
+
throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
|
|
1605
|
+
}
|
|
1606
|
+
if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
|
|
1607
|
+
throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
|
|
1608
|
+
}
|
|
1609
|
+
return { name, segments };
|
|
1610
|
+
};
|
|
1611
|
+
var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
|
|
1612
|
+
const other = b.segments[index];
|
|
1613
|
+
return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
|
|
1614
|
+
});
|
|
1615
|
+
var createPageRouter = (pages) => {
|
|
1616
|
+
const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
|
|
1617
|
+
for (const [index, page] of compiled.entries()) {
|
|
1618
|
+
const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
|
|
1619
|
+
if (other !== void 0) {
|
|
1620
|
+
throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
return {
|
|
1624
|
+
match: (path) => {
|
|
1625
|
+
const parts = segmentsOf(path);
|
|
1626
|
+
for (const page of compiled) {
|
|
1627
|
+
if (page.segments.length !== parts.length) continue;
|
|
1628
|
+
const params = {};
|
|
1629
|
+
let matches = true;
|
|
1630
|
+
for (const [index, segment] of page.segments.entries()) {
|
|
1631
|
+
const part = parts[index];
|
|
1632
|
+
if (part === void 0) {
|
|
1633
|
+
matches = false;
|
|
1634
|
+
break;
|
|
1635
|
+
}
|
|
1636
|
+
if ("param" in segment) {
|
|
1637
|
+
try {
|
|
1638
|
+
params[segment.param] = decodeURIComponent(part);
|
|
1639
|
+
} catch {
|
|
1640
|
+
matches = false;
|
|
1641
|
+
break;
|
|
1642
|
+
}
|
|
1643
|
+
} else if (segment.literal !== part) {
|
|
1644
|
+
matches = false;
|
|
1645
|
+
break;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
if (matches) return { name: page.name, params };
|
|
1649
|
+
}
|
|
1650
|
+
return void 0;
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
};
|
|
1654
|
+
var exportDocuments = async (config) => {
|
|
1655
|
+
const { paths, ...rest } = config;
|
|
1656
|
+
const out = [];
|
|
1657
|
+
for (const path of paths) {
|
|
1658
|
+
const page = await renderDocument({ ...rest, request: { path, cookie: null } });
|
|
1659
|
+
out.push({
|
|
1660
|
+
path,
|
|
1661
|
+
html: page.html,
|
|
1662
|
+
...page.page !== void 0 ? { page: page.page } : {},
|
|
1663
|
+
...page.head !== void 0 ? { head: page.head } : {},
|
|
1664
|
+
drawn: page.drawn,
|
|
1665
|
+
// A page that could not be drawn is not taken to be finished.
|
|
1666
|
+
live: page.live ?? true,
|
|
1667
|
+
why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
|
|
1668
|
+
drawnWith: page.drawnWith ?? [],
|
|
1669
|
+
settled: page.settled ?? false
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
return out;
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
// src/socket/revalidation.ts
|
|
1676
|
+
var DEFAULT_REVALIDATE_MS = 60 * 1e3;
|
|
1677
|
+
var MAX_INTERVAL_MS2 = 2 ** 31 - 1;
|
|
1678
|
+
var createRevalidation = (config) => {
|
|
1679
|
+
const live = /* @__PURE__ */ new Map();
|
|
1680
|
+
const expire = (connection) => {
|
|
1681
|
+
live.delete(connection);
|
|
1682
|
+
const told = () => connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
|
|
1683
|
+
const closed = () => connection.close(chunk3RIWTXGI_cjs.CLOSE_INVALID_TOKEN, "session expired");
|
|
1684
|
+
for (const step of [told, closed]) {
|
|
1685
|
+
try {
|
|
1686
|
+
step();
|
|
1687
|
+
} catch (error) {
|
|
1688
|
+
console.error("[moss/socket] a connection whose session expired could not be told so or closed, and is let go:", error);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
};
|
|
1692
|
+
const revalidate = async () => {
|
|
1693
|
+
let asked = 0;
|
|
1694
|
+
const unanswered = [];
|
|
1695
|
+
for (const [connection, credential] of [...live]) {
|
|
1696
|
+
if (credential === null) continue;
|
|
1697
|
+
asked += 1;
|
|
1698
|
+
let resolved;
|
|
1699
|
+
try {
|
|
1700
|
+
resolved = await config.session(credential.token);
|
|
1701
|
+
} catch (error) {
|
|
1702
|
+
unanswered.push(error);
|
|
1703
|
+
continue;
|
|
1704
|
+
}
|
|
1705
|
+
if (resolved === credential.principal) continue;
|
|
1706
|
+
if (!live.has(connection)) continue;
|
|
1707
|
+
expire(connection);
|
|
1708
|
+
}
|
|
1709
|
+
if (unanswered.length > 0) {
|
|
1710
|
+
console.error(`[moss/socket] the session verifier could not be asked about ${unanswered.length} of ${asked} connection(s). They stay open and are asked again:`, unanswered[0]);
|
|
1711
|
+
}
|
|
1712
|
+
};
|
|
1713
|
+
let passing = false;
|
|
1714
|
+
const pass = async () => {
|
|
1715
|
+
if (passing) return;
|
|
1716
|
+
passing = true;
|
|
1717
|
+
try {
|
|
1718
|
+
await revalidate();
|
|
1719
|
+
} catch (error) {
|
|
1720
|
+
console.error("[moss/socket] a revalidation pass failed, and the next one starts over:", error);
|
|
1721
|
+
} finally {
|
|
1722
|
+
passing = false;
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
const revalidateMs = config.revalidateMs ?? DEFAULT_REVALIDATE_MS;
|
|
1726
|
+
let sweeper;
|
|
1727
|
+
if (revalidateMs > 0 && revalidateMs <= MAX_INTERVAL_MS2) {
|
|
1728
|
+
sweeper = setInterval(() => void pass(), revalidateMs);
|
|
1729
|
+
sweeper.unref?.();
|
|
1730
|
+
}
|
|
1731
|
+
return {
|
|
1732
|
+
hold: (connection, credential) => {
|
|
1733
|
+
live.set(connection, credential);
|
|
1734
|
+
},
|
|
1735
|
+
release: (connection) => {
|
|
1736
|
+
live.delete(connection);
|
|
1737
|
+
},
|
|
1738
|
+
stop: () => {
|
|
1739
|
+
if (sweeper !== void 0) clearInterval(sweeper);
|
|
1740
|
+
sweeper = void 0;
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
};
|
|
1744
|
+
var flag = zod.z.literal("1").optional().catch(void 0);
|
|
1745
|
+
var UpgradeParametersSchema = zod.z.object({
|
|
1746
|
+
protocol: zod.z.string().default("1"),
|
|
1747
|
+
key: zod.z.string().regex(/^[\w.-]{1,64}$/).optional().catch(void 0),
|
|
1748
|
+
seed: zod.z.string().regex(/^[0-9a-f]{8,40}$/).optional().catch(void 0),
|
|
1749
|
+
path: zod.z.string().optional(),
|
|
1750
|
+
delta: flag,
|
|
1751
|
+
sealed: flag,
|
|
1752
|
+
leave: flag
|
|
1753
|
+
});
|
|
1754
|
+
var parametersOf = (url) => {
|
|
1755
|
+
const written = new URL(url, "http://nisc.local").searchParams;
|
|
1756
|
+
return UpgradeParametersSchema.parse(Object.fromEntries(Object.keys(UpgradeParametersSchema.shape).map((name) => [name, written.get(name) ?? void 0])));
|
|
1757
|
+
};
|
|
1758
|
+
var SpokenProtocolSchema = zod.z.string().regex(/^\d{1,15}$/).transform(Number);
|
|
1759
|
+
var protocolRefusal = (parameters) => {
|
|
1760
|
+
const spoken = SpokenProtocolSchema.safeParse(parameters.protocol);
|
|
1761
|
+
if (spoken.success && spoken.data >= chunk3RIWTXGI_cjs.PROTOCOL_MIN && spoken.data <= chunk3RIWTXGI_cjs.PROTOCOL) return void 0;
|
|
1762
|
+
const behind = spoken.success && spoken.data > chunk3RIWTXGI_cjs.PROTOCOL ? "server" : "client";
|
|
1763
|
+
return {
|
|
1764
|
+
type: "error",
|
|
1765
|
+
code: `${behind}_too_old`,
|
|
1766
|
+
message: `This terminal speaks protocol ${parameters.protocol}; this server speaks ${chunk3RIWTXGI_cjs.PROTOCOL_MIN}\u2013${chunk3RIWTXGI_cjs.PROTOCOL}. ` + (behind === "client" ? "Reload the terminal to get the current build." : "The server has not been updated yet.")
|
|
1767
|
+
};
|
|
1768
|
+
};
|
|
1769
|
+
var authenticateUpgrade = async (url, upgrade, config, foreignPageWarning) => {
|
|
1770
|
+
const parameters = parametersOf(url);
|
|
1771
|
+
const key = parameters.key ?? chunk3RIWTXGI_cjs.DEFAULT_TOKEN_KEY;
|
|
1772
|
+
const page = upgrade === void 0 ? void 0 : ownOriginOf(upgrade.origin, upgrade.host, config.origins);
|
|
1773
|
+
const secure = page?.protocol === "https:";
|
|
1774
|
+
const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
|
|
1775
|
+
const sealing = page !== void 0 && parameters.sealed === "1";
|
|
1776
|
+
if (page === void 0 && parameters.sealed === "1" && typeof upgrade?.origin === "string" && !foreignPageWarning.warned) {
|
|
1777
|
+
foreignPageWarning.warned = true;
|
|
1778
|
+
console.warn(
|
|
1779
|
+
`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? "nothing"}, so that is not the app\u2019s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`
|
|
1780
|
+
);
|
|
1781
|
+
}
|
|
1782
|
+
const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;
|
|
1783
|
+
const sealedOffer = chunk3RIWTXGI_cjs.offeredSealed(upgrade?.offered);
|
|
1784
|
+
const sealLost = sealing && sealedOffer !== null && hadSeal === null;
|
|
1785
|
+
const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
|
|
1786
|
+
const offered = chunk3RIWTXGI_cjs.offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
|
|
1787
|
+
const carried = offered ?? (parameters.leave === "1" ? null : held?.token ?? null);
|
|
1788
|
+
const principal = carried === null ? null : await config.session(carried);
|
|
1789
|
+
if (offered !== null && principal === null) return "invalid_token";
|
|
1790
|
+
const token = principal === null ? null : carried;
|
|
1791
|
+
const cookies = [
|
|
1792
|
+
...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await config.sessionLastsMs?.(token) ?? null }),
|
|
1793
|
+
...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
|
|
1794
|
+
];
|
|
1795
|
+
return { token, principal, cookies, seal, sealLost };
|
|
1796
|
+
};
|
|
1797
|
+
|
|
1798
|
+
// src/socket/routing.ts
|
|
1799
|
+
var messageOf2 = (text) => {
|
|
1800
|
+
try {
|
|
1801
|
+
const parsed = chunk3RIWTXGI_cjs.ClientMessageSchema.safeParse(JSON.parse(text));
|
|
1802
|
+
return parsed.success ? parsed.data : void 0;
|
|
1803
|
+
} catch {
|
|
1804
|
+
return void 0;
|
|
1805
|
+
}
|
|
1806
|
+
};
|
|
1807
|
+
var INVALID_MESSAGE = `Not a message of protocol ${chunk3RIWTXGI_cjs.PROTOCOL}: it must be JSON, name a type a terminal sends, and carry that type's fields and no others.`;
|
|
1808
|
+
var messageHandler = (session, connection, send) => {
|
|
1809
|
+
const act = (text) => {
|
|
1810
|
+
const message = messageOf2(text);
|
|
1811
|
+
if (message === void 0) {
|
|
1812
|
+
send({ type: "error", code: "invalid_message", message: INVALID_MESSAGE });
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
if (session === void 0) {
|
|
1816
|
+
send({ type: "error", code: "no_shell", message: "This app serves no shell.", ...message.type === "event" ? { canvas: message.canvas } : {} });
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
switch (message.type) {
|
|
1820
|
+
case "reset":
|
|
1821
|
+
session.reset();
|
|
1822
|
+
return;
|
|
1823
|
+
case "resync":
|
|
1824
|
+
session.resync(connection);
|
|
1825
|
+
return;
|
|
1826
|
+
case "back":
|
|
1827
|
+
session.back();
|
|
1828
|
+
return;
|
|
1829
|
+
case "popTo":
|
|
1830
|
+
session.popTo(message.canvas, message.instance);
|
|
1831
|
+
return;
|
|
1832
|
+
case "publish":
|
|
1833
|
+
session.publish(message.channel, message.payload);
|
|
1834
|
+
return;
|
|
1835
|
+
case "event":
|
|
1836
|
+
session.dispatch(message.canvas, message.event);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
return (text) => {
|
|
1841
|
+
try {
|
|
1842
|
+
act(text);
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
console.error("[moss/socket] a message could not be acted on:", error);
|
|
1845
|
+
try {
|
|
1846
|
+
send({ type: "error", code: "message_failed", message: "The server could not act on that message. Why is in its log, not here. The connection is still open." });
|
|
1847
|
+
} catch {
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
};
|
|
1851
|
+
};
|
|
1852
|
+
|
|
1853
|
+
// src/socket/socket.ts
|
|
1854
|
+
var closeOf = (connection) => {
|
|
1855
|
+
let ended = false;
|
|
1856
|
+
const undoing = [];
|
|
1857
|
+
connection.onClose(() => {
|
|
1858
|
+
ended = true;
|
|
1859
|
+
for (const undo of undoing.splice(0)) undo();
|
|
1860
|
+
});
|
|
1861
|
+
return {
|
|
1862
|
+
ended: () => ended,
|
|
1863
|
+
whenClosed: (undo) => {
|
|
1864
|
+
if (ended) undo();
|
|
1865
|
+
else undoing.push(undo);
|
|
1866
|
+
}
|
|
1867
|
+
};
|
|
1868
|
+
};
|
|
1869
|
+
var DEFAULT_ANONYMOUS_SHELL_MAX = 1e3;
|
|
1870
|
+
var createAnonymousShellLimit = (max) => {
|
|
1871
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1872
|
+
return {
|
|
1873
|
+
acquire: (connection) => {
|
|
1874
|
+
if (taken.size >= max) return false;
|
|
1875
|
+
taken.add(connection);
|
|
1876
|
+
return true;
|
|
1877
|
+
},
|
|
1878
|
+
release: (connection) => {
|
|
1879
|
+
taken.delete(connection);
|
|
1880
|
+
}
|
|
1881
|
+
};
|
|
1882
|
+
};
|
|
1883
|
+
var FailuresSchema = zod.z.object({ failures: zod.z.array(zod.z.object({ id: zod.z.string() })) });
|
|
1884
|
+
var failedDefinitions = (error) => {
|
|
1885
|
+
const parsed = FailuresSchema.safeParse(error.context);
|
|
1886
|
+
return parsed.success ? parsed.data.failures.map((failure) => failure.id) : [];
|
|
1887
|
+
};
|
|
1888
|
+
var refusalOf2 = (error) => {
|
|
1889
|
+
const failures = error instanceof nova.DefinitionValidationError ? failedDefinitions(error) : [];
|
|
1890
|
+
const refusal = error instanceof nova.DefinitionValidationError && failures.length > 0 ? `This session could not be opened \u2014 ${error.message}: ${failures.join(", ")}.` : "This session could not be opened. Why is in the server's log, not here.";
|
|
1891
|
+
return { type: "error", code: "session_failed", message: `${refusal} The refusal is this terminal's alone; the server is up.` };
|
|
1892
|
+
};
|
|
1893
|
+
var spanOf = (emit) => {
|
|
1894
|
+
if (emit === void 0) return void 0;
|
|
1895
|
+
const clock = chunkJYBHJDT7_cjs.spanClock();
|
|
1896
|
+
return (name, status, hasPrincipal) => emit({ name, startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status, attributes: { hasPrincipal } });
|
|
1897
|
+
};
|
|
1898
|
+
var openingOf = (config, { seed, path }) => {
|
|
1899
|
+
const route = path === void 0 ? void 0 : config.page?.(path);
|
|
1900
|
+
const host = route?.host ?? config.shells;
|
|
1901
|
+
if (host === void 0) return void 0;
|
|
1902
|
+
return (token, principal) => host.session(token, principal, { ...seed === void 0 ? {} : { seed }, ...route === void 0 ? {} : { inputs: route.inputs } });
|
|
1903
|
+
};
|
|
1904
|
+
var AT_CAPACITY = { type: "error", code: "at_capacity", message: "This server is serving as many terminals with nobody signed in as it is set to. Try again in a moment." };
|
|
1905
|
+
var served = async (config, connection, send, close, opening, who) => {
|
|
1906
|
+
const { ids, hash } = await config.catalog(who.principal);
|
|
1907
|
+
if (close.ended()) return void 0;
|
|
1908
|
+
send({ type: "hello", protocol: chunk3RIWTXGI_cjs.PROTOCOL, principal: who.principal, catalog: { actions: ids, hash } });
|
|
1909
|
+
const session = await opening.session?.(who.token, who.principal);
|
|
1910
|
+
if (session === void 0) return void 0;
|
|
1911
|
+
if (!close.ended()) session.attach(connection, { delta: opening.delta });
|
|
1912
|
+
close.whenClosed(() => session.detach(connection));
|
|
1913
|
+
return session;
|
|
1914
|
+
};
|
|
1915
|
+
var open = async (held, url, connection, send, span, found) => {
|
|
1916
|
+
const { config, foreignPageWarning, revalidation, anonymousShells } = held;
|
|
1917
|
+
const params = parametersOf(url);
|
|
1918
|
+
const mismatch = protocolRefusal(params);
|
|
1919
|
+
if (mismatch !== void 0) {
|
|
1920
|
+
send(mismatch);
|
|
1921
|
+
connection.close(chunk3RIWTXGI_cjs.CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
const asking = await authenticateUpgrade(url, connection.upgrade, config, foreignPageWarning);
|
|
1925
|
+
if (asking === "invalid_token") {
|
|
1926
|
+
span?.("socket.upgrade", "refused", false);
|
|
1927
|
+
send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
|
|
1928
|
+
connection.close(chunk3RIWTXGI_cjs.CLOSE_INVALID_TOKEN, "invalid token");
|
|
1929
|
+
return;
|
|
1930
|
+
}
|
|
1931
|
+
const { token, principal, seal } = asking;
|
|
1932
|
+
found.principal = principal !== null;
|
|
1933
|
+
if (asking.cookies.length > 0) connection.upgrade?.answer?.(asking.cookies);
|
|
1934
|
+
if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);
|
|
1935
|
+
if (asking.sealLost) {
|
|
1936
|
+
send({ type: "error", code: "seal_not_kept", message: "This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token." });
|
|
1937
|
+
}
|
|
1938
|
+
const session = openingOf(config, params);
|
|
1939
|
+
if (principal === null && session !== void 0 && !anonymousShells.acquire(connection)) {
|
|
1940
|
+
span?.("socket.upgrade", "refused", false);
|
|
1941
|
+
send(AT_CAPACITY);
|
|
1942
|
+
connection.close(chunk3RIWTXGI_cjs.CLOSE_AT_CAPACITY, "at capacity");
|
|
1943
|
+
return;
|
|
1944
|
+
}
|
|
1945
|
+
revalidation.hold(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
|
|
1946
|
+
const close = closeOf(connection);
|
|
1947
|
+
close.whenClosed(() => revalidation.release(connection));
|
|
1948
|
+
close.whenClosed(() => anonymousShells.release(connection));
|
|
1949
|
+
if (span !== void 0) close.whenClosed(() => span("socket.close", "ok", principal !== null));
|
|
1950
|
+
const attached = await served(config, connection, send, close, { session, delta: params.delta === "1" }, { token, principal });
|
|
1951
|
+
span?.("socket.upgrade", "ok", principal !== null);
|
|
1952
|
+
connection.onMessage(messageHandler(attached, connection, send));
|
|
1953
|
+
};
|
|
1954
|
+
var createSocket = (config) => {
|
|
1955
|
+
const emit = chunkJYBHJDT7_cjs.emitterOf(config.telemetry);
|
|
1956
|
+
const revalidation = createRevalidation(config);
|
|
1957
|
+
const anonymousShells = createAnonymousShellLimit(config.anonymousShellMax ?? DEFAULT_ANONYMOUS_SHELL_MAX);
|
|
1958
|
+
const held = { config, foreignPageWarning: { warned: false }, revalidation, anonymousShells };
|
|
1959
|
+
const accept = async (url, connection) => {
|
|
1960
|
+
const send = (message) => connection.send(JSON.stringify(message));
|
|
1961
|
+
const span = spanOf(emit);
|
|
1962
|
+
const found = { principal: false };
|
|
1963
|
+
try {
|
|
1964
|
+
await open(held, url, connection, send, span, found);
|
|
1965
|
+
} catch (error) {
|
|
1966
|
+
console.error("[moss/socket] refused a session:", error);
|
|
1967
|
+
span?.("socket.upgrade", "error", found.principal);
|
|
1968
|
+
revalidation.release(connection);
|
|
1969
|
+
anonymousShells.release(connection);
|
|
1970
|
+
try {
|
|
1971
|
+
send(refusalOf2(error));
|
|
1972
|
+
connection.close(chunk3RIWTXGI_cjs.CLOSE_SHELL_FAILED, "session failed");
|
|
1973
|
+
} catch {
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
};
|
|
1977
|
+
return Object.assign(accept, { stop: revalidation.stop });
|
|
1978
|
+
};
|
|
1979
|
+
|
|
1980
|
+
// src/server/features.ts
|
|
1981
|
+
var emptyRegister = () => ({ credentials: [], wireWraps: [] });
|
|
1982
|
+
var composeWireWraps = (registered) => (inner) => registered.wireWraps.reduce((wire, wrap) => wrap(wire), inner);
|
|
1983
|
+
var seamsOf = (feature, { app, runtime, server, operator, registered, identity, running, data }) => {
|
|
1984
|
+
const actions = running.claim(feature.name, `the feature "${feature.name}"`);
|
|
1985
|
+
return seamsFor(feature, actions, { app, runtime, server, operator, registered, identity, running, data });
|
|
1986
|
+
};
|
|
1987
|
+
var kitOf = (app) => new Map(Object.entries(app.shell?.components ?? {}).map(([name, contract]) => [name, { propsSchema: contract.meta?.propsSchema }]));
|
|
1988
|
+
var seamsFor = (feature, owned, { app, runtime, server, operator, registered, identity, running, data }) => ({
|
|
1989
|
+
mountRoutes: (routes) => {
|
|
1990
|
+
server.route("/", routes);
|
|
1991
|
+
},
|
|
1992
|
+
mountOperatorRoutes: (routes) => {
|
|
1993
|
+
operator.route("/", routes);
|
|
1994
|
+
},
|
|
1995
|
+
registerCredential: (prefix, principalOf) => {
|
|
1996
|
+
registered.credentials.push({ prefix, principalOf });
|
|
1997
|
+
},
|
|
1998
|
+
resolveIdentity: identity.resolve,
|
|
1999
|
+
scopeOf: identity.scopeValuesFor,
|
|
2000
|
+
grantedActionIds: (roles, installed) => running.catalogFor(roles, installed).ids,
|
|
2001
|
+
actions: running.actions,
|
|
2002
|
+
replaceActions: owned.replace,
|
|
2003
|
+
refusalOf: (actions) => refusalOf(running.verify(actions), "refresh"),
|
|
2004
|
+
setActionsLoader: owned.setLoader,
|
|
2005
|
+
addCatalogFilter: running.addCatalogFilter,
|
|
2006
|
+
charter: app.charter,
|
|
2007
|
+
components: app.shell?.components ?? {},
|
|
2008
|
+
layoutMisfits: (layout2) => layoutMisfits(layout2, kitOf(app)),
|
|
2009
|
+
endlessChains,
|
|
2010
|
+
ownEntries: (entries) => data.ownEntries(feature.name, entries),
|
|
2011
|
+
grammars: data.grammars,
|
|
2012
|
+
upgradeStore: (store) => data.upgradeStore(feature.name, store),
|
|
2013
|
+
fingerprints: data.fingerprints,
|
|
2014
|
+
fingerprintsFor: async (principal) => data.fingerprintsFor(await identity.resolve(principal)),
|
|
2015
|
+
onWrite: data.onWrite,
|
|
2016
|
+
telemetry: runtime.telemetry,
|
|
2017
|
+
wrapWire: (wrap) => {
|
|
2018
|
+
registered.wireWraps.push(wrap);
|
|
2019
|
+
}
|
|
2020
|
+
});
|
|
2021
|
+
var startFeatures = async (features, deps) => {
|
|
2022
|
+
for (const feature of features) await feature.start(seamsOf(feature, deps));
|
|
2023
|
+
};
|
|
2024
|
+
var fingerprintOf = (request) => {
|
|
2025
|
+
if (request === null || typeof request !== "object" || Array.isArray(request)) return void 0;
|
|
2026
|
+
const fingerprint = Reflect.get(request, "fingerprint");
|
|
2027
|
+
return typeof fingerprint === "string" ? fingerprint : void 0;
|
|
2028
|
+
};
|
|
2029
|
+
var shellNeedOf = (definition, entries) => {
|
|
2030
|
+
const facts = reflect.livenessOf(definition);
|
|
2031
|
+
const why = [];
|
|
2032
|
+
const drawnWith = [];
|
|
2033
|
+
if (facts.gestures) why.push("a person can act on it");
|
|
2034
|
+
if (facts.opaqueLayout) why.push("its layout is kept in the store, so what can be pressed on it is not readable");
|
|
2035
|
+
for (const channel of facts.listens) why.push(`it waits on the channel "${channel}"`);
|
|
2036
|
+
for (const use of facts.endpoints) {
|
|
2037
|
+
if (!use.onOpen && !use.later) continue;
|
|
2038
|
+
if (use.kind === "fn") {
|
|
2039
|
+
why.push(`it calls the function endpoint "${use.name}", which is code`);
|
|
2040
|
+
continue;
|
|
2041
|
+
}
|
|
2042
|
+
const fingerprint = fingerprintOf(use.request);
|
|
2043
|
+
const entry2 = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
|
|
2044
|
+
if (entry2 !== void 0 && !("mutation" in entry2) && entry2.refresh === "reactive") {
|
|
2045
|
+
why.push(`its read "${use.name}" keeps answering (${entry2.fingerprint} is reactive)`);
|
|
2046
|
+
continue;
|
|
2047
|
+
}
|
|
2048
|
+
if (fingerprint !== void 0 && entry2 === void 0) {
|
|
2049
|
+
why.push(`its read "${use.name}" replays "${fingerprint}", which the manifest does not carry \u2014 whether it keeps answering is not readable`);
|
|
2050
|
+
continue;
|
|
2051
|
+
}
|
|
2052
|
+
if (use.onOpen) drawnWith.push(fingerprint ?? use.url ?? use.name);
|
|
2053
|
+
}
|
|
2054
|
+
return { live: why.length > 0, why, drawnWith };
|
|
2055
|
+
};
|
|
2056
|
+
var DEFAULT_SNAPSHOT_WAIT_MS = 300;
|
|
2057
|
+
var settle = async (live, waitMs) => {
|
|
2058
|
+
const started = Date.now();
|
|
2059
|
+
let timer;
|
|
2060
|
+
const deadline = new Promise((resolve2) => {
|
|
2061
|
+
timer = setTimeout(() => resolve2(false), waitMs);
|
|
2062
|
+
});
|
|
2063
|
+
const whole = live.seeded.then(() => nova.shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));
|
|
2064
|
+
const settled = await Promise.race([whole, deadline]);
|
|
2065
|
+
clearTimeout(timer);
|
|
2066
|
+
return settled;
|
|
2067
|
+
};
|
|
2068
|
+
var read = (live) => {
|
|
2069
|
+
let frameTree = [];
|
|
2070
|
+
try {
|
|
2071
|
+
frameTree = live.shell.getShellRenderTree();
|
|
2072
|
+
} catch (error) {
|
|
2073
|
+
console.error("[moss/shells] the shell frame failed to render for a snapshot \u2014 serving an empty arrangement:", error);
|
|
2074
|
+
}
|
|
2075
|
+
const trees = {};
|
|
2076
|
+
for (const canvasId of chunkFTFME3HS_cjs.canvasesOf(live)) {
|
|
2077
|
+
try {
|
|
2078
|
+
trees[canvasId] = chunkFTFME3HS_cjs.treeOf(live, canvasId);
|
|
2079
|
+
} catch (error) {
|
|
2080
|
+
console.error(`[moss/shells] canvas "${canvasId}" failed to render for a snapshot \u2014 leaving it out:`, error);
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
return { frame: frameTree, trees };
|
|
2084
|
+
};
|
|
2085
|
+
var needOf = (live, principal, kept) => {
|
|
2086
|
+
const why = [];
|
|
2087
|
+
const drawnWith = [];
|
|
2088
|
+
const { entries } = live;
|
|
2089
|
+
if (entries === void 0) return { live: true, why: ["this host was given no way to ask what its actions need"], drawnWith };
|
|
2090
|
+
if (kept && principal !== null) why.push("the app\u2019s shell is kept for whoever is signed in");
|
|
2091
|
+
for (const canvas of Object.values(live.shell.getState().canvases)) {
|
|
2092
|
+
for (const instance of canvas.stack) {
|
|
2093
|
+
const definition = live.shell.getRuntime(instance.id)?.definition;
|
|
2094
|
+
if (definition === void 0) continue;
|
|
2095
|
+
const need = shellNeedOf(definition, entries);
|
|
2096
|
+
for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
|
|
2097
|
+
for (const read2 of need.drawnWith) drawnWith.push(read2);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
return { live: why.length > 0, why, drawnWith };
|
|
2101
|
+
};
|
|
2102
|
+
|
|
2103
|
+
// src/shells/host.ts
|
|
2104
|
+
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
2105
|
+
var SWEEP_EVERY_MS2 = 60 * 1e3;
|
|
2106
|
+
var DEFAULT_BUILD_TIMEOUT_MS = 3e4;
|
|
2107
|
+
var sweep = (host, idleMs) => {
|
|
2108
|
+
const { durable } = host;
|
|
2109
|
+
const now = Date.now();
|
|
2110
|
+
for (const [principal, cell] of [...durable]) {
|
|
2111
|
+
const live = cell.live;
|
|
2112
|
+
if (live.ended) {
|
|
2113
|
+
durable.delete(principal);
|
|
2114
|
+
continue;
|
|
2115
|
+
}
|
|
2116
|
+
if (live.connections.size > 0 || live.idleSince === null) continue;
|
|
2117
|
+
if (now - live.idleSince < idleMs) continue;
|
|
2118
|
+
chunkFTFME3HS_cjs.endShell(host, live);
|
|
2119
|
+
live.shell.dispose();
|
|
2120
|
+
durable.delete(principal);
|
|
2121
|
+
}
|
|
2122
|
+
};
|
|
2123
|
+
var rosterOf = (durable) => {
|
|
2124
|
+
const reports = [];
|
|
2125
|
+
for (const [principal, cell] of durable) {
|
|
2126
|
+
const live = cell.live;
|
|
2127
|
+
if (live.ended) continue;
|
|
2128
|
+
try {
|
|
2129
|
+
const canvases = reflect.snapshotShell(live.shell).canvases.filter((canvas) => canvas.items.length > 0).map((canvas) => ({ id: canvas.id, actions: canvas.items.map((item) => item.definitionId) }));
|
|
2130
|
+
reports.push({ principal, connections: live.connections.size, since: live.builtAt, idleSince: live.idleSince, canvases });
|
|
2131
|
+
} catch (error) {
|
|
2132
|
+
console.error(`[moss/shells] the shell of ${principal} could not be read for the roster, and is left off it:`, error);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
return reports;
|
|
2136
|
+
};
|
|
2137
|
+
var sameDocument = (one, other) => one === other || JSON.stringify(one) === JSON.stringify(other);
|
|
2138
|
+
var takeLayouts = (live, made) => {
|
|
2139
|
+
const taken = live.layouts;
|
|
2140
|
+
const answered = chunkFTFME3HS_cjs.layoutsOf(made);
|
|
2141
|
+
for (const [ref, layout2] of Object.entries(answered.layoutStore)) {
|
|
2142
|
+
if (!sameDocument(taken.layoutStore[ref], layout2)) live.shell.setLayout(ref, layout2);
|
|
2143
|
+
}
|
|
2144
|
+
for (const [id, fragment] of Object.entries(answered.fragments)) {
|
|
2145
|
+
if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerFragment({ ...fragment, id });
|
|
2146
|
+
}
|
|
2147
|
+
if (answered.frame !== void 0 && !sameDocument(taken.frame, answered.frame)) live.shell.setCanvasLayout(answered.frame);
|
|
2148
|
+
live.layouts = answered;
|
|
2149
|
+
};
|
|
2150
|
+
var adopt = (host, cell) => {
|
|
2151
|
+
const adopting = async () => {
|
|
2152
|
+
if (cell.live.ended) return;
|
|
2153
|
+
const changes = host.changes;
|
|
2154
|
+
const made = await host.config.composition(cell.principal);
|
|
2155
|
+
const live = cell.live;
|
|
2156
|
+
if (live.ended || changes <= cell.changes) return;
|
|
2157
|
+
cell.changes = changes;
|
|
2158
|
+
for (const [name, contract] of Object.entries(made.components)) {
|
|
2159
|
+
if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
|
|
2160
|
+
}
|
|
2161
|
+
for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
|
|
2162
|
+
for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
|
|
2163
|
+
live.actionIds = new Set(Object.keys(made.actions));
|
|
2164
|
+
live.entries = made.entries;
|
|
2165
|
+
takeLayouts(live, made);
|
|
2166
|
+
};
|
|
2167
|
+
adopting().catch((error) => {
|
|
2168
|
+
console.error(`[moss/shells] the shell of ${cell.principal ?? "nobody"} could not adopt what changed, and keeps what it held:`, error);
|
|
2169
|
+
});
|
|
2170
|
+
};
|
|
2171
|
+
var adoptAll = (host) => {
|
|
2172
|
+
host.changes += 1;
|
|
2173
|
+
for (const cell of [...host.living.values()]) adopt(host, cell);
|
|
2174
|
+
};
|
|
2175
|
+
var build = (host, asked, wanted = () => true) => {
|
|
2176
|
+
const changes = host.changes;
|
|
2177
|
+
const limit = host.config.limits?.endpointTimeoutMs ?? DEFAULT_BUILD_TIMEOUT_MS;
|
|
2178
|
+
return new Promise((resolve2, reject) => {
|
|
2179
|
+
let inTime = true;
|
|
2180
|
+
const timer = setTimeout(() => {
|
|
2181
|
+
inTime = false;
|
|
2182
|
+
reject(new Error(`moss: the shell of ${asked.principal ?? "nobody"} was not built within ${limit}ms.`));
|
|
2183
|
+
}, limit);
|
|
2184
|
+
timer.unref?.();
|
|
2185
|
+
chunkFTFME3HS_cjs.buildShell(host, { ...asked, wanted: () => inTime && wanted() }).then((live) => resolve2(live === void 0 ? void 0 : { live, changes }), reject).finally(() => clearTimeout(timer));
|
|
2186
|
+
});
|
|
2187
|
+
};
|
|
2188
|
+
var builtOrThrow = (built) => {
|
|
2189
|
+
if (built === void 0) throw new Error("moss: a build stopped without a shell, and without having run out of time.");
|
|
2190
|
+
return built;
|
|
2191
|
+
};
|
|
2192
|
+
var registerLiving = (host, cell) => {
|
|
2193
|
+
if (cell.live.ended) return;
|
|
2194
|
+
host.living.set(cell.live, cell);
|
|
2195
|
+
if (cell.changes < host.changes) adopt(host, cell);
|
|
2196
|
+
};
|
|
2197
|
+
var open2 = async (host, asked, keep) => {
|
|
2198
|
+
const { live, changes } = builtOrThrow(await build(host, { ...asked, reset: false }));
|
|
2199
|
+
const cell = { live, token: asked.token, principal: asked.principal, ...asked.opening !== void 0 ? { opening: asked.opening } : {}, changes };
|
|
2200
|
+
if (keep && asked.principal !== null) host.durable.set(asked.principal, cell);
|
|
2201
|
+
registerLiving(host, cell);
|
|
2202
|
+
return cell;
|
|
2203
|
+
};
|
|
2204
|
+
var keptCell = (host, token, principal) => {
|
|
2205
|
+
const { durable, building } = host;
|
|
2206
|
+
const newest = (cell) => {
|
|
2207
|
+
cell.token = token;
|
|
2208
|
+
return cell;
|
|
2209
|
+
};
|
|
2210
|
+
const existing = durable.get(principal);
|
|
2211
|
+
if (existing !== void 0) return Promise.resolve(newest(existing));
|
|
2212
|
+
const arriving = building.get(principal);
|
|
2213
|
+
if (arriving !== void 0) return arriving.then(newest);
|
|
2214
|
+
const started = open2(host, { token, principal }, true).finally(() => building.delete(principal));
|
|
2215
|
+
building.set(principal, started);
|
|
2216
|
+
return started;
|
|
2217
|
+
};
|
|
2218
|
+
var replaceShell = async (host, cell) => {
|
|
2219
|
+
const stands = () => !cell.live.ended;
|
|
2220
|
+
if (!stands()) return;
|
|
2221
|
+
const built = await build(host, { token: cell.token, principal: cell.principal, ...cell.opening !== void 0 ? { opening: cell.opening } : {}, reset: true }, stands);
|
|
2222
|
+
if (built === void 0) return;
|
|
2223
|
+
const old = cell.live;
|
|
2224
|
+
if (!stands()) {
|
|
2225
|
+
chunkFTFME3HS_cjs.endShell(host, built.live);
|
|
2226
|
+
built.live.shell.dispose();
|
|
2227
|
+
return;
|
|
2228
|
+
}
|
|
2229
|
+
const carried = [...old.connections].map((connection) => ({ connection, wants: old.deltaReady.has(connection) }));
|
|
2230
|
+
chunkFTFME3HS_cjs.endShell(host, old);
|
|
2231
|
+
old.connections.clear();
|
|
2232
|
+
old.shell.dispose();
|
|
2233
|
+
cell.live = built.live;
|
|
2234
|
+
cell.changes = built.changes;
|
|
2235
|
+
registerLiving(host, cell);
|
|
2236
|
+
for (const { connection, wants } of carried) chunkFTFME3HS_cjs.attach(built.live, connection, host.delta && wants);
|
|
2237
|
+
};
|
|
2238
|
+
var resetCell = (host, cell) => {
|
|
2239
|
+
const turn = (cell.resetting ?? Promise.resolve()).then(() => replaceShell(host, cell));
|
|
2240
|
+
cell.resetting = turn.catch((error) => console.error("[moss/shells] a reset failed to rebuild", error));
|
|
2241
|
+
};
|
|
2242
|
+
var shellsOf = (host, principal) => {
|
|
2243
|
+
if (!host.kept) return [...host.living.values()].filter((cell2) => cell2.principal === principal);
|
|
2244
|
+
const cell = host.durable.get(principal);
|
|
2245
|
+
return cell === void 0 || cell.live.ended ? [] : [cell];
|
|
2246
|
+
};
|
|
2247
|
+
var startSweep = (host) => {
|
|
2248
|
+
const idleMs = host.config.limits?.idleMs ?? DEFAULT_IDLE_MS;
|
|
2249
|
+
let sweeper;
|
|
2250
|
+
if (idleMs > 0 && Number.isFinite(idleMs)) {
|
|
2251
|
+
sweeper = setInterval(() => sweep(host, idleMs), Math.min(idleMs, SWEEP_EVERY_MS2));
|
|
2252
|
+
sweeper.unref?.();
|
|
2253
|
+
}
|
|
2254
|
+
return () => {
|
|
2255
|
+
if (sweeper !== void 0) clearInterval(sweeper);
|
|
2256
|
+
sweeper = void 0;
|
|
2257
|
+
};
|
|
2258
|
+
};
|
|
2259
|
+
var snapshotOf = (host) => async (token, principal, options) => {
|
|
2260
|
+
const { kept } = host;
|
|
2261
|
+
const waitMs = options?.waitMs ?? DEFAULT_SNAPSHOT_WAIT_MS;
|
|
2262
|
+
if (principal !== null && kept) {
|
|
2263
|
+
const cell = await keptCell(host, token, principal);
|
|
2264
|
+
const settled = await settle(cell.live, waitMs);
|
|
2265
|
+
return { ...read(cell.live), settled, ...needOf(cell.live, principal, kept) };
|
|
2266
|
+
}
|
|
2267
|
+
const seed = crypto$1.randomBytes(9).toString("hex");
|
|
2268
|
+
const opening = { seed, ...options?.inputs !== void 0 ? { inputs: options.inputs } : {} };
|
|
2269
|
+
const { live } = builtOrThrow(await build(host, { token, principal, opening, reset: false }));
|
|
2270
|
+
try {
|
|
2271
|
+
const settled = await settle(live, waitMs);
|
|
2272
|
+
return { ...read(live), seed, settled, ...needOf(live, principal, kept) };
|
|
2273
|
+
} finally {
|
|
2274
|
+
chunkFTFME3HS_cjs.endShell(host, live);
|
|
2275
|
+
live.shell.dispose();
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2278
|
+
var deliverTo = (host) => (principal, channel, payload) => {
|
|
2279
|
+
const took = shellsOf(host, principal).map((cell) => {
|
|
2280
|
+
try {
|
|
2281
|
+
cell.live.shell.publish(channel, payload);
|
|
2282
|
+
return true;
|
|
2283
|
+
} catch (error) {
|
|
2284
|
+
console.error(`[moss/shells] a delivery on "${channel}" to the shell of ${principal} failed:`, error);
|
|
2285
|
+
return false;
|
|
2286
|
+
}
|
|
2287
|
+
});
|
|
2288
|
+
return took.includes(true);
|
|
2289
|
+
};
|
|
2290
|
+
var createShellHost = (config) => {
|
|
2291
|
+
const host = {
|
|
2292
|
+
config,
|
|
2293
|
+
emit: chunkJYBHJDT7_cjs.emitterOf(config.telemetry),
|
|
2294
|
+
kept: config.kept ?? true,
|
|
2295
|
+
delta: config.limits?.delta ?? false,
|
|
2296
|
+
durable: /* @__PURE__ */ new Map(),
|
|
2297
|
+
building: /* @__PURE__ */ new Map(),
|
|
2298
|
+
living: /* @__PURE__ */ new Map(),
|
|
2299
|
+
changes: 0
|
|
2300
|
+
};
|
|
2301
|
+
const reset = (cell) => resetCell(host, cell);
|
|
2302
|
+
const handedOut = {
|
|
2303
|
+
session: async (token, principal, options) => {
|
|
2304
|
+
if (principal === null || !host.kept) {
|
|
2305
|
+
return chunkFTFME3HS_cjs.sessionOn(host, await open2(host, { token, principal, ...options !== void 0 ? { opening: options } : {} }, false), true, reset);
|
|
2306
|
+
}
|
|
2307
|
+
return chunkFTFME3HS_cjs.sessionOn(host, await keptCell(host, token, principal), false, reset);
|
|
2308
|
+
},
|
|
2309
|
+
snapshot: snapshotOf(host),
|
|
2310
|
+
deliver: deliverTo(host),
|
|
2311
|
+
list: () => rosterOf(host.durable),
|
|
2312
|
+
reset: (principal) => {
|
|
2313
|
+
const theirs = shellsOf(host, principal);
|
|
2314
|
+
for (const cell of theirs) reset(cell);
|
|
2315
|
+
return theirs.length > 0;
|
|
2316
|
+
}
|
|
2317
|
+
};
|
|
2318
|
+
return { host: handedOut, adopt: () => adoptAll(host), stop: startSweep(host) };
|
|
2319
|
+
};
|
|
2320
|
+
|
|
2321
|
+
// src/server/hosts.ts
|
|
2322
|
+
var hostConfig = (deps, shell2, kept) => {
|
|
2323
|
+
const { app, runtime, identity, running, data } = deps;
|
|
2324
|
+
return {
|
|
2325
|
+
composition: async (principal) => {
|
|
2326
|
+
const resolved = await identity.resolve(principal);
|
|
2327
|
+
return { roles: resolved.roles, scope: resolved.scope, ...running.artifactsFor(shell2, resolved.roles, resolved.installed) };
|
|
2328
|
+
},
|
|
2329
|
+
hooks: {
|
|
2330
|
+
...shell2.inputs !== void 0 ? { inputs: shell2.inputs } : {},
|
|
2331
|
+
...shell2.seeds !== void 0 ? { seeds: shell2.seeds } : {},
|
|
2332
|
+
...app.phrases !== void 0 ? { phrases: app.phrases } : {},
|
|
2333
|
+
...app.functions !== void 0 ? { functions: app.functions } : {},
|
|
2334
|
+
...app.onSession !== void 0 ? { onSession: app.onSession } : {},
|
|
2335
|
+
...app.runs !== void 0 ? { runs: app.runs } : {}
|
|
2336
|
+
},
|
|
2337
|
+
...app.phraseKeys !== void 0 ? { phraseKeys: app.phraseKeys } : {},
|
|
2338
|
+
kept,
|
|
2339
|
+
wire: deps.wire,
|
|
2340
|
+
wrapWire: deps.wrapWire,
|
|
2341
|
+
answerIntent: async (principal, writers, asked) => {
|
|
2342
|
+
const resolved = await identity.resolve(principal);
|
|
2343
|
+
return data.answerIntent(writers, asked, resolved, identity.composeScope(principal, resolved));
|
|
2344
|
+
},
|
|
2345
|
+
...deps.revokeSessions !== void 0 ? { revokeSessions: deps.revokeSessions } : {},
|
|
2346
|
+
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
|
|
2347
|
+
limits: {
|
|
2348
|
+
...runtime.shellIdleMs !== void 0 ? { idleMs: runtime.shellIdleMs } : {},
|
|
2349
|
+
...runtime.shellFrameDelta !== void 0 ? { delta: runtime.shellFrameDelta } : {},
|
|
2350
|
+
...runtime.endpointTimeoutMs !== void 0 ? { endpointTimeoutMs: runtime.endpointTimeoutMs } : {}
|
|
2351
|
+
}
|
|
2352
|
+
};
|
|
2353
|
+
};
|
|
2354
|
+
var buildShellHosts = (deps) => {
|
|
2355
|
+
const { app } = deps;
|
|
2356
|
+
const pageManifests = app.pages ?? {};
|
|
2357
|
+
const pageRouter = createPageRouter(pageManifests);
|
|
2358
|
+
const shells = app.shell !== void 0 ? createShellHost(hostConfig(deps, app.shell, true)) : void 0;
|
|
2359
|
+
const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(deps, manifest, false))]));
|
|
2360
|
+
const owned = [...shells !== void 0 ? [shells] : [], ...pageHosts.values()];
|
|
2361
|
+
const every = owned.map((made) => made.host);
|
|
2362
|
+
return {
|
|
2363
|
+
shells: shells?.host,
|
|
2364
|
+
pageAt: (path) => {
|
|
2365
|
+
const matched = pageRouter.match(path);
|
|
2366
|
+
if (matched === void 0) return void 0;
|
|
2367
|
+
const host = pageHosts.get(matched.name)?.host;
|
|
2368
|
+
const manifest = pageManifests[matched.name];
|
|
2369
|
+
if (host === void 0 || manifest === void 0) return void 0;
|
|
2370
|
+
return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
|
|
2371
|
+
},
|
|
2372
|
+
pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
|
|
2373
|
+
adopt: () => {
|
|
2374
|
+
for (const made of owned) made.adopt();
|
|
2375
|
+
},
|
|
2376
|
+
// `map`, not `some`: each host is asked, whatever the one before answered.
|
|
2377
|
+
reset: (principal) => every.map((host) => host.reset(principal)).includes(true),
|
|
2378
|
+
deliver: (principal, channel, payload) => every.map((host) => host.deliver(principal, channel, payload)).includes(true),
|
|
2379
|
+
stop: () => {
|
|
2380
|
+
for (const made of owned) made.stop();
|
|
2381
|
+
}
|
|
2382
|
+
};
|
|
2383
|
+
};
|
|
2384
|
+
var createInternalWire = (server) => (token) => async (url, init) => {
|
|
2385
|
+
const isVex = url.split("?")[0]?.endsWith("/vex") === true;
|
|
2386
|
+
const follower = isVex && init?.signal !== void 0 ? createWireFollower(init.signal) : void 0;
|
|
2387
|
+
const res = await server.request(
|
|
2388
|
+
url,
|
|
2389
|
+
{
|
|
2390
|
+
method: init?.method ?? "GET",
|
|
2391
|
+
headers: { ...init?.headers ?? {}, ...token !== null ? { Authorization: `Bearer ${token}` } : {} },
|
|
2392
|
+
...init?.body !== void 0 ? { body: init.body } : {}
|
|
2393
|
+
},
|
|
2394
|
+
follower === void 0 ? void 0 : { [hono$1.VEX_LIVE_ENV]: follower.live }
|
|
2395
|
+
);
|
|
2396
|
+
if (!isVex || !res.ok) {
|
|
2397
|
+
follower?.end();
|
|
2398
|
+
return res;
|
|
2399
|
+
}
|
|
2400
|
+
const body = await res.json();
|
|
2401
|
+
const result = body !== null && typeof body === "object" && "result" in body ? body.result : body;
|
|
2402
|
+
follower?.handedOver();
|
|
2403
|
+
return {
|
|
2404
|
+
ok: res.ok,
|
|
2405
|
+
status: res.status,
|
|
2406
|
+
json: () => Promise.resolve(result),
|
|
2407
|
+
text: () => Promise.resolve(JSON.stringify(result)),
|
|
2408
|
+
...follower === void 0 ? {} : { onChange: follower.onChange }
|
|
2409
|
+
};
|
|
2410
|
+
};
|
|
2411
|
+
var mountRoutes = (server, { app, session, credentials, identity, running, data }) => {
|
|
2412
|
+
server.use("*", authentication({ session, credentials, resolve: identity.resolve }));
|
|
2413
|
+
server.get("/catalog", (c) => {
|
|
2414
|
+
const principal = c.get("principal");
|
|
2415
|
+
const resolved = c.get("resolved");
|
|
2416
|
+
const { ids, hash } = running.catalogFor(resolved.roles, resolved.installed);
|
|
2417
|
+
return c.json({ principal, actions: ids, hash });
|
|
2418
|
+
});
|
|
2419
|
+
server.route(
|
|
2420
|
+
"/",
|
|
2421
|
+
data.routes({
|
|
2422
|
+
resources: app.resources,
|
|
2423
|
+
scope: (c) => identity.composeScope(c.get("principal"), c.get("resolved")),
|
|
2424
|
+
caller: (c) => c.get("resolved")
|
|
2425
|
+
})
|
|
2426
|
+
);
|
|
2427
|
+
};
|
|
2428
|
+
var INVALID_TOKEN = { refused: { status: 401, error: "invalid_token", message: "The session token did not resolve to a principal." } };
|
|
2429
|
+
var authenticateRequest = async (deps, header, request) => {
|
|
2430
|
+
if (header === void 0) return { principal: null, resolved: await deps.resolve(null) };
|
|
2431
|
+
const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
|
|
2432
|
+
const credential = deps.credentials.find(({ prefix }) => token.startsWith(prefix));
|
|
2433
|
+
if (credential !== void 0) {
|
|
2434
|
+
const answer = await credential.principalOf(token, request);
|
|
2435
|
+
if ("refused" in answer) return answer;
|
|
2436
|
+
return { principal: answer.principal, resolved: await deps.resolve(answer.principal) };
|
|
2437
|
+
}
|
|
2438
|
+
const principal = await deps.session(token);
|
|
2439
|
+
if (principal === null) return INVALID_TOKEN;
|
|
2440
|
+
return { principal, resolved: await deps.resolve(principal) };
|
|
2441
|
+
};
|
|
2442
|
+
var authentication = (deps) => async (c, next) => {
|
|
2443
|
+
let found;
|
|
2444
|
+
try {
|
|
2445
|
+
found = await authenticateRequest(deps, c.req.header("Authorization"), c.req.raw);
|
|
2446
|
+
} catch (error) {
|
|
2447
|
+
console.error("[moss] who is calling could not be found out \u2014 answering 500:", error);
|
|
2448
|
+
return c.json({ error: "identity_failed", message: "The server could not find out who is calling. Why is in its log, not here." }, 500);
|
|
2449
|
+
}
|
|
2450
|
+
if ("refused" in found) return c.json({ error: found.refused.error, message: found.refused.message }, found.refused.status);
|
|
2451
|
+
c.set("principal", found.principal);
|
|
2452
|
+
c.set("resolved", found.resolved);
|
|
2453
|
+
return next();
|
|
2454
|
+
};
|
|
2455
|
+
var secretsEqual = (a, b) => crypto$1.timingSafeEqual(crypto$1.createHash("sha256").update(a).digest(), crypto$1.createHash("sha256").update(b).digest());
|
|
2456
|
+
var guardOperator = (operator, opts) => {
|
|
2457
|
+
const gate = opts.gate;
|
|
2458
|
+
if (gate !== void 0) {
|
|
2459
|
+
operator.use("*", async (c, next) => {
|
|
2460
|
+
let wentOn = false;
|
|
2461
|
+
const answer = await gate(c, async () => {
|
|
2462
|
+
wentOn = true;
|
|
2463
|
+
await next();
|
|
2464
|
+
});
|
|
2465
|
+
if (answer === void 0 && !wentOn) await next();
|
|
2466
|
+
return answer;
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
operator.use("*", async (c, next) => {
|
|
2470
|
+
const presented = c.req.header("x-operator-key") ?? "";
|
|
2471
|
+
if (opts.key === "" || !secretsEqual(presented, opts.key)) return c.json({ message: "Not found." }, 404);
|
|
2472
|
+
return next();
|
|
2473
|
+
});
|
|
2474
|
+
};
|
|
2475
|
+
var operatorPrefix = (runtime) => {
|
|
2476
|
+
const operator = new hono.Hono();
|
|
2477
|
+
guardOperator(operator, { key: runtime.operatorKey ?? "", gate: runtime.operatorGate });
|
|
2478
|
+
return operator;
|
|
2479
|
+
};
|
|
2480
|
+
var buildSignals = ({ fabric, identity, reset, deliver }) => {
|
|
2481
|
+
const origin = crypto$1.randomBytes(8).toString("hex");
|
|
2482
|
+
const applyInvalidateIdentity = (principal) => {
|
|
2483
|
+
const held = identity.invalidate(principal);
|
|
2484
|
+
reset(principal);
|
|
2485
|
+
return held;
|
|
2486
|
+
};
|
|
2487
|
+
const applyInvalidateTenant = (tag) => identity.invalidateTag(tag).length;
|
|
2488
|
+
const applyNudge = (principal, channel) => {
|
|
2489
|
+
deliver(principal, channel);
|
|
2490
|
+
};
|
|
2491
|
+
const publish = wireFabric(fabric, origin, {
|
|
2492
|
+
invalidateIdentity: applyInvalidateIdentity,
|
|
2493
|
+
invalidateTenant: applyInvalidateTenant,
|
|
2494
|
+
nudge: applyNudge
|
|
2495
|
+
});
|
|
2496
|
+
return {
|
|
2497
|
+
invalidateIdentity: (principal) => {
|
|
2498
|
+
const held = applyInvalidateIdentity(principal);
|
|
2499
|
+
publish({ kind: "invalidate-identity", principal });
|
|
2500
|
+
return held;
|
|
2501
|
+
},
|
|
2502
|
+
invalidateTenant: (tag) => {
|
|
2503
|
+
const forgotten = applyInvalidateTenant(tag);
|
|
2504
|
+
publish({ kind: "invalidate-tenant", tag });
|
|
2505
|
+
return forgotten;
|
|
2506
|
+
},
|
|
2507
|
+
nudge: (principal, channel) => {
|
|
2508
|
+
applyNudge(principal, channel);
|
|
2509
|
+
publish({ kind: "nudge", principal, channel });
|
|
2510
|
+
},
|
|
2511
|
+
// The payload stays in this process. Across processes only the channel is
|
|
2512
|
+
// said, and a shell there reads again under its own policy.
|
|
2513
|
+
deliver: (principal, channel, payload) => {
|
|
2514
|
+
const local = deliver(principal, channel, payload);
|
|
2515
|
+
publish({ kind: "nudge", principal, channel });
|
|
2516
|
+
return local;
|
|
2517
|
+
}
|
|
2518
|
+
};
|
|
2519
|
+
};
|
|
2520
|
+
var wireFabric = (fabric, origin, apply) => {
|
|
2521
|
+
if (fabric === void 0) return () => {
|
|
2522
|
+
};
|
|
2523
|
+
let refusalSaid = false;
|
|
2524
|
+
fabric.subscribe((handed) => {
|
|
2525
|
+
const parsed = chunkJYBHJDT7_cjs.FabricMessageSchema.safeParse(handed);
|
|
2526
|
+
if (!parsed.success) {
|
|
2527
|
+
if (refusalSaid) return;
|
|
2528
|
+
refusalSaid = true;
|
|
2529
|
+
const wrong = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(the message)"}: ${issue.message}`).join("; ");
|
|
2530
|
+
console.error(`[moss:fabric] the transport handed over what is not a message, and it was dropped (${wrong}). Said once: what follows it and does not parse is dropped without a line.`);
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
const message = parsed.data;
|
|
2534
|
+
if (message.origin === origin) return;
|
|
2535
|
+
try {
|
|
2536
|
+
switch (message.kind) {
|
|
2537
|
+
case "invalidate-identity":
|
|
2538
|
+
apply.invalidateIdentity(message.principal);
|
|
2539
|
+
break;
|
|
2540
|
+
case "invalidate-tenant":
|
|
2541
|
+
apply.invalidateTenant(message.tag);
|
|
2542
|
+
break;
|
|
2543
|
+
case "nudge":
|
|
2544
|
+
apply.nudge(message.principal, message.channel);
|
|
2545
|
+
break;
|
|
2546
|
+
}
|
|
2547
|
+
} catch (err) {
|
|
2548
|
+
console.error("[moss:fabric] a remote signal failed to apply", err);
|
|
2549
|
+
}
|
|
2550
|
+
});
|
|
2551
|
+
return (signal) => {
|
|
2552
|
+
try {
|
|
2553
|
+
fabric.publish({ ...signal, origin });
|
|
2554
|
+
} catch (err) {
|
|
2555
|
+
console.error("[moss:fabric] publish failed", err);
|
|
2556
|
+
}
|
|
2557
|
+
};
|
|
2558
|
+
};
|
|
2559
|
+
|
|
2560
|
+
// src/server/server.ts
|
|
2561
|
+
var createServerWith = async (app, runtime, dataOf) => {
|
|
2562
|
+
receiveManifest(app);
|
|
2563
|
+
const session = sessionVerifierOf(runtime);
|
|
2564
|
+
const revokeSessions = sessionRevokerOf(runtime);
|
|
2565
|
+
const data = await dataOf(app, runtime);
|
|
2566
|
+
return assembleServer({ app, runtime, session, revokeSessions, data });
|
|
2567
|
+
};
|
|
2568
|
+
var createServer = (app, runtime) => createServerWith(app, runtime, buildData);
|
|
2569
|
+
var buildData = (app, runtime) => createData({
|
|
2570
|
+
pool: runtime.pool,
|
|
2571
|
+
db: runtime.db,
|
|
2572
|
+
cache: runtime.cache,
|
|
2573
|
+
vexConfig: runtime.vexConfig,
|
|
2574
|
+
migrations: runtime.migrations,
|
|
2575
|
+
storesSessions: runtime.session === "sessions",
|
|
2576
|
+
featureTables: featureTablesOf(app),
|
|
2577
|
+
tables: runtime.tables,
|
|
2578
|
+
grammars: app.grammars,
|
|
2579
|
+
charter: app.charter,
|
|
2580
|
+
behaviors: app.behaviors,
|
|
2581
|
+
telemetry: runtime.telemetry
|
|
2582
|
+
});
|
|
2583
|
+
var assembleServer = async (deps) => {
|
|
2584
|
+
const stops = [];
|
|
2585
|
+
try {
|
|
2586
|
+
return await assemble(deps, stops);
|
|
2587
|
+
} catch (error) {
|
|
2588
|
+
for (const stop of stops) stop();
|
|
2589
|
+
throw error;
|
|
2590
|
+
}
|
|
2591
|
+
};
|
|
2592
|
+
var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) => {
|
|
2593
|
+
const running = await buildRunningManifest(app, runtime, data);
|
|
2594
|
+
stops.push(running.stop);
|
|
2595
|
+
const identity = buildIdentity(app, runtime, data);
|
|
2596
|
+
stops.push(identity.stop);
|
|
2597
|
+
const server = new hono.Hono();
|
|
2598
|
+
const registered = emptyRegister();
|
|
2599
|
+
mountRoutes(server, { app, session, credentials: registered.credentials, identity, running, data });
|
|
2600
|
+
const hosts = buildShellHosts({ app, runtime, identity, running, data, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
|
|
2601
|
+
stops.push(hosts.stop);
|
|
2602
|
+
const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, deliver: hosts.deliver });
|
|
2603
|
+
running.onChange(() => {
|
|
2604
|
+
identity.invalidateAll();
|
|
2605
|
+
hosts.adopt();
|
|
2606
|
+
});
|
|
2607
|
+
const operator = operatorPrefix(runtime);
|
|
2608
|
+
await startFeatures(app.features ?? [], { app, runtime, server, operator, registered, identity, running, data });
|
|
2609
|
+
server.route("/operator", operator);
|
|
2610
|
+
subscribeReactions({ app, onWrite: data.onWrite, deliver: signals.deliver });
|
|
2611
|
+
running.watch();
|
|
2612
|
+
const socket = buildSocket({ runtime, session, identity, running, hosts });
|
|
2613
|
+
stops.push(socket.stop);
|
|
2614
|
+
return Object.assign(server, {
|
|
2615
|
+
socket,
|
|
2616
|
+
principalOf: async (token) => session(token),
|
|
2617
|
+
page: hosts.pageAt,
|
|
2618
|
+
pages: hosts.pages,
|
|
2619
|
+
...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
|
|
2620
|
+
refresh: running.refresh,
|
|
2621
|
+
replaceActions: running.replace,
|
|
2622
|
+
actions: running.actions,
|
|
2623
|
+
catalogOf: async (principal) => {
|
|
2624
|
+
const resolved = await identity.resolve(principal);
|
|
2625
|
+
return running.catalogFor(resolved.roles, resolved.installed);
|
|
2626
|
+
},
|
|
2627
|
+
policyForRoles: data.policyForRoles,
|
|
2628
|
+
charterReport: () => running.report().charter,
|
|
2629
|
+
close: () => {
|
|
2630
|
+
for (const stop of stops) stop();
|
|
2631
|
+
},
|
|
2632
|
+
executeAs: data.executeAs,
|
|
2633
|
+
identity: async (principal) => {
|
|
2634
|
+
const resolved = await identity.resolve(principal);
|
|
2635
|
+
return { roles: resolved.roles, scope: resolved.scope, ...resolved.installed !== void 0 ? { installed: resolved.installed } : {} };
|
|
2636
|
+
},
|
|
2637
|
+
invalidateTenant: signals.invalidateTenant,
|
|
2638
|
+
invalidateIdentity: signals.invalidateIdentity,
|
|
2639
|
+
nudge: signals.nudge,
|
|
2640
|
+
...identity.roster !== void 0 ? { identities: identity.roster } : {}
|
|
2641
|
+
});
|
|
2642
|
+
};
|
|
2643
|
+
var buildRunningManifest = async (app, runtime, data) => {
|
|
2644
|
+
const running = createRunningManifest({
|
|
2645
|
+
shipped: app,
|
|
2646
|
+
grants: data.grants,
|
|
2647
|
+
// Polled on the clock a socket's credential is re-verified on.
|
|
2648
|
+
pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} }
|
|
2649
|
+
});
|
|
2650
|
+
data.dropOnChange(running.onChange);
|
|
2651
|
+
await data.seed(running.entries());
|
|
2652
|
+
return running;
|
|
2653
|
+
};
|
|
2654
|
+
var buildIdentity = (app, runtime, data) => createIdentity({
|
|
2655
|
+
seam: app.identity,
|
|
2656
|
+
assignments: app.assignments,
|
|
2657
|
+
scope: app.scope,
|
|
2658
|
+
readAs: (role, fingerprint, scope) => data.executeAs(role, fingerprint, {}, scope),
|
|
2659
|
+
max: runtime.identityMax,
|
|
2660
|
+
idleMs: runtime.identityIdleMs,
|
|
2661
|
+
revalidateMs: runtime.sessionRevalidateMs ?? DEFAULT_REVALIDATE_MS
|
|
2662
|
+
});
|
|
2663
|
+
var buildSocket = ({ runtime, session, identity, running, hosts }) => {
|
|
2664
|
+
const socket = createSocket({
|
|
2665
|
+
session,
|
|
2666
|
+
catalog: async (principal) => {
|
|
2667
|
+
const resolved = await identity.resolve(principal);
|
|
2668
|
+
return running.catalogFor(resolved.roles, resolved.installed);
|
|
2669
|
+
},
|
|
2670
|
+
...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
|
|
2671
|
+
page: hosts.pageAt,
|
|
2672
|
+
...runtime.sessionRevalidateMs !== void 0 ? { revalidateMs: runtime.sessionRevalidateMs } : {},
|
|
2673
|
+
...runtime.anonymousShellMax !== void 0 ? { anonymousShellMax: runtime.anonymousShellMax } : {},
|
|
2674
|
+
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
|
|
2675
|
+
...runtime.origins !== void 0 ? { origins: runtime.origins } : {},
|
|
2676
|
+
...runtime.session === "sessions" ? { sessionLastsMs: (token) => sessionRemainingMs(runtime.pool, token) } : {}
|
|
2677
|
+
});
|
|
2678
|
+
return Object.assign(socket, {
|
|
2679
|
+
transport: {
|
|
2680
|
+
...runtime.socketCompression !== void 0 ? { compression: runtime.socketCompression } : {},
|
|
2681
|
+
...runtime.socketMaxMessageBytes !== void 0 ? { maxMessageBytes: runtime.socketMaxMessageBytes } : {}
|
|
2682
|
+
}
|
|
2683
|
+
});
|
|
2684
|
+
};
|
|
2685
|
+
var subscribeReactions = ({ app, onWrite, deliver }) => {
|
|
2686
|
+
const reactions = app.reactions;
|
|
2687
|
+
if (reactions === void 0) return;
|
|
2688
|
+
onWrite((event) => {
|
|
2689
|
+
const tools = { deliver };
|
|
2690
|
+
for (const write of event.writes) {
|
|
2691
|
+
if (write.rows.length === 0) continue;
|
|
2692
|
+
for (const reaction of reactions) {
|
|
2693
|
+
if (reaction.table !== write.table || reaction.op !== void 0 && reaction.op !== write.op) continue;
|
|
2694
|
+
try {
|
|
2695
|
+
reaction.run({ fingerprint: event.fingerprint, table: write.table, op: write.op, count: write.rows.length, scope: event.scope }, tools);
|
|
2696
|
+
} catch (err) {
|
|
2697
|
+
console.error("[moss:reactions]", err);
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
});
|
|
2702
|
+
};
|
|
2703
|
+
|
|
2704
|
+
exports.MOSS_SEQUENCE = MOSS_SEQUENCE;
|
|
2705
|
+
exports.createServer = createServer;
|
|
2706
|
+
exports.defineApp = defineApp;
|
|
2707
|
+
exports.exportDocuments = exportDocuments;
|
|
2708
|
+
exports.migrateTables = migrateTables;
|
|
2709
|
+
exports.mintDevToken = mintDevToken;
|
|
2710
|
+
exports.mintSession = mintSession;
|
|
2711
|
+
exports.renderDocument = renderDocument;
|
|
2712
|
+
exports.revokeAllFor = revokeAllFor;
|
|
2713
|
+
exports.sessionCookies = sessionCookies;
|
|
2714
|
+
exports.verifyApp = verifyApp;
|
|
2715
|
+
//# sourceMappingURL=chunk-BZK37HR3.cjs.map
|
|
2716
|
+
//# sourceMappingURL=chunk-BZK37HR3.cjs.map
|