@niscorp/moss 0.3.2 → 0.4.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 +155 -0
- package/DESIGN.md +84 -19
- package/DOCS.md +170 -35
- package/README.md +2 -2
- package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
- package/dist/chunk-4T6KAXBP.js.map +1 -0
- package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
- package/dist/chunk-HOZID4EM.js.map +1 -0
- package/dist/{chunk-ZP3C53AC.js → chunk-R3QMJ3JF.js} +744 -661
- package/dist/chunk-R3QMJ3JF.js.map +1 -0
- package/dist/chunk-U3UR5AOQ.js +103 -0
- package/dist/chunk-U3UR5AOQ.js.map +1 -0
- package/dist/client/node.cjs +1 -1
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.js +1 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +60 -26
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.js +2 -2
- package/dist/{document-D9khv9jI.d.cts → document-DhWxieUc.d.cts} +22 -3
- package/dist/{document-D9khv9jI.d.ts → document-DhWxieUc.d.ts} +22 -3
- package/dist/index.cjs +786 -583
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -3
- package/dist/index.d.ts +19 -3
- package/dist/index.js +2 -2
- package/dist/node.cjs +379 -230
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +2 -1
- package/dist/node.d.ts +2 -1
- package/dist/node.js +3 -3
- package/dist/terminal/index.cjs +60 -26
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.js +2 -2
- package/dist/vite.cjs +103 -28
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +14 -9
- package/dist/vite.js.map +1 -1
- package/package.json +12 -12
- package/dist/chunk-J72N3EMJ.js.map +0 -1
- package/dist/chunk-SUVDISEG.js +0 -64
- package/dist/chunk-SUVDISEG.js.map +0 -1
- package/dist/chunk-ZOEUEMDX.js.map +0 -1
- package/dist/chunk-ZP3C53AC.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var crypto = require('crypto');
|
|
3
|
+
var crypto$1 = require('crypto');
|
|
4
4
|
var postgres = require('@niscorp/strata/postgres');
|
|
5
5
|
var async_hooks = require('async_hooks');
|
|
6
6
|
var hono = require('hono');
|
|
7
7
|
var hono$1 = require('@niscorp/vex/hono');
|
|
8
8
|
var vex = require('@niscorp/vex');
|
|
9
9
|
var strata = require('@niscorp/strata');
|
|
10
|
-
var migrations
|
|
11
|
-
var
|
|
10
|
+
var migrations = require('@niscorp/nova/migrations');
|
|
11
|
+
var prism = require('@niscorp/prism');
|
|
12
|
+
var migrations$1 = require('@niscorp/prism/migrations');
|
|
12
13
|
var charter = require('@niscorp/charter');
|
|
13
14
|
var nova = require('@niscorp/nova');
|
|
14
|
-
var tide = require('@niscorp/tide');
|
|
15
15
|
var zod = require('zod');
|
|
16
16
|
var reflect = require('@niscorp/nova/reflect');
|
|
17
17
|
var i18n = require('@niscorp/nova/i18n');
|
|
18
|
-
var
|
|
18
|
+
var tide = require('@niscorp/tide');
|
|
19
19
|
var document = require('@niscorp/nova/document');
|
|
20
20
|
|
|
21
21
|
// src/app.ts
|
|
@@ -78,7 +78,7 @@ var wireFabric = (fabric, origin, apply) => {
|
|
|
78
78
|
}
|
|
79
79
|
};
|
|
80
80
|
};
|
|
81
|
-
var hashSessionToken = (token) => crypto.createHash("sha256").update(token).digest("hex");
|
|
81
|
+
var hashSessionToken = (token) => crypto$1.createHash("sha256").update(token).digest("hex");
|
|
82
82
|
var SESSIONS_SEQUENCE = {
|
|
83
83
|
id: "nisc.moss.sessions",
|
|
84
84
|
migrations: [
|
|
@@ -104,7 +104,7 @@ var initSessions = async (pool) => {
|
|
|
104
104
|
};
|
|
105
105
|
var mintSession = async (pool, principal, ttlMs) => {
|
|
106
106
|
await pool.query("DELETE FROM sessions WHERE expires_at < now()");
|
|
107
|
-
const token = `st_${crypto.randomBytes(32).toString("base64url")}`;
|
|
107
|
+
const token = `st_${crypto$1.randomBytes(32).toString("base64url")}`;
|
|
108
108
|
await pool.query("INSERT INTO sessions (token_hash, principal, expires_at) VALUES ($1, $2, $3)", [
|
|
109
109
|
hashSessionToken(token),
|
|
110
110
|
principal,
|
|
@@ -117,6 +117,11 @@ var sessionOf = async (pool, token) => {
|
|
|
117
117
|
const principal = res.rows[0]?.principal;
|
|
118
118
|
return typeof principal === "string" ? principal : null;
|
|
119
119
|
};
|
|
120
|
+
var sessionRemainingMs = async (pool, token) => {
|
|
121
|
+
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)]);
|
|
122
|
+
const remaining = Number(res.rows[0]?.["remaining"]);
|
|
123
|
+
return res.rows.length > 0 && Number.isFinite(remaining) ? remaining : null;
|
|
124
|
+
};
|
|
120
125
|
var revokeSession = async (pool, token) => {
|
|
121
126
|
await pool.query("DELETE FROM sessions WHERE token_hash = $1", [hashSessionToken(token)]);
|
|
122
127
|
};
|
|
@@ -180,11 +185,11 @@ var createWireFollower = (callSignal) => {
|
|
|
180
185
|
return { live, onChange, handedOver, end };
|
|
181
186
|
};
|
|
182
187
|
var grammarsOf = (app) => [
|
|
183
|
-
migrations
|
|
184
|
-
migrations.PRISM_SEQUENCE,
|
|
188
|
+
migrations.NOVA_SEQUENCE,
|
|
189
|
+
migrations$1.PRISM_SEQUENCE,
|
|
185
190
|
...app.grammars ?? []
|
|
186
191
|
];
|
|
187
|
-
var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform:
|
|
192
|
+
var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
|
|
188
193
|
var auditClosure = (definitions, variants = {}) => {
|
|
189
194
|
return (grantedIds, layoutIds = []) => {
|
|
190
195
|
const bindings = /* @__PURE__ */ new Map();
|
|
@@ -223,454 +228,95 @@ var createDataLayer = async (runtime, entries = []) => {
|
|
|
223
228
|
const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
|
|
224
229
|
await cache.init?.();
|
|
225
230
|
await vex.seedCache(cache, entries);
|
|
226
|
-
const engine = vex.createQueryEngine({ adapter, cache });
|
|
231
|
+
const engine = vex.createQueryEngine({ adapter, cache, ...runtime.vexConfig !== void 0 ? { config: runtime.vexConfig } : {} });
|
|
227
232
|
const schema = await engine.introspect();
|
|
228
233
|
return { engine, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)) };
|
|
229
234
|
};
|
|
230
|
-
var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
|
|
231
|
-
var TIDE_DDL = `
|
|
232
|
-
CREATE TABLE IF NOT EXISTS tide_fact (
|
|
233
|
-
id text PRIMARY KEY,
|
|
234
|
-
kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
|
|
235
|
-
entity text,
|
|
236
|
-
op text CHECK (op IN ('insert','update','delete')),
|
|
237
|
-
row jsonb,
|
|
238
|
-
name text,
|
|
239
|
-
payload jsonb,
|
|
240
|
-
reflex text,
|
|
241
|
-
run_id text,
|
|
242
|
-
occurrence text,
|
|
243
|
-
stats jsonb,
|
|
244
|
-
target text,
|
|
245
|
-
by text,
|
|
246
|
-
at bigint NOT NULL,
|
|
247
|
-
not_before bigint,
|
|
248
|
-
dedupe_key text,
|
|
249
|
-
cause text,
|
|
250
|
-
depth integer NOT NULL DEFAULT 0,
|
|
251
|
-
delivered_at bigint,
|
|
252
|
-
parked text,
|
|
253
|
-
released boolean,
|
|
254
|
-
-- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
|
|
255
|
-
-- anything the host ingested. The matcher refuses to hand a fact minted
|
|
256
|
-
-- under one identity to a reflex running under another, which is the only
|
|
257
|
-
-- thing standing between a carried row and somebody else's effect \u2014 tide is
|
|
258
|
-
-- the one place a row travels without being read, so no scope policy is
|
|
259
|
-
-- consulted on the way.
|
|
260
|
-
as_who text
|
|
261
|
-
);
|
|
262
|
-
|
|
263
|
-
-- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
|
|
264
|
-
-- unique: it is a distinct occurrence of something, not a repeat of it.
|
|
265
|
-
-- entity is in the key: without it, two producers over different tables
|
|
266
|
-
-- that agreed on a key value silently ate each other's rows.
|
|
267
|
-
CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
|
|
268
|
-
ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
|
|
269
|
-
WHERE dedupe_key IS NOT NULL;
|
|
270
|
-
|
|
271
|
-
-- The matcher's query, every advance.
|
|
272
|
-
CREATE INDEX IF NOT EXISTS tide_fact_due
|
|
273
|
-
ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
|
|
274
|
-
CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
|
|
275
|
-
|
|
276
|
-
CREATE TABLE IF NOT EXISTS tide_run (
|
|
277
|
-
id text PRIMARY KEY,
|
|
278
|
-
reflex_id text NOT NULL,
|
|
279
|
-
version text NOT NULL,
|
|
280
|
-
as_who text,
|
|
281
|
-
cause text NOT NULL,
|
|
282
|
-
occurrence text,
|
|
283
|
-
fact_ids jsonb,
|
|
284
|
-
state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
|
|
285
|
-
depth integer NOT NULL DEFAULT 0,
|
|
286
|
-
selected integer,
|
|
287
|
-
total integer NOT NULL DEFAULT 0,
|
|
288
|
-
done integer NOT NULL DEFAULT 0,
|
|
289
|
-
failed integer NOT NULL DEFAULT 0,
|
|
290
|
-
due_at bigint NOT NULL,
|
|
291
|
-
created_at bigint NOT NULL,
|
|
292
|
-
settled_at bigint,
|
|
293
|
-
drained boolean,
|
|
294
|
-
note text,
|
|
295
|
-
-- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
|
|
296
|
-
-- cannot open twice, a replayed fact cannot open twice, and two instances
|
|
297
|
-
-- ticking at the same moment contend instead of duplicating.
|
|
298
|
-
UNIQUE (reflex_id, cause)
|
|
299
|
-
);
|
|
300
|
-
|
|
301
|
-
CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
|
|
302
|
-
CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
|
|
303
|
-
CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
|
|
304
|
-
|
|
305
|
-
CREATE TABLE IF NOT EXISTS tide_work (
|
|
306
|
-
id text PRIMARY KEY,
|
|
307
|
-
-- ON DELETE CASCADE, because a run and its work are one fact about the
|
|
308
|
-
-- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
|
|
309
|
-
-- row that IS the "this unit already ran" record \u2014 and a restore then
|
|
310
|
-
-- re-charges the invoice.
|
|
311
|
-
run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
|
|
312
|
-
reflex_id text NOT NULL,
|
|
313
|
-
unit text NOT NULL,
|
|
314
|
-
cause text NOT NULL,
|
|
315
|
-
env jsonb NOT NULL,
|
|
316
|
-
depth integer NOT NULL DEFAULT 0,
|
|
317
|
-
state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
|
|
318
|
-
attempt integer NOT NULL DEFAULT 0,
|
|
319
|
-
token text,
|
|
320
|
-
-- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
|
|
321
|
-
-- comparison rather than a disjunction.
|
|
322
|
-
claimed_until bigint NOT NULL DEFAULT 0,
|
|
323
|
-
not_before bigint NOT NULL,
|
|
324
|
-
input jsonb,
|
|
325
|
-
output jsonb,
|
|
326
|
-
error text,
|
|
327
|
-
created_at bigint NOT NULL,
|
|
328
|
-
settled_at bigint,
|
|
329
|
-
UNIQUE (run_id, unit)
|
|
330
|
-
);
|
|
331
|
-
|
|
332
|
-
CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
|
|
333
|
-
CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
|
|
334
|
-
CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
|
|
335
|
-
|
|
336
|
-
CREATE TABLE IF NOT EXISTS tide_reflex_state (
|
|
337
|
-
reflex_id text PRIMARY KEY,
|
|
338
|
-
armed_at bigint NOT NULL DEFAULT 0,
|
|
339
|
-
materialized_through bigint
|
|
340
|
-
);
|
|
341
235
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
var
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
236
|
+
// src/generation.ts
|
|
237
|
+
var GENERATION_DDL = [
|
|
238
|
+
/* sql */
|
|
239
|
+
`CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
|
|
240
|
+
/* sql */
|
|
241
|
+
`INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
|
|
242
|
+
];
|
|
243
|
+
var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
|
|
244
|
+
var createGeneration = (pool, ctx) => {
|
|
245
|
+
const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
|
|
246
|
+
let seen = -1;
|
|
247
|
+
let checking = false;
|
|
248
|
+
const read = async () => {
|
|
249
|
+
if (checking) return;
|
|
250
|
+
checking = true;
|
|
251
|
+
try {
|
|
252
|
+
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
253
|
+
const n = Number(result.rows[0]?.n ?? 0);
|
|
254
|
+
if (!Number.isFinite(n)) return;
|
|
255
|
+
const first = seen === -1;
|
|
256
|
+
const moved = !first && n !== seen;
|
|
257
|
+
seen = n;
|
|
258
|
+
if (moved) await ctx.onMoved();
|
|
259
|
+
} catch (err) {
|
|
260
|
+
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
261
|
+
} finally {
|
|
262
|
+
checking = false;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
void read();
|
|
266
|
+
const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : void 0;
|
|
267
|
+
timer?.unref?.();
|
|
268
|
+
return {
|
|
269
|
+
bump: () => {
|
|
270
|
+
void pool.query("UPDATE moss_generation SET n = n + 1 WHERE id = 1").then(async () => {
|
|
271
|
+
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
272
|
+
seen = Number(result.rows[0]?.n ?? seen);
|
|
273
|
+
}).catch((err) => console.error("[moss:generation] could not move the pointer", err));
|
|
274
|
+
},
|
|
275
|
+
current: () => seen,
|
|
276
|
+
stop: () => {
|
|
277
|
+
if (timer !== void 0) clearInterval(timer);
|
|
278
|
+
}
|
|
279
|
+
};
|
|
360
280
|
};
|
|
361
|
-
var
|
|
362
|
-
var
|
|
363
|
-
|
|
364
|
-
"
|
|
365
|
-
"
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
"due_at",
|
|
369
|
-
"created_at",
|
|
370
|
-
"settled_at",
|
|
371
|
-
"claimed_until",
|
|
372
|
-
"armed_at",
|
|
373
|
-
"materialized_through",
|
|
374
|
-
"attempt",
|
|
375
|
-
"selected",
|
|
376
|
-
"total",
|
|
377
|
-
"done",
|
|
378
|
-
"failed"
|
|
379
|
-
]);
|
|
380
|
-
var toColumn = (column, value) => {
|
|
381
|
-
if (value === void 0) return null;
|
|
382
|
-
if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
|
|
383
|
-
return value;
|
|
281
|
+
var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
282
|
+
var fromB64url = (text) => Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
283
|
+
var signerFromSeed = (seed) => {
|
|
284
|
+
const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
|
|
285
|
+
const privateKey = crypto$1.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
|
|
286
|
+
const asInput = privateKey;
|
|
287
|
+
return { privateKey, publicKey: crypto$1.createPublicKey(asInput) };
|
|
384
288
|
};
|
|
385
|
-
var
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
return
|
|
289
|
+
var createAssertionSigner = (seedB64) => {
|
|
290
|
+
const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
|
|
291
|
+
const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : crypto$1.generateKeyPairSync("ed25519");
|
|
292
|
+
const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
|
|
293
|
+
return {
|
|
294
|
+
verifyKey,
|
|
295
|
+
mint: (claims, ttlMs = 3e4) => {
|
|
296
|
+
const iat = Date.now();
|
|
297
|
+
const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
|
|
298
|
+
return `${b64url(body)}.${b64url(crypto$1.sign(null, body, privateKey))}`;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
390
301
|
};
|
|
391
|
-
var
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
302
|
+
var verifyAssertion = (token, verifyKey, now = Date.now()) => {
|
|
303
|
+
const dot = token.indexOf(".");
|
|
304
|
+
if (dot <= 0) return void 0;
|
|
305
|
+
try {
|
|
306
|
+
const body = fromB64url(token.slice(0, dot));
|
|
307
|
+
const signature = fromB64url(token.slice(dot + 1));
|
|
308
|
+
const key = crypto$1.createPublicKey({ key: fromB64url(verifyKey), format: "der", type: "spki" });
|
|
309
|
+
if (!crypto$1.verify(null, body, key, signature)) return void 0;
|
|
310
|
+
const parsed = JSON.parse(body.toString());
|
|
311
|
+
if (typeof parsed.integration !== "string" || typeof parsed.principal !== "string") return void 0;
|
|
312
|
+
if (typeof parsed.exp !== "number" || parsed.exp <= now) return void 0;
|
|
313
|
+
return parsed;
|
|
314
|
+
} catch {
|
|
315
|
+
return void 0;
|
|
396
316
|
}
|
|
397
|
-
return entity;
|
|
398
317
|
};
|
|
399
|
-
var
|
|
400
|
-
var
|
|
401
|
-
const clauses = [];
|
|
402
|
-
const params = [];
|
|
403
|
-
const prefix = alias === "" ? "" : `${alias}.`;
|
|
404
|
-
const slot = (value) => {
|
|
405
|
-
params.push(value);
|
|
406
|
-
return `$${start + params.length - 1}`;
|
|
407
|
-
};
|
|
408
|
-
for (const [field, test] of Object.entries(where ?? {})) {
|
|
409
|
-
const column = `${prefix}${snake(field)}`;
|
|
410
|
-
const bare = snake(field);
|
|
411
|
-
if (test === null || typeof test !== "object" || Array.isArray(test)) {
|
|
412
|
-
clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
|
|
413
|
-
continue;
|
|
414
|
-
}
|
|
415
|
-
const comparison = test;
|
|
416
|
-
for (const [op, symbol] of Object.entries(COMPARATORS)) {
|
|
417
|
-
const operand = comparison[op];
|
|
418
|
-
if (operand === void 0) continue;
|
|
419
|
-
clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
|
|
420
|
-
}
|
|
421
|
-
if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
|
|
422
|
-
if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
|
|
423
|
-
if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
|
|
424
|
-
}
|
|
425
|
-
return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
|
|
426
|
-
};
|
|
427
|
-
var compileOrder = (order, alias = "") => {
|
|
428
|
-
if (order === void 0 || order.length === 0) return "";
|
|
429
|
-
const prefix = alias === "" ? "" : `${alias}.`;
|
|
430
|
-
return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
|
|
431
|
-
};
|
|
432
|
-
var sortRows = (rows, order) => {
|
|
433
|
-
if (order === void 0 || order.length === 0) return [...rows];
|
|
434
|
-
return [...rows].sort((left, right) => {
|
|
435
|
-
for (const key of order) {
|
|
436
|
-
const a = left[String(key.by)];
|
|
437
|
-
const b = right[String(key.by)];
|
|
438
|
-
const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
|
|
439
|
-
if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
|
|
440
|
-
}
|
|
441
|
-
return 0;
|
|
442
|
-
});
|
|
443
|
-
};
|
|
444
|
-
var compileSet = (set, start) => {
|
|
445
|
-
const assignments = [];
|
|
446
|
-
const params = [];
|
|
447
|
-
for (const [field, value] of Object.entries(set)) {
|
|
448
|
-
const column = snake(field);
|
|
449
|
-
if (value !== null && typeof value === "object" && "inc" in value) {
|
|
450
|
-
assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
|
|
451
|
-
continue;
|
|
452
|
-
}
|
|
453
|
-
params.push(toColumn(column, value));
|
|
454
|
-
assignments.push(`${column} = $${start + params.length - 1}`);
|
|
455
|
-
}
|
|
456
|
-
return { sql: assignments.join(", "), params };
|
|
457
|
-
};
|
|
458
|
-
var mintId = /* @__PURE__ */ (() => {
|
|
459
|
-
let sequence = 0;
|
|
460
|
-
return (table) => {
|
|
461
|
-
sequence += 1;
|
|
462
|
-
return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
|
|
463
|
-
};
|
|
464
|
-
})();
|
|
465
|
-
var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
|
|
466
|
-
var TIDE_SEQUENCE = {
|
|
467
|
-
id: "nisc.moss.tide",
|
|
468
|
-
migrations: [
|
|
469
|
-
{ description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
|
|
470
|
-
{
|
|
471
|
-
// A fact's chain: the root it belongs to, and — on a root — how many facts
|
|
472
|
-
// the chain has minted beneath it. Nullable: every existing fact is a
|
|
473
|
-
// root nothing has been counted against yet.
|
|
474
|
-
description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
|
|
475
|
-
steps: [
|
|
476
|
-
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
|
|
477
|
-
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
|
|
478
|
-
]
|
|
479
|
-
}
|
|
480
|
-
]
|
|
481
|
-
};
|
|
482
|
-
var createTideStore = (pool, options = {}) => {
|
|
483
|
-
const ready = options.migrate === false ? Promise.resolve() : postgres.migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
|
|
484
|
-
ready.catch(() => void 0);
|
|
485
|
-
const build = (client) => {
|
|
486
|
-
const store = {
|
|
487
|
-
query: async (spec) => {
|
|
488
|
-
await ready;
|
|
489
|
-
const where = compileWhere(spec.where, 1);
|
|
490
|
-
const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
|
|
491
|
-
const result = await client.query(
|
|
492
|
-
`SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
|
|
493
|
-
where.params
|
|
494
|
-
);
|
|
495
|
-
return result.rows.map((row) => rowToEntity(spec.table, row));
|
|
496
|
-
},
|
|
497
|
-
// ON CONFLICT DO NOTHING, which is the whole point: the refusal is the
|
|
498
|
-
// DATABASE's, decided under the constraint, not a read the caller races.
|
|
499
|
-
appendIfAbsent: async (table, input) => {
|
|
500
|
-
await ready;
|
|
501
|
-
const withId = tide.PRIMARY_KEY[table] === "id" ? { ...input, id: input.id ?? mintId(table) } : { ...input };
|
|
502
|
-
const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
|
|
503
|
-
const columns = entries.map(([field]) => snake(field));
|
|
504
|
-
const params = entries.map(([field, value]) => toColumn(snake(field), value));
|
|
505
|
-
const unique = tide.UNIQUE_BY[table];
|
|
506
|
-
const target = unique.when === void 0 ? `(${unique.by.map((column) => snake(String(column))).join(", ")})` : `(${unique.by.map((column) => column === "entity" || column === "name" ? `coalesce(${snake(String(column))},'')` : snake(String(column))).join(", ")}) WHERE ${snake(String(unique.when))} IS NOT NULL`;
|
|
507
|
-
const result = await client.query(
|
|
508
|
-
`INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
|
|
509
|
-
ON CONFLICT ${target} DO NOTHING RETURNING *`,
|
|
510
|
-
params
|
|
511
|
-
);
|
|
512
|
-
const row = result.rows[0];
|
|
513
|
-
return row === void 0 ? void 0 : rowToEntity(table, row);
|
|
514
|
-
},
|
|
515
|
-
// Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`
|
|
516
|
-
// makes N instances ticking at once ordinary contention rather than a
|
|
517
|
-
// lock service — it is a throughput choice; the exactly-once promise is
|
|
518
|
-
// the single statement.
|
|
519
|
-
claim: async (spec) => {
|
|
520
|
-
await ready;
|
|
521
|
-
const table = SQL_TABLE[spec.table];
|
|
522
|
-
const order = compileOrder(spec.order, "c");
|
|
523
|
-
const take = async (extra, limit) => {
|
|
524
|
-
if (limit <= 0) return [];
|
|
525
|
-
const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
|
|
526
|
-
const set = compileSet(spec.set, where.params.length + 1);
|
|
527
|
-
const result = await client.query(
|
|
528
|
-
`UPDATE ${table} SET ${set.sql}
|
|
529
|
-
WHERE ctid IN (
|
|
530
|
-
SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
|
|
531
|
-
LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
|
|
532
|
-
)
|
|
533
|
-
RETURNING *`,
|
|
534
|
-
[...where.params, ...set.params]
|
|
535
|
-
);
|
|
536
|
-
return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
|
|
537
|
-
};
|
|
538
|
-
if (spec.onePer === void 0) return take({}, spec.limit);
|
|
539
|
-
const { column, held, only } = spec.onePer;
|
|
540
|
-
const restricted = [...only];
|
|
541
|
-
const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);
|
|
542
|
-
for (const group of restricted) {
|
|
543
|
-
if (claimed.length >= spec.limit) break;
|
|
544
|
-
const busy = compileWhere({ ...held, [String(column)]: group }, 1, "c");
|
|
545
|
-
const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
|
|
546
|
-
if (taken.rows.length > 0) continue;
|
|
547
|
-
claimed.push(...await take({ [String(column)]: group }, 1));
|
|
548
|
-
}
|
|
549
|
-
return claimed;
|
|
550
|
-
},
|
|
551
|
-
cas: async (table, id, expect, set) => {
|
|
552
|
-
await ready;
|
|
553
|
-
const key = snake(String(tide.PRIMARY_KEY[table]));
|
|
554
|
-
const where = compileWhere(expect, 2);
|
|
555
|
-
const patch = compileSet(set, where.params.length + 2);
|
|
556
|
-
const result = await client.query(
|
|
557
|
-
`UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
|
|
558
|
-
[id, ...where.params, ...patch.params]
|
|
559
|
-
);
|
|
560
|
-
return result.rows.length > 0;
|
|
561
|
-
},
|
|
562
|
-
remove: async (spec) => {
|
|
563
|
-
await ready;
|
|
564
|
-
const where = compileWhere(spec.where, 1);
|
|
565
|
-
const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(tide.PRIMARY_KEY[spec.table]))}`, where.params);
|
|
566
|
-
return result.rows.length;
|
|
567
|
-
},
|
|
568
|
-
transact: async (fn) => {
|
|
569
|
-
await ready;
|
|
570
|
-
if (client.transaction === void 0)
|
|
571
|
-
throw new Error("tide store: this pool cannot transact \u2014 fan-out and attempt recording are transactions, not conventions");
|
|
572
|
-
return client.transaction((tx) => fn(build({ ...client, query: (text, values) => tx.query(text, values) })));
|
|
573
|
-
}
|
|
574
|
-
};
|
|
575
|
-
return store;
|
|
576
|
-
};
|
|
577
|
-
return { ...build(pool), ready };
|
|
578
|
-
};
|
|
579
|
-
var mintWrites = async (intake, event, as, at, chain) => {
|
|
580
|
-
for (const write of event.writes) {
|
|
581
|
-
for (const row of write.rows) {
|
|
582
|
-
await intake.ingest(
|
|
583
|
-
{ kind: "write", entity: write.table, op: write.op, row, at },
|
|
584
|
-
{ as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
|
|
585
|
-
);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
// src/generation.ts
|
|
591
|
-
var GENERATION_DDL = [
|
|
592
|
-
/* sql */
|
|
593
|
-
`CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
|
|
594
|
-
/* sql */
|
|
595
|
-
`INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
|
|
596
|
-
];
|
|
597
|
-
var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
|
|
598
|
-
var createGeneration = (pool, ctx) => {
|
|
599
|
-
const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
|
|
600
|
-
let seen = -1;
|
|
601
|
-
let checking = false;
|
|
602
|
-
const read = async () => {
|
|
603
|
-
if (checking) return;
|
|
604
|
-
checking = true;
|
|
605
|
-
try {
|
|
606
|
-
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
607
|
-
const n = Number(result.rows[0]?.n ?? 0);
|
|
608
|
-
if (!Number.isFinite(n)) return;
|
|
609
|
-
const first = seen === -1;
|
|
610
|
-
const moved = !first && n !== seen;
|
|
611
|
-
seen = n;
|
|
612
|
-
if (moved) await ctx.onMoved();
|
|
613
|
-
} catch (err) {
|
|
614
|
-
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
615
|
-
} finally {
|
|
616
|
-
checking = false;
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
void read();
|
|
620
|
-
const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : void 0;
|
|
621
|
-
timer?.unref?.();
|
|
622
|
-
return {
|
|
623
|
-
bump: () => {
|
|
624
|
-
void pool.query("UPDATE moss_generation SET n = n + 1 WHERE id = 1").then(async () => {
|
|
625
|
-
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
626
|
-
seen = Number(result.rows[0]?.n ?? seen);
|
|
627
|
-
}).catch((err) => console.error("[moss:generation] could not move the pointer", err));
|
|
628
|
-
},
|
|
629
|
-
current: () => seen,
|
|
630
|
-
stop: () => {
|
|
631
|
-
if (timer !== void 0) clearInterval(timer);
|
|
632
|
-
}
|
|
633
|
-
};
|
|
634
|
-
};
|
|
635
|
-
var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
636
|
-
var fromB64url = (text) => Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
637
|
-
var signerFromSeed = (seed) => {
|
|
638
|
-
const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
|
|
639
|
-
const privateKey = crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
|
|
640
|
-
const asInput = privateKey;
|
|
641
|
-
return { privateKey, publicKey: crypto.createPublicKey(asInput) };
|
|
642
|
-
};
|
|
643
|
-
var createAssertionSigner = (seedB64) => {
|
|
644
|
-
const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
|
|
645
|
-
const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : crypto.generateKeyPairSync("ed25519");
|
|
646
|
-
const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
|
|
647
|
-
return {
|
|
648
|
-
verifyKey,
|
|
649
|
-
mint: (claims, ttlMs = 3e4) => {
|
|
650
|
-
const iat = Date.now();
|
|
651
|
-
const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
|
|
652
|
-
return `${b64url(body)}.${b64url(crypto.sign(null, body, privateKey))}`;
|
|
653
|
-
}
|
|
654
|
-
};
|
|
655
|
-
};
|
|
656
|
-
var verifyAssertion = (token, verifyKey, now = Date.now()) => {
|
|
657
|
-
const dot = token.indexOf(".");
|
|
658
|
-
if (dot <= 0) return void 0;
|
|
659
|
-
try {
|
|
660
|
-
const body = fromB64url(token.slice(0, dot));
|
|
661
|
-
const signature = fromB64url(token.slice(dot + 1));
|
|
662
|
-
const key = crypto.createPublicKey({ key: fromB64url(verifyKey), format: "der", type: "spki" });
|
|
663
|
-
if (!crypto.verify(null, body, key, signature)) return void 0;
|
|
664
|
-
const parsed = JSON.parse(body.toString());
|
|
665
|
-
if (typeof parsed.integration !== "string" || typeof parsed.principal !== "string") return void 0;
|
|
666
|
-
if (typeof parsed.exp !== "number" || parsed.exp <= now) return void 0;
|
|
667
|
-
return parsed;
|
|
668
|
-
} catch {
|
|
669
|
-
return void 0;
|
|
670
|
-
}
|
|
671
|
-
};
|
|
672
|
-
var mintIntegrationKey = () => `ik_${crypto.randomBytes(32).toString("hex")}`;
|
|
673
|
-
var hashIntegrationKey = (key) => crypto.createHash("sha256").update(key).digest("hex");
|
|
318
|
+
var mintIntegrationKey = () => `ik_${crypto$1.randomBytes(32).toString("hex")}`;
|
|
319
|
+
var hashIntegrationKey = (key) => crypto$1.createHash("sha256").update(key).digest("hex");
|
|
674
320
|
|
|
675
321
|
// src/integrations.ts
|
|
676
322
|
var configurationBase = {
|
|
@@ -1508,89 +1154,539 @@ var buildContract = (app, integrationId) => {
|
|
|
1508
1154
|
const parts = String(entry).split(".");
|
|
1509
1155
|
if (parts[0] === "ext" && parts[1] !== void 0 && parts[1] !== "*") audiences.add(parts[1]);
|
|
1510
1156
|
}
|
|
1511
|
-
}
|
|
1512
|
-
const attachable = {};
|
|
1513
|
-
for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);
|
|
1514
|
-
return {
|
|
1515
|
-
components,
|
|
1516
|
-
audiences: [...audiences].sort(),
|
|
1517
|
-
namespace: `ext.<audience>.${integrationId}.<name>`,
|
|
1518
|
-
actionSchema: "nova ActionDefinition",
|
|
1519
|
-
attachable,
|
|
1520
|
-
menuSlots: [...app.menuSlots ?? []]
|
|
1157
|
+
}
|
|
1158
|
+
const attachable = {};
|
|
1159
|
+
for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);
|
|
1160
|
+
return {
|
|
1161
|
+
components,
|
|
1162
|
+
audiences: [...audiences].sort(),
|
|
1163
|
+
namespace: `ext.<audience>.${integrationId}.<name>`,
|
|
1164
|
+
actionSchema: "nova ActionDefinition",
|
|
1165
|
+
attachable,
|
|
1166
|
+
menuSlots: [...app.menuSlots ?? []]
|
|
1167
|
+
};
|
|
1168
|
+
};
|
|
1169
|
+
var describeProp = (schema) => {
|
|
1170
|
+
const enumValues = schema["enum"];
|
|
1171
|
+
if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(", ")}`;
|
|
1172
|
+
const anyOf = schema["anyOf"];
|
|
1173
|
+
if (Array.isArray(anyOf)) {
|
|
1174
|
+
const consts = anyOf.map((s) => s["const"]).filter((v) => v !== void 0);
|
|
1175
|
+
if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(", ")}`;
|
|
1176
|
+
}
|
|
1177
|
+
const type = schema["type"];
|
|
1178
|
+
const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
|
|
1179
|
+
const min = schema["minimum"];
|
|
1180
|
+
const max = schema["maximum"];
|
|
1181
|
+
if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
|
|
1182
|
+
return base;
|
|
1183
|
+
};
|
|
1184
|
+
var componentAsMarkdown = (component) => {
|
|
1185
|
+
const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
|
|
1186
|
+
const schema = component.propsSchema;
|
|
1187
|
+
const properties = schema?.properties;
|
|
1188
|
+
if (properties === void 0 || Object.keys(properties).length === 0) return head;
|
|
1189
|
+
const required = new Set(schema?.required ?? []);
|
|
1190
|
+
const rows = Object.entries(properties).map(
|
|
1191
|
+
([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
|
|
1192
|
+
);
|
|
1193
|
+
return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
|
|
1194
|
+
};
|
|
1195
|
+
var contractAsMarkdown = (contract, fingerprints) => [
|
|
1196
|
+
`# What you can build against`,
|
|
1197
|
+
``,
|
|
1198
|
+
`## Your namespace`,
|
|
1199
|
+
``,
|
|
1200
|
+
` ${contract.namespace}`,
|
|
1201
|
+
``,
|
|
1202
|
+
`Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
|
|
1203
|
+
``,
|
|
1204
|
+
`## Components your layouts may use`,
|
|
1205
|
+
``,
|
|
1206
|
+
contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
|
|
1207
|
+
``,
|
|
1208
|
+
`## Fingerprints you may call`,
|
|
1209
|
+
``,
|
|
1210
|
+
`Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
|
|
1211
|
+
`\`/integrations/<your id>/\`. Nothing else.`,
|
|
1212
|
+
``,
|
|
1213
|
+
fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
|
|
1214
|
+
``,
|
|
1215
|
+
`## Where your screens may appear`,
|
|
1216
|
+
``,
|
|
1217
|
+
`Declare \`attachments\` (action \u2192 host action) to ride a host screen, and`,
|
|
1218
|
+
`\`placements\` (action \u2192 hub) to list under a menu hub. \`settings\` names the one`,
|
|
1219
|
+
`action the store tile opens. Anything else is refused.`,
|
|
1220
|
+
``,
|
|
1221
|
+
`Attachable, with what each hands you as input:`,
|
|
1222
|
+
``,
|
|
1223
|
+
Object.entries(contract.attachable).map(([action, offers]) => `- ${action} \u2014 offers ${offers.join(", ") || "(nothing)"}`).join("\n") || "(none)",
|
|
1224
|
+
``,
|
|
1225
|
+
`Menu hubs accepting placements:`,
|
|
1226
|
+
``,
|
|
1227
|
+
contract.menuSlots.map((hub) => `- ${hub}`).join("\n") || "(none)",
|
|
1228
|
+
``,
|
|
1229
|
+
`## What you cannot ship`,
|
|
1230
|
+
``,
|
|
1231
|
+
`- vex entries or mutations. Call what is listed above; if you need a read that`,
|
|
1232
|
+
` does not exist, it is a change to the app.`,
|
|
1233
|
+
`- \`fn:\` endpoints. Those run in the app's process.`,
|
|
1234
|
+
`- components. Layouts compose what is listed above.`,
|
|
1235
|
+
`- tables. Bring your own storage; we hand you identifiers.`,
|
|
1236
|
+
``
|
|
1237
|
+
].join("\n");
|
|
1238
|
+
|
|
1239
|
+
// src/migrate.ts
|
|
1240
|
+
var tableSequencesOf = (runtime) => {
|
|
1241
|
+
const cacheSequence = (runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool })).sequence;
|
|
1242
|
+
return [
|
|
1243
|
+
MOSS_SEQUENCE,
|
|
1244
|
+
...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [],
|
|
1245
|
+
...cacheSequence === void 0 ? [] : [cacheSequence],
|
|
1246
|
+
...runtime.tables ?? []
|
|
1247
|
+
];
|
|
1248
|
+
};
|
|
1249
|
+
var misfitOf = (entry, schema) => {
|
|
1250
|
+
if (!("mutation" in entry)) {
|
|
1251
|
+
try {
|
|
1252
|
+
vex.resolve(vex.pruneOptional(entry.dsl, "all"), schema);
|
|
1253
|
+
return void 0;
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
return error instanceof Error ? error.message : String(error);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
return vex.mutationMisfits(entry.mutation, schema)[0];
|
|
1259
|
+
};
|
|
1260
|
+
var misfitsOf = (entries, schema) => {
|
|
1261
|
+
const misfits = /* @__PURE__ */ new Map();
|
|
1262
|
+
for (const entry of entries) {
|
|
1263
|
+
const why = misfitOf(entry, schema);
|
|
1264
|
+
if (why !== void 0) misfits.set(entry.fingerprint, why);
|
|
1265
|
+
}
|
|
1266
|
+
return misfits;
|
|
1267
|
+
};
|
|
1268
|
+
var canonical = (value) => {
|
|
1269
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
1270
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1271
|
+
const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
|
|
1272
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
|
|
1273
|
+
};
|
|
1274
|
+
var isSeededAs = async (cache, entry) => {
|
|
1275
|
+
const held = await cache.get(entry.fingerprint);
|
|
1276
|
+
if (held === void 0 || held.protected !== true) return false;
|
|
1277
|
+
if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
|
|
1278
|
+
return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
|
|
1279
|
+
};
|
|
1280
|
+
var changesBetween = (before, after) => {
|
|
1281
|
+
const removed = [];
|
|
1282
|
+
const retyped = [];
|
|
1283
|
+
for (const was of before.entities) {
|
|
1284
|
+
const now = after.entities.find((entity) => entity.table === was.table);
|
|
1285
|
+
if (now === void 0) {
|
|
1286
|
+
removed.push(was.table);
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
for (const field of was.fields) {
|
|
1290
|
+
const kept = now.fields.find((f) => f.name === field.name);
|
|
1291
|
+
if (kept === void 0) removed.push(`${was.table}.${field.name}`);
|
|
1292
|
+
else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
return { removed, retyped };
|
|
1296
|
+
};
|
|
1297
|
+
var oneAtATime = (query) => {
|
|
1298
|
+
let last = Promise.resolve();
|
|
1299
|
+
return (text, values) => {
|
|
1300
|
+
const next = last.then(() => query(text, values));
|
|
1301
|
+
last = next.catch(() => void 0);
|
|
1302
|
+
return next;
|
|
1303
|
+
};
|
|
1304
|
+
};
|
|
1305
|
+
var migrateTables = async (runtime, app, options = {}) => {
|
|
1306
|
+
const entries = app.entries ?? [];
|
|
1307
|
+
const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
|
|
1308
|
+
const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
|
|
1309
|
+
const misfitsBefore = misfitsOf(entries, before);
|
|
1310
|
+
const excused = /* @__PURE__ */ new Set();
|
|
1311
|
+
for (const entry of entries) {
|
|
1312
|
+
if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
|
|
1313
|
+
}
|
|
1314
|
+
let found = { removed: [], retyped: [], alreadyBroken: [] };
|
|
1315
|
+
const report = await postgres.migrate(runtime.pool, tableSequencesOf(runtime), {
|
|
1316
|
+
...options.dryRun === true ? { dryRun: true } : {},
|
|
1317
|
+
guard: async (tx) => {
|
|
1318
|
+
const after = await vex.createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
|
|
1319
|
+
const refused = [];
|
|
1320
|
+
const alreadyBroken = [];
|
|
1321
|
+
for (const [fingerprint, why] of misfitsOf(entries, after)) {
|
|
1322
|
+
if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
|
|
1323
|
+
else refused.push(`${fingerprint}: ${why}`);
|
|
1324
|
+
}
|
|
1325
|
+
found = { ...changesBetween(before, after), alreadyBroken };
|
|
1326
|
+
return refused;
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
|
|
1330
|
+
};
|
|
1331
|
+
var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
|
|
1332
|
+
var TIDE_DDL = `
|
|
1333
|
+
CREATE TABLE IF NOT EXISTS tide_fact (
|
|
1334
|
+
id text PRIMARY KEY,
|
|
1335
|
+
kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
|
|
1336
|
+
entity text,
|
|
1337
|
+
op text CHECK (op IN ('insert','update','delete')),
|
|
1338
|
+
row jsonb,
|
|
1339
|
+
name text,
|
|
1340
|
+
payload jsonb,
|
|
1341
|
+
reflex text,
|
|
1342
|
+
run_id text,
|
|
1343
|
+
occurrence text,
|
|
1344
|
+
stats jsonb,
|
|
1345
|
+
target text,
|
|
1346
|
+
by text,
|
|
1347
|
+
at bigint NOT NULL,
|
|
1348
|
+
not_before bigint,
|
|
1349
|
+
dedupe_key text,
|
|
1350
|
+
cause text,
|
|
1351
|
+
depth integer NOT NULL DEFAULT 0,
|
|
1352
|
+
delivered_at bigint,
|
|
1353
|
+
parked text,
|
|
1354
|
+
released boolean,
|
|
1355
|
+
-- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
|
|
1356
|
+
-- anything the host ingested. The matcher refuses to hand a fact minted
|
|
1357
|
+
-- under one identity to a reflex running under another, which is the only
|
|
1358
|
+
-- thing standing between a carried row and somebody else's effect \u2014 tide is
|
|
1359
|
+
-- the one place a row travels without being read, so no scope policy is
|
|
1360
|
+
-- consulted on the way.
|
|
1361
|
+
as_who text
|
|
1362
|
+
);
|
|
1363
|
+
|
|
1364
|
+
-- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
|
|
1365
|
+
-- unique: it is a distinct occurrence of something, not a repeat of it.
|
|
1366
|
+
-- entity is in the key: without it, two producers over different tables
|
|
1367
|
+
-- that agreed on a key value silently ate each other's rows.
|
|
1368
|
+
CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
|
|
1369
|
+
ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
|
|
1370
|
+
WHERE dedupe_key IS NOT NULL;
|
|
1371
|
+
|
|
1372
|
+
-- The matcher's query, every advance.
|
|
1373
|
+
CREATE INDEX IF NOT EXISTS tide_fact_due
|
|
1374
|
+
ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
|
|
1375
|
+
CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
|
|
1376
|
+
|
|
1377
|
+
CREATE TABLE IF NOT EXISTS tide_run (
|
|
1378
|
+
id text PRIMARY KEY,
|
|
1379
|
+
reflex_id text NOT NULL,
|
|
1380
|
+
version text NOT NULL,
|
|
1381
|
+
as_who text,
|
|
1382
|
+
cause text NOT NULL,
|
|
1383
|
+
occurrence text,
|
|
1384
|
+
fact_ids jsonb,
|
|
1385
|
+
state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
|
|
1386
|
+
depth integer NOT NULL DEFAULT 0,
|
|
1387
|
+
selected integer,
|
|
1388
|
+
total integer NOT NULL DEFAULT 0,
|
|
1389
|
+
done integer NOT NULL DEFAULT 0,
|
|
1390
|
+
failed integer NOT NULL DEFAULT 0,
|
|
1391
|
+
due_at bigint NOT NULL,
|
|
1392
|
+
created_at bigint NOT NULL,
|
|
1393
|
+
settled_at bigint,
|
|
1394
|
+
drained boolean,
|
|
1395
|
+
note text,
|
|
1396
|
+
-- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
|
|
1397
|
+
-- cannot open twice, a replayed fact cannot open twice, and two instances
|
|
1398
|
+
-- ticking at the same moment contend instead of duplicating.
|
|
1399
|
+
UNIQUE (reflex_id, cause)
|
|
1400
|
+
);
|
|
1401
|
+
|
|
1402
|
+
CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
|
|
1403
|
+
CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
|
|
1404
|
+
CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
|
|
1405
|
+
|
|
1406
|
+
CREATE TABLE IF NOT EXISTS tide_work (
|
|
1407
|
+
id text PRIMARY KEY,
|
|
1408
|
+
-- ON DELETE CASCADE, because a run and its work are one fact about the
|
|
1409
|
+
-- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
|
|
1410
|
+
-- row that IS the "this unit already ran" record \u2014 and a restore then
|
|
1411
|
+
-- re-charges the invoice.
|
|
1412
|
+
run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
|
|
1413
|
+
reflex_id text NOT NULL,
|
|
1414
|
+
unit text NOT NULL,
|
|
1415
|
+
cause text NOT NULL,
|
|
1416
|
+
env jsonb NOT NULL,
|
|
1417
|
+
depth integer NOT NULL DEFAULT 0,
|
|
1418
|
+
state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
|
|
1419
|
+
attempt integer NOT NULL DEFAULT 0,
|
|
1420
|
+
token text,
|
|
1421
|
+
-- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
|
|
1422
|
+
-- comparison rather than a disjunction.
|
|
1423
|
+
claimed_until bigint NOT NULL DEFAULT 0,
|
|
1424
|
+
not_before bigint NOT NULL,
|
|
1425
|
+
input jsonb,
|
|
1426
|
+
output jsonb,
|
|
1427
|
+
error text,
|
|
1428
|
+
created_at bigint NOT NULL,
|
|
1429
|
+
settled_at bigint,
|
|
1430
|
+
UNIQUE (run_id, unit)
|
|
1431
|
+
);
|
|
1432
|
+
|
|
1433
|
+
CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
|
|
1434
|
+
CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
|
|
1435
|
+
CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
|
|
1436
|
+
|
|
1437
|
+
CREATE TABLE IF NOT EXISTS tide_reflex_state (
|
|
1438
|
+
reflex_id text PRIMARY KEY,
|
|
1439
|
+
armed_at bigint NOT NULL DEFAULT 0,
|
|
1440
|
+
materialized_through bigint
|
|
1441
|
+
);
|
|
1442
|
+
|
|
1443
|
+
-- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
|
|
1444
|
+
-- re-discover them late), and their cursor state goes with them. IF EXISTS,
|
|
1445
|
+
-- so a store created after the removal is not asked to drop what it never had.
|
|
1446
|
+
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
|
|
1447
|
+
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
|
|
1448
|
+
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
|
|
1449
|
+
`;
|
|
1450
|
+
var SQL_TABLE = {
|
|
1451
|
+
fact: "tide_fact",
|
|
1452
|
+
run: "tide_run",
|
|
1453
|
+
task: "tide_work",
|
|
1454
|
+
state: "tide_reflex_state"
|
|
1455
|
+
};
|
|
1456
|
+
var COLUMN_OVERRIDES = { as: "as_who" };
|
|
1457
|
+
var snake = (field) => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
1458
|
+
var camel = (column) => {
|
|
1459
|
+
for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;
|
|
1460
|
+
return column.replace(/_([a-z])/g, (_all, c) => c.toUpperCase());
|
|
1461
|
+
};
|
|
1462
|
+
var JSON_COLUMNS = /* @__PURE__ */ new Set(["row", "payload", "stats", "fact_ids", "env", "input", "output"]);
|
|
1463
|
+
var BIGINT_COLUMNS = /* @__PURE__ */ new Set([
|
|
1464
|
+
"at",
|
|
1465
|
+
"not_before",
|
|
1466
|
+
"delivered_at",
|
|
1467
|
+
"depth",
|
|
1468
|
+
"descendants",
|
|
1469
|
+
"due_at",
|
|
1470
|
+
"created_at",
|
|
1471
|
+
"settled_at",
|
|
1472
|
+
"claimed_until",
|
|
1473
|
+
"armed_at",
|
|
1474
|
+
"materialized_through",
|
|
1475
|
+
"attempt",
|
|
1476
|
+
"selected",
|
|
1477
|
+
"total",
|
|
1478
|
+
"done",
|
|
1479
|
+
"failed"
|
|
1480
|
+
]);
|
|
1481
|
+
var toColumn = (column, value) => {
|
|
1482
|
+
if (value === void 0) return null;
|
|
1483
|
+
if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
|
|
1484
|
+
return value;
|
|
1485
|
+
};
|
|
1486
|
+
var fromColumn = (column, value) => {
|
|
1487
|
+
if (value === null) return void 0;
|
|
1488
|
+
if (JSON_COLUMNS.has(column)) return typeof value === "string" ? JSON.parse(value) : value;
|
|
1489
|
+
if (BIGINT_COLUMNS.has(column)) return Number(value);
|
|
1490
|
+
return value;
|
|
1491
|
+
};
|
|
1492
|
+
var rowToEntity = (table, row) => {
|
|
1493
|
+
const entity = {};
|
|
1494
|
+
for (const [column, value] of Object.entries(row)) {
|
|
1495
|
+
const mapped = fromColumn(column, value);
|
|
1496
|
+
if (mapped !== void 0) entity[camel(column)] = mapped;
|
|
1497
|
+
}
|
|
1498
|
+
return entity;
|
|
1499
|
+
};
|
|
1500
|
+
var COMPARATORS = { eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=" };
|
|
1501
|
+
var compileWhere = (where, start, alias = "") => {
|
|
1502
|
+
const clauses = [];
|
|
1503
|
+
const params = [];
|
|
1504
|
+
const prefix = alias === "" ? "" : `${alias}.`;
|
|
1505
|
+
const slot = (value) => {
|
|
1506
|
+
params.push(value);
|
|
1507
|
+
return `$${start + params.length - 1}`;
|
|
1508
|
+
};
|
|
1509
|
+
for (const [field, test] of Object.entries(where ?? {})) {
|
|
1510
|
+
const column = `${prefix}${snake(field)}`;
|
|
1511
|
+
const bare = snake(field);
|
|
1512
|
+
if (test === null || typeof test !== "object" || Array.isArray(test)) {
|
|
1513
|
+
clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
const comparison = test;
|
|
1517
|
+
for (const [op, symbol] of Object.entries(COMPARATORS)) {
|
|
1518
|
+
const operand = comparison[op];
|
|
1519
|
+
if (operand === void 0) continue;
|
|
1520
|
+
clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
|
|
1521
|
+
}
|
|
1522
|
+
if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
|
|
1523
|
+
if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
|
|
1524
|
+
if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
|
|
1525
|
+
}
|
|
1526
|
+
return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
|
|
1527
|
+
};
|
|
1528
|
+
var compileOrder = (order, alias = "") => {
|
|
1529
|
+
if (order === void 0 || order.length === 0) return "";
|
|
1530
|
+
const prefix = alias === "" ? "" : `${alias}.`;
|
|
1531
|
+
return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
|
|
1532
|
+
};
|
|
1533
|
+
var sortRows = (rows, order) => {
|
|
1534
|
+
if (order === void 0 || order.length === 0) return [...rows];
|
|
1535
|
+
return [...rows].sort((left, right) => {
|
|
1536
|
+
for (const key of order) {
|
|
1537
|
+
const a = left[String(key.by)];
|
|
1538
|
+
const b = right[String(key.by)];
|
|
1539
|
+
const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
|
|
1540
|
+
if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
|
|
1541
|
+
}
|
|
1542
|
+
return 0;
|
|
1543
|
+
});
|
|
1544
|
+
};
|
|
1545
|
+
var compileSet = (set, start) => {
|
|
1546
|
+
const assignments = [];
|
|
1547
|
+
const params = [];
|
|
1548
|
+
for (const [field, value] of Object.entries(set)) {
|
|
1549
|
+
const column = snake(field);
|
|
1550
|
+
if (value !== null && typeof value === "object" && "inc" in value) {
|
|
1551
|
+
assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
|
|
1552
|
+
continue;
|
|
1553
|
+
}
|
|
1554
|
+
params.push(toColumn(column, value));
|
|
1555
|
+
assignments.push(`${column} = $${start + params.length - 1}`);
|
|
1556
|
+
}
|
|
1557
|
+
return { sql: assignments.join(", "), params };
|
|
1558
|
+
};
|
|
1559
|
+
var mintId = /* @__PURE__ */ (() => {
|
|
1560
|
+
let sequence = 0;
|
|
1561
|
+
return (table) => {
|
|
1562
|
+
sequence += 1;
|
|
1563
|
+
return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
|
|
1564
|
+
};
|
|
1565
|
+
})();
|
|
1566
|
+
var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
|
|
1567
|
+
var TIDE_SEQUENCE = {
|
|
1568
|
+
id: "nisc.moss.tide",
|
|
1569
|
+
migrations: [
|
|
1570
|
+
{ description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
|
|
1571
|
+
{
|
|
1572
|
+
// A fact's chain: the root it belongs to, and — on a root — how many facts
|
|
1573
|
+
// the chain has minted beneath it. Nullable: every existing fact is a
|
|
1574
|
+
// root nothing has been counted against yet.
|
|
1575
|
+
description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
|
|
1576
|
+
steps: [
|
|
1577
|
+
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
|
|
1578
|
+
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
|
|
1579
|
+
]
|
|
1580
|
+
}
|
|
1581
|
+
]
|
|
1582
|
+
};
|
|
1583
|
+
var createTideStore = (pool, options = {}) => {
|
|
1584
|
+
const ready = options.migrate === false ? Promise.resolve() : postgres.migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
|
|
1585
|
+
ready.catch(() => void 0);
|
|
1586
|
+
const build = (client) => {
|
|
1587
|
+
const store = {
|
|
1588
|
+
query: async (spec) => {
|
|
1589
|
+
await ready;
|
|
1590
|
+
const where = compileWhere(spec.where, 1);
|
|
1591
|
+
const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
|
|
1592
|
+
const result = await client.query(
|
|
1593
|
+
`SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
|
|
1594
|
+
where.params
|
|
1595
|
+
);
|
|
1596
|
+
return result.rows.map((row) => rowToEntity(spec.table, row));
|
|
1597
|
+
},
|
|
1598
|
+
// ON CONFLICT DO NOTHING, which is the whole point: the refusal is the
|
|
1599
|
+
// DATABASE's, decided under the constraint, not a read the caller races.
|
|
1600
|
+
appendIfAbsent: async (table, input) => {
|
|
1601
|
+
await ready;
|
|
1602
|
+
const withId = tide.PRIMARY_KEY[table] === "id" ? { ...input, id: input.id ?? mintId(table) } : { ...input };
|
|
1603
|
+
const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
|
|
1604
|
+
const columns = entries.map(([field]) => snake(field));
|
|
1605
|
+
const params = entries.map(([field, value]) => toColumn(snake(field), value));
|
|
1606
|
+
const unique = tide.UNIQUE_BY[table];
|
|
1607
|
+
const target = unique.when === void 0 ? `(${unique.by.map((column) => snake(String(column))).join(", ")})` : `(${unique.by.map((column) => column === "entity" || column === "name" ? `coalesce(${snake(String(column))},'')` : snake(String(column))).join(", ")}) WHERE ${snake(String(unique.when))} IS NOT NULL`;
|
|
1608
|
+
const result = await client.query(
|
|
1609
|
+
`INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
|
|
1610
|
+
ON CONFLICT ${target} DO NOTHING RETURNING *`,
|
|
1611
|
+
params
|
|
1612
|
+
);
|
|
1613
|
+
const row = result.rows[0];
|
|
1614
|
+
return row === void 0 ? void 0 : rowToEntity(table, row);
|
|
1615
|
+
},
|
|
1616
|
+
// Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`
|
|
1617
|
+
// makes N instances ticking at once ordinary contention rather than a
|
|
1618
|
+
// lock service — it is a throughput choice; the exactly-once promise is
|
|
1619
|
+
// the single statement.
|
|
1620
|
+
claim: async (spec) => {
|
|
1621
|
+
await ready;
|
|
1622
|
+
const table = SQL_TABLE[spec.table];
|
|
1623
|
+
const order = compileOrder(spec.order, "c");
|
|
1624
|
+
const take = async (extra, limit) => {
|
|
1625
|
+
if (limit <= 0) return [];
|
|
1626
|
+
const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
|
|
1627
|
+
const set = compileSet(spec.set, where.params.length + 1);
|
|
1628
|
+
const result = await client.query(
|
|
1629
|
+
`UPDATE ${table} SET ${set.sql}
|
|
1630
|
+
WHERE ctid IN (
|
|
1631
|
+
SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
|
|
1632
|
+
LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
|
|
1633
|
+
)
|
|
1634
|
+
RETURNING *`,
|
|
1635
|
+
[...where.params, ...set.params]
|
|
1636
|
+
);
|
|
1637
|
+
return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
|
|
1638
|
+
};
|
|
1639
|
+
if (spec.onePer === void 0) return take({}, spec.limit);
|
|
1640
|
+
const { column, held, only } = spec.onePer;
|
|
1641
|
+
const restricted = [...only];
|
|
1642
|
+
const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);
|
|
1643
|
+
for (const group of restricted) {
|
|
1644
|
+
if (claimed.length >= spec.limit) break;
|
|
1645
|
+
const busy = compileWhere({ ...held, [String(column)]: group }, 1, "c");
|
|
1646
|
+
const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
|
|
1647
|
+
if (taken.rows.length > 0) continue;
|
|
1648
|
+
claimed.push(...await take({ [String(column)]: group }, 1));
|
|
1649
|
+
}
|
|
1650
|
+
return claimed;
|
|
1651
|
+
},
|
|
1652
|
+
cas: async (table, id, expect, set) => {
|
|
1653
|
+
await ready;
|
|
1654
|
+
const key = snake(String(tide.PRIMARY_KEY[table]));
|
|
1655
|
+
const where = compileWhere(expect, 2);
|
|
1656
|
+
const patch = compileSet(set, where.params.length + 2);
|
|
1657
|
+
const result = await client.query(
|
|
1658
|
+
`UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
|
|
1659
|
+
[id, ...where.params, ...patch.params]
|
|
1660
|
+
);
|
|
1661
|
+
return result.rows.length > 0;
|
|
1662
|
+
},
|
|
1663
|
+
remove: async (spec) => {
|
|
1664
|
+
await ready;
|
|
1665
|
+
const where = compileWhere(spec.where, 1);
|
|
1666
|
+
const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(tide.PRIMARY_KEY[spec.table]))}`, where.params);
|
|
1667
|
+
return result.rows.length;
|
|
1668
|
+
},
|
|
1669
|
+
transact: async (fn) => {
|
|
1670
|
+
await ready;
|
|
1671
|
+
if (client.transaction === void 0)
|
|
1672
|
+
throw new Error("tide store: this pool cannot transact \u2014 fan-out and attempt recording are transactions, not conventions");
|
|
1673
|
+
return client.transaction((tx) => fn(build({ ...client, query: (text, values) => tx.query(text, values) })));
|
|
1674
|
+
}
|
|
1675
|
+
};
|
|
1676
|
+
return store;
|
|
1521
1677
|
};
|
|
1678
|
+
return { ...build(pool), ready };
|
|
1522
1679
|
};
|
|
1523
|
-
var
|
|
1524
|
-
const
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1680
|
+
var mintWrites = async (intake, event, as, at, chain) => {
|
|
1681
|
+
for (const write of event.writes) {
|
|
1682
|
+
for (const row of write.rows) {
|
|
1683
|
+
await intake.ingest(
|
|
1684
|
+
{ kind: "write", entity: write.table, op: write.op, row, at },
|
|
1685
|
+
{ as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
|
|
1686
|
+
);
|
|
1687
|
+
}
|
|
1530
1688
|
}
|
|
1531
|
-
const type = schema["type"];
|
|
1532
|
-
const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
|
|
1533
|
-
const min = schema["minimum"];
|
|
1534
|
-
const max = schema["maximum"];
|
|
1535
|
-
if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
|
|
1536
|
-
return base;
|
|
1537
|
-
};
|
|
1538
|
-
var componentAsMarkdown = (component) => {
|
|
1539
|
-
const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
|
|
1540
|
-
const schema = component.propsSchema;
|
|
1541
|
-
const properties = schema?.properties;
|
|
1542
|
-
if (properties === void 0 || Object.keys(properties).length === 0) return head;
|
|
1543
|
-
const required = new Set(schema?.required ?? []);
|
|
1544
|
-
const rows = Object.entries(properties).map(
|
|
1545
|
-
([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
|
|
1546
|
-
);
|
|
1547
|
-
return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
|
|
1548
1689
|
};
|
|
1549
|
-
var contractAsMarkdown = (contract, fingerprints) => [
|
|
1550
|
-
`# What you can build against`,
|
|
1551
|
-
``,
|
|
1552
|
-
`## Your namespace`,
|
|
1553
|
-
``,
|
|
1554
|
-
` ${contract.namespace}`,
|
|
1555
|
-
``,
|
|
1556
|
-
`Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
|
|
1557
|
-
``,
|
|
1558
|
-
`## Components your layouts may use`,
|
|
1559
|
-
``,
|
|
1560
|
-
contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
|
|
1561
|
-
``,
|
|
1562
|
-
`## Fingerprints you may call`,
|
|
1563
|
-
``,
|
|
1564
|
-
`Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
|
|
1565
|
-
`\`/integrations/<your id>/\`. Nothing else.`,
|
|
1566
|
-
``,
|
|
1567
|
-
fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
|
|
1568
|
-
``,
|
|
1569
|
-
`## Where your screens may appear`,
|
|
1570
|
-
``,
|
|
1571
|
-
`Declare \`attachments\` (action \u2192 host action) to ride a host screen, and`,
|
|
1572
|
-
`\`placements\` (action \u2192 hub) to list under a menu hub. \`settings\` names the one`,
|
|
1573
|
-
`action the store tile opens. Anything else is refused.`,
|
|
1574
|
-
``,
|
|
1575
|
-
`Attachable, with what each hands you as input:`,
|
|
1576
|
-
``,
|
|
1577
|
-
Object.entries(contract.attachable).map(([action, offers]) => `- ${action} \u2014 offers ${offers.join(", ") || "(nothing)"}`).join("\n") || "(none)",
|
|
1578
|
-
``,
|
|
1579
|
-
`Menu hubs accepting placements:`,
|
|
1580
|
-
``,
|
|
1581
|
-
contract.menuSlots.map((hub) => `- ${hub}`).join("\n") || "(none)",
|
|
1582
|
-
``,
|
|
1583
|
-
`## What you cannot ship`,
|
|
1584
|
-
``,
|
|
1585
|
-
`- vex entries or mutations. Call what is listed above; if you need a read that`,
|
|
1586
|
-
` does not exist, it is a change to the app.`,
|
|
1587
|
-
`- \`fn:\` endpoints. Those run in the app's process.`,
|
|
1588
|
-
`- components. Layouts compose what is listed above.`,
|
|
1589
|
-
`- tables. Bring your own storage; we hand you identifiers.`,
|
|
1590
|
-
``
|
|
1591
|
-
].join("\n");
|
|
1592
|
-
|
|
1593
|
-
// src/principal.ts
|
|
1594
1690
|
var resolveRoles = (app, principal) => principal === null ? ["public"] : app.assignments?.[principal] ?? ["public"];
|
|
1595
1691
|
var wearableOf = (app) => {
|
|
1596
1692
|
const declared = app.wearable;
|
|
@@ -1686,8 +1782,101 @@ var versionToken = (ids) => {
|
|
|
1686
1782
|
}
|
|
1687
1783
|
return h.toString(16).padStart(8, "0");
|
|
1688
1784
|
};
|
|
1689
|
-
|
|
1690
|
-
|
|
1785
|
+
|
|
1786
|
+
// src/session-cookie.ts
|
|
1787
|
+
var DEFAULT_TOKEN_KEY = "nisc.token";
|
|
1788
|
+
var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
|
|
1789
|
+
if (header === void 0 || header === null) return null;
|
|
1790
|
+
const wanted = encodeURIComponent(name);
|
|
1791
|
+
for (const part of header.split(";")) {
|
|
1792
|
+
const at = part.indexOf("=");
|
|
1793
|
+
if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
|
|
1794
|
+
try {
|
|
1795
|
+
const value = decodeURIComponent(part.slice(at + 1).trim());
|
|
1796
|
+
return value === "" ? null : value;
|
|
1797
|
+
} catch {
|
|
1798
|
+
return null;
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
return null;
|
|
1802
|
+
};
|
|
1803
|
+
var isOwnOrigin = (origin, host, listed = []) => {
|
|
1804
|
+
if (origin === void 0 || origin === null || !URL.canParse(origin)) return false;
|
|
1805
|
+
const asked = new URL(origin);
|
|
1806
|
+
return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
|
|
1807
|
+
};
|
|
1808
|
+
var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
|
|
1809
|
+
var cookiesAt = (where, key, token, lastsMs) => {
|
|
1810
|
+
const name = encodeURIComponent(nameOf(key, where.port));
|
|
1811
|
+
const life = token === null ? "; Max-Age=0" : typeof lastsMs === "number" ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1e3))}` : "";
|
|
1812
|
+
const kept = `Path=/; SameSite=Lax${where.secure ? "; Secure" : ""}${life}`;
|
|
1813
|
+
return [`${where.secure ? "__Host-" : ""}${name}=${encodeURIComponent(token ?? "")}; HttpOnly; ${kept}`, `${name}.held=${token === null ? "" : "1"}; ${kept}`];
|
|
1814
|
+
};
|
|
1815
|
+
var originOf = (request) => {
|
|
1816
|
+
const said = request.headers.get("origin");
|
|
1817
|
+
if (said !== null && URL.canParse(said)) return said;
|
|
1818
|
+
const here = new URL(request.url);
|
|
1819
|
+
const scheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || here.protocol.slice(0, -1);
|
|
1820
|
+
return `${scheme}://${request.headers.get("host") ?? here.host}`;
|
|
1821
|
+
};
|
|
1822
|
+
var sessionCookies = (page, token, options = {}) => {
|
|
1823
|
+
const at = new URL(typeof page === "string" ? page : originOf(page));
|
|
1824
|
+
return cookiesAt({ port: at.port, secure: at.protocol === "https:" }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);
|
|
1825
|
+
};
|
|
1826
|
+
var sessionTokenOf = (cookies, where, key = DEFAULT_TOKEN_KEY) => {
|
|
1827
|
+
const name = nameOf(key, where.port);
|
|
1828
|
+
for (const secure of where.secure === void 0 ? [true, false] : [where.secure]) {
|
|
1829
|
+
const token = tokenFromCookie(cookies, `${secure ? "__Host-" : ""}${name}`);
|
|
1830
|
+
if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };
|
|
1831
|
+
}
|
|
1832
|
+
return null;
|
|
1833
|
+
};
|
|
1834
|
+
var SEALED_FOR_MS = 6e4;
|
|
1835
|
+
var sealName = (secure) => `${secure ? "__Http-" : ""}nisc.seal`;
|
|
1836
|
+
var toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1837
|
+
var fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
|
|
1838
|
+
var keyOf = async (seal) => crypto.subtle.importKey("raw", await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seal)), "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
1839
|
+
var newSeal = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
1840
|
+
var sealOf = (cookies, secure) => tokenFromCookie(cookies, sealName(secure));
|
|
1841
|
+
var sealCookie = (seal, where) => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? "; Secure" : ""}`;
|
|
1842
|
+
var sealSession = async (seal, token, forMs = SEALED_FOR_MS) => {
|
|
1843
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1844
|
+
const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));
|
|
1845
|
+
return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));
|
|
1846
|
+
};
|
|
1847
|
+
var openSealed = async (seal, sealed) => {
|
|
1848
|
+
try {
|
|
1849
|
+
const bytes = fromBase64Url(sealed);
|
|
1850
|
+
const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));
|
|
1851
|
+
const { token, until } = JSON.parse(new TextDecoder().decode(opened));
|
|
1852
|
+
return typeof token === "string" && typeof until === "number" && until > Date.now() ? token : null;
|
|
1853
|
+
} catch {
|
|
1854
|
+
return null;
|
|
1855
|
+
}
|
|
1856
|
+
};
|
|
1857
|
+
|
|
1858
|
+
// src/socket.ts
|
|
1859
|
+
var PROTOCOL = 2;
|
|
1860
|
+
var PROTOCOL_MIN = 2;
|
|
1861
|
+
var SUBPROTOCOL = "nisc";
|
|
1862
|
+
var TOKEN_OFFER = "nisc.token.";
|
|
1863
|
+
var SEALED_OFFER = "nisc.sealed.";
|
|
1864
|
+
var offerToken = (token, sealed = null) => {
|
|
1865
|
+
const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
|
|
1866
|
+
if (token === null) return offer;
|
|
1867
|
+
const bytes = String.fromCharCode(...new TextEncoder().encode(token));
|
|
1868
|
+
return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
|
|
1869
|
+
};
|
|
1870
|
+
var offeredToken = (offered = []) => {
|
|
1871
|
+
const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));
|
|
1872
|
+
if (offer === void 0) return null;
|
|
1873
|
+
try {
|
|
1874
|
+
const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, "+").replace(/_/g, "/"));
|
|
1875
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;
|
|
1876
|
+
} catch {
|
|
1877
|
+
return null;
|
|
1878
|
+
}
|
|
1879
|
+
};
|
|
1691
1880
|
var CLOSE_INVALID_TOKEN = 4401;
|
|
1692
1881
|
var CLOSE_SIGNED_OUT = 4403;
|
|
1693
1882
|
var CLOSE_SHELL_FAILED = 4500;
|
|
@@ -1703,6 +1892,7 @@ var parse = (text) => {
|
|
|
1703
1892
|
};
|
|
1704
1893
|
var createSocket = (ctx) => {
|
|
1705
1894
|
const emit = emitterOf(ctx.telemetry);
|
|
1895
|
+
let saidNotOwn = false;
|
|
1706
1896
|
const live = /* @__PURE__ */ new Map();
|
|
1707
1897
|
const expire = (connection) => {
|
|
1708
1898
|
connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
|
|
@@ -1759,18 +1949,40 @@ var createSocket = (ctx) => {
|
|
|
1759
1949
|
connection.close(CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
|
|
1760
1950
|
return;
|
|
1761
1951
|
}
|
|
1762
|
-
const
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1952
|
+
const upgrade = connection.upgrade;
|
|
1953
|
+
const key = /^[\w.-]{1,64}$/.test(params.get("key") ?? "") ? params.get("key") : DEFAULT_TOKEN_KEY;
|
|
1954
|
+
const page = upgrade !== void 0 && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : void 0;
|
|
1955
|
+
const secure = page?.protocol === "https:";
|
|
1956
|
+
const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
|
|
1957
|
+
const sealing = page !== void 0 && params.get("sealed") === "1";
|
|
1958
|
+
if (page === void 0 && params.get("sealed") === "1" && typeof upgrade?.origin === "string" && !saidNotOwn) {
|
|
1959
|
+
saidNotOwn = true;
|
|
1960
|
+
console.warn(`[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.`);
|
|
1961
|
+
}
|
|
1962
|
+
const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;
|
|
1963
|
+
const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;
|
|
1964
|
+
const sealLost = sealing && sealedOffer !== null && hadSeal === null;
|
|
1965
|
+
const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
|
|
1966
|
+
const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
|
|
1967
|
+
let token = offered ?? (params.get("leave") === "1" ? null : held?.token ?? null);
|
|
1968
|
+
let principal = token === null ? null : await ctx.session(token);
|
|
1969
|
+
if (offered !== null && principal === null) {
|
|
1970
|
+
if (emit !== void 0 && upClock !== void 0) {
|
|
1971
|
+
emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
|
|
1773
1972
|
}
|
|
1973
|
+
send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
|
|
1974
|
+
connection.close(CLOSE_INVALID_TOKEN, "invalid token");
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
if (principal === null) token = null;
|
|
1978
|
+
const answered = [
|
|
1979
|
+
...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await ctx.sessionLastsMs?.(token) ?? null }),
|
|
1980
|
+
...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
|
|
1981
|
+
];
|
|
1982
|
+
if (answered.length > 0) upgrade?.answer?.(answered);
|
|
1983
|
+
if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);
|
|
1984
|
+
if (sealLost) {
|
|
1985
|
+
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." });
|
|
1774
1986
|
}
|
|
1775
1987
|
live.set(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
|
|
1776
1988
|
connection.onClose(() => live.delete(connection));
|
|
@@ -1976,7 +2188,9 @@ var createShellHost = (ctx) => {
|
|
|
1976
2188
|
};
|
|
1977
2189
|
const delta = ctx.delta ?? false;
|
|
1978
2190
|
const DELTA_CEILING = 0.6;
|
|
2191
|
+
const DELTA_MAX_FRAME = 64 * 1024;
|
|
1979
2192
|
const shorterAsDelta = (previous, next, canvasId) => {
|
|
2193
|
+
if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;
|
|
1980
2194
|
try {
|
|
1981
2195
|
const ops = encodeDelta(previous, next);
|
|
1982
2196
|
const message = { type: "render-delta", canvas: canvasId, ops, hash: frameHash(next) };
|
|
@@ -2034,7 +2248,15 @@ var createShellHost = (ctx) => {
|
|
|
2034
2248
|
// ephemeral and dies on detach.
|
|
2035
2249
|
grant: (token2) => {
|
|
2036
2250
|
const message = JSON.stringify({ type: "session", token: token2 });
|
|
2037
|
-
for (const connection of liveRef?.connections ?? [])
|
|
2251
|
+
for (const connection of liveRef?.connections ?? []) {
|
|
2252
|
+
if (connection.seal === void 0) connection.send(message);
|
|
2253
|
+
else {
|
|
2254
|
+
void connection.seal(token2).then(
|
|
2255
|
+
(sealed) => connection.send(JSON.stringify({ type: "session", sealed })),
|
|
2256
|
+
(error) => console.error("[moss] a sign-in could not be sealed, and was not handed over:", error)
|
|
2257
|
+
);
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2038
2260
|
},
|
|
2039
2261
|
// REVOKE: forget the credential, close every terminal SIGNED_OUT,
|
|
2040
2262
|
// evict the durable shell. Under moss's own credential the rows go
|
|
@@ -2092,11 +2314,9 @@ var createShellHost = (ctx) => {
|
|
|
2092
2314
|
...shellManifest.fragments !== void 0 ? { fragments: shellManifest.fragments } : {},
|
|
2093
2315
|
// The same seam the client shell used: prism evaluates endpoint
|
|
2094
2316
|
// request/response transforms; `$.userId` and `$.today` are ambient,
|
|
2095
|
-
// never authorable by a request.
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
source !== null && typeof source === "object" && !Array.isArray(source) ? { ...source, userId, today: today() } : source
|
|
2099
|
-
),
|
|
2317
|
+
// never authorable by a request. The config is the action's own object
|
|
2318
|
+
// on every call, so evaluate checks it once (the source is new each time).
|
|
2319
|
+
transform: (config, source) => prism.evaluate(config, source !== null && typeof source === "object" && !Array.isArray(source) ? { ...source, userId, today: today() } : source),
|
|
2100
2320
|
fetch: wire,
|
|
2101
2321
|
functions,
|
|
2102
2322
|
...ctx.runtime.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: ctx.runtime.endpointTimeoutMs },
|
|
@@ -2269,8 +2489,8 @@ var createShellHost = (ctx) => {
|
|
|
2269
2489
|
const settle = async (live, waitMs) => {
|
|
2270
2490
|
const started = Date.now();
|
|
2271
2491
|
let timer;
|
|
2272
|
-
const deadline = new Promise((
|
|
2273
|
-
timer = setTimeout(() =>
|
|
2492
|
+
const deadline = new Promise((resolve2) => {
|
|
2493
|
+
timer = setTimeout(() => resolve2(false), waitMs);
|
|
2274
2494
|
});
|
|
2275
2495
|
const whole = live.seeded.then(() => nova.shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));
|
|
2276
2496
|
const settled = await Promise.race([whole, deadline]);
|
|
@@ -2359,7 +2579,7 @@ var createShellHost = (ctx) => {
|
|
|
2359
2579
|
const settled = await settle(cell.live, waitMs);
|
|
2360
2580
|
return { ...read(cell.live), settled, ...needOf(cell.live, principal) };
|
|
2361
2581
|
}
|
|
2362
|
-
const seed = crypto.randomBytes(9).toString("hex");
|
|
2582
|
+
const seed = crypto$1.randomBytes(9).toString("hex");
|
|
2363
2583
|
const live = await build(token, principal, false, seed, options?.inputs);
|
|
2364
2584
|
try {
|
|
2365
2585
|
const settled = await settle(live, waitMs);
|
|
@@ -2630,7 +2850,7 @@ var createIdentityCache = (ctx) => {
|
|
|
2630
2850
|
};
|
|
2631
2851
|
|
|
2632
2852
|
// src/server.ts
|
|
2633
|
-
var secretsEqual = (a, b) => crypto.timingSafeEqual(crypto.createHash("sha256").update(a).digest(), crypto.createHash("sha256").update(b).digest());
|
|
2853
|
+
var secretsEqual = (a, b) => crypto$1.timingSafeEqual(crypto$1.createHash("sha256").update(a).digest(), crypto$1.createHash("sha256").update(b).digest());
|
|
2634
2854
|
var guardOperator = (operator, opts) => {
|
|
2635
2855
|
const gate = opts.gate;
|
|
2636
2856
|
if (gate !== void 0) operator.use("*", (c, next) => Promise.resolve(gate(c, next)));
|
|
@@ -2658,12 +2878,7 @@ var createServer = async (app, runtime) => {
|
|
|
2658
2878
|
const session = sessionVerifierOf(runtime);
|
|
2659
2879
|
const emit = emitterOf(runtime.telemetry);
|
|
2660
2880
|
const vexOnExecute = emit === void 0 ? void 0 : (rec) => emit(vexRecordToSpan(rec));
|
|
2661
|
-
|
|
2662
|
-
await postgres.migrate(
|
|
2663
|
-
runtime.pool,
|
|
2664
|
-
[MOSS_SEQUENCE, ...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [], ...cacheSequence === void 0 ? [] : [cacheSequence]],
|
|
2665
|
-
{ mode: runtime.migrations ?? "apply" }
|
|
2666
|
-
);
|
|
2881
|
+
await postgres.migrate(runtime.pool, tableSequencesOf(runtime), { mode: runtime.migrations ?? "apply" });
|
|
2667
2882
|
const grammars = await createGrammarUpgrader(app);
|
|
2668
2883
|
await postgres.upgradeStore(runtime.pool, INTEGRATION_ACTIONS_STORE, grammars);
|
|
2669
2884
|
const data = await createDataLayer(runtime, app.entries ?? []);
|
|
@@ -2740,7 +2955,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
|
2740
2955
|
revalidateMs: runtime.sessionRevalidateMs ?? DEFAULT_REVALIDATE_MS
|
|
2741
2956
|
}) : void 0;
|
|
2742
2957
|
const keys = /* @__PURE__ */ new WeakMap();
|
|
2743
|
-
const
|
|
2958
|
+
const keyOf2 = (record) => {
|
|
2744
2959
|
const hit = keys.get(record);
|
|
2745
2960
|
if (hit !== void 0) return hit;
|
|
2746
2961
|
const key = memoKey(record.roles, record.installed);
|
|
@@ -2756,7 +2971,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
|
2756
2971
|
const resolveIdentity = async (principal) => {
|
|
2757
2972
|
if (identities !== void 0 && principal !== null) {
|
|
2758
2973
|
const record = await identities.get(principal);
|
|
2759
|
-
return { roles: record.roles, scope: record.scope, installed: record.installed, key:
|
|
2974
|
+
return { roles: record.roles, scope: record.scope, installed: record.installed, key: keyOf2(record), record };
|
|
2760
2975
|
}
|
|
2761
2976
|
return fromSeams(principal);
|
|
2762
2977
|
};
|
|
@@ -3156,7 +3371,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
|
3156
3371
|
if (!frameAdmits(found.frames ?? {}, path, held)) return c.json({ message: "No such frame." }, 404);
|
|
3157
3372
|
const now = Date.now();
|
|
3158
3373
|
sweepGrants(now);
|
|
3159
|
-
const token = crypto.randomBytes(24).toString("hex");
|
|
3374
|
+
const token = crypto$1.randomBytes(24).toString("hex");
|
|
3160
3375
|
grants.set(token, { integration: id, principal, path, expires: now + GRANT_TTL_MS });
|
|
3161
3376
|
return c.json({ src: `/integrations/${id}/frame/${token}`, expiresIn: GRANT_TTL_MS });
|
|
3162
3377
|
});
|
|
@@ -3363,7 +3578,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
|
3363
3578
|
if (host === void 0 || manifest === void 0) return void 0;
|
|
3364
3579
|
return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
|
|
3365
3580
|
};
|
|
3366
|
-
const fabricOrigin = crypto.randomBytes(8).toString("hex");
|
|
3581
|
+
const fabricOrigin = crypto$1.randomBytes(8).toString("hex");
|
|
3367
3582
|
const applyInvalidateIdentity = (principal) => {
|
|
3368
3583
|
const held = identities?.invalidate(principal) ?? false;
|
|
3369
3584
|
shells?.reset(principal);
|
|
@@ -3427,7 +3642,9 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
|
3427
3642
|
...shells !== void 0 ? { shells } : {},
|
|
3428
3643
|
page: pageAt,
|
|
3429
3644
|
...runtime.sessionRevalidateMs !== void 0 ? { revalidateMs: runtime.sessionRevalidateMs } : {},
|
|
3430
|
-
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {}
|
|
3645
|
+
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
|
|
3646
|
+
...runtime.origins !== void 0 ? { origins: runtime.origins } : {},
|
|
3647
|
+
...runtime.session === "sessions" ? { sessionLastsMs: (token) => sessionRemainingMs(runtime.pool, token) } : {}
|
|
3431
3648
|
});
|
|
3432
3649
|
return Object.assign(server, {
|
|
3433
3650
|
socket,
|
|
@@ -3559,23 +3776,7 @@ var createTideDriver = (config) => {
|
|
|
3559
3776
|
};
|
|
3560
3777
|
};
|
|
3561
3778
|
var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
|
|
3562
|
-
var DEFAULT_TOKEN_KEY = "nisc.token";
|
|
3563
3779
|
var DEFAULT_ROOT = '<div id="root"></div>';
|
|
3564
|
-
var tokenFromCookie = (header, tokenKey = DEFAULT_TOKEN_KEY) => {
|
|
3565
|
-
if (header === void 0 || header === null) return null;
|
|
3566
|
-
const wanted = encodeURIComponent(tokenKey);
|
|
3567
|
-
for (const part of header.split(";")) {
|
|
3568
|
-
const at = part.indexOf("=");
|
|
3569
|
-
if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
|
|
3570
|
-
try {
|
|
3571
|
-
const value = decodeURIComponent(part.slice(at + 1).trim());
|
|
3572
|
-
return value === "" ? null : value;
|
|
3573
|
-
} catch {
|
|
3574
|
-
return null;
|
|
3575
|
-
}
|
|
3576
|
-
}
|
|
3577
|
-
return null;
|
|
3578
|
-
};
|
|
3579
3780
|
var embedSnapshot = (snapshot, principal, path) => {
|
|
3580
3781
|
const { frame, trees, seed, live } = snapshot;
|
|
3581
3782
|
const text = JSON.stringify({ frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} }).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
@@ -3590,7 +3791,8 @@ var renderDocument = async (config) => {
|
|
|
3590
3791
|
const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
|
|
3591
3792
|
if (!template.includes(root)) return undrawn;
|
|
3592
3793
|
try {
|
|
3593
|
-
const
|
|
3794
|
+
const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
|
|
3795
|
+
const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
|
|
3594
3796
|
const principal = token === null ? null : await server.principalOf(token);
|
|
3595
3797
|
const route = server.page(request.path);
|
|
3596
3798
|
const host = route?.host ?? server.shells;
|
|
@@ -3608,10 +3810,7 @@ var renderDocument = async (config) => {
|
|
|
3608
3810
|
return {
|
|
3609
3811
|
html,
|
|
3610
3812
|
...head !== void 0 ? { head } : {},
|
|
3611
|
-
headers:
|
|
3612
|
-
...documentHeaders(principal),
|
|
3613
|
-
...token !== null && principal === null ? { "set-cookie": `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax` } : {}
|
|
3614
|
-
},
|
|
3813
|
+
headers: documentHeaders(principal),
|
|
3615
3814
|
drawn: true,
|
|
3616
3815
|
principal,
|
|
3617
3816
|
...route !== void 0 ? { page: route.name } : {},
|
|
@@ -3656,6 +3855,7 @@ exports.DEFAULT_IDLE_MS = DEFAULT_IDLE_MS;
|
|
|
3656
3855
|
exports.DEFAULT_REVALIDATE_MS = DEFAULT_REVALIDATE_MS;
|
|
3657
3856
|
exports.GENERATION_DDL = GENERATION_DDL;
|
|
3658
3857
|
exports.MOSS_SEQUENCE = MOSS_SEQUENCE;
|
|
3858
|
+
exports.PROTOCOL = PROTOCOL;
|
|
3659
3859
|
exports.SESSIONS_SEQUENCE = SESSIONS_SEQUENCE;
|
|
3660
3860
|
exports.SNAPSHOT_ELEMENT_ID = SNAPSHOT_ELEMENT_ID;
|
|
3661
3861
|
exports.TIDE_DDL = TIDE_DDL;
|
|
@@ -3694,10 +3894,12 @@ exports.listIntegrations = listIntegrations;
|
|
|
3694
3894
|
exports.listPlacements = listPlacements;
|
|
3695
3895
|
exports.loadIntegrationActions = loadIntegrationActions;
|
|
3696
3896
|
exports.memoKeyOf = memoKeyOf;
|
|
3897
|
+
exports.migrateTables = migrateTables;
|
|
3697
3898
|
exports.mintDevToken = mintDevToken;
|
|
3698
3899
|
exports.mintIntegrationKey = mintIntegrationKey;
|
|
3699
3900
|
exports.mintSession = mintSession;
|
|
3700
3901
|
exports.mintWrites = mintWrites;
|
|
3902
|
+
exports.offerToken = offerToken;
|
|
3701
3903
|
exports.renderDocument = renderDocument;
|
|
3702
3904
|
exports.resolveCatalog = resolveCatalog;
|
|
3703
3905
|
exports.resolveCatalogForRoles = resolveCatalogForRoles;
|
|
@@ -3710,6 +3912,7 @@ exports.resolveVariantsForRoles = resolveVariantsForRoles;
|
|
|
3710
3912
|
exports.revokeAllFor = revokeAllFor;
|
|
3711
3913
|
exports.revokeSession = revokeSession;
|
|
3712
3914
|
exports.runIntake = runIntake;
|
|
3915
|
+
exports.sessionCookies = sessionCookies;
|
|
3713
3916
|
exports.sessionOf = sessionOf;
|
|
3714
3917
|
exports.sessionVerifierOf = sessionVerifierOf;
|
|
3715
3918
|
exports.shellNeedOf = shellNeedOf;
|