@niscorp/moss 0.3.0 → 0.3.3

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/DESIGN.md +92 -21
  3. package/DOCS.md +190 -40
  4. package/README.md +7 -2
  5. package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
  6. package/dist/chunk-4T6KAXBP.js.map +1 -0
  7. package/dist/{chunk-3CJCJKKY.js → chunk-AUZMT3GL.js} +742 -654
  8. package/dist/chunk-AUZMT3GL.js.map +1 -0
  9. package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
  10. package/dist/chunk-HOZID4EM.js.map +1 -0
  11. package/dist/chunk-NE2EXMTO.js +103 -0
  12. package/dist/chunk-NE2EXMTO.js.map +1 -0
  13. package/dist/client/node.cjs +1 -1
  14. package/dist/client/node.cjs.map +1 -1
  15. package/dist/client/node.js +1 -1
  16. package/dist/client/node.js.map +1 -1
  17. package/dist/client.cjs +60 -26
  18. package/dist/client.cjs.map +1 -1
  19. package/dist/client.d.cts +6 -1
  20. package/dist/client.d.ts +6 -1
  21. package/dist/client.js +2 -2
  22. package/dist/{document-Jhfii6kd.d.cts → document-DhWxieUc.d.cts} +24 -4
  23. package/dist/{document-Jhfii6kd.d.ts → document-DhWxieUc.d.ts} +24 -4
  24. package/dist/index.cjs +780 -572
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +19 -3
  27. package/dist/index.d.ts +19 -3
  28. package/dist/index.js +2 -2
  29. package/dist/node.cjs +373 -219
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +2 -1
  32. package/dist/node.d.ts +2 -1
  33. package/dist/node.js +3 -3
  34. package/dist/terminal/index.cjs +60 -26
  35. package/dist/terminal/index.cjs.map +1 -1
  36. package/dist/terminal/index.js +2 -2
  37. package/dist/vite.cjs +103 -28
  38. package/dist/vite.cjs.map +1 -1
  39. package/dist/vite.d.cts +1 -1
  40. package/dist/vite.d.ts +1 -1
  41. package/dist/vite.js +14 -9
  42. package/dist/vite.js.map +1 -1
  43. package/package.json +15 -14
  44. package/dist/chunk-3CJCJKKY.js.map +0 -1
  45. package/dist/chunk-DPFWL7BS.js +0 -64
  46. package/dist/chunk-DPFWL7BS.js.map +0 -1
  47. package/dist/chunk-J72N3EMJ.js.map +0 -1
  48. package/dist/chunk-ZOEUEMDX.js.map +0 -1
@@ -1,13 +1,13 @@
1
- import { emitterOf, spanClock, DEFAULT_REVALIDATE_MS, createSocket, CLOSE_SIGNED_OUT, encodeDelta, frameHash } from './chunk-ZOEUEMDX.js';
1
+ import { emitterOf, spanClock, DEFAULT_REVALIDATE_MS, createSocket, DEFAULT_TOKEN_KEY, sessionTokenOf, CLOSE_SIGNED_OUT, encodeDelta, frameHash } from './chunk-HOZID4EM.js';
2
2
  import { randomBytes, generateKeyPairSync, sign, createPublicKey, verify, createHash, createPrivateKey, timingSafeEqual } from 'crypto';
3
3
  import { migrate, upgradeStore } from '@niscorp/strata/postgres';
4
4
  import { LayoutNodeSchema, ActionDefinitionSchema, collectChannels, auditAction, paletteEntryOf, CANVAS_SLOT_NAME, ACTION_SLOT_NAME, createComponentRegistry, createLayoutStore, createShell, shellSettled, canvasTreeOf } from '@niscorp/nova';
5
- import { createPostgresAdapter, createPostgresCache, seedCache, createQueryEngine, scopeGrants, mergeScopePolicies, createScopePolicy, scopeProfiles, handleQuery } from '@niscorp/vex';
6
- import { PRIMARY_KEY, UNIQUE_BY } from '@niscorp/tide';
5
+ import { createPostgresAdapter, createPostgresCache, seedCache, createQueryEngine, scopeGrants, mergeScopePolicies, createScopePolicy, scopeProfiles, handleQuery, resolve, pruneOptional, mutationMisfits } from '@niscorp/vex';
7
6
  import { exceedsDepth, depthRefusal, StrataError, createUpgrader } from '@niscorp/strata';
8
7
  import { z } from 'zod';
9
8
  import { chainCycles, componentsOf, snapshotShell, livenessOf, walkNodes, isRecord } from '@niscorp/nova/reflect';
10
9
  import { isBinding } from '@niscorp/nova/i18n';
10
+ import { PRIMARY_KEY, UNIQUE_BY } from '@niscorp/tide';
11
11
  import { resolvePrincipal, resolveScoping, verifyCharter } from '@niscorp/charter';
12
12
  import { evaluate } from '@niscorp/prism';
13
13
  import { AsyncLocalStorage } from 'async_hooks';
@@ -98,6 +98,11 @@ var sessionOf = async (pool, token) => {
98
98
  const principal = res.rows[0]?.principal;
99
99
  return typeof principal === "string" ? principal : null;
100
100
  };
101
+ var sessionRemainingMs = async (pool, token) => {
102
+ 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)]);
103
+ const remaining = Number(res.rows[0]?.["remaining"]);
104
+ return res.rows.length > 0 && Number.isFinite(remaining) ? remaining : null;
105
+ };
101
106
  var revokeSession = async (pool, token) => {
102
107
  await pool.query("DELETE FROM sessions WHERE token_hash = $1", [hashSessionToken(token)]);
103
108
  };
@@ -156,450 +161,91 @@ var createDataLayer = async (runtime, entries = []) => {
156
161
  const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });
157
162
  await cache.init?.();
158
163
  await seedCache(cache, entries);
159
- const engine = createQueryEngine({ adapter, cache });
164
+ const engine = createQueryEngine({ adapter, cache, ...runtime.vexConfig !== void 0 ? { config: runtime.vexConfig } : {} });
160
165
  const schema = await engine.introspect();
161
166
  return { engine, schema, grants: scopeGrants(schema.entities.map((e) => e.name)) };
162
167
  };
163
- var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
164
- var TIDE_DDL = `
165
- CREATE TABLE IF NOT EXISTS tide_fact (
166
- id text PRIMARY KEY,
167
- kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
168
- entity text,
169
- op text CHECK (op IN ('insert','update','delete')),
170
- row jsonb,
171
- name text,
172
- payload jsonb,
173
- reflex text,
174
- run_id text,
175
- occurrence text,
176
- stats jsonb,
177
- target text,
178
- by text,
179
- at bigint NOT NULL,
180
- not_before bigint,
181
- dedupe_key text,
182
- cause text,
183
- depth integer NOT NULL DEFAULT 0,
184
- delivered_at bigint,
185
- parked text,
186
- released boolean,
187
- -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
188
- -- anything the host ingested. The matcher refuses to hand a fact minted
189
- -- under one identity to a reflex running under another, which is the only
190
- -- thing standing between a carried row and somebody else's effect \u2014 tide is
191
- -- the one place a row travels without being read, so no scope policy is
192
- -- consulted on the way.
193
- as_who text
194
- );
195
-
196
- -- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
197
- -- unique: it is a distinct occurrence of something, not a repeat of it.
198
- -- entity is in the key: without it, two producers over different tables
199
- -- that agreed on a key value silently ate each other's rows.
200
- CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
201
- ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
202
- WHERE dedupe_key IS NOT NULL;
203
-
204
- -- The matcher's query, every advance.
205
- CREATE INDEX IF NOT EXISTS tide_fact_due
206
- ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
207
- CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
208
-
209
- CREATE TABLE IF NOT EXISTS tide_run (
210
- id text PRIMARY KEY,
211
- reflex_id text NOT NULL,
212
- version text NOT NULL,
213
- as_who text,
214
- cause text NOT NULL,
215
- occurrence text,
216
- fact_ids jsonb,
217
- state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
218
- depth integer NOT NULL DEFAULT 0,
219
- selected integer,
220
- total integer NOT NULL DEFAULT 0,
221
- done integer NOT NULL DEFAULT 0,
222
- failed integer NOT NULL DEFAULT 0,
223
- due_at bigint NOT NULL,
224
- created_at bigint NOT NULL,
225
- settled_at bigint,
226
- drained boolean,
227
- note text,
228
- -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
229
- -- cannot open twice, a replayed fact cannot open twice, and two instances
230
- -- ticking at the same moment contend instead of duplicating.
231
- UNIQUE (reflex_id, cause)
232
- );
233
-
234
- CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
235
- CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
236
- CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
237
-
238
- CREATE TABLE IF NOT EXISTS tide_work (
239
- id text PRIMARY KEY,
240
- -- ON DELETE CASCADE, because a run and its work are one fact about the
241
- -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
242
- -- row that IS the "this unit already ran" record \u2014 and a restore then
243
- -- re-charges the invoice.
244
- run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
245
- reflex_id text NOT NULL,
246
- unit text NOT NULL,
247
- cause text NOT NULL,
248
- env jsonb NOT NULL,
249
- depth integer NOT NULL DEFAULT 0,
250
- state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
251
- attempt integer NOT NULL DEFAULT 0,
252
- token text,
253
- -- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
254
- -- comparison rather than a disjunction.
255
- claimed_until bigint NOT NULL DEFAULT 0,
256
- not_before bigint NOT NULL,
257
- input jsonb,
258
- output jsonb,
259
- error text,
260
- created_at bigint NOT NULL,
261
- settled_at bigint,
262
- UNIQUE (run_id, unit)
263
- );
264
-
265
- CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
266
- CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
267
- CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
268
-
269
- CREATE TABLE IF NOT EXISTS tide_reflex_state (
270
- reflex_id text PRIMARY KEY,
271
- armed_at bigint NOT NULL DEFAULT 0,
272
- materialized_through bigint
273
- );
274
168
 
275
- -- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
276
- -- re-discover them late), and their cursor state goes with them. IF EXISTS,
277
- -- so a store created after the removal is not asked to drop what it never had.
278
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
279
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
280
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
281
- `;
282
- var SQL_TABLE = {
283
- fact: "tide_fact",
284
- run: "tide_run",
285
- task: "tide_work",
286
- state: "tide_reflex_state"
287
- };
288
- var COLUMN_OVERRIDES = { as: "as_who" };
289
- var snake = (field) => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
290
- var camel = (column) => {
291
- for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;
292
- return column.replace(/_([a-z])/g, (_all, c) => c.toUpperCase());
169
+ // src/generation.ts
170
+ var GENERATION_DDL = [
171
+ /* sql */
172
+ `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
173
+ /* sql */
174
+ `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
175
+ ];
176
+ var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
177
+ var createGeneration = (pool, ctx) => {
178
+ const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
179
+ let seen = -1;
180
+ let checking = false;
181
+ const read = async () => {
182
+ if (checking) return;
183
+ checking = true;
184
+ try {
185
+ const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
186
+ const n = Number(result.rows[0]?.n ?? 0);
187
+ if (!Number.isFinite(n)) return;
188
+ const first = seen === -1;
189
+ const moved = !first && n !== seen;
190
+ seen = n;
191
+ if (moved) await ctx.onMoved();
192
+ } catch (err) {
193
+ console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
194
+ } finally {
195
+ checking = false;
196
+ }
197
+ };
198
+ void read();
199
+ const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : void 0;
200
+ timer?.unref?.();
201
+ return {
202
+ bump: () => {
203
+ void pool.query("UPDATE moss_generation SET n = n + 1 WHERE id = 1").then(async () => {
204
+ const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
205
+ seen = Number(result.rows[0]?.n ?? seen);
206
+ }).catch((err) => console.error("[moss:generation] could not move the pointer", err));
207
+ },
208
+ current: () => seen,
209
+ stop: () => {
210
+ if (timer !== void 0) clearInterval(timer);
211
+ }
212
+ };
293
213
  };
294
- var JSON_COLUMNS = /* @__PURE__ */ new Set(["row", "payload", "stats", "fact_ids", "env", "input", "output"]);
295
- var BIGINT_COLUMNS = /* @__PURE__ */ new Set([
296
- "at",
297
- "not_before",
298
- "delivered_at",
299
- "depth",
300
- "descendants",
301
- "due_at",
302
- "created_at",
303
- "settled_at",
304
- "claimed_until",
305
- "armed_at",
306
- "materialized_through",
307
- "attempt",
308
- "selected",
309
- "total",
310
- "done",
311
- "failed"
312
- ]);
313
- var toColumn = (column, value) => {
314
- if (value === void 0) return null;
315
- if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
316
- return value;
214
+ var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
215
+ var fromB64url = (text) => Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64");
216
+ var signerFromSeed = (seed) => {
217
+ const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
218
+ const privateKey = createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
219
+ const asInput = privateKey;
220
+ return { privateKey, publicKey: createPublicKey(asInput) };
317
221
  };
318
- var fromColumn = (column, value) => {
319
- if (value === null) return void 0;
320
- if (JSON_COLUMNS.has(column)) return typeof value === "string" ? JSON.parse(value) : value;
321
- if (BIGINT_COLUMNS.has(column)) return Number(value);
322
- return value;
222
+ var createAssertionSigner = (seedB64) => {
223
+ const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
224
+ const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : generateKeyPairSync("ed25519");
225
+ const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
226
+ return {
227
+ verifyKey,
228
+ mint: (claims, ttlMs = 3e4) => {
229
+ const iat = Date.now();
230
+ const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
231
+ return `${b64url(body)}.${b64url(sign(null, body, privateKey))}`;
232
+ }
233
+ };
323
234
  };
324
- var rowToEntity = (table, row) => {
325
- const entity = {};
326
- for (const [column, value] of Object.entries(row)) {
327
- const mapped = fromColumn(column, value);
328
- if (mapped !== void 0) entity[camel(column)] = mapped;
329
- }
330
- return entity;
331
- };
332
- var COMPARATORS = { eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=" };
333
- var compileWhere = (where, start, alias = "") => {
334
- const clauses = [];
335
- const params = [];
336
- const prefix = alias === "" ? "" : `${alias}.`;
337
- const slot = (value) => {
338
- params.push(value);
339
- return `$${start + params.length - 1}`;
340
- };
341
- for (const [field, test] of Object.entries(where ?? {})) {
342
- const column = `${prefix}${snake(field)}`;
343
- const bare = snake(field);
344
- if (test === null || typeof test !== "object" || Array.isArray(test)) {
345
- clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
346
- continue;
347
- }
348
- const comparison = test;
349
- for (const [op, symbol] of Object.entries(COMPARATORS)) {
350
- const operand = comparison[op];
351
- if (operand === void 0) continue;
352
- clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
353
- }
354
- if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
355
- if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
356
- if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
357
- }
358
- return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
359
- };
360
- var compileOrder = (order, alias = "") => {
361
- if (order === void 0 || order.length === 0) return "";
362
- const prefix = alias === "" ? "" : `${alias}.`;
363
- return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
364
- };
365
- var sortRows = (rows, order) => {
366
- if (order === void 0 || order.length === 0) return [...rows];
367
- return [...rows].sort((left, right) => {
368
- for (const key of order) {
369
- const a = left[String(key.by)];
370
- const b = right[String(key.by)];
371
- const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
372
- if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
373
- }
374
- return 0;
375
- });
376
- };
377
- var compileSet = (set, start) => {
378
- const assignments = [];
379
- const params = [];
380
- for (const [field, value] of Object.entries(set)) {
381
- const column = snake(field);
382
- if (value !== null && typeof value === "object" && "inc" in value) {
383
- assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
384
- continue;
385
- }
386
- params.push(toColumn(column, value));
387
- assignments.push(`${column} = $${start + params.length - 1}`);
388
- }
389
- return { sql: assignments.join(", "), params };
390
- };
391
- var mintId = /* @__PURE__ */ (() => {
392
- let sequence = 0;
393
- return (table) => {
394
- sequence += 1;
395
- return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
396
- };
397
- })();
398
- 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 }));
399
- var TIDE_SEQUENCE = {
400
- id: "nisc.moss.tide",
401
- migrations: [
402
- { description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
403
- {
404
- // A fact's chain: the root it belongs to, and — on a root — how many facts
405
- // the chain has minted beneath it. Nullable: every existing fact is a
406
- // root nothing has been counted against yet.
407
- description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
408
- steps: [
409
- { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
410
- { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
411
- ]
412
- }
413
- ]
414
- };
415
- var createTideStore = (pool, options = {}) => {
416
- const ready = options.migrate === false ? Promise.resolve() : migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
417
- ready.catch(() => void 0);
418
- const build = (client) => {
419
- const store = {
420
- query: async (spec) => {
421
- await ready;
422
- const where = compileWhere(spec.where, 1);
423
- const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
424
- const result = await client.query(
425
- `SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
426
- where.params
427
- );
428
- return result.rows.map((row) => rowToEntity(spec.table, row));
429
- },
430
- // ON CONFLICT DO NOTHING, which is the whole point: the refusal is the
431
- // DATABASE's, decided under the constraint, not a read the caller races.
432
- appendIfAbsent: async (table, input) => {
433
- await ready;
434
- const withId = PRIMARY_KEY[table] === "id" ? { ...input, id: input.id ?? mintId(table) } : { ...input };
435
- const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
436
- const columns = entries.map(([field]) => snake(field));
437
- const params = entries.map(([field, value]) => toColumn(snake(field), value));
438
- const unique = UNIQUE_BY[table];
439
- 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`;
440
- const result = await client.query(
441
- `INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
442
- ON CONFLICT ${target} DO NOTHING RETURNING *`,
443
- params
444
- );
445
- const row = result.rows[0];
446
- return row === void 0 ? void 0 : rowToEntity(table, row);
447
- },
448
- // Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`
449
- // makes N instances ticking at once ordinary contention rather than a
450
- // lock service — it is a throughput choice; the exactly-once promise is
451
- // the single statement.
452
- claim: async (spec) => {
453
- await ready;
454
- const table = SQL_TABLE[spec.table];
455
- const order = compileOrder(spec.order, "c");
456
- const take = async (extra, limit) => {
457
- if (limit <= 0) return [];
458
- const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
459
- const set = compileSet(spec.set, where.params.length + 1);
460
- const result = await client.query(
461
- `UPDATE ${table} SET ${set.sql}
462
- WHERE ctid IN (
463
- SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
464
- LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
465
- )
466
- RETURNING *`,
467
- [...where.params, ...set.params]
468
- );
469
- return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
470
- };
471
- if (spec.onePer === void 0) return take({}, spec.limit);
472
- const { column, held, only } = spec.onePer;
473
- const restricted = [...only];
474
- const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);
475
- for (const group of restricted) {
476
- if (claimed.length >= spec.limit) break;
477
- const busy = compileWhere({ ...held, [String(column)]: group }, 1, "c");
478
- const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
479
- if (taken.rows.length > 0) continue;
480
- claimed.push(...await take({ [String(column)]: group }, 1));
481
- }
482
- return claimed;
483
- },
484
- cas: async (table, id, expect, set) => {
485
- await ready;
486
- const key = snake(String(PRIMARY_KEY[table]));
487
- const where = compileWhere(expect, 2);
488
- const patch = compileSet(set, where.params.length + 2);
489
- const result = await client.query(
490
- `UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
491
- [id, ...where.params, ...patch.params]
492
- );
493
- return result.rows.length > 0;
494
- },
495
- remove: async (spec) => {
496
- await ready;
497
- const where = compileWhere(spec.where, 1);
498
- const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(PRIMARY_KEY[spec.table]))}`, where.params);
499
- return result.rows.length;
500
- },
501
- transact: async (fn) => {
502
- await ready;
503
- if (client.transaction === void 0)
504
- throw new Error("tide store: this pool cannot transact \u2014 fan-out and attempt recording are transactions, not conventions");
505
- return client.transaction((tx) => fn(build({ ...client, query: tx.query })));
506
- }
507
- };
508
- return store;
509
- };
510
- return { ...build(pool), ready };
511
- };
512
- var mintWrites = async (intake, event, as, at, chain) => {
513
- for (const write of event.writes) {
514
- for (const row of write.rows) {
515
- await intake.ingest(
516
- { kind: "write", entity: write.table, op: write.op, row, at },
517
- { as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
518
- );
519
- }
520
- }
521
- };
522
-
523
- // src/generation.ts
524
- var GENERATION_DDL = [
525
- /* sql */
526
- `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
527
- /* sql */
528
- `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
529
- ];
530
- var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
531
- var createGeneration = (pool, ctx) => {
532
- const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
533
- let seen = -1;
534
- let checking = false;
535
- const read = async () => {
536
- if (checking) return;
537
- checking = true;
538
- try {
539
- const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
540
- const n = Number(result.rows[0]?.n ?? 0);
541
- if (!Number.isFinite(n)) return;
542
- const first = seen === -1;
543
- const moved = !first && n !== seen;
544
- seen = n;
545
- if (moved) await ctx.onMoved();
546
- } catch (err) {
547
- console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
548
- } finally {
549
- checking = false;
550
- }
551
- };
552
- void read();
553
- const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : void 0;
554
- timer?.unref?.();
555
- return {
556
- bump: () => {
557
- void pool.query("UPDATE moss_generation SET n = n + 1 WHERE id = 1").then(async () => {
558
- const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
559
- seen = Number(result.rows[0]?.n ?? seen);
560
- }).catch((err) => console.error("[moss:generation] could not move the pointer", err));
561
- },
562
- current: () => seen,
563
- stop: () => {
564
- if (timer !== void 0) clearInterval(timer);
565
- }
566
- };
567
- };
568
- var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
569
- var fromB64url = (text) => Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64");
570
- var signerFromSeed = (seed) => {
571
- const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
572
- const privateKey = createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
573
- const asInput = privateKey;
574
- return { privateKey, publicKey: createPublicKey(asInput) };
575
- };
576
- var createAssertionSigner = (seedB64) => {
577
- const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
578
- const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : generateKeyPairSync("ed25519");
579
- const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
580
- return {
581
- verifyKey,
582
- mint: (claims, ttlMs = 3e4) => {
583
- const iat = Date.now();
584
- const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
585
- return `${b64url(body)}.${b64url(sign(null, body, privateKey))}`;
586
- }
587
- };
588
- };
589
- var verifyAssertion = (token, verifyKey, now = Date.now()) => {
590
- const dot = token.indexOf(".");
591
- if (dot <= 0) return void 0;
592
- try {
593
- const body = fromB64url(token.slice(0, dot));
594
- const signature = fromB64url(token.slice(dot + 1));
595
- const key = createPublicKey({ key: fromB64url(verifyKey), format: "der", type: "spki" });
596
- if (!verify(null, body, key, signature)) return void 0;
597
- const parsed = JSON.parse(body.toString());
598
- if (typeof parsed.integration !== "string" || typeof parsed.principal !== "string") return void 0;
599
- if (typeof parsed.exp !== "number" || parsed.exp <= now) return void 0;
600
- return parsed;
601
- } catch {
602
- return void 0;
235
+ var verifyAssertion = (token, verifyKey, now = Date.now()) => {
236
+ const dot = token.indexOf(".");
237
+ if (dot <= 0) return void 0;
238
+ try {
239
+ const body = fromB64url(token.slice(0, dot));
240
+ const signature = fromB64url(token.slice(dot + 1));
241
+ const key = createPublicKey({ key: fromB64url(verifyKey), format: "der", type: "spki" });
242
+ if (!verify(null, body, key, signature)) return void 0;
243
+ const parsed = JSON.parse(body.toString());
244
+ if (typeof parsed.integration !== "string" || typeof parsed.principal !== "string") return void 0;
245
+ if (typeof parsed.exp !== "number" || parsed.exp <= now) return void 0;
246
+ return parsed;
247
+ } catch {
248
+ return void 0;
603
249
  }
604
250
  };
605
251
  var mintIntegrationKey = () => `ik_${randomBytes(32).toString("hex")}`;
@@ -1322,204 +968,654 @@ var MOSS_SEQUENCE = {
1322
968
  }
1323
969
  ]
1324
970
  };
1325
- var INTEGRATION_ACTIONS_STORE = {
1326
- table: "integration_actions",
1327
- column: "definition",
1328
- stamp: "grammar",
1329
- kind: "nisc.nova/action",
1330
- key: ["integration_id", "action_id"]
971
+ var INTEGRATION_ACTIONS_STORE = {
972
+ table: "integration_actions",
973
+ column: "definition",
974
+ stamp: "grammar",
975
+ kind: "nisc.nova/action",
976
+ key: ["integration_id", "action_id"]
977
+ };
978
+ var initIntegrations = async (pool) => {
979
+ await migrate(pool, [MOSS_SEQUENCE]);
980
+ };
981
+ var listAttachments = async (pool, hostAction) => {
982
+ const res = await pool.query(
983
+ `SELECT a.action_id, a.preview FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
984
+ WHERE i.status = 'approved' AND a.attach_to = $1 ORDER BY a.action_id`,
985
+ [hostAction]
986
+ );
987
+ return res.rows.map((r) => {
988
+ const row = r;
989
+ return { actionId: String(row.action_id), preview: String(row.preview ?? "") };
990
+ });
991
+ };
992
+ var listPlacements = async (pool) => {
993
+ const res = await pool.query(
994
+ `SELECT a.action_id, a.place_in FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
995
+ WHERE i.status = 'approved' AND a.place_in <> ''`
996
+ );
997
+ const out = {};
998
+ for (const r of res.rows) {
999
+ const row = r;
1000
+ out[String(row.action_id)] = String(row.place_in);
1001
+ }
1002
+ return out;
1003
+ };
1004
+ var integrationByKey = async (pool, key) => {
1005
+ const res = await pool.query("SELECT id FROM integrations WHERE key_hash = $1 AND status = 'approved'", [hashIntegrationKey(key)]);
1006
+ const id = res.rows[0]?.id;
1007
+ return id === void 0 ? void 0 : String(id);
1008
+ };
1009
+ var listIntegrations = async (pool) => {
1010
+ const res = await pool.query(`
1011
+ SELECT i.id, i.url, i.status, i.title, i.tagline, i.adds, i.settings_action,
1012
+ i.requested_actions, i.requested_data, i.approved_data,
1013
+ i.offers, i.needs, i.capabilities, i.configuration, i.documents, i.assistants,
1014
+ i.last_import_at, i.last_error,
1015
+ (SELECT count(*) FROM integration_actions a WHERE a.integration_id = i.id) AS action_count
1016
+ FROM integrations i ORDER BY i.id
1017
+ `);
1018
+ return res.rows.map((r) => {
1019
+ const row = r;
1020
+ const at = row["last_import_at"];
1021
+ return {
1022
+ id: String(row["id"]),
1023
+ url: String(row["url"]),
1024
+ status: String(row["status"]),
1025
+ title: String(row["title"] ?? ""),
1026
+ tagline: String(row["tagline"] ?? ""),
1027
+ adds: String(row["adds"] ?? ""),
1028
+ settingsAction: String(row["settings_action"] ?? ""),
1029
+ requestedActions: row["requested_actions"] ?? [],
1030
+ requestedData: row["requested_data"] ?? [],
1031
+ approvedData: row["approved_data"] ?? [],
1032
+ offers: row["offers"] ?? [],
1033
+ needs: row["needs"] ?? [],
1034
+ capabilities: row["capabilities"] ?? [],
1035
+ configuration: row["configuration"] ?? [],
1036
+ documents: row["documents"] ?? [],
1037
+ assistants: row["assistants"] ?? [],
1038
+ lastImportAt: at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : null,
1039
+ lastError: row["last_error"] ?? null,
1040
+ actionCount: Number(row["action_count"] ?? 0)
1041
+ };
1042
+ });
1043
+ };
1044
+ var loadIntegrationActions = async (pool, upgrader) => {
1045
+ const res = await pool.query(
1046
+ `SELECT a.action_id, a.definition, a.grammar FROM integration_actions a
1047
+ JOIN integrations i ON i.id = a.integration_id
1048
+ WHERE i.status = 'approved'`
1049
+ );
1050
+ const out = {};
1051
+ for (const r of res.rows) {
1052
+ const row = r;
1053
+ const id = String(row["action_id"]);
1054
+ if (upgrader === void 0) {
1055
+ out[id] = row["definition"];
1056
+ continue;
1057
+ }
1058
+ const stamp = isPlainRecord(row["grammar"]) ? Object.fromEntries(Object.entries(row["grammar"]).map(([k, v]) => [k, Number(v)])) : {};
1059
+ try {
1060
+ out[id] = upgrader.upgrade(row["definition"], { kind: "nisc.nova/action", stamp }).document;
1061
+ } catch (error) {
1062
+ if (!(error instanceof StrataError)) throw error;
1063
+ console.error(`[moss] integration action "${id}" is not served: ${error.message.split("\n")[0] ?? error.code}`);
1064
+ }
1065
+ }
1066
+ return out;
1067
+ };
1068
+ var integrationOfAction = (id) => id.startsWith("ext.") ? id.split(".")[2] : void 0;
1069
+ var filterInstalled = (ids, installed) => {
1070
+ if (installed === void 0) return ids;
1071
+ return ids.filter((id) => {
1072
+ const owner = integrationOfAction(id);
1073
+ return owner === void 0 || installed.has(owner);
1074
+ });
1075
+ };
1076
+ var buildContract = (app, integrationId) => {
1077
+ const registered = app.shell?.components ?? {};
1078
+ const components = Object.keys(registered).sort().map((name) => paletteEntryOf(name, registered[name]?.meta ?? {}));
1079
+ const audiences = /* @__PURE__ */ new Set();
1080
+ for (const def of Object.values(app.charter)) {
1081
+ if (def === void 0 || Array.isArray(def)) continue;
1082
+ const selection = def.actions;
1083
+ const list = Array.isArray(selection) ? selection : selection?.allow ?? [];
1084
+ for (const entry of list) {
1085
+ const parts = String(entry).split(".");
1086
+ if (parts[0] === "ext" && parts[1] !== void 0 && parts[1] !== "*") audiences.add(parts[1]);
1087
+ }
1088
+ }
1089
+ const attachable = {};
1090
+ for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);
1091
+ return {
1092
+ components,
1093
+ audiences: [...audiences].sort(),
1094
+ namespace: `ext.<audience>.${integrationId}.<name>`,
1095
+ actionSchema: "nova ActionDefinition",
1096
+ attachable,
1097
+ menuSlots: [...app.menuSlots ?? []]
1098
+ };
1099
+ };
1100
+ var describeProp = (schema) => {
1101
+ const enumValues = schema["enum"];
1102
+ if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(", ")}`;
1103
+ const anyOf = schema["anyOf"];
1104
+ if (Array.isArray(anyOf)) {
1105
+ const consts = anyOf.map((s) => s["const"]).filter((v) => v !== void 0);
1106
+ if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(", ")}`;
1107
+ }
1108
+ const type = schema["type"];
1109
+ const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
1110
+ const min = schema["minimum"];
1111
+ const max = schema["maximum"];
1112
+ if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
1113
+ return base;
1114
+ };
1115
+ var componentAsMarkdown = (component) => {
1116
+ const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
1117
+ const schema = component.propsSchema;
1118
+ const properties = schema?.properties;
1119
+ if (properties === void 0 || Object.keys(properties).length === 0) return head;
1120
+ const required = new Set(schema?.required ?? []);
1121
+ const rows = Object.entries(properties).map(
1122
+ ([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
1123
+ );
1124
+ return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
1125
+ };
1126
+ var contractAsMarkdown = (contract, fingerprints) => [
1127
+ `# What you can build against`,
1128
+ ``,
1129
+ `## Your namespace`,
1130
+ ``,
1131
+ ` ${contract.namespace}`,
1132
+ ``,
1133
+ `Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
1134
+ ``,
1135
+ `## Components your layouts may use`,
1136
+ ``,
1137
+ contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
1138
+ ``,
1139
+ `## Fingerprints you may call`,
1140
+ ``,
1141
+ `Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
1142
+ `\`/integrations/<your id>/\`. Nothing else.`,
1143
+ ``,
1144
+ fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
1145
+ ``,
1146
+ `## Where your screens may appear`,
1147
+ ``,
1148
+ `Declare \`attachments\` (action \u2192 host action) to ride a host screen, and`,
1149
+ `\`placements\` (action \u2192 hub) to list under a menu hub. \`settings\` names the one`,
1150
+ `action the store tile opens. Anything else is refused.`,
1151
+ ``,
1152
+ `Attachable, with what each hands you as input:`,
1153
+ ``,
1154
+ Object.entries(contract.attachable).map(([action, offers]) => `- ${action} \u2014 offers ${offers.join(", ") || "(nothing)"}`).join("\n") || "(none)",
1155
+ ``,
1156
+ `Menu hubs accepting placements:`,
1157
+ ``,
1158
+ contract.menuSlots.map((hub) => `- ${hub}`).join("\n") || "(none)",
1159
+ ``,
1160
+ `## What you cannot ship`,
1161
+ ``,
1162
+ `- vex entries or mutations. Call what is listed above; if you need a read that`,
1163
+ ` does not exist, it is a change to the app.`,
1164
+ `- \`fn:\` endpoints. Those run in the app's process.`,
1165
+ `- components. Layouts compose what is listed above.`,
1166
+ `- tables. Bring your own storage; we hand you identifiers.`,
1167
+ ``
1168
+ ].join("\n");
1169
+ var tableSequencesOf = (runtime) => {
1170
+ const cacheSequence = (runtime.cache ?? createPostgresCache({ pool: runtime.pool })).sequence;
1171
+ return [
1172
+ MOSS_SEQUENCE,
1173
+ ...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [],
1174
+ ...cacheSequence === void 0 ? [] : [cacheSequence],
1175
+ ...runtime.tables ?? []
1176
+ ];
1177
+ };
1178
+ var misfitOf = (entry, schema) => {
1179
+ if (!("mutation" in entry)) {
1180
+ try {
1181
+ resolve(pruneOptional(entry.dsl, "all"), schema);
1182
+ return void 0;
1183
+ } catch (error) {
1184
+ return error instanceof Error ? error.message : String(error);
1185
+ }
1186
+ }
1187
+ return mutationMisfits(entry.mutation, schema)[0];
1188
+ };
1189
+ var misfitsOf = (entries, schema) => {
1190
+ const misfits = /* @__PURE__ */ new Map();
1191
+ for (const entry of entries) {
1192
+ const why = misfitOf(entry, schema);
1193
+ if (why !== void 0) misfits.set(entry.fingerprint, why);
1194
+ }
1195
+ return misfits;
1196
+ };
1197
+ var canonical = (value) => {
1198
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1199
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1200
+ const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
1201
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
1202
+ };
1203
+ var isSeededAs = async (cache, entry) => {
1204
+ const held = await cache.get(entry.fingerprint);
1205
+ if (held === void 0 || held.protected !== true) return false;
1206
+ if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
1207
+ return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
1208
+ };
1209
+ var changesBetween = (before, after) => {
1210
+ const removed = [];
1211
+ const retyped = [];
1212
+ for (const was of before.entities) {
1213
+ const now = after.entities.find((entity) => entity.table === was.table);
1214
+ if (now === void 0) {
1215
+ removed.push(was.table);
1216
+ continue;
1217
+ }
1218
+ for (const field of was.fields) {
1219
+ const kept = now.fields.find((f) => f.name === field.name);
1220
+ if (kept === void 0) removed.push(`${was.table}.${field.name}`);
1221
+ else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
1222
+ }
1223
+ }
1224
+ return { removed, retyped };
1225
+ };
1226
+ var oneAtATime = (query) => {
1227
+ let last = Promise.resolve();
1228
+ return (text, values) => {
1229
+ const next = last.then(() => query(text, values));
1230
+ last = next.catch(() => void 0);
1231
+ return next;
1232
+ };
1233
+ };
1234
+ var migrateTables = async (runtime, app, options = {}) => {
1235
+ const entries = app.entries ?? [];
1236
+ const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });
1237
+ const before = await createPostgresAdapter({ pool: runtime.pool }).introspect();
1238
+ const misfitsBefore = misfitsOf(entries, before);
1239
+ const excused = /* @__PURE__ */ new Set();
1240
+ for (const entry of entries) {
1241
+ if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
1242
+ }
1243
+ let found = { removed: [], retyped: [], alreadyBroken: [] };
1244
+ const report = await migrate(runtime.pool, tableSequencesOf(runtime), {
1245
+ ...options.dryRun === true ? { dryRun: true } : {},
1246
+ guard: async (tx) => {
1247
+ const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
1248
+ const refused = [];
1249
+ const alreadyBroken = [];
1250
+ for (const [fingerprint, why] of misfitsOf(entries, after)) {
1251
+ if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
1252
+ else refused.push(`${fingerprint}: ${why}`);
1253
+ }
1254
+ found = { ...changesBetween(before, after), alreadyBroken };
1255
+ return refused;
1256
+ }
1257
+ });
1258
+ return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
1259
+ };
1260
+ var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
1261
+ var TIDE_DDL = `
1262
+ CREATE TABLE IF NOT EXISTS tide_fact (
1263
+ id text PRIMARY KEY,
1264
+ kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
1265
+ entity text,
1266
+ op text CHECK (op IN ('insert','update','delete')),
1267
+ row jsonb,
1268
+ name text,
1269
+ payload jsonb,
1270
+ reflex text,
1271
+ run_id text,
1272
+ occurrence text,
1273
+ stats jsonb,
1274
+ target text,
1275
+ by text,
1276
+ at bigint NOT NULL,
1277
+ not_before bigint,
1278
+ dedupe_key text,
1279
+ cause text,
1280
+ depth integer NOT NULL DEFAULT 0,
1281
+ delivered_at bigint,
1282
+ parked text,
1283
+ released boolean,
1284
+ -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
1285
+ -- anything the host ingested. The matcher refuses to hand a fact minted
1286
+ -- under one identity to a reflex running under another, which is the only
1287
+ -- thing standing between a carried row and somebody else's effect \u2014 tide is
1288
+ -- the one place a row travels without being read, so no scope policy is
1289
+ -- consulted on the way.
1290
+ as_who text
1291
+ );
1292
+
1293
+ -- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
1294
+ -- unique: it is a distinct occurrence of something, not a repeat of it.
1295
+ -- entity is in the key: without it, two producers over different tables
1296
+ -- that agreed on a key value silently ate each other's rows.
1297
+ CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
1298
+ ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
1299
+ WHERE dedupe_key IS NOT NULL;
1300
+
1301
+ -- The matcher's query, every advance.
1302
+ CREATE INDEX IF NOT EXISTS tide_fact_due
1303
+ ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
1304
+ CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
1305
+
1306
+ CREATE TABLE IF NOT EXISTS tide_run (
1307
+ id text PRIMARY KEY,
1308
+ reflex_id text NOT NULL,
1309
+ version text NOT NULL,
1310
+ as_who text,
1311
+ cause text NOT NULL,
1312
+ occurrence text,
1313
+ fact_ids jsonb,
1314
+ state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
1315
+ depth integer NOT NULL DEFAULT 0,
1316
+ selected integer,
1317
+ total integer NOT NULL DEFAULT 0,
1318
+ done integer NOT NULL DEFAULT 0,
1319
+ failed integer NOT NULL DEFAULT 0,
1320
+ due_at bigint NOT NULL,
1321
+ created_at bigint NOT NULL,
1322
+ settled_at bigint,
1323
+ drained boolean,
1324
+ note text,
1325
+ -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
1326
+ -- cannot open twice, a replayed fact cannot open twice, and two instances
1327
+ -- ticking at the same moment contend instead of duplicating.
1328
+ UNIQUE (reflex_id, cause)
1329
+ );
1330
+
1331
+ CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
1332
+ CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
1333
+ CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
1334
+
1335
+ CREATE TABLE IF NOT EXISTS tide_work (
1336
+ id text PRIMARY KEY,
1337
+ -- ON DELETE CASCADE, because a run and its work are one fact about the
1338
+ -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
1339
+ -- row that IS the "this unit already ran" record \u2014 and a restore then
1340
+ -- re-charges the invoice.
1341
+ run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
1342
+ reflex_id text NOT NULL,
1343
+ unit text NOT NULL,
1344
+ cause text NOT NULL,
1345
+ env jsonb NOT NULL,
1346
+ depth integer NOT NULL DEFAULT 0,
1347
+ state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
1348
+ attempt integer NOT NULL DEFAULT 0,
1349
+ token text,
1350
+ -- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
1351
+ -- comparison rather than a disjunction.
1352
+ claimed_until bigint NOT NULL DEFAULT 0,
1353
+ not_before bigint NOT NULL,
1354
+ input jsonb,
1355
+ output jsonb,
1356
+ error text,
1357
+ created_at bigint NOT NULL,
1358
+ settled_at bigint,
1359
+ UNIQUE (run_id, unit)
1360
+ );
1361
+
1362
+ CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
1363
+ CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
1364
+ CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
1365
+
1366
+ CREATE TABLE IF NOT EXISTS tide_reflex_state (
1367
+ reflex_id text PRIMARY KEY,
1368
+ armed_at bigint NOT NULL DEFAULT 0,
1369
+ materialized_through bigint
1370
+ );
1371
+
1372
+ -- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
1373
+ -- re-discover them late), and their cursor state goes with them. IF EXISTS,
1374
+ -- so a store created after the removal is not asked to drop what it never had.
1375
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
1376
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
1377
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
1378
+ `;
1379
+ var SQL_TABLE = {
1380
+ fact: "tide_fact",
1381
+ run: "tide_run",
1382
+ task: "tide_work",
1383
+ state: "tide_reflex_state"
1384
+ };
1385
+ var COLUMN_OVERRIDES = { as: "as_who" };
1386
+ var snake = (field) => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
1387
+ var camel = (column) => {
1388
+ for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;
1389
+ return column.replace(/_([a-z])/g, (_all, c) => c.toUpperCase());
1331
1390
  };
1332
- var initIntegrations = async (pool) => {
1333
- await migrate(pool, [MOSS_SEQUENCE]);
1391
+ var JSON_COLUMNS = /* @__PURE__ */ new Set(["row", "payload", "stats", "fact_ids", "env", "input", "output"]);
1392
+ var BIGINT_COLUMNS = /* @__PURE__ */ new Set([
1393
+ "at",
1394
+ "not_before",
1395
+ "delivered_at",
1396
+ "depth",
1397
+ "descendants",
1398
+ "due_at",
1399
+ "created_at",
1400
+ "settled_at",
1401
+ "claimed_until",
1402
+ "armed_at",
1403
+ "materialized_through",
1404
+ "attempt",
1405
+ "selected",
1406
+ "total",
1407
+ "done",
1408
+ "failed"
1409
+ ]);
1410
+ var toColumn = (column, value) => {
1411
+ if (value === void 0) return null;
1412
+ if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
1413
+ return value;
1334
1414
  };
1335
- var listAttachments = async (pool, hostAction) => {
1336
- const res = await pool.query(
1337
- `SELECT a.action_id, a.preview FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
1338
- WHERE i.status = 'approved' AND a.attach_to = $1 ORDER BY a.action_id`,
1339
- [hostAction]
1340
- );
1341
- return res.rows.map((r) => {
1342
- const row = r;
1343
- return { actionId: String(row.action_id), preview: String(row.preview ?? "") };
1344
- });
1415
+ var fromColumn = (column, value) => {
1416
+ if (value === null) return void 0;
1417
+ if (JSON_COLUMNS.has(column)) return typeof value === "string" ? JSON.parse(value) : value;
1418
+ if (BIGINT_COLUMNS.has(column)) return Number(value);
1419
+ return value;
1345
1420
  };
1346
- var listPlacements = async (pool) => {
1347
- const res = await pool.query(
1348
- `SELECT a.action_id, a.place_in FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
1349
- WHERE i.status = 'approved' AND a.place_in <> ''`
1350
- );
1351
- const out = {};
1352
- for (const r of res.rows) {
1353
- const row = r;
1354
- out[String(row.action_id)] = String(row.place_in);
1421
+ var rowToEntity = (table, row) => {
1422
+ const entity = {};
1423
+ for (const [column, value] of Object.entries(row)) {
1424
+ const mapped = fromColumn(column, value);
1425
+ if (mapped !== void 0) entity[camel(column)] = mapped;
1355
1426
  }
1356
- return out;
1357
- };
1358
- var integrationByKey = async (pool, key) => {
1359
- const res = await pool.query("SELECT id FROM integrations WHERE key_hash = $1 AND status = 'approved'", [hashIntegrationKey(key)]);
1360
- const id = res.rows[0]?.id;
1361
- return id === void 0 ? void 0 : String(id);
1362
- };
1363
- var listIntegrations = async (pool) => {
1364
- const res = await pool.query(`
1365
- SELECT i.id, i.url, i.status, i.title, i.tagline, i.adds, i.settings_action,
1366
- i.requested_actions, i.requested_data, i.approved_data,
1367
- i.offers, i.needs, i.capabilities, i.configuration, i.documents, i.assistants,
1368
- i.last_import_at, i.last_error,
1369
- (SELECT count(*) FROM integration_actions a WHERE a.integration_id = i.id) AS action_count
1370
- FROM integrations i ORDER BY i.id
1371
- `);
1372
- return res.rows.map((r) => {
1373
- const row = r;
1374
- const at = row["last_import_at"];
1375
- return {
1376
- id: String(row["id"]),
1377
- url: String(row["url"]),
1378
- status: String(row["status"]),
1379
- title: String(row["title"] ?? ""),
1380
- tagline: String(row["tagline"] ?? ""),
1381
- adds: String(row["adds"] ?? ""),
1382
- settingsAction: String(row["settings_action"] ?? ""),
1383
- requestedActions: row["requested_actions"] ?? [],
1384
- requestedData: row["requested_data"] ?? [],
1385
- approvedData: row["approved_data"] ?? [],
1386
- offers: row["offers"] ?? [],
1387
- needs: row["needs"] ?? [],
1388
- capabilities: row["capabilities"] ?? [],
1389
- configuration: row["configuration"] ?? [],
1390
- documents: row["documents"] ?? [],
1391
- assistants: row["assistants"] ?? [],
1392
- lastImportAt: at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : null,
1393
- lastError: row["last_error"] ?? null,
1394
- actionCount: Number(row["action_count"] ?? 0)
1395
- };
1396
- });
1427
+ return entity;
1397
1428
  };
1398
- var loadIntegrationActions = async (pool, upgrader) => {
1399
- const res = await pool.query(
1400
- `SELECT a.action_id, a.definition, a.grammar FROM integration_actions a
1401
- JOIN integrations i ON i.id = a.integration_id
1402
- WHERE i.status = 'approved'`
1403
- );
1404
- const out = {};
1405
- for (const r of res.rows) {
1406
- const row = r;
1407
- const id = String(row["action_id"]);
1408
- if (upgrader === void 0) {
1409
- out[id] = row["definition"];
1429
+ var COMPARATORS = { eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=" };
1430
+ var compileWhere = (where, start, alias = "") => {
1431
+ const clauses = [];
1432
+ const params = [];
1433
+ const prefix = alias === "" ? "" : `${alias}.`;
1434
+ const slot = (value) => {
1435
+ params.push(value);
1436
+ return `$${start + params.length - 1}`;
1437
+ };
1438
+ for (const [field, test] of Object.entries(where ?? {})) {
1439
+ const column = `${prefix}${snake(field)}`;
1440
+ const bare = snake(field);
1441
+ if (test === null || typeof test !== "object" || Array.isArray(test)) {
1442
+ clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
1410
1443
  continue;
1411
1444
  }
1412
- const stamp = isPlainRecord(row["grammar"]) ? Object.fromEntries(Object.entries(row["grammar"]).map(([k, v]) => [k, Number(v)])) : {};
1413
- try {
1414
- out[id] = upgrader.upgrade(row["definition"], { kind: "nisc.nova/action", stamp }).document;
1415
- } catch (error) {
1416
- if (!(error instanceof StrataError)) throw error;
1417
- console.error(`[moss] integration action "${id}" is not served: ${error.message.split("\n")[0] ?? error.code}`);
1445
+ const comparison = test;
1446
+ for (const [op, symbol] of Object.entries(COMPARATORS)) {
1447
+ const operand = comparison[op];
1448
+ if (operand === void 0) continue;
1449
+ clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
1418
1450
  }
1451
+ if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
1452
+ if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
1453
+ if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
1419
1454
  }
1420
- return out;
1455
+ return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
1456
+ };
1457
+ var compileOrder = (order, alias = "") => {
1458
+ if (order === void 0 || order.length === 0) return "";
1459
+ const prefix = alias === "" ? "" : `${alias}.`;
1460
+ return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
1421
1461
  };
1422
- var integrationOfAction = (id) => id.startsWith("ext.") ? id.split(".")[2] : void 0;
1423
- var filterInstalled = (ids, installed) => {
1424
- if (installed === void 0) return ids;
1425
- return ids.filter((id) => {
1426
- const owner = integrationOfAction(id);
1427
- return owner === void 0 || installed.has(owner);
1462
+ var sortRows = (rows, order) => {
1463
+ if (order === void 0 || order.length === 0) return [...rows];
1464
+ return [...rows].sort((left, right) => {
1465
+ for (const key of order) {
1466
+ const a = left[String(key.by)];
1467
+ const b = right[String(key.by)];
1468
+ const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
1469
+ if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
1470
+ }
1471
+ return 0;
1428
1472
  });
1429
1473
  };
1430
- var buildContract = (app, integrationId) => {
1431
- const registered = app.shell?.components ?? {};
1432
- const components = Object.keys(registered).sort().map((name) => paletteEntryOf(name, registered[name]?.meta ?? {}));
1433
- const audiences = /* @__PURE__ */ new Set();
1434
- for (const def of Object.values(app.charter)) {
1435
- if (def === void 0 || Array.isArray(def)) continue;
1436
- const selection = def.actions;
1437
- const list = Array.isArray(selection) ? selection : selection?.allow ?? [];
1438
- for (const entry of list) {
1439
- const parts = String(entry).split(".");
1440
- if (parts[0] === "ext" && parts[1] !== void 0 && parts[1] !== "*") audiences.add(parts[1]);
1474
+ var compileSet = (set, start) => {
1475
+ const assignments = [];
1476
+ const params = [];
1477
+ for (const [field, value] of Object.entries(set)) {
1478
+ const column = snake(field);
1479
+ if (value !== null && typeof value === "object" && "inc" in value) {
1480
+ assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
1481
+ continue;
1441
1482
  }
1483
+ params.push(toColumn(column, value));
1484
+ assignments.push(`${column} = $${start + params.length - 1}`);
1442
1485
  }
1443
- const attachable = {};
1444
- for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);
1445
- return {
1446
- components,
1447
- audiences: [...audiences].sort(),
1448
- namespace: `ext.<audience>.${integrationId}.<name>`,
1449
- actionSchema: "nova ActionDefinition",
1450
- attachable,
1451
- menuSlots: [...app.menuSlots ?? []]
1486
+ return { sql: assignments.join(", "), params };
1487
+ };
1488
+ var mintId = /* @__PURE__ */ (() => {
1489
+ let sequence = 0;
1490
+ return (table) => {
1491
+ sequence += 1;
1492
+ return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
1452
1493
  };
1494
+ })();
1495
+ 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 }));
1496
+ var TIDE_SEQUENCE = {
1497
+ id: "nisc.moss.tide",
1498
+ migrations: [
1499
+ { description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
1500
+ {
1501
+ // A fact's chain: the root it belongs to, and — on a root — how many facts
1502
+ // the chain has minted beneath it. Nullable: every existing fact is a
1503
+ // root nothing has been counted against yet.
1504
+ description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
1505
+ steps: [
1506
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
1507
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
1508
+ ]
1509
+ }
1510
+ ]
1453
1511
  };
1454
- var describeProp = (schema) => {
1455
- const enumValues = schema["enum"];
1456
- if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(", ")}`;
1457
- const anyOf = schema["anyOf"];
1458
- if (Array.isArray(anyOf)) {
1459
- const consts = anyOf.map((s) => s["const"]).filter((v) => v !== void 0);
1460
- if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(", ")}`;
1461
- }
1462
- const type = schema["type"];
1463
- const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
1464
- const min = schema["minimum"];
1465
- const max = schema["maximum"];
1466
- if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
1467
- return base;
1512
+ var createTideStore = (pool, options = {}) => {
1513
+ const ready = options.migrate === false ? Promise.resolve() : migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
1514
+ ready.catch(() => void 0);
1515
+ const build = (client) => {
1516
+ const store = {
1517
+ query: async (spec) => {
1518
+ await ready;
1519
+ const where = compileWhere(spec.where, 1);
1520
+ const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
1521
+ const result = await client.query(
1522
+ `SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
1523
+ where.params
1524
+ );
1525
+ return result.rows.map((row) => rowToEntity(spec.table, row));
1526
+ },
1527
+ // ON CONFLICT DO NOTHING, which is the whole point: the refusal is the
1528
+ // DATABASE's, decided under the constraint, not a read the caller races.
1529
+ appendIfAbsent: async (table, input) => {
1530
+ await ready;
1531
+ const withId = PRIMARY_KEY[table] === "id" ? { ...input, id: input.id ?? mintId(table) } : { ...input };
1532
+ const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
1533
+ const columns = entries.map(([field]) => snake(field));
1534
+ const params = entries.map(([field, value]) => toColumn(snake(field), value));
1535
+ const unique = UNIQUE_BY[table];
1536
+ 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`;
1537
+ const result = await client.query(
1538
+ `INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
1539
+ ON CONFLICT ${target} DO NOTHING RETURNING *`,
1540
+ params
1541
+ );
1542
+ const row = result.rows[0];
1543
+ return row === void 0 ? void 0 : rowToEntity(table, row);
1544
+ },
1545
+ // Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`
1546
+ // makes N instances ticking at once ordinary contention rather than a
1547
+ // lock service — it is a throughput choice; the exactly-once promise is
1548
+ // the single statement.
1549
+ claim: async (spec) => {
1550
+ await ready;
1551
+ const table = SQL_TABLE[spec.table];
1552
+ const order = compileOrder(spec.order, "c");
1553
+ const take = async (extra, limit) => {
1554
+ if (limit <= 0) return [];
1555
+ const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
1556
+ const set = compileSet(spec.set, where.params.length + 1);
1557
+ const result = await client.query(
1558
+ `UPDATE ${table} SET ${set.sql}
1559
+ WHERE ctid IN (
1560
+ SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
1561
+ LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
1562
+ )
1563
+ RETURNING *`,
1564
+ [...where.params, ...set.params]
1565
+ );
1566
+ return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
1567
+ };
1568
+ if (spec.onePer === void 0) return take({}, spec.limit);
1569
+ const { column, held, only } = spec.onePer;
1570
+ const restricted = [...only];
1571
+ const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);
1572
+ for (const group of restricted) {
1573
+ if (claimed.length >= spec.limit) break;
1574
+ const busy = compileWhere({ ...held, [String(column)]: group }, 1, "c");
1575
+ const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
1576
+ if (taken.rows.length > 0) continue;
1577
+ claimed.push(...await take({ [String(column)]: group }, 1));
1578
+ }
1579
+ return claimed;
1580
+ },
1581
+ cas: async (table, id, expect, set) => {
1582
+ await ready;
1583
+ const key = snake(String(PRIMARY_KEY[table]));
1584
+ const where = compileWhere(expect, 2);
1585
+ const patch = compileSet(set, where.params.length + 2);
1586
+ const result = await client.query(
1587
+ `UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
1588
+ [id, ...where.params, ...patch.params]
1589
+ );
1590
+ return result.rows.length > 0;
1591
+ },
1592
+ remove: async (spec) => {
1593
+ await ready;
1594
+ const where = compileWhere(spec.where, 1);
1595
+ const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(PRIMARY_KEY[spec.table]))}`, where.params);
1596
+ return result.rows.length;
1597
+ },
1598
+ transact: async (fn) => {
1599
+ await ready;
1600
+ if (client.transaction === void 0)
1601
+ throw new Error("tide store: this pool cannot transact \u2014 fan-out and attempt recording are transactions, not conventions");
1602
+ return client.transaction((tx) => fn(build({ ...client, query: (text, values) => tx.query(text, values) })));
1603
+ }
1604
+ };
1605
+ return store;
1606
+ };
1607
+ return { ...build(pool), ready };
1468
1608
  };
1469
- var componentAsMarkdown = (component) => {
1470
- const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
1471
- const schema = component.propsSchema;
1472
- const properties = schema?.properties;
1473
- if (properties === void 0 || Object.keys(properties).length === 0) return head;
1474
- const required = new Set(schema?.required ?? []);
1475
- const rows = Object.entries(properties).map(
1476
- ([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
1477
- );
1478
- return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
1609
+ var mintWrites = async (intake, event, as, at, chain) => {
1610
+ for (const write of event.writes) {
1611
+ for (const row of write.rows) {
1612
+ await intake.ingest(
1613
+ { kind: "write", entity: write.table, op: write.op, row, at },
1614
+ { as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
1615
+ );
1616
+ }
1617
+ }
1479
1618
  };
1480
- var contractAsMarkdown = (contract, fingerprints) => [
1481
- `# What you can build against`,
1482
- ``,
1483
- `## Your namespace`,
1484
- ``,
1485
- ` ${contract.namespace}`,
1486
- ``,
1487
- `Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
1488
- ``,
1489
- `## Components your layouts may use`,
1490
- ``,
1491
- contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
1492
- ``,
1493
- `## Fingerprints you may call`,
1494
- ``,
1495
- `Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
1496
- `\`/integrations/<your id>/\`. Nothing else.`,
1497
- ``,
1498
- fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
1499
- ``,
1500
- `## Where your screens may appear`,
1501
- ``,
1502
- `Declare \`attachments\` (action \u2192 host action) to ride a host screen, and`,
1503
- `\`placements\` (action \u2192 hub) to list under a menu hub. \`settings\` names the one`,
1504
- `action the store tile opens. Anything else is refused.`,
1505
- ``,
1506
- `Attachable, with what each hands you as input:`,
1507
- ``,
1508
- Object.entries(contract.attachable).map(([action, offers]) => `- ${action} \u2014 offers ${offers.join(", ") || "(nothing)"}`).join("\n") || "(none)",
1509
- ``,
1510
- `Menu hubs accepting placements:`,
1511
- ``,
1512
- contract.menuSlots.map((hub) => `- ${hub}`).join("\n") || "(none)",
1513
- ``,
1514
- `## What you cannot ship`,
1515
- ``,
1516
- `- vex entries or mutations. Call what is listed above; if you need a read that`,
1517
- ` does not exist, it is a change to the app.`,
1518
- `- \`fn:\` endpoints. Those run in the app's process.`,
1519
- `- components. Layouts compose what is listed above.`,
1520
- `- tables. Bring your own storage; we hand you identifiers.`,
1521
- ``
1522
- ].join("\n");
1523
1619
  var resolveRoles = (app, principal) => principal === null ? ["public"] : app.assignments?.[principal] ?? ["public"];
1524
1620
  var wearableOf = (app) => {
1525
1621
  const declared = app.wearable;
@@ -1687,7 +1783,9 @@ var createShellHost = (ctx) => {
1687
1783
  };
1688
1784
  const delta = ctx.delta ?? false;
1689
1785
  const DELTA_CEILING = 0.6;
1786
+ const DELTA_MAX_FRAME = 64 * 1024;
1690
1787
  const shorterAsDelta = (previous, next, canvasId) => {
1788
+ if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;
1691
1789
  try {
1692
1790
  const ops = encodeDelta(previous, next);
1693
1791
  const message = { type: "render-delta", canvas: canvasId, ops, hash: frameHash(next) };
@@ -1745,7 +1843,15 @@ var createShellHost = (ctx) => {
1745
1843
  // ephemeral and dies on detach.
1746
1844
  grant: (token2) => {
1747
1845
  const message = JSON.stringify({ type: "session", token: token2 });
1748
- for (const connection of liveRef?.connections ?? []) connection.send(message);
1846
+ for (const connection of liveRef?.connections ?? []) {
1847
+ if (connection.seal === void 0) connection.send(message);
1848
+ else {
1849
+ void connection.seal(token2).then(
1850
+ (sealed) => connection.send(JSON.stringify({ type: "session", sealed })),
1851
+ (error) => console.error("[moss] a sign-in could not be sealed, and was not handed over:", error)
1852
+ );
1853
+ }
1854
+ }
1749
1855
  },
1750
1856
  // REVOKE: forget the credential, close every terminal SIGNED_OUT,
1751
1857
  // evict the durable shell. Under moss's own credential the rows go
@@ -1980,8 +2086,8 @@ var createShellHost = (ctx) => {
1980
2086
  const settle = async (live, waitMs) => {
1981
2087
  const started = Date.now();
1982
2088
  let timer;
1983
- const deadline = new Promise((resolve) => {
1984
- timer = setTimeout(() => resolve(false), waitMs);
2089
+ const deadline = new Promise((resolve2) => {
2090
+ timer = setTimeout(() => resolve2(false), waitMs);
1985
2091
  });
1986
2092
  const whole = live.seeded.then(() => shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));
1987
2093
  const settled = await Promise.race([whole, deadline]);
@@ -2415,12 +2521,7 @@ var createServer = async (app, runtime) => {
2415
2521
  const session = sessionVerifierOf(runtime);
2416
2522
  const emit = emitterOf(runtime.telemetry);
2417
2523
  const vexOnExecute = emit === void 0 ? void 0 : (rec) => emit(vexRecordToSpan(rec));
2418
- const cacheSequence = (runtime.cache ?? createPostgresCache({ pool: runtime.pool })).sequence;
2419
- await migrate(
2420
- runtime.pool,
2421
- [MOSS_SEQUENCE, ...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [], ...cacheSequence === void 0 ? [] : [cacheSequence]],
2422
- { mode: runtime.migrations ?? "apply" }
2423
- );
2524
+ await migrate(runtime.pool, tableSequencesOf(runtime), { mode: runtime.migrations ?? "apply" });
2424
2525
  const grammars = await createGrammarUpgrader(app);
2425
2526
  await upgradeStore(runtime.pool, INTEGRATION_ACTIONS_STORE, grammars);
2426
2527
  const data = await createDataLayer(runtime, app.entries ?? []);
@@ -2434,6 +2535,7 @@ var createServer = async (app, runtime) => {
2434
2535
  throw new Error(`Charter is incoherent \u2014 refusing to serve:
2435
2536
  ${report.errors.map((e) => ` ${e.rule}: ${e.detail}`).join("\n")}`);
2436
2537
  }
2538
+ let verifiedReport = report;
2437
2539
  for (const cycle of chainCycles(app.actions)) {
2438
2540
  console.error(`[moss] a chain of steps that never ends: ${cycle.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`);
2439
2541
  }
@@ -3154,6 +3256,7 @@ ${nextReport.errors.map((e) => ` ${e.rule}: ${e.detail}`).join("\n")}`);
3154
3256
  throw new Error(`Refresh refused \u2014 layout variants incoherent:
3155
3257
  ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3156
3258
  }
3259
+ verifiedReport = nextReport;
3157
3260
  identities?.invalidateAll();
3158
3261
  policies.clear();
3159
3262
  reachPolicies.clear();
@@ -3182,7 +3285,9 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3182
3285
  ...shells !== void 0 ? { shells } : {},
3183
3286
  page: pageAt,
3184
3287
  ...runtime.sessionRevalidateMs !== void 0 ? { revalidateMs: runtime.sessionRevalidateMs } : {},
3185
- ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {}
3288
+ ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
3289
+ ...runtime.origins !== void 0 ? { origins: runtime.origins } : {},
3290
+ ...runtime.session === "sessions" ? { sessionLastsMs: (token) => sessionRemainingMs(runtime.pool, token) } : {}
3186
3291
  });
3187
3292
  return Object.assign(server, {
3188
3293
  socket,
@@ -3191,6 +3296,7 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3191
3296
  pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
3192
3297
  ...shells !== void 0 ? { shells } : {},
3193
3298
  refresh,
3299
+ charterReport: () => verifiedReport,
3194
3300
  generation: () => generation?.current() ?? -1,
3195
3301
  // Every timer this server owns, stopped once. Absent pieces (an app with no
3196
3302
  // identity seam, no shells) simply have nothing to stop — the `?.` is the
@@ -3226,23 +3332,7 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3226
3332
  });
3227
3333
  };
3228
3334
  var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
3229
- var DEFAULT_TOKEN_KEY = "nisc.token";
3230
3335
  var DEFAULT_ROOT = '<div id="root"></div>';
3231
- var tokenFromCookie = (header, tokenKey = DEFAULT_TOKEN_KEY) => {
3232
- if (header === void 0 || header === null) return null;
3233
- const wanted = encodeURIComponent(tokenKey);
3234
- for (const part of header.split(";")) {
3235
- const at = part.indexOf("=");
3236
- if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
3237
- try {
3238
- const value = decodeURIComponent(part.slice(at + 1).trim());
3239
- return value === "" ? null : value;
3240
- } catch {
3241
- return null;
3242
- }
3243
- }
3244
- return null;
3245
- };
3246
3336
  var embedSnapshot = (snapshot, principal, path) => {
3247
3337
  const { frame, trees, seed, live } = snapshot;
3248
3338
  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");
@@ -3257,7 +3347,8 @@ var renderDocument = async (config) => {
3257
3347
  const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
3258
3348
  if (!template.includes(root)) return undrawn;
3259
3349
  try {
3260
- const token = tokenFromCookie(request.cookie, tokenKey);
3350
+ const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
3351
+ const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
3261
3352
  const principal = token === null ? null : await server.principalOf(token);
3262
3353
  const route = server.page(request.path);
3263
3354
  const host = route?.host ?? server.shells;
@@ -3275,10 +3366,7 @@ var renderDocument = async (config) => {
3275
3366
  return {
3276
3367
  html,
3277
3368
  ...head !== void 0 ? { head } : {},
3278
- headers: {
3279
- ...documentHeaders(principal),
3280
- ...token !== null && principal === null ? { "set-cookie": `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax` } : {}
3281
- },
3369
+ headers: documentHeaders(principal),
3282
3370
  drawn: true,
3283
3371
  principal,
3284
3372
  ...route !== void 0 ? { page: route.name } : {},
@@ -3313,6 +3401,6 @@ var exportDocuments = async (config) => {
3313
3401
  return out;
3314
3402
  };
3315
3403
 
3316
- export { DEFAULT_GENERATION_POLL_MS, DEFAULT_IDENTITY_IDLE_MS, DEFAULT_IDENTITY_MAX, DEFAULT_IDLE_MS, GENERATION_DDL, MOSS_SEQUENCE, SESSIONS_SEQUENCE, SNAPSHOT_ELEMENT_ID, TIDE_DDL, TIDE_SEQUENCE, TIDE_TABLES, auditClosure, buildContract, callIntegrationWith, contractAsMarkdown, copyPress, createAssertionSigner, createDataLayer, createGeneration, createIdentityCache, createPageRouter, createServer, createShellHost, createTideStore, describePlacements, devSession, documentHeaders, embedSnapshot, exportDocuments, filterInstalled, hashIntegrationKey, initIntegrations, initSessions, integrationByKey, integrationOfAction, listAttachments, listIntegrations, listPlacements, loadIntegrationActions, memoKeyOf, mintDevToken, mintIntegrationKey, mintSession, mintWrites, renderDocument, resolveCatalog, resolveCatalogForRoles, resolvePolicy, resolvePolicyAtReach, resolvePolicyForRoles, resolveRoles, resolveVariants, resolveVariantsForRoles, revokeAllFor, revokeSession, runIntake, sessionOf, sessionVerifierOf, shellNeedOf, tokenFromCookie, verifyAssertion, verifyVariants, wearableOf, wireFabric };
3317
- //# sourceMappingURL=chunk-3CJCJKKY.js.map
3318
- //# sourceMappingURL=chunk-3CJCJKKY.js.map
3404
+ export { DEFAULT_GENERATION_POLL_MS, DEFAULT_IDENTITY_IDLE_MS, DEFAULT_IDENTITY_MAX, DEFAULT_IDLE_MS, GENERATION_DDL, MOSS_SEQUENCE, SESSIONS_SEQUENCE, SNAPSHOT_ELEMENT_ID, TIDE_DDL, TIDE_SEQUENCE, TIDE_TABLES, auditClosure, buildContract, callIntegrationWith, contractAsMarkdown, copyPress, createAssertionSigner, createDataLayer, createGeneration, createIdentityCache, createPageRouter, createServer, createShellHost, createTideStore, describePlacements, devSession, documentHeaders, embedSnapshot, exportDocuments, filterInstalled, hashIntegrationKey, initIntegrations, initSessions, integrationByKey, integrationOfAction, listAttachments, listIntegrations, listPlacements, loadIntegrationActions, memoKeyOf, migrateTables, mintDevToken, mintIntegrationKey, mintSession, mintWrites, renderDocument, resolveCatalog, resolveCatalogForRoles, resolvePolicy, resolvePolicyAtReach, resolvePolicyForRoles, resolveRoles, resolveVariants, resolveVariantsForRoles, revokeAllFor, revokeSession, runIntake, sessionOf, sessionVerifierOf, shellNeedOf, verifyAssertion, verifyVariants, wearableOf, wireFabric };
3405
+ //# sourceMappingURL=chunk-AUZMT3GL.js.map
3406
+ //# sourceMappingURL=chunk-AUZMT3GL.js.map