@niscorp/moss 0.6.0 → 0.8.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/DESIGN.md +77 -40
  3. package/DOCS.md +673 -78
  4. package/README.md +2 -2
  5. package/dist/chunk-3DCTQKPQ.cjs +943 -0
  6. package/dist/chunk-3DCTQKPQ.cjs.map +1 -0
  7. package/dist/{chunk-WKBH3UMB.js → chunk-3T422CCN.js} +9 -3
  8. package/dist/chunk-3T422CCN.js.map +1 -0
  9. package/dist/chunk-6XC2MD7S.js +906 -0
  10. package/dist/chunk-6XC2MD7S.js.map +1 -0
  11. package/dist/{chunk-D3YZIAYV.cjs → chunk-I4UOWER3.cjs} +11 -5
  12. package/dist/chunk-I4UOWER3.cjs.map +1 -0
  13. package/dist/{chunk-VBWNHF4H.cjs → chunk-PVZMCEBX.cjs} +4 -3
  14. package/dist/chunk-PVZMCEBX.cjs.map +1 -0
  15. package/dist/{chunk-NSK7QSSG.js → chunk-QAHDSRPK.js} +4 -3
  16. package/dist/chunk-QAHDSRPK.js.map +1 -0
  17. package/dist/{chunk-R66WUKGC.cjs → chunk-TMDKNZYL.cjs} +2169 -1319
  18. package/dist/chunk-TMDKNZYL.cjs.map +1 -0
  19. package/dist/{chunk-V5YMJL7Z.js → chunk-YZILOVCR.js} +2147 -1295
  20. package/dist/chunk-YZILOVCR.js.map +1 -0
  21. package/dist/document-BYAY-Qle.d.ts +381 -0
  22. package/dist/document-DAE71J27.d.cts +381 -0
  23. package/dist/{index-B411sK9M.d.cts → index-CSEo7Tys.d.cts} +5 -0
  24. package/dist/{index-B411sK9M.d.ts → index-CSEo7Tys.d.ts} +5 -0
  25. package/dist/index.cjs +17 -17
  26. package/dist/index.d.cts +8 -10
  27. package/dist/index.d.ts +8 -10
  28. package/dist/index.js +3 -3
  29. package/dist/integrations.cjs +3 -3
  30. package/dist/integrations.d.cts +1 -1
  31. package/dist/integrations.d.ts +1 -1
  32. package/dist/integrations.js +1 -1
  33. package/dist/node.cjs +8 -8
  34. package/dist/node.d.cts +3 -4
  35. package/dist/node.d.ts +3 -4
  36. package/dist/node.js +4 -4
  37. package/dist/tide.d.cts +1 -1
  38. package/dist/tide.d.ts +1 -1
  39. package/dist/unverified.cjs +3 -3
  40. package/dist/unverified.js +2 -2
  41. package/dist/vite.cjs +9 -9
  42. package/dist/vite.d.cts +6 -1
  43. package/dist/vite.d.ts +6 -1
  44. package/dist/vite.js +4 -4
  45. package/package.json +13 -13
  46. package/dist/app-CUnDcXQu.d.ts +0 -143
  47. package/dist/app-CdANzi2q.d.cts +0 -143
  48. package/dist/chunk-D3YZIAYV.cjs.map +0 -1
  49. package/dist/chunk-NSK7QSSG.js.map +0 -1
  50. package/dist/chunk-PWUO4RET.js +0 -374
  51. package/dist/chunk-PWUO4RET.js.map +0 -1
  52. package/dist/chunk-R2YPQHQH.cjs +0 -383
  53. package/dist/chunk-R2YPQHQH.cjs.map +0 -1
  54. package/dist/chunk-R66WUKGC.cjs.map +0 -1
  55. package/dist/chunk-V5YMJL7Z.js.map +0 -1
  56. package/dist/chunk-VBWNHF4H.cjs.map +0 -1
  57. package/dist/chunk-WKBH3UMB.js.map +0 -1
  58. package/dist/document-D7nroBww.d.cts +0 -169
  59. package/dist/document-DeTPGBil.d.ts +0 -169
@@ -1,25 +1,24 @@
1
- import { sessionOn, endShell, canvasesOf, treeOf, buildShell, attach, layoutsOf } from './chunk-PWUO4RET.js';
2
- import { emitterOf, FabricMessageSchema, spanClock } from './chunk-NSK7QSSG.js';
1
+ import { entriesOf, receiveManifest, verifiedAtBoot, verifyManifest, withFragments, candidateOf, FRAME_LAYOUT_REF, canvasLayoutRef, functionsIn, charterOverFunctions, refusalOf, functionsWarning, layoutMisfits, freezeDeep, entryMisfits, sessionOn, endlessChains, actionLayoutRef, endShell, GENERATED_ID_PREFIX, layoutNameRefusal, actionOfLayoutRef, withLayoutInPlace, canvasesOf, treeOf, buildShell, SHELL_GONE, draftedIn, attach, holdGranted, layoutsOf, withVariants, variantLayouts } from './chunk-6XC2MD7S.js';
2
+ import { emitterOf, FabricMessageSchema, spanClock } from './chunk-QAHDSRPK.js';
3
3
  import { DEFAULT_TOKEN_KEY, sessionNameOf, SNAPSHOT_ELEMENT_ID, CLOSE_SHELL_FAILED, CLOSE_PROTOCOL_MISMATCH, CLOSE_INVALID_TOKEN, CLOSE_AT_CAPACITY, PROTOCOL_MIN, PROTOCOL, offeredSealed, offeredToken, ClientMessageSchema } from './chunk-4ZGAFZGS.js';
4
4
  import { z } from 'zod';
5
- import { randomBytes, createHash, timingSafeEqual } from 'crypto';
6
- import { verifyCharter, resolvePrincipal, resolveScoping } from '@niscorp/charter';
7
- import { LayoutNodeSchema, ActionFragmentSchema, ActionDefinitionSchema, collectChannels, auditAction, DefinitionValidationError, shellSettled, CANVAS_SLOT_NAME, ACTION_SLOT_NAME } from '@niscorp/nova';
8
- import { chainCycles, snapshotShell, walkNodes, isRecord, livenessOf, componentsOf } from '@niscorp/nova/reflect';
9
- import { SequenceSchema, exceedsDepth, depthRefusal, createUpgrader } from '@niscorp/strata';
10
- import { REFRESH_MODES, QuerySchema, MutationDefinitionSchema, createPostgresCache, createPostgresAdapter, scopeProfiles, resolve, pruneOptional, mutationMisfits, handleDiscovery, seedCache, handleQuery, mergeScopePolicies, createScopePolicy, createQueryEngine, scopeGrants, createMemoryCache, tablesChangedBy } from '@niscorp/vex';
11
- import { isBinding } from '@niscorp/nova/i18n';
12
- import { ConfigSchema, evaluate } from '@niscorp/prism';
5
+ import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'crypto';
6
+ import { createPostgresCache, createPostgresAdapter, resolve, pruneOptional, mutationMisfits, createMemoryCache, seedCache, handleDiscovery, handleQuery, mergeScopePolicies, createScopePolicy, createQueryEngine, scopeGrants, tablesChangedBy } from '@niscorp/vex';
13
7
  import { migrate, upgradeStore } from '@niscorp/strata/postgres';
8
+ import { exceedsDepth, StrataError, depthRefusal, createUpgrader } from '@niscorp/strata';
14
9
  import { NOVA_SEQUENCE } from '@niscorp/nova/migrations';
10
+ import { evaluate } from '@niscorp/prism';
15
11
  import { PRISM_SEQUENCE } from '@niscorp/prism/migrations';
12
+ import { VEX_SCHEMAS, VEX_SEQUENCE } from '@niscorp/vex/migrations';
13
+ import { resolvePrincipal, resolveScoping } from '@niscorp/charter';
16
14
  import { Hono } from 'hono';
17
15
  import { VEX_LIVE_ENV, vex } from '@niscorp/vex/hono';
18
16
  import { AsyncLocalStorage } from 'async_hooks';
19
17
  import { headOf, placeHead } from '@niscorp/nova/document';
18
+ import { LayoutNodeSchema, CANVAS_SLOT_NAME, DefinitionValidationError, auditAction, shellSettled, ActionDefinitionSchema, ActionFragmentSchema, ACTION_SLOT_NAME } from '@niscorp/nova';
19
+ import { isBinding } from '@niscorp/nova/i18n';
20
+ import { isRecord, walkNodes, snapshotShell, livenessOf, componentsOf } from '@niscorp/nova/reflect';
20
21
 
21
- // src/manifest/app.ts
22
- var defineApp = (app) => app;
23
22
  var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
24
23
  if (header === void 0 || header === null) return null;
25
24
  const wanted = encodeURIComponent(name);
@@ -35,10 +34,10 @@ var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
35
34
  }
36
35
  return null;
37
36
  };
38
- var ownOriginOf = (origin, host, listed = []) => {
37
+ var ownOriginOf = (origin, host, listed2 = []) => {
39
38
  if (origin === void 0 || origin === null || !URL.canParse(origin)) return void 0;
40
39
  const asked = new URL(origin);
41
- const own = asked.host === host?.toLowerCase() || listed.some((entry2) => URL.canParse(entry2) && new URL(entry2).origin === asked.origin);
40
+ const own = asked.host === host?.toLowerCase() || listed2.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
42
41
  return own ? asked : void 0;
43
42
  };
44
43
  var cookiesAt = (where, key, token, lastsMs) => {
@@ -167,8 +166,8 @@ var createHeldRecords = (max) => {
167
166
  const held = /* @__PURE__ */ new Map();
168
167
  const tagged = /* @__PURE__ */ new Map();
169
168
  let evicted = 0;
170
- const untag = (principal, record2) => {
171
- const tag = record2.tag;
169
+ const untag = (principal, record) => {
170
+ const tag = record.tag;
172
171
  if (tag === void 0) return;
173
172
  const group = tagged.get(tag);
174
173
  if (group === void 0) return;
@@ -176,9 +175,9 @@ var createHeldRecords = (max) => {
176
175
  if (group.size === 0) tagged.delete(tag);
177
176
  };
178
177
  const forget = (principal) => {
179
- const entry2 = held.get(principal);
180
- if (entry2 === void 0) return false;
181
- untag(principal, entry2.record);
178
+ const entry = held.get(principal);
179
+ if (entry === void 0) return false;
180
+ untag(principal, entry.record);
182
181
  held.delete(principal);
183
182
  return true;
184
183
  };
@@ -188,22 +187,22 @@ var createHeldRecords = (max) => {
188
187
  forget(oldest.value);
189
188
  evicted += 1;
190
189
  };
191
- const remember = (principal, record2, at) => {
190
+ const remember = (principal, record, at) => {
192
191
  forget(principal);
193
192
  while (held.size >= max) evictOldest();
194
- held.set(principal, { record: record2, since: at, lastSeen: at });
195
- if (record2.tag !== void 0) {
196
- const group = tagged.get(record2.tag) ?? /* @__PURE__ */ new Set();
193
+ held.set(principal, { record, since: at, lastSeen: at });
194
+ if (record.tag !== void 0) {
195
+ const group = tagged.get(record.tag) ?? /* @__PURE__ */ new Set();
197
196
  group.add(principal);
198
- tagged.set(record2.tag, group);
197
+ tagged.set(record.tag, group);
199
198
  }
200
199
  };
201
200
  return {
202
201
  of: (principal) => held.get(principal),
203
- touch: (principal, entry2, at) => {
202
+ touch: (principal, entry, at) => {
204
203
  held.delete(principal);
205
- entry2.lastSeen = at;
206
- held.set(principal, entry2);
204
+ entry.lastSeen = at;
205
+ held.set(principal, entry);
207
206
  },
208
207
  forget,
209
208
  remember,
@@ -217,14 +216,14 @@ var createHeldRecords = (max) => {
217
216
  return principals;
218
217
  },
219
218
  forgetIdle: (at, idleMs) => {
220
- for (const [principal, entry2] of [...held]) {
221
- if (at - entry2.lastSeen >= idleMs) {
219
+ for (const [principal, entry] of [...held]) {
220
+ if (at - entry.lastSeen >= idleMs) {
222
221
  forget(principal);
223
222
  evicted += 1;
224
223
  }
225
224
  }
226
225
  },
227
- list: () => [...held].map(([principal, entry2]) => ({ principal, since: entry2.since, lastSeen: entry2.lastSeen })),
226
+ list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
228
227
  size: () => held.size,
229
228
  evicted: () => evicted
230
229
  };
@@ -256,11 +255,11 @@ var createIdentityCache = (ctx) => {
256
255
  if (inFlight !== void 0) return inFlight.work;
257
256
  const forgotten = /* @__PURE__ */ new Set();
258
257
  const isStillOut = () => pending.get(principal)?.work === work;
259
- const work = ctx.resolve(principal).then((record2) => {
258
+ const work = ctx.resolve(principal).then((record) => {
260
259
  resolved += 1;
261
- const wearsForgottenTag = record2.tag !== void 0 && forgotten.has(record2.tag);
262
- if (isStillOut() && !wearsForgottenTag) held.remember(principal, record2, now());
263
- return record2;
260
+ const wearsForgottenTag = record.tag !== void 0 && forgotten.has(record.tag);
261
+ if (isStillOut() && !wearsForgottenTag) held.remember(principal, record, now());
262
+ return record;
264
263
  }).finally(() => {
265
264
  if (isStillOut()) pending.delete(principal);
266
265
  });
@@ -293,6 +292,7 @@ var createIdentityCache = (ctx) => {
293
292
  };
294
293
  };
295
294
  var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
295
+ var NOBODY_USER_ID = "anonymous";
296
296
  var assignedRoles = (assignments, principal) => principal === null ? ["public"] : assignments?.[principal] ?? ["public"];
297
297
  var IdentityRecordSchema = z.looseObject({
298
298
  roles: z.array(z.string()),
@@ -303,25 +303,25 @@ var IdentityRecordSchema = z.looseObject({
303
303
  var recordRefusal = (issues) => new Error(
304
304
  `moss: \`identity.resolve\` did not answer an identity record (${issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")}). A record is { roles: string[], scope: {\u2026}, installed?: string[], tag?: string }.`
305
305
  );
306
- var resolveThrough = (seam2, readAs) => async (principal) => {
307
- const role = seam2.as;
306
+ var resolveThrough = (seam, readAs) => async (principal) => {
307
+ const role = seam.as;
308
308
  const read2 = async (fingerprint, scope) => {
309
309
  if (role === void 0) throw new Error("moss: identity.read needs identity.as \u2014 name the charter role the reader executes as");
310
310
  return readAs(role, fingerprint, scope);
311
311
  };
312
- const answered = IdentityRecordSchema.safeParse(await seam2.resolve(principal, read2));
312
+ const answered = IdentityRecordSchema.safeParse(await seam.resolve(principal, read2));
313
313
  if (!answered.success) throw recordRefusal(answered.error.issues);
314
314
  return answered.data;
315
315
  };
316
316
  var createIdentity = (config) => {
317
- const seam2 = config.seam;
318
- const cache = seam2 === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam2, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
317
+ const seam = config.seam;
318
+ const cache = seam === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
319
319
  const keys = /* @__PURE__ */ new WeakMap();
320
- const keyOf2 = (record2) => {
321
- const hit = keys.get(record2);
320
+ const keyOf2 = (record) => {
321
+ const hit = keys.get(record);
322
322
  if (hit !== void 0) return hit;
323
- const key = memoKey(record2.roles, record2.installed);
324
- keys.set(record2, key);
323
+ const key = memoKey(record.roles, record.installed);
324
+ keys.set(record, key);
325
325
  return key;
326
326
  };
327
327
  const fromAssignments = (principal) => {
@@ -330,13 +330,13 @@ var createIdentity = (config) => {
330
330
  };
331
331
  const resolve2 = async (principal) => {
332
332
  if (cache !== void 0 && principal !== null) {
333
- const record2 = await cache.get(principal);
334
- return { roles: record2.roles, scope: record2.scope, installed: record2.installed, memoKey: keyOf2(record2), record: record2 };
333
+ const record = await cache.get(principal);
334
+ return { roles: record.roles, scope: record.scope, installed: record.installed, memoKey: keyOf2(record), record };
335
335
  }
336
336
  return fromAssignments(principal);
337
337
  };
338
338
  const composeScope = (principal, resolved) => ({
339
- userId: principal ?? "anonymous",
339
+ userId: principal ?? NOBODY_USER_ID,
340
340
  ...resolved.scope,
341
341
  ...config.scope?.(principal, resolved.record) ?? {}
342
342
  });
@@ -351,1323 +351,2060 @@ var createIdentity = (config) => {
351
351
  stop: () => cache?.stop()
352
352
  };
353
353
  };
354
- var entriesOf = (app) => app.entries ?? [];
355
- var shellComponents = (manifest, shell2) => {
356
- const names = /* @__PURE__ */ new Set([CANVAS_SLOT_NAME, ACTION_SLOT_NAME]);
357
- for (const source of [manifest.actions, manifest.layouts ?? {}, shell2.canvases, shell2.layout ?? {}, shell2.layoutStore ?? {}, shell2.fragments ?? {}]) {
358
- for (const name of componentsOf(source)) names.add(name);
354
+
355
+ // src/data/tables.ts
356
+ var GENERATION_DDL = [
357
+ /* sql */
358
+ `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
359
+ /* sql */
360
+ `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
361
+ ];
362
+ var MOSS_SEQUENCE = {
363
+ id: "nisc.moss",
364
+ migrations: [
365
+ {
366
+ description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
367
+ steps: [
368
+ { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
369
+ id text PRIMARY KEY,
370
+ url text NOT NULL,
371
+ -- THE HASH, NEVER THE KEY. The integration key is minted at registration
372
+ -- (see assert.ts for the credential rule), returned once in that response,
373
+ -- and this is all that remains of it here. Presenting the key is the only
374
+ -- way to produce this value again, so a stolen database does not hold a
375
+ -- credential \u2014 and a lost key is re-registered, not recovered.
376
+ key_hash text,
377
+ status text NOT NULL DEFAULT 'pending',
378
+ -- The store card's words, straight from the bundle's meta. Columns
379
+ -- rather than jsonb so an app's vex read can select them like anything
380
+ -- else on this table.
381
+ title text NOT NULL DEFAULT '',
382
+ tagline text NOT NULL DEFAULT '',
383
+ description text NOT NULL DEFAULT '',
384
+ -- The listing page's long form, re-imported whole like everything else
385
+ -- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
386
+ -- intake (copyPress), never the paths the bundle declared \u2014 the listing
387
+ -- composes from host ground alone.
388
+ story jsonb NOT NULL DEFAULT '[]'::jsonb,
389
+ highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
390
+ press jsonb NOT NULL DEFAULT '[]'::jsonb,
391
+ -- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
392
+ -- printed by the approval card and the store tile from this one place.
393
+ adds text NOT NULL DEFAULT '',
394
+ -- The one integration action the store may open: its settings screen.
395
+ settings_action text NOT NULL DEFAULT '',
396
+ requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
397
+ requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
398
+ approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
399
+ -- What it tells and hears (bundle offers/needs), beside the grants
400
+ -- because they are the same kind of thing: the integration's declared
401
+ -- statement, written at import, replaced on re-registration. moss
402
+ -- never reads them; the host's bus does.
403
+ offers jsonb NOT NULL DEFAULT '[]'::jsonb,
404
+ needs jsonb NOT NULL DEFAULT '[]'::jsonb,
405
+ -- The verbs the integration gates on ({id, title}), for the host's role
406
+ -- editor to grant. Beside offers/needs because it is the same kind of
407
+ -- thing: a declaration written at import, replaced on re-registration,
408
+ -- that moss never reads \u2014 the host does.
409
+ capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
410
+ -- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
411
+ -- beside capabilities because it is the same kind of thing: a declaration
412
+ -- written at import, replaced on re-registration, that moss never reads.
413
+ -- The host renders a settings form from it and stores the values itself.
414
+ configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
415
+ -- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
416
+ -- and a section model the host's editor renders. Beside configuration
417
+ -- because it is the same kind of thing: a declaration written at import,
418
+ -- replaced on re-registration, that moss never reads \u2014 the host does.
419
+ documents jsonb NOT NULL DEFAULT '[]'::jsonb,
420
+ -- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
421
+ -- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
422
+ -- the host's assistant is the consumer.
423
+ assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
424
+ -- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
425
+ -- (reachOf). Beside the grants because it is one: a grant of reach, held
426
+ -- by the same row, revoked by the same delete.
427
+ reach jsonb NOT NULL DEFAULT '[]'::jsonb,
428
+ -- Pages this integration serves and the host frames. Kept apart from reach
429
+ -- because they are spent differently: reach is a screen's call carrying a
430
+ -- session, a frame is a document GET carrying a grant.
431
+ frames jsonb NOT NULL DEFAULT '[]'::jsonb,
432
+ last_import_at timestamptz,
433
+ last_error text
434
+ )
435
+ ` },
436
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
437
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
438
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
439
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
440
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
441
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
442
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
443
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
444
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
445
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
446
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
447
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
448
+ { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
449
+ integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
450
+ action_id text NOT NULL,
451
+ definition jsonb NOT NULL,
452
+ -- The bindings, beside the artifact and never inside it: which host
453
+ -- action this one rides (a panel), or which menu hub lists it. Empty
454
+ -- means neither \u2014 reachable only through whatever else names it.
455
+ -- preview is the rider's display endpoint (own-prefix, validated at
456
+ -- intake): the host calls it with the offered ids to paint the strip.
457
+ attach_to text NOT NULL DEFAULT '',
458
+ preview text NOT NULL DEFAULT '',
459
+ place_in text NOT NULL DEFAULT '',
460
+ PRIMARY KEY (integration_id, action_id)
461
+ )
462
+ ` },
463
+ ...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
464
+ ]
465
+ },
466
+ {
467
+ description: "Stored integration actions carry the grammar stamp their definition is written in",
468
+ steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
469
+ },
470
+ {
471
+ description: "No two integrations hold the hash of one key",
472
+ steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
473
+ },
474
+ {
475
+ description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
476
+ steps: [
477
+ { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
478
+ {
479
+ kind: "sql",
480
+ sql: `ALTER TABLE integrations
481
+ DROP COLUMN IF EXISTS title,
482
+ DROP COLUMN IF EXISTS tagline,
483
+ DROP COLUMN IF EXISTS description,
484
+ DROP COLUMN IF EXISTS story,
485
+ DROP COLUMN IF EXISTS highlights,
486
+ DROP COLUMN IF EXISTS press,
487
+ DROP COLUMN IF EXISTS adds,
488
+ DROP COLUMN IF EXISTS settings_action,
489
+ DROP COLUMN IF EXISTS offers,
490
+ DROP COLUMN IF EXISTS needs,
491
+ DROP COLUMN IF EXISTS capabilities,
492
+ DROP COLUMN IF EXISTS configuration,
493
+ DROP COLUMN IF EXISTS documents,
494
+ DROP COLUMN IF EXISTS assistants,
495
+ DROP COLUMN IF EXISTS frames`
496
+ },
497
+ {
498
+ kind: "sql",
499
+ sql: `ALTER TABLE integration_actions
500
+ DROP COLUMN IF EXISTS attach_to,
501
+ DROP COLUMN IF EXISTS preview,
502
+ DROP COLUMN IF EXISTS place_in`
503
+ }
504
+ ]
505
+ },
506
+ {
507
+ description: "The artifactory\u2019s two tables: a row for each save, and a row for each version of an artifact a save holds",
508
+ steps: [
509
+ {
510
+ kind: "sql",
511
+ sql: `CREATE TABLE artifact_saves (
512
+ id uuid PRIMARY KEY,
513
+ created_by text NOT NULL,
514
+ -- Whose the save is: the userId of whoever made it, written by vex.
515
+ principal text NOT NULL,
516
+ created_at timestamptz NOT NULL DEFAULT now()
517
+ )`
518
+ },
519
+ {
520
+ kind: "sql",
521
+ sql: `CREATE TABLE artifacts (
522
+ save uuid NOT NULL REFERENCES artifact_saves(id),
523
+ kind text NOT NULL,
524
+ id text NOT NULL,
525
+ -- Whose the version is, as its save's.
526
+ principal text NOT NULL,
527
+ -- null, as SQL or as JSON: this version says none is in force.
528
+ body jsonb,
529
+ grammar jsonb NOT NULL DEFAULT '{}'::jsonb,
530
+ -- The save whose version of this artifact this one is a copy of.
531
+ copied_from uuid,
532
+ created_at timestamptz NOT NULL DEFAULT now(),
533
+ PRIMARY KEY (save, kind, id)
534
+ )`
535
+ },
536
+ // What is in force for an artifact is its latest row, and that is asked at every shell.
537
+ { kind: "sql", sql: `CREATE INDEX artifacts_latest ON artifacts (principal, kind, id, created_at)` }
538
+ ]
539
+ },
540
+ {
541
+ description: "When a version of an artifact was last loaded into a shell, for the sweep over what is unused",
542
+ steps: [{ kind: "sql", sql: `ALTER TABLE artifacts ADD COLUMN last_used_at timestamptz` }]
543
+ }
544
+ ]
545
+ };
546
+ var ARTIFACT_TABLES = ["artifacts", "artifact_saves"];
547
+ var tableSequencesOf = (owners) => {
548
+ const cacheSequence = (owners.cache ?? createPostgresCache({ pool: owners.pool })).sequence;
549
+ return [
550
+ MOSS_SEQUENCE,
551
+ ...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
552
+ ...cacheSequence === void 0 ? [] : [cacheSequence],
553
+ ...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
554
+ ...owners.tables ?? []
555
+ ];
556
+ };
557
+ var misfitOf = (entry, schema) => {
558
+ if (!("mutation" in entry)) {
559
+ try {
560
+ resolve(pruneOptional(entry.dsl, "all"), schema);
561
+ return void 0;
562
+ } catch (error) {
563
+ return error instanceof Error ? error.message : String(error);
564
+ }
359
565
  }
360
- const contracts = shell2.components ?? {};
361
- for (const name of Object.keys(contracts)) names.add(name);
362
- return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
566
+ return mutationMisfits(entry.mutation, schema)[0];
363
567
  };
364
- var wearableOf = (app) => {
365
- const declared = app.wearable;
366
- const source = declared ?? Object.values(app.assignments ?? {});
367
- const seen = /* @__PURE__ */ new Map();
368
- for (const roles of source) {
369
- const key = [...roles].sort().join("\0");
370
- if (!seen.has(key)) seen.set(key, roles);
568
+ var misfitsOf = (entries, schema) => {
569
+ const misfits = /* @__PURE__ */ new Map();
570
+ for (const entry of entries) {
571
+ const why = misfitOf(entry, schema);
572
+ if (why !== void 0) misfits.set(entry.fingerprint, why);
371
573
  }
372
- return [...seen.values()];
574
+ return misfits;
373
575
  };
374
- var narrowedBy = (filter, ids, installed) => {
375
- const answered = new Set(filter(ids, installed));
376
- return ids.filter((id) => answered.has(id));
576
+ var canonical = (value) => {
577
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
578
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
579
+ const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
580
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
377
581
  };
378
- var catalogFor = (app, roles, installed, installedOnly) => {
379
- const granted = [...resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
380
- const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
381
- return { ids, hash: versionToken(ids) };
582
+ var isSeededAs = async (cache, entry) => {
583
+ const held = await cache.get(entry.fingerprint);
584
+ if (held === void 0 || held.protected !== true) return false;
585
+ if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
586
+ return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
382
587
  };
383
- var variantLayouts = (variants, held) => {
384
- const layouts = /* @__PURE__ */ new Map();
385
- for (const id of held) {
386
- const variant = variants[id];
387
- if (variant !== void 0) layouts.set(variant.action, variant.layout);
588
+ var changesBetween = (before, after) => {
589
+ const removed = [];
590
+ const retyped = [];
591
+ for (const was of before.entities) {
592
+ const now = after.entities.find((entity) => entity.table === was.table);
593
+ if (now === void 0) {
594
+ removed.push(was.table);
595
+ continue;
596
+ }
597
+ for (const field of was.fields) {
598
+ const kept = now.fields.find((f) => f.name === field.name);
599
+ if (kept === void 0) removed.push(`${was.table}.${field.name}`);
600
+ else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
601
+ }
388
602
  }
389
- return layouts;
390
- };
391
- var resolveVariantsForRoles = (app, roles) => {
392
- const variants = app.layouts ?? {};
393
- return variantLayouts(variants, resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
603
+ return { removed, retyped };
394
604
  };
395
- var withVariants = (actions, ids, layouts) => ids.flatMap((id) => {
396
- const definition = actions[id];
397
- if (definition === void 0) return [];
398
- const layout2 = layouts.get(id);
399
- return [[id, layout2 === void 0 ? definition : { ...definition, layout: layout2 }]];
400
- });
401
- var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
402
- var createRoleMemo = (config) => {
403
- const catalogs = /* @__PURE__ */ new Map();
404
- const variants = /* @__PURE__ */ new Map();
405
- const definitions = /* @__PURE__ */ new Map();
406
- const kept = (memo, key, resolve2) => {
407
- const hit = memo.get(key);
408
- if (hit !== void 0) return hit;
409
- const resolved = resolve2();
410
- memo.set(key, resolved);
411
- return resolved;
412
- };
413
- const roleMemo = {
414
- catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
415
- variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
416
- definitionsFor: (roles, installed) => kept(definitions, memoKey(roles, installed), () => definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles))),
417
- drop: () => {
418
- catalogs.clear();
419
- variants.clear();
420
- definitions.clear();
421
- }
605
+ var oneAtATime = (query) => {
606
+ let last = Promise.resolve();
607
+ return (text, values) => {
608
+ const next = last.then(() => query(text, values));
609
+ last = next.catch(() => void 0);
610
+ return next;
422
611
  };
423
- return roleMemo;
424
612
  };
425
- var versionToken = (ids) => {
426
- const s = ids.join("\n");
427
- let h = 2166136261;
428
- for (let i = 0; i < s.length; i += 1) {
429
- h ^= s.charCodeAt(i);
430
- h = Math.imul(h, 16777619) >>> 0;
431
- }
432
- return h.toString(16).padStart(8, "0");
433
- };
434
-
435
- // src/manifest/verify.ts
436
- var candidateOf = (shipped, inForce, grants) => ({
437
- charter: shipped.charter,
438
- actions: inForce.actions,
439
- layouts: shipped.layouts ?? {},
440
- wearable: wearableOf(shipped),
441
- grants,
442
- entries: inForce.entries,
443
- profiles: scopeProfiles(shipped.behaviors ?? {})
444
- });
445
- var unreadActions = (actions) => Object.entries(actions).flatMap(([id, definition]) => {
446
- if (exceedsDepth(definition)) return [{ id, why: depthRefusal() }];
447
- const parsed = ActionDefinitionSchema.safeParse(definition);
448
- if (parsed.success) return [];
449
- const first = parsed.error.issues[0];
450
- return [{ id, why: first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}` }];
451
- });
452
- var reachErrors = (entries, profiles) => {
453
- const unknown = entries.flatMap((entry2) => entry2.reach !== void 0 && !profiles.has(entry2.reach) ? [`${entry2.fingerprint} declares reach "${entry2.reach}"`] : []);
454
- return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(", ") || "(none)"}`];
455
- };
456
- var endlessChains = (actions) => chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));
457
- var verifyManifest = (candidate) => {
458
- const unread = unreadActions(candidate.actions);
459
- const refused = new Set(unread.map((action) => action.id));
460
- const read2 = refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };
461
- const charter = verifyCharter(
462
- read2.charter,
463
- { actions: Object.keys(read2.actions), data: read2.grants, layouts: Object.keys(read2.layouts) },
464
- read2.wearable,
465
- auditClosure(read2.actions, read2.layouts)
466
- );
467
- const found = (check, details) => details.map((detail) => ({ check, detail }));
468
- return {
469
- errors: [
470
- ...found("actions", unread.map((action) => `"${action.id}" is not an action nova reads: ${action.why}`)),
471
- ...found("charter", charter.errors.map((error) => `${error.rule}: ${error.detail}`)),
472
- ...found("reach", reachErrors(read2.entries, read2.profiles)),
473
- ...found("variants", verifyVariants(read2))
474
- ],
475
- said: endlessChains(read2.actions).map((chain) => `a chain of steps that never ends: ${chain.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),
476
- charter
477
- };
478
- };
479
- var verifyApp = (app, grants) => verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));
480
- var HEADLINES = {
481
- boot: {
482
- actions: "Actions are not ones nova reads \u2014 refusing to serve:",
483
- charter: "Charter is incoherent \u2014 refusing to serve:",
484
- reach: "Entries declare a reach no table offers \u2014 refusing to serve:",
485
- variants: "Layout variants are incoherent \u2014 refusing to serve:"
486
- },
487
- refresh: {
488
- actions: "Refresh refused \u2014 actions nova does not read:",
489
- charter: "Refresh refused \u2014 charter incoherent over the new artifacts:",
490
- reach: "Refresh refused \u2014 entries declare a reach no table offers:",
491
- variants: "Refresh refused \u2014 layout variants incoherent:"
492
- }
493
- };
494
- var refusalOf = (report, moment) => {
495
- const first = report.errors[0];
496
- if (first === void 0) return void 0;
497
- const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);
498
- return [HEADLINES[moment][first.check], ...findings].join("\n");
499
- };
500
- var verifyVariants = (app) => {
501
- const variants = app.layouts ?? {};
502
- const ids = Object.keys(variants);
503
- if (ids.length === 0) return [];
504
- const errors = [];
505
- for (const [id, variant] of Object.entries(variants)) {
506
- if (app.actions[variant.action] === void 0) {
507
- errors.push(`layout variant "${id}" reshapes unknown action "${variant.action}"`);
508
- }
509
- }
510
- const wearers = /* @__PURE__ */ new Map();
511
- for (const role of Object.keys(app.charter)) wearers.set(`role "${role}"`, [role]);
512
- for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(", ")}]`, roles);
513
- wearers.set("the anonymous principal", ["public"]);
514
- for (const [who, roles] of wearers) {
515
- let granted;
516
- try {
517
- granted = resolvePrincipal(app.charter, ids, roles, "layouts");
518
- } catch {
519
- continue;
520
- }
521
- const byAction = /* @__PURE__ */ new Map();
522
- for (const id of granted) {
523
- const variant = variants[id];
524
- if (variant !== void 0) byAction.set(variant.action, [...byAction.get(variant.action) ?? [], id]);
525
- }
526
- for (const [action, held] of byAction) {
527
- if (held.length > 1) {
528
- errors.push(`${who} holds ${held.length} variants of "${action}" (${held.sort().join(", ")}) \u2014 one variant per action per principal`);
529
- }
530
- }
613
+ var migrateTables = async (runtime, app, options = {}) => {
614
+ const entries = entriesOf(app);
615
+ const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });
616
+ const before = await createPostgresAdapter({ pool: runtime.pool }).introspect();
617
+ const misfitsBefore = misfitsOf(entries, before);
618
+ const excused = /* @__PURE__ */ new Set();
619
+ for (const entry of entries) {
620
+ if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
531
621
  }
532
- return errors;
533
- };
534
- var auditClosure = (definitions, variants = {}) => {
535
- return (grantedIds, layoutIds = []) => {
536
- const granted = withVariants(definitions, grantedIds, variantLayouts(variants, layoutIds)).map(([, definition]) => definition);
537
- const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));
538
- const channels = [
539
- ...new Set(
540
- granted.flatMap((definition) => {
541
- const found = collectChannels(definition);
542
- return [...found.emits, ...found.listens];
543
- })
544
- )
545
- ];
546
- const issues = [];
547
- for (const definition of granted) {
548
- const audit = auditAction(definition, { catalog, channels });
549
- if (audit.ok) continue;
550
- for (const issue of audit.issues) {
551
- if (issue.includes("which is not in the catalog") && !issue.includes("{{")) issues.push(`${definition.id}: ${issue}`);
622
+ let found = { removed: [], retyped: [], alreadyBroken: [] };
623
+ const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
624
+ const report = await migrate(runtime.pool, tableSequencesOf(owners), {
625
+ ...options.dryRun === true ? { dryRun: true } : {},
626
+ guard: async (tx) => {
627
+ const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
628
+ const refused = [];
629
+ const alreadyBroken = [];
630
+ for (const [fingerprint, why] of misfitsOf(entries, after)) {
631
+ if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
632
+ else refused.push(`${fingerprint}: ${why}`);
552
633
  }
634
+ found = { ...changesBetween(before, after), alreadyBroken };
635
+ return refused;
553
636
  }
554
- return issues;
555
- };
637
+ });
638
+ return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
556
639
  };
557
- var isDeferred = (value) => typeof value === "string" && isBinding(value) || isRecord(value) && Object.keys(value).some((key) => key.startsWith("$"));
558
- var layoutMisfits = (layout2, components) => {
559
- const found = /* @__PURE__ */ new Set();
560
- walkNodes(layout2, (record2) => {
561
- const name = record2["component"];
562
- if (typeof name !== "string") return;
563
- const spec = components.get(name);
564
- if (spec === void 0) {
565
- found.add(`layout uses "${name}", which this app has no component for`);
566
- return;
567
- }
568
- const schema = spec.propsSchema;
569
- const props = record2["props"];
570
- if (!(schema instanceof z.ZodObject) || !isRecord(props)) return;
571
- const shape = schema.shape;
572
- for (const [key, value] of Object.entries(props)) {
573
- const prop = shape[key];
574
- if (prop === void 0) {
575
- found.add(`"${name}" has no prop "${key}"`);
576
- continue;
577
- }
578
- if (isDeferred(value)) continue;
579
- const check = z.safeParse(prop, value);
580
- if (!check.success) found.add(`"${name}" prop "${key}" \u2014 ${check.error.issues[0]?.message ?? "invalid"}`);
640
+ var featureTablesOf = (app) => {
641
+ const features = /* @__PURE__ */ new Set();
642
+ return (app.features ?? []).map((feature) => {
643
+ if (features.has(feature.name)) {
644
+ throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
581
645
  }
646
+ features.add(feature.name);
647
+ const names = feature.tables?.names ?? [];
648
+ return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
582
649
  });
583
- return [...found];
584
650
  };
585
651
 
586
- // src/manifest/generation.ts
587
- var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
588
- var MAX_INTERVAL_MS = 2 ** 31 - 1;
589
- var MOVE_ATTEMPTS = 5;
590
- var createGeneration = (pointer, ctx) => {
591
- const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
592
- let seen = -1;
593
- let checking = false;
594
- const poll = async () => {
595
- if (checking) return;
596
- checking = true;
597
- try {
598
- const n = await readPointer();
599
- if (n === void 0 || n === seen) return;
600
- if (seen !== -1 && !await follow(n)) return;
601
- seen = n;
602
- } finally {
603
- checking = false;
604
- }
605
- };
606
- const readPointer = async () => {
607
- try {
608
- return await pointer.read();
609
- } catch (err) {
610
- console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
611
- return void 0;
612
- }
613
- };
614
- let unfollowed;
615
- const follow = async (n) => {
652
+ // src/data/aging.ts
653
+ var UNUSED_VERSIONS = (
654
+ /* sql */
655
+ `DELETE FROM artifacts a
656
+ WHERE a.principal <> '*'
657
+ AND (SELECT max(coalesce(b.last_used_at, b.created_at)) FROM artifacts b WHERE b.principal = a.principal AND b.kind = a.kind AND b.id = a.id) < now() - ($1::bigint * interval '1 millisecond')
658
+ RETURNING a.save`
659
+ );
660
+ var EMPTY_SAVES = (
661
+ /* sql */
662
+ `DELETE FROM artifact_saves s WHERE NOT EXISTS (SELECT 1 FROM artifacts a WHERE a.save = s.id) RETURNING s.id`
663
+ );
664
+ var sweepUnused = async (pool, unusedMs) => {
665
+ const versions = (await pool.query(UNUSED_VERSIONS, [unusedMs])).rows.length;
666
+ const saves = (await pool.query(EMPTY_SAVES)).rows.length;
667
+ return { versions, saves };
668
+ };
669
+ var AGING_EVERY_MS = 36e5;
670
+ var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
671
+ const sweep2 = async () => {
616
672
  try {
617
- await ctx.onMoved();
618
- } catch (err) {
619
- const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
620
- if (unfollowed?.said !== what) {
621
- console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
622
- }
623
- unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
624
- return false;
625
- }
626
- if (unfollowed !== void 0) {
627
- console.log(
628
- `[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
629
- );
630
- unfollowed = void 0;
631
- }
632
- return true;
673
+ const swept = await sweepUnused(pool, unusedMs);
674
+ if (swept.versions > 0) console.log(`[moss] aging: ${swept.versions} version(s) of what was generated and unused for ${unusedMs} ms deleted, and ${swept.saves} save(s) left empty`);
675
+ } catch (error) {
676
+ console.error("[moss] aging: the sweep failed, and is tried again at the next:", error);
677
+ }
678
+ };
679
+ void sweep2();
680
+ const timer = setInterval(() => void sweep2(), everyMs);
681
+ return () => clearInterval(timer);
682
+ };
683
+ var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
684
+ var createEntryCache = (table) => {
685
+ let held;
686
+ const fromTable = (entry) => entry !== void 0 && isWrittenForRequest(entry) ? entry : void 0;
687
+ const tableEntries = async () => {
688
+ const rows = table.entries !== void 0 ? await table.entries() : await Promise.all((await table.keys()).map(async (key) => ({ key, entry: await table.get(key) })));
689
+ return rows.flatMap(({ key, entry }) => {
690
+ const kept = fromTable(entry);
691
+ return kept === void 0 ? [] : [{ key, entry: kept }];
692
+ });
633
693
  };
634
- const move = async () => {
635
- for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
636
- const n = await pointer.read();
637
- if (await pointer.move(n)) {
638
- if (seen === n || seen === -1) seen = n + 1;
639
- return;
640
- }
641
- }
642
- throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
694
+ const entries = async () => {
695
+ const first = await held?.entries() ?? [];
696
+ const answered = new Set(first.map((row) => row.key));
697
+ return [...first, ...(await tableEntries()).filter((row) => !answered.has(row.key))];
643
698
  };
644
- void poll();
645
- const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
646
- timer?.unref?.();
647
699
  return {
648
- bump: () => {
649
- void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
700
+ askFirst: (holder) => {
701
+ held = holder;
650
702
  },
651
- current: () => seen,
652
- stop: () => {
653
- if (timer !== void 0) clearInterval(timer);
703
+ cache: {
704
+ get: async (key, scope) => await held?.get(key, scope) ?? fromTable(await table.get(key)),
705
+ // Vex stamps an entry it replays by writing it back: one that was not written for a request is not the table's to keep.
706
+ set: async (key, entry) => {
707
+ if (isWrittenForRequest(entry)) await table.set(key, entry);
708
+ },
709
+ delete: (key) => table.delete(key),
710
+ clear: () => table.clear(),
711
+ keys: async () => (await entries()).map((row) => row.key),
712
+ entries
654
713
  }
655
714
  };
656
715
  };
657
- var seam = z.custom((value) => typeof value === "function", "expected a function");
658
- var depthChecked = (schema) => z.unknown().refine((value) => !exceedsDepth(value), { message: depthRefusal(), abort: true }).pipe(schema);
659
- var strings = z.array(z.string()).readonly();
660
- var record = z.record(z.string(), z.unknown());
661
- var layout = depthChecked(LayoutNodeSchema);
662
- var LayoutVariantSchema = z.object({ action: z.string(), layout }).strict();
663
- var CanvasSeedSchema = z.union([z.string(), z.object({ action: z.string(), input: record.optional(), with: strings.optional() }).strict()]);
664
- var CanvasSchema = z.object({
665
- id: z.string(),
666
- mode: z.enum(["stack", "list"]).optional(),
667
- actionLayout: z.union([z.string(), layout]).optional(),
668
- initial: z.union([CanvasSeedSchema, z.array(CanvasSeedSchema)]).optional()
669
- }).strict();
670
- var ComponentContractSchema = z.looseObject({ meta: z.looseObject({ description: z.string().optional() }).optional() });
671
- var shell = {
672
- canvases: z.array(CanvasSchema),
673
- layout: layout.optional(),
674
- layoutStore: z.record(z.string(), layout).optional(),
675
- fragments: z.record(z.string(), depthChecked(ActionFragmentSchema)).optional(),
676
- seeds: seam.optional(),
677
- components: z.record(z.string(), ComponentContractSchema).optional(),
678
- inputs: seam.optional()
679
- };
680
- var ShellManifestSchema = z.object(shell).strict();
681
- var PageManifestSchema = z.object({ ...shell, path: z.string(), params: z.string().optional() }).strict();
682
- var entry = { fingerprint: z.string(), intent: z.string().optional(), reach: z.string().optional() };
683
- var ReadEntrySchema = z.object({
684
- ...entry,
685
- shape: z.unknown().optional(),
686
- dsl: depthChecked(QuerySchema),
687
- mapping: depthChecked(ConfigSchema).optional(),
688
- refresh: z.enum(REFRESH_MODES).optional()
689
- }).strict();
690
- var WriteEntrySchema = z.object({ ...entry, mutation: depthChecked(MutationDefinitionSchema) }).strict();
691
- var FeatureSchema = z.looseObject({
692
- name: z.string(),
693
- tables: z.object({ names: strings, sequences: z.array(SequenceSchema).readonly().optional() }).strict().optional(),
694
- start: seam
716
+ var createDataLayer = async (deps) => {
717
+ const adapter = createPostgresAdapter({ pool: deps.pool });
718
+ const table = deps.cache ?? createPostgresCache({ pool: deps.pool });
719
+ await table.init?.();
720
+ const { cache, askFirst } = createEntryCache(table);
721
+ const engine = createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
722
+ const schema = await engine.introspect();
723
+ return { engine, adapter, schema, grants: scopeGrants(schema.entities.map((e) => e.name)), askFirst };
724
+ };
725
+ var grammarsOf = (app) => [
726
+ NOVA_SEQUENCE,
727
+ PRISM_SEQUENCE,
728
+ VEX_SEQUENCE,
729
+ ...app.grammars ?? []
730
+ ];
731
+ var createGrammarUpgrader = (app) => createUpgrader(grammarsOf(app), { transform: evaluate });
732
+ var vexRecordToSpan = (rec) => ({
733
+ name: "vex.execute",
734
+ startUnixNano: rec.startUnixNano,
735
+ endUnixNano: rec.endUnixNano,
736
+ status: rec.status,
737
+ attributes: {
738
+ op: rec.kind,
739
+ hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
740
+ ...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
741
+ ...rec.reach !== void 0 ? { reach: rec.reach } : {},
742
+ ...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
743
+ ...rec.rows !== void 0 ? { rows: rec.rows } : {}
744
+ }
695
745
  });
696
- var ReactionSchema = z.object({ table: z.string(), op: z.enum(["insert", "update", "delete"]).optional(), run: seam }).strict();
697
- var fields = {
698
- charter: record,
699
- assignments: z.record(z.string(), strings).optional(),
700
- wearable: z.array(strings).readonly().optional(),
701
- actions: z.record(z.string(), depthChecked(ActionDefinitionSchema)),
702
- layouts: z.record(z.string(), LayoutVariantSchema).optional(),
703
- behaviors: z.record(z.string(), record).optional(),
704
- scope: seam.optional(),
705
- identity: z.object({ as: z.string().optional(), resolve: seam }).strict().optional(),
706
- phrases: seam.optional(),
707
- phraseKeys: z.object({ props: strings.optional(), suffixes: strings.optional(), text: z.boolean().optional() }).strict().optional(),
708
- features: z.array(FeatureSchema).readonly().optional(),
709
- entries: z.array(z.union([ReadEntrySchema, WriteEntrySchema])).readonly().optional(),
710
- resources: z.record(z.string(), z.union([strings, z.looseObject({ entities: strings })])).optional(),
711
- shell: ShellManifestSchema.optional(),
712
- pages: z.record(z.string(), PageManifestSchema).optional(),
713
- grammars: z.array(SequenceSchema).readonly().optional(),
714
- functions: seam.optional(),
715
- onSession: seam.optional(),
716
- runs: seam.optional(),
717
- reactions: z.array(ReactionSchema).readonly().optional()
718
- };
719
- var ManifestSchema = z.object(fields).strict();
720
- var placesOf = (issue, under) => {
721
- const path = [...under, ...issue.path];
722
- if (issue.code !== "invalid_union") return [{ path, message: issue.message }];
723
- const branches = issue.errors.map((branch) => branch.flatMap((inner) => placesOf(inner, path))).filter((branch) => branch.length > 0);
724
- const reach = (places) => Math.max(...places.map((place) => place.path.length));
725
- const closer = (best, branch) => reach(branch) > reach(best) || reach(branch) === reach(best) && branch.length < best.length ? branch : best;
726
- const [first, ...others] = branches;
727
- return first === void 0 ? [{ path, message: issue.message }] : others.reduce(closer, first);
728
- };
729
- var manifestMisfits = (app) => {
730
- const parsed = ManifestSchema.safeParse(app);
731
- if (parsed.success) return [];
732
- return parsed.error.issues.flatMap((issue) => placesOf(issue, [])).map((place) => `${place.path.map(String).join(".") || "(the manifest)"}: ${place.message}`);
733
- };
734
- var isData = (value) => {
735
- if (Array.isArray(value)) return true;
736
- const made = Object.getPrototypeOf(value);
737
- return made === Object.prototype || made === null;
738
- };
739
- var freezeDeep = (data) => {
740
- const seen = /* @__PURE__ */ new Set();
741
- const pending = [data];
742
- while (pending.length > 0) {
743
- const value = pending.pop();
744
- if (typeof value !== "object" || value === null || !isData(value) || seen.has(value)) continue;
745
- seen.add(value);
746
- Object.freeze(value);
747
- for (const inner of Object.values(value)) pending.push(inner);
748
- }
749
- };
750
- var receiveManifest = (app) => {
751
- const misfits = manifestMisfits(app);
752
- if (misfits.length > 0) throw new Error(["The manifest does not parse \u2014 refusing to serve:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
753
- freezeDeep(app);
746
+ var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
747
+ var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
748
+ var createOwnEntries = (deps) => async (own) => {
749
+ const cache = createMemoryCache();
750
+ await seedCache(cache, own.entries);
751
+ const schema = await deps.adapter.introspect({ entities: [...own.tables] });
752
+ const engine = createQueryEngine({
753
+ adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
754
+ cache
755
+ });
756
+ await engine.introspect();
757
+ const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, own.rules?.[table] ?? { public: true }])) };
758
+ const reachable = new Set((await handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed2) => listed2.fingerprint));
759
+ const outside = own.entries.map((entry) => entry.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
760
+ if (outside.length > 0) {
761
+ throw new Error(
762
+ `moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
763
+ );
764
+ }
765
+ return async (fingerprint, context, scope = {}) => {
766
+ const outcome = await handleQuery(
767
+ {
768
+ engine,
769
+ locked: true,
770
+ scopePolicy: policy,
771
+ mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(tablesChangedBy(event.writes, schema)) },
772
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
773
+ },
774
+ { fingerprint, context },
775
+ scope
776
+ );
777
+ if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
778
+ return resultOf(outcome.body);
779
+ };
754
780
  };
755
-
756
- // src/manifest/running.ts
757
- var mergedActions = (own, sets) => Object.freeze([...sets.values()].reduce((all, set) => ({ ...all, ...set }), { ...own }));
758
- var tell = (listener) => {
759
- try {
760
- listener();
761
- } catch (error) {
762
- console.error("[moss:manifest] a listener to a manifest change threw:", error);
781
+ var TABLE = "moss_generation";
782
+ var THE_ROW = { eq: [`${TABLE}.id`, 1] };
783
+ var readPointerEntry = {
784
+ fingerprint: "moss/generation",
785
+ intent: "Where the generation pointer is",
786
+ dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
787
+ };
788
+ var movePointerEntry = {
789
+ fingerprint: "moss/generation-move",
790
+ intent: "Move the generation pointer to the next number, if it is still where it was read",
791
+ mutation: {
792
+ op: "update",
793
+ table: TABLE,
794
+ set: { n: { $context: "next" } },
795
+ where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
763
796
  }
764
797
  };
765
- var createSetOwners = () => {
766
- const owners = /* @__PURE__ */ new Map();
767
- const ownerRefusalOf = (source) => {
768
- const owner = owners.get(source);
769
- return owner === void 0 ? void 0 : `the set of actions "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
770
- };
798
+ var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
799
+ var RowSchema = z.object({ n: z.coerce.number() });
800
+ var RowsSchema = z.array(z.unknown());
801
+ var createPointer = (replay) => ({
802
+ read: async () => {
803
+ const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
804
+ return RowSchema.parse(rows[0] ?? { n: 0 }).n;
805
+ },
806
+ // A write that changed one row answers that row; one that changed none
807
+ // answers no row, which does not parse: the counter moved since it was read.
808
+ move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
809
+ });
810
+ var resolvePolicyForRoles = (app, grants, roles) => {
811
+ const behaviors = app.behaviors ?? {};
812
+ return mergeScopePolicies(
813
+ roles.map(
814
+ (role) => createScopePolicy(resolvePrincipal(app.charter, grants, [role], "data"), behaviors, resolveScoping(app.charter, role))
815
+ )
816
+ );
817
+ };
818
+ var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => createScopePolicy(resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
819
+ var createPolicies = (config) => {
820
+ const { grants } = config;
821
+ const governed = { charter: config.charter, behaviors: config.behaviors };
822
+ const policies = /* @__PURE__ */ new Map();
823
+ const reachPolicies = /* @__PURE__ */ new Map();
771
824
  return {
772
- ownerRefusalOf,
773
- claim: (source, owner, handedOver) => {
774
- const held = owners.get(source);
775
- if (held !== void 0) throw new Error(`moss: the set of actions "${source}" is ${held}'s, and ${owner} claims it too. A set of actions has one writer.`);
776
- if (handedOver) throw new Error(`moss: the set of actions "${source}" was handed over by the app, and ${owner} claims it. A set of actions has one writer.`);
777
- owners.set(source, owner);
825
+ of: (who) => {
826
+ const hit = policies.get(who.memoKey);
827
+ if (hit !== void 0) return hit;
828
+ const compiled = resolvePolicyForRoles(governed, grants, who.roles);
829
+ policies.set(who.memoKey, compiled);
830
+ return compiled;
778
831
  },
779
- assertAppOwned: (source) => {
780
- const refusal = ownerRefusalOf(source);
781
- if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
782
- return source;
832
+ atReach: (who, reach) => {
833
+ const key = `${who.memoKey}\0${reach}`;
834
+ const hit = reachPolicies.get(key);
835
+ if (hit !== void 0) return hit;
836
+ const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
837
+ reachPolicies.set(key, compiled);
838
+ return compiled;
839
+ },
840
+ drop: () => {
841
+ policies.clear();
842
+ reachPolicies.clear();
783
843
  }
784
844
  };
785
845
  };
786
- var verifiedAtBoot = (candidate) => {
787
- const report = verifyManifest(candidate);
788
- for (const line of report.said) console.error(`[moss] ${line}`);
789
- const refused = refusalOf(report, "boot");
790
- if (refused !== void 0) throw new Error(refused);
791
- return report;
792
- };
793
- var createComponentNames = (read2) => {
794
- let components = /* @__PURE__ */ new WeakMap();
795
- return {
796
- of: (shell2) => {
797
- const kept = components.get(shell2);
798
- if (kept !== void 0) return kept;
799
- const names = read2(shell2);
800
- components.set(shell2, names);
801
- return names;
846
+ var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
847
+ const roles = [role];
848
+ const policy = deps.policyFor(roles);
849
+ const outcome = await handleQuery(
850
+ {
851
+ engine: deps.engine,
852
+ locked: true,
853
+ scopePolicy: policy,
854
+ policyForReach: (reach) => deps.policyAtReach(roles, reach),
855
+ mutations: { client: deps.db, policy },
856
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
802
857
  },
803
- drop: () => {
804
- components = /* @__PURE__ */ new WeakMap();
805
- }
806
- };
858
+ { fingerprint, context },
859
+ scope
860
+ );
861
+ if (outcome.status !== 200) {
862
+ console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
863
+ return void 0;
864
+ }
865
+ const body = outcome.body;
866
+ return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
807
867
  };
808
- var createRunningManifest = (config) => {
809
- const { shipped } = config;
810
- const entries = entriesOf(shipped);
811
- const candidate = (actions) => candidateOf(shipped, { actions, entries }, config.grants);
812
- const own = shipped.actions;
813
- const loaders = /* @__PURE__ */ new Map();
814
- const owners = createSetOwners();
815
- let sets = /* @__PURE__ */ new Map();
816
- let inForce = mergedActions(own, sets);
817
- let report = verifiedAtBoot(candidate(inForce));
818
- const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
819
- const roleMemo = createRoleMemo({
820
- manifest: () => ({ charter: shipped.charter, actions: inForce, layouts: shipped.layouts }),
821
- installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
822
- });
823
- const components = createComponentNames((shell2) => shellComponents({ actions: inForce, layouts: shipped.layouts }, shell2));
824
- const byFingerprint = new Map(entries.map((entry2) => [entry2.fingerprint, entry2]));
868
+ var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
869
+ var writeRequestOf = (header) => ({
870
+ header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
871
+ });
872
+ var SAID_NOTHING = { header: () => void 0 };
873
+ var createWriteNotifier = () => {
874
+ const requests = new AsyncLocalStorage();
825
875
  const listeners = /* @__PURE__ */ new Set();
826
- let pointer;
827
- const applySets = (arrived, announce) => {
828
- const next = new Map([...sets, ...arrived]);
829
- const actions = mergedActions(own, next);
830
- const verified = verifyManifest(candidate(actions));
831
- const refusal = refusalOf(verified, "refresh");
832
- if (refusal !== void 0) throw new Error(refusal);
833
- for (const set of arrived.values()) freezeDeep(set);
834
- sets = next;
835
- inForce = actions;
836
- report = verified;
837
- roleMemo.drop();
838
- components.drop();
839
- for (const listener of [...listeners]) tell(listener);
840
- if (announce) pointer?.bump();
841
- };
842
- const reload = async () => {
843
- const read2 = [];
844
- for (const [source, load] of loaders) read2.push([source, await load()]);
845
- applySets(new Map(read2), false);
846
- };
847
876
  return {
848
- actions: () => inForce,
849
- entries: () => entries,
850
- verify: (actions) => verifyManifest(candidate(actions)),
851
- report: () => report,
852
- replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
853
- claim: (source, owner) => {
854
- owners.claim(source, owner, sets.has(source));
855
- return {
856
- replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
857
- setLoader: (load) => {
858
- loaders.set(source, load);
859
- if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
860
- }
861
- };
862
- },
863
- refresh: () => applySets(/* @__PURE__ */ new Map(), true),
864
- watch: () => {
865
- const where = config.pointer;
866
- if (pointer !== void 0 || where === void 0) return;
867
- pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
868
- },
869
- onChange: (listener) => {
877
+ subscribe: (listener) => {
870
878
  listeners.add(listener);
871
879
  return () => {
872
880
  listeners.delete(listener);
873
881
  };
874
882
  },
875
- addCatalogFilter: (filter) => {
876
- catalogFilters.push(filter);
877
- roleMemo.drop();
878
- },
879
- catalogFor: roleMemo.catalogFor,
880
- artifactsFor: (shell2, roles, installed) => ({
881
- actions: roleMemo.definitionsFor(roles, installed),
882
- canvases: shell2.canvases,
883
- ...shell2.layout !== void 0 ? { frame: shell2.layout } : {},
884
- ...shell2.layoutStore !== void 0 ? { layoutStore: shell2.layoutStore } : {},
885
- ...shell2.fragments !== void 0 ? { fragments: shell2.fragments } : {},
886
- entries: byFingerprint,
887
- components: components.of(shell2)
888
- }),
889
- generation: () => pointer?.current() ?? -1,
890
- stop: () => pointer?.stop()
883
+ within: (request, run) => requests.run(request, run),
884
+ report: (event) => {
885
+ const request = requests.getStore() ?? SAID_NOTHING;
886
+ for (const listener of [...listeners]) {
887
+ try {
888
+ listener(event, request);
889
+ } catch (error) {
890
+ console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
891
+ }
892
+ }
893
+ }
894
+ };
895
+ };
896
+ var createWireFollower = (callSignal) => {
897
+ const controller = new AbortController();
898
+ const end = () => {
899
+ controller.abort();
900
+ };
901
+ if (callSignal.aborted) end();
902
+ else callSignal.addEventListener("abort", end, { once: true });
903
+ const handlers = /* @__PURE__ */ new Set();
904
+ let missed;
905
+ const live = {
906
+ signal: controller.signal,
907
+ onChange: (response) => {
908
+ if (handlers.size === 0) {
909
+ missed = { body: response.result };
910
+ return;
911
+ }
912
+ for (const handler of [...handlers]) handler(response.result);
913
+ }
914
+ };
915
+ const onChange = (handler) => {
916
+ if (controller.signal.aborted) return () => {
917
+ };
918
+ handlers.add(handler);
919
+ if (missed !== void 0) {
920
+ const { body } = missed;
921
+ missed = void 0;
922
+ handler(body);
923
+ }
924
+ return () => {
925
+ handlers.delete(handler);
926
+ if (handlers.size === 0) end();
927
+ };
928
+ };
929
+ const handedOver = () => {
930
+ setTimeout(() => {
931
+ if (handlers.size === 0) end();
932
+ }, 0);
891
933
  };
934
+ return { live, onChange, handedOver, end };
892
935
  };
893
936
 
894
- // src/data/tables.ts
895
- var GENERATION_DDL = [
896
- /* sql */
897
- `CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
898
- /* sql */
899
- `INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
900
- ];
901
- var MOSS_SEQUENCE = {
902
- id: "nisc.moss",
903
- migrations: [
904
- {
905
- description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
906
- steps: [
907
- { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
908
- id text PRIMARY KEY,
909
- url text NOT NULL,
910
- -- THE HASH, NEVER THE KEY. The integration key is minted at registration
911
- -- (see assert.ts for the credential rule), returned once in that response,
912
- -- and this is all that remains of it here. Presenting the key is the only
913
- -- way to produce this value again, so a stolen database does not hold a
914
- -- credential \u2014 and a lost key is re-registered, not recovered.
915
- key_hash text,
916
- status text NOT NULL DEFAULT 'pending',
917
- -- The store card's words, straight from the bundle's meta. Columns
918
- -- rather than jsonb so an app's vex read can select them like anything
919
- -- else on this table.
920
- title text NOT NULL DEFAULT '',
921
- tagline text NOT NULL DEFAULT '',
922
- description text NOT NULL DEFAULT '',
923
- -- The listing page's long form, re-imported whole like everything else
924
- -- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
925
- -- intake (copyPress), never the paths the bundle declared \u2014 the listing
926
- -- composes from host ground alone.
927
- story jsonb NOT NULL DEFAULT '[]'::jsonb,
928
- highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
929
- press jsonb NOT NULL DEFAULT '[]'::jsonb,
930
- -- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
931
- -- printed by the approval card and the store tile from this one place.
932
- adds text NOT NULL DEFAULT '',
933
- -- The one integration action the store may open: its settings screen.
934
- settings_action text NOT NULL DEFAULT '',
935
- requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
936
- requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
937
- approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
938
- -- What it tells and hears (bundle offers/needs), beside the grants
939
- -- because they are the same kind of thing: the integration's declared
940
- -- statement, written at import, replaced on re-registration. moss
941
- -- never reads them; the host's bus does.
942
- offers jsonb NOT NULL DEFAULT '[]'::jsonb,
943
- needs jsonb NOT NULL DEFAULT '[]'::jsonb,
944
- -- The verbs the integration gates on ({id, title}), for the host's role
945
- -- editor to grant. Beside offers/needs because it is the same kind of
946
- -- thing: a declaration written at import, replaced on re-registration,
947
- -- that moss never reads \u2014 the host does.
948
- capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
949
- -- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
950
- -- beside capabilities because it is the same kind of thing: a declaration
951
- -- written at import, replaced on re-registration, that moss never reads.
952
- -- The host renders a settings form from it and stores the values itself.
953
- configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
954
- -- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
955
- -- and a section model the host's editor renders. Beside configuration
956
- -- because it is the same kind of thing: a declaration written at import,
957
- -- replaced on re-registration, that moss never reads \u2014 the host does.
958
- documents jsonb NOT NULL DEFAULT '[]'::jsonb,
959
- -- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
960
- -- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
961
- -- the host's assistant is the consumer.
962
- assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
963
- -- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
964
- -- (reachOf). Beside the grants because it is one: a grant of reach, held
965
- -- by the same row, revoked by the same delete.
966
- reach jsonb NOT NULL DEFAULT '[]'::jsonb,
967
- -- Pages this integration serves and the host frames. Kept apart from reach
968
- -- because they are spent differently: reach is a screen's call carrying a
969
- -- session, a frame is a document GET carrying a grant.
970
- frames jsonb NOT NULL DEFAULT '[]'::jsonb,
971
- last_import_at timestamptz,
972
- last_error text
973
- )
974
- ` },
975
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
976
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
977
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
978
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
979
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
980
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
981
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
982
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
983
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
984
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
985
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
986
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
987
- { kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
988
- integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
989
- action_id text NOT NULL,
990
- definition jsonb NOT NULL,
991
- -- The bindings, beside the artifact and never inside it: which host
992
- -- action this one rides (a panel), or which menu hub lists it. Empty
993
- -- means neither \u2014 reachable only through whatever else names it.
994
- -- preview is the rider's display endpoint (own-prefix, validated at
995
- -- intake): the host calls it with the offered ids to paint the strip.
996
- attach_to text NOT NULL DEFAULT '',
997
- preview text NOT NULL DEFAULT '',
998
- place_in text NOT NULL DEFAULT '',
999
- PRIMARY KEY (integration_id, action_id)
1000
- )
1001
- ` },
1002
- ...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
1003
- ]
1004
- },
1005
- {
1006
- description: "Stored integration actions carry the grammar stamp their definition is written in",
1007
- steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
1008
- },
1009
- {
1010
- description: "No two integrations hold the hash of one key",
1011
- steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
1012
- },
1013
- {
1014
- description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
1015
- steps: [
1016
- { kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
1017
- {
1018
- kind: "sql",
1019
- sql: `ALTER TABLE integrations
1020
- DROP COLUMN IF EXISTS title,
1021
- DROP COLUMN IF EXISTS tagline,
1022
- DROP COLUMN IF EXISTS description,
1023
- DROP COLUMN IF EXISTS story,
1024
- DROP COLUMN IF EXISTS highlights,
1025
- DROP COLUMN IF EXISTS press,
1026
- DROP COLUMN IF EXISTS adds,
1027
- DROP COLUMN IF EXISTS settings_action,
1028
- DROP COLUMN IF EXISTS offers,
1029
- DROP COLUMN IF EXISTS needs,
1030
- DROP COLUMN IF EXISTS capabilities,
1031
- DROP COLUMN IF EXISTS configuration,
1032
- DROP COLUMN IF EXISTS documents,
1033
- DROP COLUMN IF EXISTS assistants,
1034
- DROP COLUMN IF EXISTS frames`
1035
- },
1036
- {
1037
- kind: "sql",
1038
- sql: `ALTER TABLE integration_actions
1039
- DROP COLUMN IF EXISTS attach_to,
1040
- DROP COLUMN IF EXISTS preview,
1041
- DROP COLUMN IF EXISTS place_in`
1042
- }
1043
- ]
937
+ // src/data/routes.ts
938
+ var createVexRoutes = (deps) => {
939
+ const routes = new Hono();
940
+ routes.use(
941
+ "/api/*",
942
+ (c, next) => deps.writes.within(
943
+ writeRequestOf((name) => c.req.header(name)),
944
+ () => next()
945
+ )
946
+ );
947
+ const mount = (path, entities) => {
948
+ routes.route(
949
+ path,
950
+ vex({
951
+ engine: deps.engine,
952
+ ...entities !== void 0 ? { entities: [...entities] } : {},
953
+ locked: true,
954
+ getScope: deps.scope,
955
+ getPolicy: deps.policy,
956
+ getPolicyForReach: deps.policyAtReach,
957
+ ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
958
+ mutations: { client: deps.db, onWrite: deps.writes.report }
959
+ })
960
+ );
961
+ };
962
+ mount("/api/vex");
963
+ for (const [name, resource] of Object.entries(deps.resources ?? {})) {
964
+ mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
965
+ }
966
+ return routes;
967
+ };
968
+ var createIntentAnswers = (deps) => {
969
+ const engines = /* @__PURE__ */ new WeakMap();
970
+ const engineFor = (writers) => {
971
+ const kept = engines.get(writers);
972
+ if (kept !== void 0) return kept;
973
+ const { adapter, schema } = deps;
974
+ const created = (async () => {
975
+ const engine = createQueryEngine({
976
+ adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
977
+ cache: deps.cache,
978
+ generateDsl: writers.generateDsl,
979
+ mapToShape: writers.mapToShape,
980
+ ...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
981
+ ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
982
+ });
983
+ await engine.introspect();
984
+ return engine;
985
+ })();
986
+ engines.set(writers, created);
987
+ return created;
988
+ };
989
+ return async (writers, asked, caller) => (await engineFor(writers)).execute(
990
+ "fingerprint" in asked ? { fingerprint: asked.fingerprint, context: asked.context ?? {} } : { intent: asked.intent, shape: asked.shape, context: asked.context ?? {} },
991
+ { scope: caller.scope, scopePolicy: caller.policy }
992
+ );
993
+ };
994
+
995
+ // src/data/data.ts
996
+ var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
997
+ var prepareEngine = async (config) => {
998
+ await migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
999
+ const grammars = await createGrammarUpgrader({ grammars: config.grammars });
1000
+ const layer = await createDataLayer(config);
1001
+ return {
1002
+ grammars,
1003
+ engine: layer.engine,
1004
+ grants: layer.grants,
1005
+ adapter: layer.adapter,
1006
+ askFirst: layer.askFirst,
1007
+ upgradeStore: async (store) => {
1008
+ await upgradeStore(config.pool, store, grammars);
1044
1009
  }
1045
- ]
1010
+ };
1046
1011
  };
1047
- var tableSequencesOf = (owners) => {
1048
- const cacheSequence = (owners.cache ?? createPostgresCache({ pool: owners.pool })).sequence;
1049
- return [
1050
- MOSS_SEQUENCE,
1051
- ...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
1052
- ...cacheSequence === void 0 ? [] : [cacheSequence],
1053
- ...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
1054
- ...owners.tables ?? []
1055
- ];
1012
+ var lazyIntentAnswers = (prepared, config) => {
1013
+ const { engine } = prepared;
1014
+ let answers;
1015
+ const answering = () => {
1016
+ if (answers !== void 0) return answers;
1017
+ const schema = engine.getSchema();
1018
+ if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
1019
+ answers = createIntentAnswers({
1020
+ adapter: prepared.adapter,
1021
+ schema,
1022
+ cache: engine.cache,
1023
+ ...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
1024
+ ...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
1025
+ });
1026
+ return answers;
1027
+ };
1028
+ return answering;
1056
1029
  };
1057
- var misfitOf = (entry2, schema) => {
1058
- if (!("mutation" in entry2)) {
1059
- try {
1060
- resolve(pruneOptional(entry2.dsl, "all"), schema);
1061
- return void 0;
1062
- } catch (error) {
1063
- return error instanceof Error ? error.message : String(error);
1030
+ var tablesByFeature = (config) => (feature) => {
1031
+ const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
1032
+ if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
1033
+ return kept.names;
1034
+ };
1035
+ var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
1036
+ const own = tablesOf(feature);
1037
+ if (store.schema !== void 0) {
1038
+ throw new Error(
1039
+ `moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
1040
+ );
1041
+ }
1042
+ if (!own.includes(store.table)) {
1043
+ throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
1044
+ }
1045
+ await prepared.upgradeStore(store);
1046
+ };
1047
+ var createDataWith = (prepared, config) => {
1048
+ const { grammars, engine, grants } = prepared;
1049
+ const governed = { charter: config.charter, behaviors: { ...config.behaviors, ...config.rowRules } };
1050
+ const policies = createPolicies({ ...governed, grants });
1051
+ const emit = emitterOf(config.telemetry);
1052
+ const onExecute = emit === void 0 ? void 0 : (record) => emit(vexRecordToSpan(record));
1053
+ const writes = createWriteNotifier();
1054
+ const answering = lazyIntentAnswers(prepared, config);
1055
+ const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
1056
+ const tablesOf = tablesByFeature(config);
1057
+ let pointerEntries;
1058
+ const pointerReplay = () => {
1059
+ pointerEntries ??= ownEntries(POINTER, void 0);
1060
+ return pointerEntries;
1061
+ };
1062
+ return {
1063
+ grants,
1064
+ grammars,
1065
+ entriesHeldBy: prepared.askFirst,
1066
+ fingerprints: async () => await engine.cache.keys?.() ?? [],
1067
+ policyOf: policies.of,
1068
+ // Compiled afresh and not taken from the kept ones: the caller owns its
1069
+ // copy, and nothing it does to it reaches a policy a request is served under.
1070
+ policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
1071
+ fingerprintsFor: async (who) => (await handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry) => entry.fingerprint).sort(),
1072
+ vexEntry: (fingerprint) => engine.cache.get(fingerprint),
1073
+ compileQuery: (dsl) => {
1074
+ engine.compile(dsl);
1075
+ },
1076
+ executeAs: createExecuteAs({
1077
+ engine,
1078
+ db: config.db,
1079
+ policyFor: (roles) => policies.of(callerOfRoles(roles)),
1080
+ policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
1081
+ ...onExecute !== void 0 ? { onExecute } : {}
1082
+ }),
1083
+ answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
1084
+ ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
1085
+ artifactEntries: (entries, rules) => ownEntries({ owner: "the artifactory", entries, tables: ARTIFACT_TABLES, rules }, onExecute),
1086
+ routes: (routing) => createVexRoutes({
1087
+ engine,
1088
+ db: config.db,
1089
+ resources: routing.resources,
1090
+ scope: routing.scope,
1091
+ policy: (c) => policies.of(routing.caller(c)),
1092
+ policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
1093
+ ...onExecute !== void 0 ? { onExecute } : {},
1094
+ writes
1095
+ }),
1096
+ upgradeStore: createUpgradeStore(prepared, tablesOf),
1097
+ onWrite: writes.subscribe,
1098
+ pointer: createPointer(pointerReplay),
1099
+ dropOnChange: (changed) => {
1100
+ changed(policies.drop);
1064
1101
  }
1065
- }
1066
- return mutationMisfits(entry2.mutation, schema)[0];
1102
+ };
1067
1103
  };
1068
- var misfitsOf = (entries, schema) => {
1069
- const misfits = /* @__PURE__ */ new Map();
1070
- for (const entry2 of entries) {
1071
- const why = misfitOf(entry2, schema);
1072
- if (why !== void 0) misfits.set(entry2.fingerprint, why);
1073
- }
1074
- return misfits;
1104
+ var createData = async (config) => createDataWith(await prepareEngine(config), config);
1105
+ var DEFAULT_ROOT = '<div id="root"></div>';
1106
+ var embedSnapshot = (snapshot, principal, path) => {
1107
+ const { frame, trees, seed, live } = snapshot;
1108
+ const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
1109
+ const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1110
+ return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
1075
1111
  };
1076
- var canonical = (value) => {
1077
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1078
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1079
- const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
1080
- return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
1112
+ var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
1113
+ var rootHolding = (root) => {
1114
+ const closing = root.lastIndexOf("</");
1115
+ if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
1116
+ return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
1081
1117
  };
1082
- var isSeededAs = async (cache, entry2) => {
1083
- const held = await cache.get(entry2.fingerprint);
1084
- if (held === void 0 || held.protected !== true) return false;
1085
- if ("mutation" in entry2) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry2.mutation);
1086
- return held.kind === "ok" && canonical(held.dsl) === canonical(entry2.dsl);
1118
+ var escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1119
+ var renderDocument = async (config) => {
1120
+ const { server, template, request, draw } = config;
1121
+ const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;
1122
+ const root = config.root ?? DEFAULT_ROOT;
1123
+ const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
1124
+ if (!template.includes(root)) return undrawn;
1125
+ const holding = rootHolding(root);
1126
+ if (holding === void 0) {
1127
+ console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
1128
+ return undrawn;
1129
+ }
1130
+ try {
1131
+ const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
1132
+ const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
1133
+ const principal = token === null ? null : await server.principalOf(token);
1134
+ const route = server.page(request.path);
1135
+ const host = route?.host ?? server.shells;
1136
+ if (host === void 0) return undrawn;
1137
+ const snapshot = await host.snapshot(principal === null ? null : token, principal, {
1138
+ ...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
1139
+ ...route !== void 0 ? { inputs: route.inputs } : {}
1140
+ });
1141
+ const screen = await draw(snapshot);
1142
+ const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
1143
+ const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1144
+ const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
1145
+ for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
1146
+ const html = placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
1147
+ return {
1148
+ html,
1149
+ ...head !== void 0 ? { head } : {},
1150
+ headers: documentHeaders(principal),
1151
+ drawn: true,
1152
+ principal,
1153
+ ...route !== void 0 ? { page: route.name } : {},
1154
+ live: snapshot.live,
1155
+ why: snapshot.why,
1156
+ drawnWith: snapshot.drawnWith,
1157
+ settled: snapshot.settled
1158
+ };
1159
+ } catch (error) {
1160
+ console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
1161
+ return undrawn;
1162
+ }
1087
1163
  };
1088
- var changesBetween = (before, after) => {
1089
- const removed = [];
1090
- const retyped = [];
1091
- for (const was of before.entities) {
1092
- const now = after.entities.find((entity) => entity.table === was.table);
1093
- if (now === void 0) {
1094
- removed.push(was.table);
1095
- continue;
1096
- }
1097
- for (const field of was.fields) {
1098
- const kept = now.fields.find((f) => f.name === field.name);
1099
- if (kept === void 0) removed.push(`${was.table}.${field.name}`);
1100
- else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
1164
+
1165
+ // src/documents/pages.ts
1166
+ var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
1167
+ var compile = (name, page) => {
1168
+ if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
1169
+ const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
1170
+ for (const segment of segments) {
1171
+ if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
1172
+ throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
1101
1173
  }
1102
1174
  }
1103
- return { removed, retyped };
1104
- };
1105
- var oneAtATime = (query) => {
1106
- let last = Promise.resolve();
1107
- return (text, values) => {
1108
- const next = last.then(() => query(text, values));
1109
- last = next.catch(() => void 0);
1110
- return next;
1111
- };
1175
+ const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
1176
+ const twice = named.find((param, index) => named.indexOf(param) !== index);
1177
+ if (twice !== void 0) {
1178
+ throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
1179
+ }
1180
+ if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
1181
+ throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
1182
+ }
1183
+ return { name, segments };
1112
1184
  };
1113
- var migrateTables = async (runtime, app, options = {}) => {
1114
- const entries = entriesOf(app);
1115
- const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });
1116
- const before = await createPostgresAdapter({ pool: runtime.pool }).introspect();
1117
- const misfitsBefore = misfitsOf(entries, before);
1118
- const excused = /* @__PURE__ */ new Set();
1119
- for (const entry2 of entries) {
1120
- if (misfitsBefore.has(entry2.fingerprint) && await isSeededAs(cache, entry2).catch(() => false)) excused.add(entry2.fingerprint);
1185
+ var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
1186
+ const other = b.segments[index];
1187
+ return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
1188
+ });
1189
+ var createPageRouter = (pages) => {
1190
+ const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
1191
+ for (const [index, page] of compiled.entries()) {
1192
+ const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
1193
+ if (other !== void 0) {
1194
+ throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
1195
+ }
1121
1196
  }
1122
- let found = { removed: [], retyped: [], alreadyBroken: [] };
1123
- const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
1124
- const report = await migrate(runtime.pool, tableSequencesOf(owners), {
1125
- ...options.dryRun === true ? { dryRun: true } : {},
1126
- guard: async (tx) => {
1127
- const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
1128
- const refused = [];
1129
- const alreadyBroken = [];
1130
- for (const [fingerprint, why] of misfitsOf(entries, after)) {
1131
- if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
1132
- else refused.push(`${fingerprint}: ${why}`);
1197
+ return {
1198
+ match: (path) => {
1199
+ const parts = segmentsOf(path);
1200
+ for (const page of compiled) {
1201
+ if (page.segments.length !== parts.length) continue;
1202
+ const params = {};
1203
+ let matches = true;
1204
+ for (const [index, segment] of page.segments.entries()) {
1205
+ const part = parts[index];
1206
+ if (part === void 0) {
1207
+ matches = false;
1208
+ break;
1209
+ }
1210
+ if ("param" in segment) {
1211
+ try {
1212
+ params[segment.param] = decodeURIComponent(part);
1213
+ } catch {
1214
+ matches = false;
1215
+ break;
1216
+ }
1217
+ } else if (segment.literal !== part) {
1218
+ matches = false;
1219
+ break;
1220
+ }
1221
+ }
1222
+ if (matches) return { name: page.name, params };
1133
1223
  }
1134
- found = { ...changesBetween(before, after), alreadyBroken };
1135
- return refused;
1224
+ return void 0;
1136
1225
  }
1226
+ };
1227
+ };
1228
+ var exportDocuments = async (config) => {
1229
+ const { paths, ...rest } = config;
1230
+ const out = [];
1231
+ for (const path of paths) {
1232
+ const page = await renderDocument({ ...rest, request: { path, cookie: null } });
1233
+ out.push({
1234
+ path,
1235
+ html: page.html,
1236
+ ...page.page !== void 0 ? { page: page.page } : {},
1237
+ ...page.head !== void 0 ? { head: page.head } : {},
1238
+ drawn: page.drawn,
1239
+ // A page that could not be drawn is not taken to be finished.
1240
+ live: page.live ?? true,
1241
+ why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
1242
+ drawnWith: page.drawnWith ?? [],
1243
+ settled: page.settled ?? false
1244
+ });
1245
+ }
1246
+ return out;
1247
+ };
1248
+ var isKept = (layout) => layout !== void 0 && layout !== null && typeof layout !== "string";
1249
+ var shellWithStoredLayouts = (shell) => {
1250
+ const layouts = {};
1251
+ const frame = shell.layout;
1252
+ if (isKept(frame)) layouts[FRAME_LAYOUT_REF] = frame;
1253
+ const canvases = shell.canvases.map((canvas) => {
1254
+ const layout = canvas.actionLayout;
1255
+ if (!isKept(layout)) return canvas;
1256
+ const ref = canvasLayoutRef(canvas.id);
1257
+ layouts[ref] = layout;
1258
+ return { ...canvas, actionLayout: ref };
1137
1259
  });
1138
- return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
1260
+ return { canvases, ...isKept(frame) ? { frame: FRAME_LAYOUT_REF } : typeof frame === "string" ? { frame } : {}, layouts };
1261
+ };
1262
+ var slottedIn = /* @__PURE__ */ new WeakMap();
1263
+ var canvasesSlottedIn = (layout) => {
1264
+ const kept = slottedIn.get(layout);
1265
+ if (kept !== void 0) return kept;
1266
+ const ids = /* @__PURE__ */ new Set();
1267
+ walkNodes(layout, (node) => {
1268
+ const id = node["component"] === CANVAS_SLOT_NAME && isRecord(node["props"]) ? node["props"]["canvasId"] : void 0;
1269
+ if (typeof id === "string" && id !== "" && !isBinding(id)) ids.add(id);
1270
+ });
1271
+ const found = [...ids];
1272
+ slottedIn.set(layout, found);
1273
+ return found;
1274
+ };
1275
+ var slottedCanvases = (declared, layouts) => {
1276
+ const ids = /* @__PURE__ */ new Set();
1277
+ for (const layout of layouts) {
1278
+ if (layout === null || typeof layout !== "object") continue;
1279
+ for (const id of canvasesSlottedIn(layout)) ids.add(id);
1280
+ }
1281
+ for (const canvas of declared) ids.delete(canvas.id);
1282
+ return [...ids];
1139
1283
  };
1140
- var featureTablesOf = (app) => {
1141
- const features = /* @__PURE__ */ new Set();
1142
- return (app.features ?? []).map((feature) => {
1143
- if (features.has(feature.name)) {
1144
- throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
1284
+ var shellComponents = (manifest, shell) => {
1285
+ const names = /* @__PURE__ */ new Set([CANVAS_SLOT_NAME, ACTION_SLOT_NAME]);
1286
+ for (const source of [manifest.actions, manifest.layouts ?? {}, shell.canvases, shell.layout ?? {}, shell.layoutStore ?? {}, shell.fragments ?? {}]) {
1287
+ for (const name of componentsOf(source)) names.add(name);
1288
+ }
1289
+ const contracts = shell.components ?? {};
1290
+ for (const name of Object.keys(contracts)) names.add(name);
1291
+ return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
1292
+ };
1293
+ var createComponentNames = (read2) => {
1294
+ let components = /* @__PURE__ */ new WeakMap();
1295
+ return {
1296
+ of: (shell) => {
1297
+ const kept = components.get(shell);
1298
+ if (kept !== void 0) return kept;
1299
+ const names = read2(shell);
1300
+ components.set(shell, names);
1301
+ return names;
1302
+ },
1303
+ drop: () => {
1304
+ components = /* @__PURE__ */ new WeakMap();
1145
1305
  }
1146
- features.add(feature.name);
1147
- const names = feature.tables?.names ?? [];
1148
- return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
1149
- });
1306
+ };
1150
1307
  };
1151
- var createDataLayer = async (deps) => {
1152
- const adapter = createPostgresAdapter({ pool: deps.pool });
1153
- const cache = deps.cache ?? createPostgresCache({ pool: deps.pool });
1154
- await cache.init?.();
1155
- const engine = createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
1156
- const schema = await engine.introspect();
1157
- return { engine, adapter, schema, grants: scopeGrants(schema.entities.map((e) => e.name)) };
1308
+ var SavedLayoutSchema = z.strictObject({ ref: z.string(), layout: LayoutNodeSchema, use: z.boolean().optional() });
1309
+ var upgradedLayoutBody = (upgrader, body, stamp) => isRecord(body) && body["layout"] !== void 0 ? { ...body, layout: upgrader.upgrade(body["layout"], { kind: "nisc.nova/layout", stamp }).document } : body;
1310
+ var actionAtRef = (actions, layouts) => (ref) => {
1311
+ const id = actionOfLayoutRef(ref);
1312
+ const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
1313
+ const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
1314
+ return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1158
1315
  };
1159
- var grammarsOf = (app) => [
1160
- NOVA_SEQUENCE,
1161
- PRISM_SEQUENCE,
1162
- ...app.grammars ?? []
1163
- ];
1164
- var createGrammarUpgrader = (app) => createUpgrader(grammarsOf(app), { transform: evaluate });
1165
- var vexRecordToSpan = (rec) => ({
1166
- name: "vex.execute",
1167
- startUnixNano: rec.startUnixNano,
1168
- endUnixNano: rec.endUnixNano,
1169
- status: rec.status,
1170
- attributes: {
1171
- op: rec.kind,
1172
- hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
1173
- ...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
1174
- ...rec.reach !== void 0 ? { reach: rec.reach } : {},
1175
- ...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
1176
- ...rec.rows !== void 0 ? { rows: rec.rows } : {}
1316
+ var nothingKeptUnder = (ref) => `nothing is kept under "${ref}". A saved layout takes the place of the layout of an action its holder has, under "action/<the action\u2019s id>", or of one the app\u2019s own shell declares: its own under "frame", a canvas\u2019s under "canvas/<the canvas\u2019s id>".`;
1317
+ var targetAt = (ref, heldTo) => {
1318
+ if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
1319
+ const action = heldTo.actionAt(ref);
1320
+ return action === void 0 ? void 0 : { kit: heldTo.kit, action };
1321
+ };
1322
+ var refOf = (body) => {
1323
+ const ref = isRecord(body) ? body["ref"] : void 0;
1324
+ return typeof ref === "string" ? ref : void 0;
1325
+ };
1326
+ var readLayout = (body, heldTo) => {
1327
+ if (exceedsDepth(body)) return { refusal: depthRefusal() };
1328
+ const parsed = SavedLayoutSchema.safeParse(body);
1329
+ if (!parsed.success) {
1330
+ const first = parsed.error.issues[0];
1331
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1332
+ }
1333
+ const { ref, layout } = parsed.data;
1334
+ const target = targetAt(ref, heldTo);
1335
+ if (target === void 0) return { refusal: nothingKeptUnder(ref) };
1336
+ const misfits = layoutMisfits(layout, target.kit);
1337
+ if (misfits.length > 0) return { refusal: misfits.join("; ") };
1338
+ const named = layoutNameRefusal(layout);
1339
+ if (named !== void 0) return { refusal: `it ${named}` };
1340
+ const { action } = target;
1341
+ if (action === void 0) return { layout: parsed.data };
1342
+ const found = new Set(auditAction(action).issues);
1343
+ const added = auditAction({ ...action, layout }).issues.filter((issue) => !found.has(issue));
1344
+ if (added.length > 0) return { refusal: added.join("; ") };
1345
+ return { layout: parsed.data };
1346
+ };
1347
+ var loaded = (version, { whose, heldTo, say }) => {
1348
+ const ref = refOf(version.body);
1349
+ if (ref === void 0 || targetAt(ref, heldTo) === void 0) return void 0;
1350
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : readLayout(version.body, heldTo);
1351
+ if ("layout" in read2) return read2.layout;
1352
+ (say ?? console.error)(`[moss] the layout "${version.id}" ${whose} is left out: ${read2.refusal}`);
1353
+ return void 0;
1354
+ };
1355
+ var isInUse = (version) => version.kind === "layout" && isRecord(version.body) && version.body["use"] === true;
1356
+ var isLater = (one, other) => one.createdAt === other.createdAt ? one.save > other.save : one.createdAt > other.createdAt;
1357
+ var layoutsInUse = (inForce2, drawnFor) => {
1358
+ const marked = /* @__PURE__ */ new Map();
1359
+ for (const version of inForce2.filter(isInUse)) {
1360
+ const ref = refOf(version.body);
1361
+ if (ref === void 0) continue;
1362
+ const held = marked.get(ref);
1363
+ if (held === void 0 || isLater(version, held)) marked.set(ref, version);
1364
+ }
1365
+ const layouts = {};
1366
+ for (const version of marked.values()) {
1367
+ const read2 = loaded(version, drawnFor);
1368
+ if (read2 !== void 0) layouts[read2.ref] = read2.layout;
1369
+ }
1370
+ return layouts;
1371
+ };
1372
+ var generatedId = () => `${GENERATED_ID_PREFIX}${randomUUID()}`;
1373
+ var VEX_ROUTE = /^\/api\/(?:[A-Za-z0-9_-]+\/)?vex$/;
1374
+ var endpointRefusals = async (endpoints, heldTo) => {
1375
+ const refusals = [];
1376
+ for (const [name, endpoint] of Object.entries(endpoints ?? {})) {
1377
+ if ("fn" in endpoint) {
1378
+ if (endpoint.fn.includes("{{")) refusals.push(`endpoint "${name}" names a function that is worked out when it is called, and what is generated names one written out`);
1379
+ else if (!heldTo.mayCall(endpoint.fn)) refusals.push(`endpoint "${name}" calls the function "${endpoint.fn}", which its owner\u2019s roles do not grant`);
1380
+ continue;
1381
+ }
1382
+ if (endpoint.method !== "POST" || !VEX_ROUTE.test(endpoint.url)) {
1383
+ refusals.push(`endpoint "${name}" calls "${endpoint.method} ${endpoint.url}", and what is generated calls only the app\u2019s vex route, with POST`);
1384
+ continue;
1385
+ }
1386
+ const fingerprint = isRecord(endpoint.request) ? endpoint.request["fingerprint"] : void 0;
1387
+ if (typeof fingerprint !== "string") {
1388
+ refusals.push(`endpoint "${name}" names no fingerprint`);
1389
+ continue;
1390
+ }
1391
+ const entry = heldTo.entryOf(fingerprint);
1392
+ if (entry === void 0) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is no entry the app ships or was handed, nor a read its owner saved`);
1393
+ else if ("mutation" in entry) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is a write, and what is generated only reads`);
1394
+ else if (!(await heldTo.replayable()).has(fingerprint)) refusals.push(`endpoint "${name}" replays "${fingerprint}", which its owner may not replay`);
1177
1395
  }
1178
- });
1179
- var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
1180
- var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
1181
- var createOwnEntries = (deps) => async (own) => {
1182
- const cache = createMemoryCache();
1183
- await seedCache(cache, own.entries);
1184
- const schema = await deps.adapter.introspect({ entities: [...own.tables] });
1185
- const engine = createQueryEngine({
1186
- adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
1187
- cache
1188
- });
1189
- await engine.introspect();
1190
- const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, { public: true }])) };
1191
- const reachable = new Set((await handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed) => listed.fingerprint));
1192
- const outside = own.entries.map((entry2) => entry2.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
1193
- if (outside.length > 0) {
1194
- throw new Error(
1195
- `moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
1196
- );
1396
+ return refusals;
1397
+ };
1398
+ var parsedUnder = (schema, body, id, more = {}) => {
1399
+ if (exceedsDepth(body)) return { refusal: depthRefusal() };
1400
+ if (isRecord(body) && body["id"] !== void 0 && body["id"] !== id) {
1401
+ return { refusal: `it names the id "${String(body["id"])}", and is kept under "${id}": leave the id out of the body.` };
1197
1402
  }
1198
- return async (fingerprint, context) => {
1199
- const outcome = await handleQuery(
1200
- {
1201
- engine,
1202
- locked: true,
1203
- scopePolicy: policy,
1204
- mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(tablesChangedBy(event.writes, schema)) },
1205
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
1206
- },
1207
- { fingerprint, context },
1208
- {}
1209
- );
1210
- if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
1211
- return resultOf(outcome.body);
1403
+ const parsed = schema.safeParse(isRecord(body) ? { ...more, ...body, id } : body);
1404
+ if (parsed.success) return { body: parsed.data };
1405
+ const first = parsed.error.issues[0];
1406
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1407
+ };
1408
+ var layoutRefusals = (layout, kit) => {
1409
+ const named = layoutNameRefusal(layout);
1410
+ return [...layout === void 0 || typeof layout === "string" ? [] : layoutMisfits(layout, kit), ...named === void 0 ? [] : [`it ${named}`]];
1411
+ };
1412
+ var passedOrRefused = (body, refusals) => refusals.length > 0 ? { refusal: refusals.join("; ") } : { body };
1413
+ var readAction = async (body, id, heldTo) => {
1414
+ const parsed = parsedUnder(ActionDefinitionSchema, body, id);
1415
+ if ("refusal" in parsed) return parsed;
1416
+ const action = parsed.body;
1417
+ return passedOrRefused(action, [
1418
+ ...layoutRefusals(action.layout, heldTo.kit),
1419
+ ...await endpointRefusals(action.endpoints, heldTo),
1420
+ ...auditAction(action, { catalog: heldTo.catalog() }).issues
1421
+ ]);
1422
+ };
1423
+ var readFragment = async (body, id, heldTo) => {
1424
+ const parsed = parsedUnder(ActionFragmentSchema, body, id, { kind: "fragment" });
1425
+ if ("refusal" in parsed) return parsed;
1426
+ const fragment = parsed.body;
1427
+ return passedOrRefused(fragment, [...layoutRefusals(fragment.layout, heldTo.kit), ...await endpointRefusals(fragment.endpoints, heldTo)]);
1428
+ };
1429
+ var generatedIn = (inForce2, kind) => inForce2.filter((version) => version.kind === kind && version.body !== null);
1430
+ var catalogOfGenerated = (inForce2) => generatedIn(inForce2, "action").map((version) => ({ id: version.id, input: isRecord(version.body) && isRecord(version.body["input"]) ? version.body["input"] : {} }));
1431
+ var generatedInForce = async (inForce2, heldTo, whose) => {
1432
+ const passed = async (kind, read2) => {
1433
+ const kept = {};
1434
+ for (const version of generatedIn(inForce2, kind)) {
1435
+ const answered = version.unread !== void 0 ? { refusal: version.unread } : await read2(version.body, version.id, heldTo);
1436
+ if ("body" in answered) kept[version.id] = answered.body;
1437
+ else if (whose !== void 0) console.error(`[moss] the ${kind} "${version.id}" ${whose} is left out: ${answered.refusal}`);
1438
+ }
1439
+ return kept;
1440
+ };
1441
+ return { actions: await passed("action", readAction), fragments: await passed("fragment", readFragment) };
1442
+ };
1443
+ var compileEntries = async (entries) => {
1444
+ const compiled = createMemoryCache();
1445
+ await seedCache(compiled, entries);
1446
+ return new Map((await compiled.entries?.() ?? []).map(({ key, entry }) => [key, entry]));
1447
+ };
1448
+ var mergedEntries = (own, sets) => {
1449
+ const byFingerprint = /* @__PURE__ */ new Map();
1450
+ for (const entry of [...own, ...[...sets.values()].flat()]) byFingerprint.set(entry.fingerprint, entry);
1451
+ return Object.freeze([...byFingerprint.values()]);
1452
+ };
1453
+ var createEntriesInForce = (own) => {
1454
+ let sets = /* @__PURE__ */ new Map();
1455
+ let list = mergedEntries(own, sets);
1456
+ let byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
1457
+ let ownCompiled;
1458
+ let setsCompiled = /* @__PURE__ */ new Map();
1459
+ let compiled;
1460
+ return {
1461
+ list: () => list,
1462
+ byFingerprint: () => byFingerprint,
1463
+ holdsSet: (source) => sets.has(source),
1464
+ withSet: (source, handed) => mergedEntries(own, new Map([...sets, [source, handed]])),
1465
+ takeSet: (source, handed, taken) => {
1466
+ sets = new Map([...sets, [source, handed]]);
1467
+ list = mergedEntries(own, sets);
1468
+ byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
1469
+ setsCompiled = new Map([...setsCompiled, [source, taken]]);
1470
+ compiled = void 0;
1471
+ },
1472
+ compiled: () => {
1473
+ compiled ??= (async () => {
1474
+ ownCompiled ??= compileEntries(own);
1475
+ return new Map([...await ownCompiled, ...[...setsCompiled.values()].flatMap((set) => [...set])]);
1476
+ })();
1477
+ return compiled;
1478
+ }
1212
1479
  };
1213
1480
  };
1214
- var TABLE = "moss_generation";
1215
- var THE_ROW = { eq: [`${TABLE}.id`, 1] };
1216
- var readPointerEntry = {
1217
- fingerprint: "moss/generation",
1218
- intent: "Where the generation pointer is",
1219
- dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
1481
+
1482
+ // src/artifactory/reads.ts
1483
+ var SavedReadSchema = VEX_SCHEMAS["nisc.vex/entry"];
1484
+ var sentenceOf = (error) => error instanceof Error ? error.message : String(error);
1485
+ var seedOf = (fingerprint, read2) => ({ fingerprint, ...read2 });
1486
+ var compiledRead = async (fingerprint, read2) => {
1487
+ const compiled = (await compileEntries([seedOf(fingerprint, read2)])).get(fingerprint);
1488
+ if (compiled === void 0) return void 0;
1489
+ const { protected: _shipped, ...entry } = compiled;
1490
+ return entry;
1491
+ };
1492
+ var shippedRefusal = (fingerprint) => `"${fingerprint}" is the fingerprint of an entry the app ships or was handed, and a read somebody generated never answers in its place`;
1493
+ var readSaved = async (body, fingerprint, heldTo) => {
1494
+ if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1495
+ if (exceedsDepth(body)) return { refusal: depthRefusal() };
1496
+ const parsed = SavedReadSchema.safeParse(body);
1497
+ if (!parsed.success) {
1498
+ const first = parsed.error.issues[0];
1499
+ return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1500
+ }
1501
+ try {
1502
+ heldTo.sources.compile(parsed.data.dsl);
1503
+ await compiledRead(fingerprint, parsed.data);
1504
+ } catch (error) {
1505
+ return { refusal: sentenceOf(error) };
1506
+ }
1507
+ return { body: parsed.data };
1508
+ };
1509
+ var readWritten = async (fingerprint, heldTo) => {
1510
+ if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
1511
+ const entry = await heldTo.sources.written(fingerprint);
1512
+ if (entry === void 0 || entry.requestHash === void 0) return { refusal: `vex holds no query it wrote under "${fingerprint}"` };
1513
+ if (entry.kind !== "ok") return { refusal: `vex found no query to answer under "${fingerprint}"` };
1514
+ if (entry.shape !== void 0 && entry.mapping === void 0) {
1515
+ return { refusal: `vex kept no prism config for the mapping of "${fingerprint}": it was written before vex kept one. Ask for it again.` };
1516
+ }
1517
+ return readSaved(
1518
+ {
1519
+ dsl: entry.dsl,
1520
+ ...entry.mapping !== void 0 ? { mapping: entry.mapping } : {},
1521
+ ...entry.shape !== void 0 ? { shape: entry.shape } : {},
1522
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1523
+ ...entry.reach !== void 0 ? { reach: entry.reach } : {},
1524
+ ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {}
1525
+ },
1526
+ fingerprint,
1527
+ heldTo
1528
+ );
1220
1529
  };
1221
- var movePointerEntry = {
1222
- fingerprint: "moss/generation-move",
1223
- intent: "Move the generation pointer to the next number, if it is still where it was read",
1224
- mutation: {
1225
- op: "update",
1226
- table: TABLE,
1227
- set: { n: { $context: "next" } },
1228
- where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
1530
+ var answeredRead = async (fingerprint, body) => {
1531
+ if (exceedsDepth(body)) return void 0;
1532
+ const parsed = SavedReadSchema.safeParse(body);
1533
+ return parsed.success ? compiledRead(fingerprint, parsed.data) : void 0;
1534
+ };
1535
+ var readsInForce = async (inForce2, heldTo, whose) => {
1536
+ const reads = /* @__PURE__ */ new Map();
1537
+ for (const version of inForce2) {
1538
+ if (version.kind !== "read" || version.body === null) continue;
1539
+ const read2 = version.unread !== void 0 ? { refusal: version.unread } : await readSaved(version.body, version.id, heldTo);
1540
+ if ("body" in read2) reads.set(version.id, read2.body);
1541
+ else if (whose !== void 0) console.error(`[moss] the read "${version.id}" ${whose} is left out: ${read2.refusal}`);
1229
1542
  }
1543
+ return reads;
1230
1544
  };
1231
- var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
1232
- var RowSchema = z.object({ n: z.coerce.number() });
1233
- var RowsSchema = z.array(z.unknown());
1234
- var createPointer = (replay) => ({
1235
- read: async () => {
1236
- const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
1237
- return RowSchema.parse(rows[0] ?? { n: 0 }).n;
1238
- },
1239
- // A write that changed one row answers that row; one that changed none
1240
- // answers no row, which does not parse: the counter moved since it was read.
1241
- move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
1545
+
1546
+ // src/artifactory/session.ts
1547
+ var SaveIdSchema = z.uuid();
1548
+ var ToSaveSchema = z.array(z.strictObject({ kind: z.string(), id: z.string().optional(), body: z.unknown() })).min(1);
1549
+ var NEW_ID = {
1550
+ layout: randomUUID,
1551
+ action: generatedId,
1552
+ fragment: generatedId,
1553
+ read: () => {
1554
+ throw new Error("moss: a read is saved under the fingerprint vex gave it: name it as the id.");
1555
+ }
1556
+ };
1557
+ var listed = (version, kind) => ({
1558
+ kind,
1559
+ id: version.id,
1560
+ save: version.save,
1561
+ createdAt: version.createdAt,
1562
+ copiedFrom: version.copiedFrom,
1563
+ body: version.body
1242
1564
  });
1243
- var resolvePolicyForRoles = (app, grants, roles) => {
1244
- const behaviors = app.behaviors ?? {};
1245
- return mergeScopePolicies(
1246
- roles.map(
1247
- (role) => createScopePolicy(resolvePrincipal(app.charter, grants, [role], "data"), behaviors, resolveScoping(app.charter, role))
1248
- )
1249
- );
1565
+ var withoutMark = ({ use: _mark, ...layout }) => layout;
1566
+ var checked = async (kind, id, body, heldTo) => {
1567
+ if (kind === "layout") {
1568
+ const read3 = readLayout(body, heldTo.layouts);
1569
+ if ("refusal" in read3) throw new Error(`moss: the layout for "${refOf(body) ?? "(no ref)"}" is refused: ${read3.refusal}`);
1570
+ return read3.layout;
1571
+ }
1572
+ if (kind === "read") {
1573
+ const read3 = heldTo.reads === void 0 ? { refusal: "no read is saved here" } : body === void 0 ? await readWritten(id, heldTo.reads) : await readSaved(body, id, heldTo.reads);
1574
+ if ("refusal" in read3) throw new Error(`moss: the read "${id}" is refused: ${read3.refusal}`);
1575
+ return read3.body;
1576
+ }
1577
+ const read2 = await (kind === "action" ? readAction : readFragment)(body, id, heldTo.generated);
1578
+ if ("refusal" in read2) throw new Error(`moss: the ${kind} is refused: ${read2.refusal}`);
1579
+ return read2.body;
1580
+ };
1581
+ var markedRefs = (versions) => {
1582
+ const marked = versions.flatMap((version) => {
1583
+ const ref = refOf(version.body);
1584
+ return version.kind === "layout" && isRecord(version.body) && version.body["use"] === true && ref !== void 0 ? [ref] : [];
1585
+ });
1586
+ const twice = marked.find((ref, at) => marked.indexOf(ref) !== at);
1587
+ if (twice !== void 0) throw new Error(`moss: two layouts of one save are marked in use for "${twice}". One is in use at a time.`);
1588
+ return marked;
1589
+ };
1590
+ var unmarked = (versions, inForce2) => {
1591
+ const layouts = versions.filter((version) => version.kind === "layout");
1592
+ const marked = markedRefs(layouts);
1593
+ const saved = new Set(layouts.map((version) => version.id));
1594
+ const takenOut = inForce2.flatMap((held) => isInUse(held) && saved.has(held.id) ? [refOf(held.body)] : []);
1595
+ const decided = /* @__PURE__ */ new Set([...marked, ...takenOut]);
1596
+ return inForce2.flatMap((held) => {
1597
+ const ref = refOf(held.body);
1598
+ if (!isInUse(held) || held.unread !== void 0 || !isRecord(held.body) || ref === void 0 || !decided.has(ref) || saved.has(held.id)) return [];
1599
+ return [{ kind: "layout", id: held.id, body: withoutMark(held.body), copiedFrom: held.save }];
1600
+ });
1250
1601
  };
1251
- var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => createScopePolicy(resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
1252
- var createPolicies = (config) => {
1253
- const { grants } = config;
1254
- const governed = { charter: config.charter, behaviors: config.behaviors };
1255
- const policies = /* @__PURE__ */ new Map();
1256
- const reachPolicies = /* @__PURE__ */ new Map();
1602
+ var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
1603
+ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1604
+ const requireHolder = () => {
1605
+ if (holder === void 0) throw new Error(nobody);
1606
+ return holder;
1607
+ };
1608
+ const ofKind = (kind) => {
1609
+ const known = kinds.find((one) => one === kind);
1610
+ if (known === void 0) throw new Error(`moss: "${String(kind)}" is not a kind that is saved. The kinds: ${kinds.join(", ")}.`);
1611
+ return known;
1612
+ };
1613
+ const askedOf = (artifacts) => {
1614
+ const asked = ToSaveSchema.safeParse(artifacts);
1615
+ if (!asked.success) throw new Error("moss: a save holds one or several artifacts, each `{ kind, id?, body }` and nothing else.");
1616
+ return asked.data.map((artifact) => ({ ...artifact, kind: ofKind(artifact.kind) }));
1617
+ };
1618
+ const checkedEach = async (asked, inForce2, held) => {
1619
+ const versions = [];
1620
+ for (const { kind, id: named2, body } of asked) {
1621
+ if (defaults !== void 0 && named2 === void 0 && kind !== "layout" && kind !== "read") throw new Error(`moss: a published ${kind} is given its id by whoever publishes it: name it.`);
1622
+ const id = named2 ?? NEW_ID[kind]();
1623
+ if (kind === "read" && body !== void 0) throw new Error(`moss: the read "${id}" is refused: it is what vex wrote for the request. Leave the body out.`);
1624
+ versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
1625
+ }
1626
+ const named = (kind) => kind !== "read" && (defaults === void 0 || kind === "layout");
1627
+ const notTheirs = asked.find(({ kind, id }) => id !== void 0 && named(kind) && !inForce2.some((version) => version.kind === kind && version.id === id));
1628
+ if (notTheirs !== void 0) {
1629
+ throw new Error(`moss: there is no ${notTheirs.kind} "${notTheirs.id}" ${whose}. Leave the id out, and moss gives a new ${notTheirs.kind} its id.`);
1630
+ }
1631
+ const twice = versions.find((version, at) => versions.findIndex((other) => other.kind === version.kind && other.id === version.id) !== at);
1632
+ if (twice !== void 0) throw new Error(`moss: the ${twice.kind} "${twice.id}" is in one save twice.`);
1633
+ return versions;
1634
+ };
1635
+ const write = async (saved, versions, inForce2) => {
1636
+ const save2 = randomUUID();
1637
+ await saved.write({ id: save2, versions: [...versions, ...unmarked(versions, inForce2)] });
1638
+ written();
1639
+ return save2;
1640
+ };
1641
+ return { requireHolder, ofKind, askedOf, checkedEach, write };
1642
+ };
1643
+ var savedArtifacts = (deps) => {
1644
+ const { holder, whose, kinds, defaults } = deps;
1645
+ const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1257
1646
  return {
1258
- of: (who) => {
1259
- const hit = policies.get(who.memoKey);
1260
- if (hit !== void 0) return hit;
1261
- const compiled = resolvePolicyForRoles(governed, grants, who.roles);
1262
- policies.set(who.memoKey, compiled);
1263
- return compiled;
1647
+ save: async (artifacts) => {
1648
+ const holderOf = requireHolder();
1649
+ const asked = askedOf(artifacts);
1650
+ const { saved, heldTo } = await holderOf();
1651
+ const inForce2 = await saved.inForce();
1652
+ const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1653
+ await defaults?.verify(versions, inForce2);
1654
+ return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1264
1655
  },
1265
- atReach: (who, reach) => {
1266
- const key = `${who.memoKey}\0${reach}`;
1267
- const hit = reachPolicies.get(key);
1268
- if (hit !== void 0) return hit;
1269
- const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
1270
- reachPolicies.set(key, compiled);
1271
- return compiled;
1656
+ list: async (kind) => {
1657
+ const only = kind === void 0 ? void 0 : ofKind(kind);
1658
+ if (holder === void 0) return [];
1659
+ const inForce2 = await (await holder()).saved.inForce();
1660
+ return inForce2.flatMap((version) => {
1661
+ const known = kinds.find((one) => one === version.kind);
1662
+ return version.body !== null && known !== void 0 && (only === void 0 || known === only) ? [listed(version, known)] : [];
1663
+ });
1664
+ },
1665
+ history: async (kind, id) => {
1666
+ const known = ofKind(kind);
1667
+ if (holder === void 0) return [];
1668
+ return (await (await holder()).saved.history(known, id)).map((version) => listed(version, known));
1669
+ },
1670
+ restore: async (kind, id, save2) => {
1671
+ const holderOf = requireHolder();
1672
+ const known = ofKind(kind);
1673
+ const { saved, heldTo } = await holderOf();
1674
+ const version = SaveIdSchema.safeParse(save2).success ? (await saved.history(known, id, save2))[0] : void 0;
1675
+ if (version === void 0) throw new Error(`moss: no ${known} "${id}" ${whose} was saved in "${save2}".`);
1676
+ if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
1677
+ const inForce2 = await saved.inForce();
1678
+ const body = version.body === null ? null : await checked(known, id, version.body, await heldTo(inForce2));
1679
+ const restored = { kind: known, id, body, copiedFrom: version.save };
1680
+ await defaults?.verify([restored], inForce2);
1681
+ return { save: await write(saved, [restored], inForce2) };
1682
+ },
1683
+ reset: async (kind, id) => {
1684
+ const holderOf = requireHolder();
1685
+ const known = ofKind(kind);
1686
+ const { saved } = await holderOf();
1687
+ const inForce2 = await saved.inForce();
1688
+ if (!inForce2.some((version) => version.kind === known && version.id === id && version.body !== null)) throw new Error(`moss: no ${known} "${id}" ${whose} is in force.`);
1689
+ return { save: await write(saved, [{ kind: known, id, body: null, copiedFrom: null }], inForce2) };
1690
+ }
1691
+ };
1692
+ };
1693
+
1694
+ // src/artifactory/draft.ts
1695
+ var LATER_THAN_ANY_SAVE = "9999-12-31T23:59:59.999Z";
1696
+ var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
1697
+ ...inForce2.filter((version) => !drafted.some((one) => one.kind === version.kind && one.id === version.id)),
1698
+ ...drafted.map((one) => ({ ...one, save: "draft", copiedFrom: null, createdAt: LATER_THAN_ANY_SAVE }))
1699
+ ];
1700
+ var draftSaving = (deps) => {
1701
+ const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
1702
+ return {
1703
+ // The draft with these added to it. Each is checked beside what is in force for its holder with the draft laid over.
1704
+ add: async (artifacts, drafted) => {
1705
+ const holderOf = requireHolder();
1706
+ const asked = askedOf(artifacts);
1707
+ const { saved, heldTo } = await holderOf();
1708
+ const inForce2 = laidOver(await saved.inForce(), drafted);
1709
+ const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1710
+ const added = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1711
+ const marked = new Set(markedRefs(added));
1712
+ const kept = drafted.flatMap((one) => {
1713
+ if (added.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1714
+ const ref = refOf(one.body);
1715
+ const loses = one.kind === "layout" && isRecord(one.body) && one.body["use"] === true && ref !== void 0 && marked.has(ref);
1716
+ return [loses && isRecord(one.body) ? { ...one, body: withoutMark(one.body) } : one];
1717
+ });
1718
+ return { drafted: [...kept, ...added], added: idsOf(versions) };
1719
+ },
1720
+ save: async (drafted) => {
1721
+ const holderOf = requireHolder();
1722
+ if (drafted.length === 0) throw new Error("moss: the draft holds nothing to save.");
1723
+ const { saved, heldTo } = await holderOf();
1724
+ const inForce2 = await saved.inForce();
1725
+ const held = await heldTo(laidOver(inForce2, drafted));
1726
+ const versions = [];
1727
+ for (const one of drafted) {
1728
+ const kind = ofKind(one.kind);
1729
+ versions.push({ kind, id: one.id, body: await checked(kind, one.id, one.body, held), copiedFrom: null });
1730
+ }
1731
+ return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1732
+ }
1733
+ };
1734
+ };
1735
+
1736
+ // src/artifactory/generation.ts
1737
+ var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
1738
+ var MAX_INTERVAL_MS = 2 ** 31 - 1;
1739
+ var MOVE_ATTEMPTS = 5;
1740
+ var createGeneration = (pointer, ctx) => {
1741
+ const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
1742
+ let seen = -1;
1743
+ let checking = false;
1744
+ const poll = async () => {
1745
+ if (checking) return;
1746
+ checking = true;
1747
+ try {
1748
+ const n = await readPointer();
1749
+ if (n === void 0 || n === seen) return;
1750
+ if (seen !== -1 && !await follow(n)) return;
1751
+ seen = n;
1752
+ } finally {
1753
+ checking = false;
1754
+ }
1755
+ };
1756
+ const readPointer = async () => {
1757
+ try {
1758
+ return await pointer.read();
1759
+ } catch (err) {
1760
+ console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
1761
+ return void 0;
1762
+ }
1763
+ };
1764
+ let unfollowed;
1765
+ const follow = async (n) => {
1766
+ try {
1767
+ await ctx.onMoved();
1768
+ } catch (err) {
1769
+ const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
1770
+ if (unfollowed?.said !== what) {
1771
+ console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
1772
+ }
1773
+ unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
1774
+ return false;
1775
+ }
1776
+ if (unfollowed !== void 0) {
1777
+ console.log(
1778
+ `[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
1779
+ );
1780
+ unfollowed = void 0;
1781
+ }
1782
+ return true;
1783
+ };
1784
+ const move = async () => {
1785
+ for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
1786
+ const n = await pointer.read();
1787
+ if (await pointer.move(n)) {
1788
+ if (seen === n || seen === -1) seen = n + 1;
1789
+ return;
1790
+ }
1791
+ }
1792
+ throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
1793
+ };
1794
+ void poll();
1795
+ const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
1796
+ timer?.unref?.();
1797
+ return {
1798
+ bump: () => {
1799
+ void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
1800
+ },
1801
+ current: () => seen,
1802
+ stop: () => {
1803
+ if (timer !== void 0) clearInterval(timer);
1804
+ }
1805
+ };
1806
+ };
1807
+
1808
+ // src/artifactory/published.ts
1809
+ var NO_DEFAULTS = { actions: {}, fragments: {}, reads: /* @__PURE__ */ new Map() };
1810
+ var drawableIn = (fragments, kit, say) => Object.fromEntries(
1811
+ Object.entries(fragments).filter(([id, fragment]) => {
1812
+ const misfits = layoutMisfits(fragment.layout, kit);
1813
+ if (misfits.length > 0) say(`[moss] the fragment "${id}" published for everybody is left out of a shell that cannot draw it: ${misfits.join("; ")}`);
1814
+ return misfits.length === 0;
1815
+ })
1816
+ );
1817
+ var createPublishedMemo = () => {
1818
+ let read2;
1819
+ let said = /* @__PURE__ */ new Set();
1820
+ return {
1821
+ held: () => read2,
1822
+ keep: (promise) => {
1823
+ read2 = promise;
1272
1824
  },
1273
1825
  drop: () => {
1274
- policies.clear();
1275
- reachPolicies.clear();
1826
+ read2 = void 0;
1827
+ said = /* @__PURE__ */ new Set();
1828
+ },
1829
+ sayOnce: (line) => {
1830
+ if (said.has(line)) return;
1831
+ said.add(line);
1832
+ console.error(line);
1276
1833
  }
1277
1834
  };
1278
1835
  };
1279
- var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
1280
- const roles = [role];
1281
- const policy = deps.policyFor(roles);
1282
- const outcome = await handleQuery(
1283
- {
1284
- engine: deps.engine,
1285
- locked: true,
1286
- scopePolicy: policy,
1287
- policyForReach: (reach) => deps.policyAtReach(roles, reach),
1288
- mutations: { client: deps.db, policy },
1289
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
1836
+ var hasDefaults = (defaults) => Object.keys(defaults.actions).length > 0 || Object.keys(defaults.fragments).length > 0 || defaults.reads.size > 0;
1837
+ var checkedDefaults = async (versions, heldTo, whose) => {
1838
+ const reads = heldTo.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, heldTo.reads, whose);
1839
+ const checks = {
1840
+ kit: heldTo.kit,
1841
+ entryOf: (fingerprint) => {
1842
+ const read2 = reads.get(fingerprint);
1843
+ return heldTo.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1290
1844
  },
1291
- { fingerprint, context },
1292
- scope
1293
- );
1294
- if (outcome.status !== 200) {
1295
- console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
1296
- return void 0;
1845
+ replayable: async () => /* @__PURE__ */ new Set([...heldTo.fingerprints(), ...reads.keys()]),
1846
+ mayCall: () => true,
1847
+ catalog: () => [...Object.values(heldTo.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1848
+ };
1849
+ const passed = await generatedInForce(versions, checks, whose);
1850
+ return { passed, reads, verified: verifyManifest(heldTo.candidate({ ...heldTo.built, ...passed.actions }, passed.fragments)) };
1851
+ };
1852
+ var narrowedBy = (filter, ids, installed) => {
1853
+ const answered = new Set(filter(ids, installed));
1854
+ return ids.filter((id) => answered.has(id));
1855
+ };
1856
+ var catalogFor = (app, roles, installed, installedOnly) => {
1857
+ const granted = [...resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
1858
+ const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
1859
+ return { ids, hash: versionToken(ids) };
1860
+ };
1861
+ var resolveVariantsForRoles = (app, roles) => {
1862
+ const variants = app.layouts ?? {};
1863
+ return variantLayouts(variants, resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
1864
+ };
1865
+ var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
1866
+ var actionsWithStoredLayouts = (definitions) => {
1867
+ const actions = {};
1868
+ const layouts = {};
1869
+ for (const [id, definition] of Object.entries(definitions)) {
1870
+ const layout = definition.layout;
1871
+ if (layout === void 0 || typeof layout === "string") {
1872
+ actions[id] = definition;
1873
+ continue;
1874
+ }
1875
+ const ref = actionLayoutRef(id);
1876
+ layouts[ref] = layout;
1877
+ actions[id] = { ...definition, layout: { ref } };
1878
+ }
1879
+ return { actions: Object.freeze(actions), layouts: Object.freeze(layouts) };
1880
+ };
1881
+ var createRoleMemo = (config) => {
1882
+ const catalogs = /* @__PURE__ */ new Map();
1883
+ const variants = /* @__PURE__ */ new Map();
1884
+ const stored = /* @__PURE__ */ new Map();
1885
+ const kept = (memo, key, resolve2) => {
1886
+ const hit = memo.get(key);
1887
+ if (hit !== void 0) return hit;
1888
+ const resolved = resolve2();
1889
+ memo.set(key, resolved);
1890
+ return resolved;
1891
+ };
1892
+ const roleMemo = {
1893
+ catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
1894
+ variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
1895
+ storedLayoutsFor: (roles, installed) => kept(
1896
+ stored,
1897
+ memoKey(roles, installed),
1898
+ () => actionsWithStoredLayouts(definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles)))
1899
+ ),
1900
+ drop: () => {
1901
+ catalogs.clear();
1902
+ variants.clear();
1903
+ stored.clear();
1904
+ }
1905
+ };
1906
+ return roleMemo;
1907
+ };
1908
+ var versionToken = (ids) => {
1909
+ const s = ids.join("\n");
1910
+ let h = 2166136261;
1911
+ for (let i = 0; i < s.length; i += 1) {
1912
+ h ^= s.charCodeAt(i);
1913
+ h = Math.imul(h, 16777619) >>> 0;
1297
1914
  }
1298
- const body = outcome.body;
1299
- return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
1915
+ return h.toString(16).padStart(8, "0");
1300
1916
  };
1301
- var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
1302
- var writeRequestOf = (header) => ({
1303
- header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
1304
- });
1305
- var SAID_NOTHING = { header: () => void 0 };
1306
- var createWriteNotifier = () => {
1307
- const requests = new AsyncLocalStorage();
1308
- const listeners = /* @__PURE__ */ new Set();
1917
+
1918
+ // src/artifactory/sets.ts
1919
+ var createSetOwners = () => {
1920
+ const owners = /* @__PURE__ */ new Map();
1921
+ const ownerRefusalOf = (source) => {
1922
+ const owner = owners.get(source);
1923
+ return owner === void 0 ? void 0 : `the set "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
1924
+ };
1309
1925
  return {
1310
- subscribe: (listener) => {
1311
- listeners.add(listener);
1312
- return () => {
1313
- listeners.delete(listener);
1314
- };
1926
+ ownerRefusalOf,
1927
+ claim: (source, owner, handedOver) => {
1928
+ const held = owners.get(source);
1929
+ if (held !== void 0) throw new Error(`moss: the set "${source}" is ${held}'s, and ${owner} claims it too. A set has one writer.`);
1930
+ if (handedOver) throw new Error(`moss: the set "${source}" was handed over by the app, and ${owner} claims it. A set has one writer.`);
1931
+ owners.set(source, owner);
1315
1932
  },
1316
- within: (request, run) => requests.run(request, run),
1317
- report: (event) => {
1318
- const request = requests.getStore() ?? SAID_NOTHING;
1319
- for (const listener of [...listeners]) {
1320
- try {
1321
- listener(event, request);
1322
- } catch (error) {
1323
- console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
1324
- }
1325
- }
1933
+ assertAppOwned: (source) => {
1934
+ const refusal = ownerRefusalOf(source);
1935
+ if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
1936
+ return source;
1326
1937
  }
1327
1938
  };
1328
1939
  };
1329
- var createWireFollower = (callSignal) => {
1330
- const controller = new AbortController();
1331
- const end = () => {
1332
- controller.abort();
1333
- };
1334
- if (callSignal.aborted) end();
1335
- else callSignal.addEventListener("abort", end, { once: true });
1336
- const handlers = /* @__PURE__ */ new Set();
1337
- let missed;
1338
- const live = {
1339
- signal: controller.signal,
1340
- onChange: (response) => {
1341
- if (handlers.size === 0) {
1342
- missed = { body: response.result };
1343
- return;
1344
- }
1345
- for (const handler of [...handlers]) handler(response.result);
1940
+
1941
+ // src/artifactory/usage.ts
1942
+ var TOUCH_EVERY_MS = 36e5;
1943
+ var createUsage = (everyMs, now = Date.now) => {
1944
+ const stamped2 = /* @__PURE__ */ new Map();
1945
+ return {
1946
+ touch: (principal, versions, rows) => {
1947
+ const at = now();
1948
+ for (const [key, when] of stamped2) if (when <= at - everyMs) stamped2.delete(key);
1949
+ const due = versions.filter((version) => version.body !== null && !stamped2.has(`${principal}\0${version.kind}\0${version.id}`));
1950
+ if (due.length === 0) return;
1951
+ for (const version of due) stamped2.set(`${principal}\0${version.kind}\0${version.id}`, at);
1952
+ rows.touch(
1953
+ due.map((version) => ({ kind: version.kind, id: version.id })),
1954
+ new Date(at).toISOString()
1955
+ ).catch((error) => console.error(`[moss] the artifacts of ${principal} could not be stamped as used:`, error));
1346
1956
  }
1347
1957
  };
1348
- const onChange = (handler) => {
1349
- if (controller.signal.aborted) return () => {
1958
+ };
1959
+
1960
+ // src/artifactory/running.ts
1961
+ var mergedActions = (own, sets, over = {}) => Object.freeze([...sets.values(), over].reduce((all, set) => ({ ...all, ...set }), { ...own }));
1962
+ var tell = (listener, ...told) => {
1963
+ try {
1964
+ listener(...told);
1965
+ } catch (error) {
1966
+ console.error("[moss:manifest] a listener to a manifest change threw:", error);
1967
+ }
1968
+ };
1969
+ var createRunningManifest = (config) => {
1970
+ const { shipped } = config;
1971
+ const entries = createEntriesInForce(entriesOf(shipped));
1972
+ let defaults = NO_DEFAULTS;
1973
+ const usage = createUsage(config.touchEveryMs ?? TOUCH_EVERY_MS);
1974
+ let functionIds;
1975
+ const candidate = (actions, held = entries.list(), fragments = defaults.fragments) => withFragments({ ...candidateOf(shipped, { actions, entries: held }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
1976
+ const own = shipped.actions;
1977
+ const loaders = /* @__PURE__ */ new Map();
1978
+ const owners = createSetOwners();
1979
+ let sets = /* @__PURE__ */ new Map();
1980
+ let inForce2 = mergedActions(own, sets);
1981
+ let report = verifiedAtBoot(candidate(inForce2));
1982
+ const components = createComponentNames((shell) => shellComponents({ actions: inForce2, layouts: shipped.layouts }, shell));
1983
+ const componentsOf2 = (shells) => {
1984
+ const kit = /* @__PURE__ */ new Map();
1985
+ for (const shell of shells) {
1986
+ for (const [name, contract] of Object.entries(components.of(shell))) kit.set(name, { propsSchema: contract.meta?.propsSchema ?? kit.get(name)?.propsSchema });
1987
+ }
1988
+ return kit;
1989
+ };
1990
+ let ofTheApp;
1991
+ const dropMemos = () => {
1992
+ roleMemo.drop();
1993
+ components.drop();
1994
+ ofTheApp = void 0;
1995
+ };
1996
+ const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
1997
+ const roleMemo = createRoleMemo({
1998
+ manifest: () => ({ charter: shipped.charter, actions: inForce2, layouts: shipped.layouts }),
1999
+ installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
2000
+ });
2001
+ const kitOf2 = (shell) => shell === void 0 ? ofTheApp ??= componentsOf2(config.shells) : componentsOf2([shell]);
2002
+ const ownShell = shipped.shell;
2003
+ const ownShellRefs = new Set(ownShell === void 0 ? [] : Object.keys(shellWithStoredLayouts(ownShell).layouts));
2004
+ const heldTo = ({ actions, layouts }, shell) => {
2005
+ const kit = kitOf2(shell);
2006
+ return {
2007
+ kit,
2008
+ // A layout saved for the frame or a canvas is the app's own shell's, whichever shell it is saved from.
2009
+ ...ownShell !== void 0 && (shell === void 0 || shell === ownShell) ? { ownShell: { refs: ownShellRefs, kit: shell === ownShell ? kit : kitOf2(ownShell) } } : {},
2010
+ actionAt: actionAtRef(actions, layouts)
1350
2011
  };
1351
- handlers.add(handler);
1352
- if (missed !== void 0) {
1353
- const { body } = missed;
1354
- missed = void 0;
1355
- handler(body);
2012
+ };
2013
+ const { reads: readSources } = config;
2014
+ const functionsWritten = (written) => {
2015
+ if (functionIds !== void 0) return;
2016
+ const ids = functionsIn(written).map((definition) => definition.id);
2017
+ const charter = charterOverFunctions(shipped.charter, { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) }, ids);
2018
+ if (charter.errors.length > 0) throw new Error(`Charter is incoherent over the app\u2019s functions \u2014 refusing to serve:
2019
+ ${charter.errors.join("\n ")}`);
2020
+ functionIds = new Set(ids);
2021
+ const built = mergedActions(own, sets);
2022
+ const verified = verifyManifest(candidate(built, entries.list(), {}));
2023
+ const refusal = refusalOf(verified, "boot");
2024
+ if (refusal !== void 0) {
2025
+ functionIds = void 0;
2026
+ throw new Error(refusal);
1356
2027
  }
1357
- return () => {
1358
- handlers.delete(handler);
1359
- if (handlers.size === 0) end();
2028
+ report = verified;
2029
+ defaults = NO_DEFAULTS;
2030
+ inForce2 = built;
2031
+ dropMemos();
2032
+ memo.drop();
2033
+ for (const warning2 of charter.warnings) console.warn(`[moss] charter: ${warning2}`);
2034
+ const warning = functionsWarning(written);
2035
+ if (warning !== void 0) console.warn(warning);
2036
+ };
2037
+ const grantedFunctionsOf = (roles) => (names) => resolvePrincipal(shipped.charter, names, roles, "functions");
2038
+ const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
2039
+ const heldWithGenerated = async (held, versions, who, shell, whose) => {
2040
+ let replayable;
2041
+ let catalog;
2042
+ const reads = new Map([...defaults.reads, ...readsHeldTo === void 0 ? [] : await readsInForce(versions, readsHeldTo, whose)]);
2043
+ const checks = {
2044
+ kit: kitOf2(shell),
2045
+ entryOf: (fingerprint) => {
2046
+ const read2 = reads.get(fingerprint);
2047
+ return entries.byFingerprint().get(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
2048
+ },
2049
+ replayable: () => replayable ??= (async () => /* @__PURE__ */ new Set([...await who.replayable?.() ?? [], ...reads.keys()]))(),
2050
+ mayCall: (name) => who.roles !== void 0 && resolvePrincipal(shipped.charter, [name], who.roles, "functions").has(name),
2051
+ catalog: () => catalog ??= [...Object.values(held.actions).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1360
2052
  };
2053
+ const passed = await generatedInForce(versions, checks, whose);
2054
+ const stored = actionsWithStoredLayouts(passed.actions);
2055
+ const all = Object.keys(passed.actions).length === 0 ? held : { actions: { ...held.actions, ...stored.actions }, layouts: { ...held.layouts, ...stored.layouts } };
2056
+ return { all, fragments: passed.fragments, heldTo: { layouts: heldTo(all, shell), generated: checks, ...readsHeldTo !== void 0 ? { reads: readsHeldTo } : {} } };
1361
2057
  };
1362
- const handedOver = () => {
1363
- setTimeout(() => {
1364
- if (handlers.size === 0) end();
1365
- }, 0);
2058
+ const listeners = /* @__PURE__ */ new Set();
2059
+ const listenersFor = /* @__PURE__ */ new Set();
2060
+ const kinds = readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"];
2061
+ const sessionDeps = (principal, callerOf, shell) => ({
2062
+ whose: "of yours",
2063
+ kinds,
2064
+ holder: principal === null ? void 0 : async () => {
2065
+ await publishedNow();
2066
+ const caller = await callerOf();
2067
+ const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
2068
+ return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
2069
+ },
2070
+ written: () => {
2071
+ if (principal !== null) for (const listener of [...listenersFor]) tell(listener, principal);
2072
+ }
2073
+ });
2074
+ let pointer;
2075
+ const memo = createPublishedMemo();
2076
+ const defaultsHeldTo = () => ({
2077
+ kit: kitOf2(),
2078
+ entryOf: (fingerprint) => entries.byFingerprint().get(fingerprint),
2079
+ fingerprints: () => entries.byFingerprint().keys(),
2080
+ reads: readsHeldTo,
2081
+ built: mergedActions(own, sets),
2082
+ candidate: (actions, fragments) => candidate(actions, entries.list(), fragments)
2083
+ });
2084
+ const applyPublished = async (versions) => {
2085
+ const over = sets;
2086
+ const { passed, reads, verified } = await checkedDefaults(versions, defaultsHeldTo(), "published for everybody");
2087
+ if (sets !== over) return applyPublished(versions);
2088
+ const refusal = refusalOf(verified, "boot");
2089
+ if (refusal !== void 0) memo.sayOnce(`[moss] what is published for everybody is left out, and the build\u2019s copies stand: ${refusal}`);
2090
+ const next = refusal === void 0 ? { actions: passed.actions, fragments: passed.fragments, reads } : { ...NO_DEFAULTS, reads };
2091
+ if (!hasDefaults(next) && !hasDefaults(defaults)) return;
2092
+ defaults = next;
2093
+ if (refusal === void 0) report = verified;
2094
+ inForce2 = mergedActions(own, sets, defaults.actions);
2095
+ dropMemos();
2096
+ };
2097
+ const publishedNow = () => {
2098
+ const held = memo.held();
2099
+ if (held !== void 0) return held;
2100
+ const read2 = (async () => {
2101
+ const versions = await config.published?.() ?? [];
2102
+ await applyPublished(versions);
2103
+ return versions;
2104
+ })();
2105
+ memo.keep(read2);
2106
+ read2.catch(memo.drop);
2107
+ return read2;
1366
2108
  };
1367
- return { live, onChange, handedOver, end };
1368
- };
1369
-
1370
- // src/data/routes.ts
1371
- var createVexRoutes = (deps) => {
1372
- const routes = new Hono();
1373
- routes.use(
1374
- "/api/*",
1375
- (c, next) => deps.writes.within(
1376
- writeRequestOf((name) => c.req.header(name)),
1377
- () => next()
1378
- )
1379
- );
1380
- const mount = (path, entities) => {
1381
- routes.route(
1382
- path,
1383
- vex({
1384
- engine: deps.engine,
1385
- ...entities !== void 0 ? { entities: [...entities] } : {},
1386
- locked: true,
1387
- getScope: deps.scope,
1388
- getPolicy: deps.policy,
1389
- getPolicyForReach: deps.policyAtReach,
1390
- ...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
1391
- mutations: { client: deps.db, onWrite: deps.writes.report }
1392
- })
1393
- );
2109
+ const applySets = (arrived, announce) => {
2110
+ const next = new Map([...sets, ...arrived]);
2111
+ const actions = mergedActions(own, next, defaults.actions);
2112
+ const verified = verifyManifest(candidate(actions));
2113
+ const refusal = refusalOf(verified, "refresh");
2114
+ if (refusal !== void 0) throw new Error(refusal);
2115
+ for (const set of arrived.values()) freezeDeep(set);
2116
+ sets = next;
2117
+ inForce2 = actions;
2118
+ report = verified;
2119
+ dropMemos();
2120
+ for (const listener of [...listeners]) tell(listener);
2121
+ if (announce) pointer?.bump();
1394
2122
  };
1395
- mount("/api/vex");
1396
- for (const [name, resource] of Object.entries(deps.resources ?? {})) {
1397
- mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
1398
- }
1399
- return routes;
1400
- };
1401
- var createIntentAnswers = (deps) => {
1402
- const engines = /* @__PURE__ */ new WeakMap();
1403
- const engineFor = (writers) => {
1404
- const kept = engines.get(writers);
1405
- if (kept !== void 0) return kept;
1406
- const { adapter, schema } = deps;
1407
- const created = (async () => {
1408
- const engine = createQueryEngine({
1409
- adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
1410
- cache: deps.cache,
1411
- generateDsl: writers.generateDsl,
1412
- mapToShape: writers.mapToShape,
1413
- ...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
1414
- ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
1415
- });
1416
- await engine.introspect();
1417
- return engine;
1418
- })();
1419
- engines.set(writers, created);
1420
- return created;
2123
+ const reload = async () => {
2124
+ const read2 = [];
2125
+ for (const [source, load] of loaders) read2.push([source, await load()]);
2126
+ memo.drop();
2127
+ applySets(new Map(read2), false);
1421
2128
  };
1422
- return async (writers, asked, caller) => (await engineFor(writers)).execute({ intent: asked.intent, shape: asked.shape, context: asked.context ?? {} }, { scope: caller.scope, scopePolicy: caller.policy });
1423
- };
1424
-
1425
- // src/data/data.ts
1426
- var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
1427
- var prepareEngine = async (config) => {
1428
- await migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
1429
- const grammars = await createGrammarUpgrader({ grammars: config.grammars });
1430
- const layer = await createDataLayer(config);
1431
- return {
1432
- grammars,
1433
- engine: layer.engine,
1434
- grants: layer.grants,
1435
- adapter: layer.adapter,
1436
- upgradeStore: async (store) => {
1437
- await upgradeStore(config.pool, store, grammars);
1438
- }
2129
+ const takeEntries = async (source, handed) => {
2130
+ owners.assertAppOwned(source);
2131
+ const misfits = entryMisfits(handed);
2132
+ if (misfits.length > 0) throw new Error(["Refresh refused \u2014 entries that do not parse:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
2133
+ const compiled = await compileEntries(handed);
2134
+ const verified = verifyManifest(candidate(inForce2, entries.withSet(source, handed)));
2135
+ const refusal = refusalOf(verified, "refresh");
2136
+ if (refusal !== void 0) throw new Error(refusal);
2137
+ freezeDeep(handed);
2138
+ entries.takeSet(source, handed, compiled);
2139
+ report = verified;
2140
+ for (const listener of [...listeners]) tell(listener);
2141
+ pointer?.bump();
1439
2142
  };
1440
- };
1441
- var lazyIntentAnswers = (prepared, config) => {
1442
- const { engine } = prepared;
1443
- let answers;
1444
- const answering = () => {
1445
- if (answers !== void 0) return answers;
1446
- const schema = engine.getSchema();
1447
- if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
1448
- answers = createIntentAnswers({
1449
- adapter: prepared.adapter,
1450
- schema,
1451
- cache: engine.cache,
1452
- ...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
1453
- ...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
1454
- });
1455
- return answers;
2143
+ let entriesTaken = Promise.resolve();
2144
+ return {
2145
+ actions: () => inForce2,
2146
+ entries: entries.list,
2147
+ verify: (actions) => verifyManifest(candidate(actions)),
2148
+ report: () => report,
2149
+ replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
2150
+ // In turn: a set is compiled before it is taken, and of two handed over
2151
+ // the later has to be the one in force.
2152
+ replaceEntries: (source, handed) => {
2153
+ const taken = entriesTaken.then(() => takeEntries(source, handed));
2154
+ entriesTaken = taken.catch(() => void 0);
2155
+ return taken;
2156
+ },
2157
+ cacheEntry: async (fingerprint, scope) => {
2158
+ const shippedEntry = (await entries.compiled()).get(fingerprint);
2159
+ if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0) return shippedEntry;
2160
+ const userId = scope["userId"];
2161
+ if (typeof userId === "string" && userId !== NOBODY_USER_ID) {
2162
+ const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
2163
+ if (newest !== void 0 && newest.body !== null && newest.unread === void 0) return answeredRead(fingerprint, newest.body);
2164
+ }
2165
+ await publishedNow();
2166
+ const everybodys = defaults.reads.get(fingerprint);
2167
+ return everybodys === void 0 ? void 0 : compiledRead(fingerprint, everybodys);
2168
+ },
2169
+ cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
2170
+ claim: (source, owner) => {
2171
+ owners.claim(source, owner, sets.has(source) || entries.holdsSet(source));
2172
+ return {
2173
+ replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
2174
+ setLoader: (load) => {
2175
+ loaders.set(source, load);
2176
+ if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
2177
+ }
2178
+ };
2179
+ },
2180
+ refresh: () => applySets(/* @__PURE__ */ new Map(), true),
2181
+ functionsWritten,
2182
+ watch: () => {
2183
+ const where = config.pointer;
2184
+ if (pointer !== void 0 || where === void 0) return;
2185
+ pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
2186
+ },
2187
+ onChange: (listener) => {
2188
+ listeners.add(listener);
2189
+ return () => {
2190
+ listeners.delete(listener);
2191
+ };
2192
+ },
2193
+ addCatalogFilter: (filter) => {
2194
+ catalogFilters.push(filter);
2195
+ roleMemo.drop();
2196
+ },
2197
+ catalogFor: roleMemo.catalogFor,
2198
+ artifactsFor: async (shell, { principal, roles, installed, saved, replayable, drafted }) => {
2199
+ const own2 = saved === void 0 || principal === null ? [] : await saved.inForce();
2200
+ if (saved !== void 0 && principal !== null) usage.touch(principal, own2, saved);
2201
+ const versions = own2.length === 0 && drafted === void 0 ? [] : laidOver(own2, drafted);
2202
+ const everybodysVersions = await publishedNow();
2203
+ const whose = `of ${principal ?? "nobody"}`;
2204
+ const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2205
+ const drawable = theirOwn.heldTo.layouts;
2206
+ const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
2207
+ const variants = roleMemo.variantsFor(roles);
2208
+ const underVariants = { ...drawable, actionAt: (ref) => variants.has(actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
2209
+ const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", heldTo: underVariants, say: memo.sayOnce });
2210
+ const laidOverShell = { ...drawableIn(defaults.fragments, kitOf2(shell), memo.sayOnce), ...theirOwn.fragments };
2211
+ const fragments = Object.keys(laidOverShell).length === 0 ? shell.fragments : { ...shell.fragments, ...laidOverShell };
2212
+ const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
2213
+ const layoutStore = { ...shell.layoutStore, ...ofShell, ...theirOwn.all.layouts, ...everybodys, ...theirs2 };
2214
+ return {
2215
+ actions: theirOwn.all.actions,
2216
+ ...named,
2217
+ slottedCanvases: slottedCanvases(shell.canvases, [...Object.values(layoutStore), ...Object.values(fragments ?? {}).map((fragment) => fragment.layout)]),
2218
+ grantedFunctions: grantedFunctionsOf(roles),
2219
+ layoutStore,
2220
+ ...fragments !== void 0 ? { fragments } : {},
2221
+ entries: entries.byFingerprint(),
2222
+ components: components.of(shell)
2223
+ };
2224
+ },
2225
+ sessionArtifacts: (principal, callerOf) => savedArtifacts(sessionDeps(principal, callerOf)),
2226
+ draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
2227
+ // Held to every action in force with the layout it is built with: who holds
2228
+ // which is asked when a shell is built for them.
2229
+ publishedArtifacts: (saved, publisher) => savedArtifacts({
2230
+ whose: "published for everybody",
2231
+ kinds,
2232
+ holder: async () => {
2233
+ const who = await publisher();
2234
+ return { saved, heldTo: async (inForce3) => (await heldWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).heldTo };
2235
+ },
2236
+ defaults: {
2237
+ verify: async (versions, inForce3) => {
2238
+ const kept = inForce3.filter((held) => !versions.some((version) => version.kind === held.kind && version.id === held.id));
2239
+ const asked = versions.map((version) => ({ ...version, save: "", createdAt: "" }));
2240
+ const refusal = refusalOf((await checkedDefaults([...kept, ...asked], defaultsHeldTo(), void 0)).verified, "publish");
2241
+ if (refusal !== void 0) throw new Error(refusal);
2242
+ }
2243
+ },
2244
+ written: () => {
2245
+ memo.drop();
2246
+ for (const listener of [...listeners]) tell(listener);
2247
+ pointer?.bump();
2248
+ }
2249
+ }),
2250
+ readPublished: async () => {
2251
+ memo.drop();
2252
+ await publishedNow();
2253
+ },
2254
+ onChangeFor: (listener) => {
2255
+ listenersFor.add(listener);
2256
+ return () => {
2257
+ listenersFor.delete(listener);
2258
+ };
2259
+ },
2260
+ generation: () => pointer?.current() ?? -1,
2261
+ stop: () => pointer?.stop()
1456
2262
  };
1457
- return answering;
1458
2263
  };
1459
- var tablesByFeature = (config) => (feature) => {
1460
- const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
1461
- if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
1462
- return kept.names;
2264
+ var theirs = { match: "principal", to: "userId" };
2265
+ var stamped = { set: "principal", to: "userId" };
2266
+ var MADE_BY = "artifactSavedBy";
2267
+ var madeBy = { set: "created_by", to: MADE_BY };
2268
+ var SAVE_ROW_RULES = {
2269
+ artifacts: { read: [theirs], write: [theirs, stamped] },
2270
+ artifact_saves: { read: [theirs], write: [theirs, stamped, madeBy] }
1463
2271
  };
1464
- var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
1465
- const own = tablesOf(feature);
1466
- if (store.schema !== void 0) {
2272
+ var EVERYBODY = "*";
2273
+ var callerScope = (scope) => {
2274
+ if (scope["userId"] === EVERYBODY) {
1467
2275
  throw new Error(
1468
- `moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
2276
+ `moss: a caller\u2019s \`userId\` is "${EVERYBODY}", and that is whose the rows published for everybody are. No caller is it: the app\u2019s sign-in or its \`scope\` answers another.`
1469
2277
  );
1470
2278
  }
1471
- if (!own.includes(store.table)) {
1472
- throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
2279
+ if (Object.hasOwn(scope, MADE_BY)) {
2280
+ throw new Error(`moss: a caller\u2019s scope carries \`${MADE_BY}\`. Who made a save is written from that value, and it is moss\u2019s to say: the app\u2019s \`scope\` names its own otherwise.`);
1473
2281
  }
1474
- await prepared.upgradeStore(store);
1475
- };
1476
- var createDataWith = (prepared, config) => {
1477
- const { grammars, engine, grants } = prepared;
1478
- const governed = { charter: config.charter, behaviors: config.behaviors };
1479
- const policies = createPolicies({ ...governed, grants });
1480
- const emit = emitterOf(config.telemetry);
1481
- const onExecute = emit === void 0 ? void 0 : (record2) => emit(vexRecordToSpan(record2));
1482
- const writes = createWriteNotifier();
1483
- const answering = lazyIntentAnswers(prepared, config);
1484
- const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
1485
- const tablesOf = tablesByFeature(config);
1486
- let pointerEntries;
1487
- const pointerReplay = () => {
1488
- pointerEntries ??= ownEntries(POINTER, void 0);
1489
- return pointerEntries;
1490
- };
1491
- return {
1492
- grants,
1493
- grammars,
1494
- seed: (entries) => seedCache(engine.cache, entries),
1495
- fingerprints: async () => await engine.cache.keys?.() ?? [],
1496
- policyOf: policies.of,
1497
- // Compiled afresh and not taken from the kept ones: the caller owns its
1498
- // copy, and nothing it does to it reaches a policy a request is served under.
1499
- policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
1500
- fingerprintsFor: async (who) => (await handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry2) => entry2.fingerprint).sort(),
1501
- executeAs: createExecuteAs({
1502
- engine,
1503
- db: config.db,
1504
- policyFor: (roles) => policies.of(callerOfRoles(roles)),
1505
- policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
1506
- ...onExecute !== void 0 ? { onExecute } : {}
1507
- }),
1508
- answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
1509
- ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
1510
- routes: (routing) => createVexRoutes({
1511
- engine,
1512
- db: config.db,
1513
- resources: routing.resources,
1514
- scope: routing.scope,
1515
- policy: (c) => policies.of(routing.caller(c)),
1516
- policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
1517
- ...onExecute !== void 0 ? { onExecute } : {},
1518
- writes
1519
- }),
1520
- upgradeStore: createUpgradeStore(prepared, tablesOf),
1521
- onWrite: writes.subscribe,
1522
- pointer: createPointer(pointerReplay),
1523
- dropOnChange: (changed) => {
1524
- changed(policies.drop);
1525
- }
1526
- };
1527
- };
1528
- var createData = async (config) => createDataWith(await prepareEngine(config), config);
1529
- var DEFAULT_ROOT = '<div id="root"></div>';
1530
- var embedSnapshot = (snapshot, principal, path) => {
1531
- const { frame, trees, seed, live } = snapshot;
1532
- const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
1533
- const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1534
- return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
1535
- };
1536
- var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
1537
- var rootHolding = (root) => {
1538
- const closing = root.lastIndexOf("</");
1539
- if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
1540
- return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
2282
+ return scope;
2283
+ };
2284
+ var PAGE = 500;
2285
+ var VERSION_COLUMNS = ["save", "kind", "id", "body", "grammar", "copied_from", "created_at"];
2286
+ var laterThanHeld = {
2287
+ and: [
2288
+ { eq: ["artifacts.kind", "held.kind"] },
2289
+ { eq: ["artifacts.id", "held.id"] },
2290
+ { or: [{ gt: ["artifacts.created_at", "held.created_at"] }, { and: [{ eq: ["artifacts.created_at", "held.created_at"] }, { gt: ["artifacts.save", "held.save"] }] }] }
2291
+ ]
1541
2292
  };
1542
- var escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1543
- var renderDocument = async (config) => {
1544
- const { server, template, request, draw } = config;
1545
- const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;
1546
- const root = config.root ?? DEFAULT_ROOT;
1547
- const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
1548
- if (!template.includes(root)) return undrawn;
1549
- const holding = rootHolding(root);
1550
- if (holding === void 0) {
1551
- console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
1552
- return undrawn;
2293
+ var afterHeld = {
2294
+ or: [{ gt: ["held.kind", { $context: "after_kind" }] }, { and: [{ eq: ["held.kind", { $context: "after_kind" }] }, { gt: ["held.id", { $context: "after_id" }] }] }]
2295
+ };
2296
+ var inForce = {
2297
+ fingerprint: "artifactory/in-force",
2298
+ intent: "The latest version of each of the caller\u2019s artifacts, a page at a time",
2299
+ dsl: {
2300
+ from: [{ as: "held", query: { from: ["artifacts"], fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`) } }],
2301
+ fields: VERSION_COLUMNS.map((column) => `held.${column}`),
2302
+ filter: { and: [{ not: { exists: { from: ["artifacts"], filter: laterThanHeld } } }, afterHeld] },
2303
+ sort: [
2304
+ { field: "held.kind", dir: "asc" },
2305
+ { field: "held.id", dir: "asc" }
2306
+ ],
2307
+ limit: PAGE
1553
2308
  }
1554
- try {
1555
- const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
1556
- const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
1557
- const principal = token === null ? null : await server.principalOf(token);
1558
- const route = server.page(request.path);
1559
- const host = route?.host ?? server.shells;
1560
- if (host === void 0) return undrawn;
1561
- const snapshot = await host.snapshot(principal === null ? null : token, principal, {
1562
- ...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
1563
- ...route !== void 0 ? { inputs: route.inputs } : {}
1564
- });
1565
- const screen = await draw(snapshot);
1566
- const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
1567
- const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
1568
- const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
1569
- for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
1570
- const html = placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
1571
- return {
1572
- html,
1573
- ...head !== void 0 ? { head } : {},
1574
- headers: documentHeaders(principal),
1575
- drawn: true,
1576
- principal,
1577
- ...route !== void 0 ? { page: route.name } : {},
1578
- live: snapshot.live,
1579
- why: snapshot.why,
1580
- drawnWith: snapshot.drawnWith,
1581
- settled: snapshot.settled
1582
- };
1583
- } catch (error) {
1584
- console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
1585
- return undrawn;
2309
+ };
2310
+ var history = {
2311
+ fingerprint: "artifactory/history",
2312
+ intent: "The versions of one of the caller\u2019s artifacts, the newest first",
2313
+ dsl: {
2314
+ from: ["artifacts"],
2315
+ fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`),
2316
+ filter: {
2317
+ and: [
2318
+ { eq: ["artifacts.kind", { $context: "kind" }] },
2319
+ { eq: ["artifacts.id", { $context: "id" }] },
2320
+ { optional: { key: "save", then: { eq: ["artifacts.save", { $context: "save" }] } } }
2321
+ ]
2322
+ },
2323
+ sort: [
2324
+ { field: "artifacts.created_at", dir: "desc" },
2325
+ { field: "artifacts.save", dir: "desc" }
2326
+ ],
2327
+ limit: PAGE
1586
2328
  }
1587
2329
  };
1588
-
1589
- // src/documents/pages.ts
1590
- var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
1591
- var compile = (name, page) => {
1592
- if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
1593
- const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
1594
- for (const segment of segments) {
1595
- if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
1596
- throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
2330
+ var save = {
2331
+ fingerprint: "artifactory/save",
2332
+ intent: "Keep a save of the caller\u2019s and the versions it holds",
2333
+ mutation: [
2334
+ { op: "insert", table: "artifact_saves", values: { id: { $context: "save" } } },
2335
+ {
2336
+ op: "insertEach",
2337
+ table: "artifacts",
2338
+ items: { $context: "versions" },
2339
+ values: { save: { $context: "save" }, kind: { $item: "kind" }, id: { $item: "id" }, body: { $item: "body" }, grammar: { $item: "grammar" }, copied_from: { $item: "copied_from" } }
1597
2340
  }
1598
- }
1599
- const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
1600
- const twice = named.find((param, index) => named.indexOf(param) !== index);
1601
- if (twice !== void 0) {
1602
- throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
1603
- }
1604
- if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
1605
- throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
1606
- }
1607
- return { name, segments };
2341
+ ]
1608
2342
  };
1609
- var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
1610
- const other = b.segments[index];
1611
- return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
1612
- });
1613
- var createPageRouter = (pages) => {
1614
- const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
1615
- for (const [index, page] of compiled.entries()) {
1616
- const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
1617
- if (other !== void 0) {
1618
- throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
2343
+ var touch = {
2344
+ fingerprint: "artifactory/touch",
2345
+ intent: "Mark one of the caller\u2019s artifacts as used now",
2346
+ mutation: [
2347
+ {
2348
+ op: "update",
2349
+ table: "artifacts",
2350
+ set: { last_used_at: { $context: "at" } },
2351
+ where: { and: [{ eq: ["artifacts.kind", { $context: "kind" }] }, { eq: ["artifacts.id", { $context: "id" }] }] }
1619
2352
  }
2353
+ ]
2354
+ };
2355
+ var SAVE_ENTRIES = [inForce, history, save, touch];
2356
+ var RowSchema2 = z.object({
2357
+ save: z.string(),
2358
+ kind: z.string(),
2359
+ id: z.string(),
2360
+ body: z.unknown(),
2361
+ grammar: z.record(z.string(), z.coerce.number()).catch({}),
2362
+ copied_from: z.string().nullish(),
2363
+ // Drivers hand back a Date, an ISO string or a number for the same column.
2364
+ created_at: z.union([z.date(), z.string(), z.number()]).transform((at) => new Date(at).toISOString())
2365
+ });
2366
+ var upgradedAs = (grammarKind) => (upgrader, body, stamp) => upgrader.upgrade(body, { kind: grammarKind, stamp }).document;
2367
+ var upgradedBody = {
2368
+ layout: upgradedLayoutBody,
2369
+ action: upgradedAs("nisc.nova/action"),
2370
+ fragment: upgradedAs("nisc.nova/fragment"),
2371
+ read: upgradedAs("nisc.vex/entry")
2372
+ };
2373
+ var versionOf = (row, upgrader) => {
2374
+ const version = { save: row.save, kind: row.kind, id: row.id, copiedFrom: row.copied_from ?? null, createdAt: row.created_at };
2375
+ const upgrade = upgradedBody[row.kind];
2376
+ if (row.body === null || row.body === void 0 || upgrade === void 0) return { ...version, body: row.body ?? null };
2377
+ try {
2378
+ return { ...version, body: upgrade(upgrader, row.body, row.grammar) };
2379
+ } catch (error) {
2380
+ if (!(error instanceof StrataError)) throw error;
2381
+ return { ...version, body: row.body, unread: error.message.split("\n")[0] ?? error.code };
1620
2382
  }
1621
- return {
1622
- match: (path) => {
1623
- const parts = segmentsOf(path);
1624
- for (const page of compiled) {
1625
- if (page.segments.length !== parts.length) continue;
1626
- const params = {};
1627
- let matches = true;
1628
- for (const [index, segment] of page.segments.entries()) {
1629
- const part = parts[index];
1630
- if (part === void 0) {
1631
- matches = false;
1632
- break;
1633
- }
1634
- if ("param" in segment) {
1635
- try {
1636
- params[segment.param] = decodeURIComponent(part);
1637
- } catch {
1638
- matches = false;
1639
- break;
1640
- }
1641
- } else if (segment.literal !== part) {
1642
- matches = false;
1643
- break;
1644
- }
1645
- }
1646
- if (matches) return { name: page.name, params };
2383
+ };
2384
+ var savedRowsOver = (replay, upgrader) => {
2385
+ const versionsIn = (answered) => z.array(RowSchema2).parse(answered).map((row) => versionOf(row, upgrader));
2386
+ const rows = (scope) => {
2387
+ const everyVersionInForce = async (after) => {
2388
+ const page = versionsIn(await replay(inForce.fingerprint, { after_kind: after?.kind ?? "", after_id: after?.id ?? "" }, scope));
2389
+ const last = page.at(-1);
2390
+ return page.length < PAGE || last === void 0 ? page : [...page, ...await everyVersionInForce(last)];
2391
+ };
2392
+ return {
2393
+ inForce: () => everyVersionInForce(),
2394
+ history: async (kind, id, saved) => versionsIn(await replay(history.fingerprint, { kind, id, ...saved === void 0 ? {} : { save: saved } }, scope)),
2395
+ write: async (saved) => {
2396
+ const versions = saved.versions.map((version) => ({ kind: version.kind, id: version.id, body: version.body, grammar: upgrader.stamp, copied_from: version.copiedFrom }));
2397
+ await replay(save.fingerprint, { save: saved.id, versions }, scope);
2398
+ },
2399
+ touch: async (artifacts, at) => {
2400
+ for (const { kind, id } of artifacts) await replay(touch.fingerprint, { kind, id, at }, scope);
1647
2401
  }
1648
- return void 0;
1649
- }
2402
+ };
2403
+ };
2404
+ return {
2405
+ of: (scope) => rows({ ...callerScope(scope), [MADE_BY]: scope["userId"] }),
2406
+ published: (by) => rows({ userId: EVERYBODY, ...by === void 0 ? {} : { [MADE_BY]: by } })
1650
2407
  };
1651
- };
1652
- var exportDocuments = async (config) => {
1653
- const { paths, ...rest } = config;
1654
- const out = [];
1655
- for (const path of paths) {
1656
- const page = await renderDocument({ ...rest, request: { path, cookie: null } });
1657
- out.push({
1658
- path,
1659
- html: page.html,
1660
- ...page.page !== void 0 ? { page: page.page } : {},
1661
- ...page.head !== void 0 ? { head: page.head } : {},
1662
- drawn: page.drawn,
1663
- // A page that could not be drawn is not taken to be finished.
1664
- live: page.live ?? true,
1665
- why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
1666
- drawnWith: page.drawnWith ?? [],
1667
- settled: page.settled ?? false
1668
- });
1669
- }
1670
- return out;
1671
2408
  };
1672
2409
 
1673
2410
  // src/socket/revalidation.ts
@@ -2003,7 +2740,7 @@ var seamsFor = (feature, owned, { app, runtime, server, operator, registered, id
2003
2740
  addCatalogFilter: running.addCatalogFilter,
2004
2741
  charter: app.charter,
2005
2742
  components: app.shell?.components ?? {},
2006
- layoutMisfits: (layout2) => layoutMisfits(layout2, kitOf(app)),
2743
+ layoutMisfits: (layout) => layoutMisfits(layout, kitOf(app)),
2007
2744
  endlessChains,
2008
2745
  ownEntries: (entries) => data.ownEntries(feature.name, entries),
2009
2746
  grammars: data.grammars,
@@ -2029,7 +2766,7 @@ var shellNeedOf = (definition, entries) => {
2029
2766
  const why = [];
2030
2767
  const drawnWith = [];
2031
2768
  if (facts.gestures) why.push("a person can act on it");
2032
- if (facts.opaqueLayout) why.push("its layout is kept in the store, so what can be pressed on it is not readable");
2769
+ if (facts.opaqueLayout) why.push("its layout is the name of a stored layout, so what can be pressed on it is not readable");
2033
2770
  for (const channel of facts.listens) why.push(`it waits on the channel "${channel}"`);
2034
2771
  for (const use of facts.endpoints) {
2035
2772
  if (!use.onOpen && !use.later) continue;
@@ -2038,12 +2775,12 @@ var shellNeedOf = (definition, entries) => {
2038
2775
  continue;
2039
2776
  }
2040
2777
  const fingerprint = fingerprintOf(use.request);
2041
- const entry2 = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
2042
- if (entry2 !== void 0 && !("mutation" in entry2) && entry2.refresh === "reactive") {
2043
- why.push(`its read "${use.name}" keeps answering (${entry2.fingerprint} is reactive)`);
2778
+ const entry = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
2779
+ if (entry !== void 0 && !("mutation" in entry) && entry.refresh === "reactive") {
2780
+ why.push(`its read "${use.name}" keeps answering (${entry.fingerprint} is reactive)`);
2044
2781
  continue;
2045
2782
  }
2046
- if (fingerprint !== void 0 && entry2 === void 0) {
2783
+ if (fingerprint !== void 0 && entry === void 0) {
2047
2784
  why.push(`its read "${use.name}" replays "${fingerprint}", which the manifest does not carry \u2014 whether it keeps answering is not readable`);
2048
2785
  continue;
2049
2786
  }
@@ -2090,7 +2827,7 @@ var needOf = (live, principal, kept) => {
2090
2827
  for (const instance of canvas.stack) {
2091
2828
  const definition = live.shell.getRuntime(instance.id)?.definition;
2092
2829
  if (definition === void 0) continue;
2093
- const need = shellNeedOf(definition, entries);
2830
+ const need = shellNeedOf(withLayoutInPlace(definition, live.shell.layoutStore), entries);
2094
2831
  for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
2095
2832
  for (const read2 of need.drawnWith) drawnWith.push(read2);
2096
2833
  }
@@ -2136,31 +2873,65 @@ var sameDocument = (one, other) => one === other || JSON.stringify(one) === JSON
2136
2873
  var takeLayouts = (live, made) => {
2137
2874
  const taken = live.layouts;
2138
2875
  const answered = layoutsOf(made);
2139
- for (const [ref, layout2] of Object.entries(answered.layoutStore)) {
2140
- if (!sameDocument(taken.layoutStore[ref], layout2)) live.shell.setLayout(ref, layout2);
2876
+ for (const [ref, layout] of Object.entries(answered.layoutStore)) {
2877
+ if (!sameDocument(taken.layoutStore[ref], layout)) live.shell.setLayout(ref, layout);
2878
+ }
2879
+ for (const ref of Object.keys(taken.layoutStore)) {
2880
+ if (!Object.hasOwn(answered.layoutStore, ref)) live.shell.layoutStore.delete(ref);
2141
2881
  }
2142
2882
  for (const [id, fragment] of Object.entries(answered.fragments)) {
2143
- if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerFragment({ ...fragment, id });
2883
+ if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerAction({ ...fragment, id });
2884
+ }
2885
+ for (const id of Object.keys(taken.fragments)) {
2886
+ if (!Object.hasOwn(answered.fragments, id)) live.shell.removeAction(id);
2144
2887
  }
2145
- if (answered.frame !== void 0 && !sameDocument(taken.frame, answered.frame)) live.shell.setCanvasLayout(answered.frame);
2146
2888
  live.layouts = answered;
2147
2889
  };
2890
+ var takeCanvases = (live, made) => {
2891
+ const slotted = new Set(made.slottedCanvases);
2892
+ for (const id of live.slottedCanvases) if (!slotted.has(id)) live.shell.removeCanvas(id);
2893
+ live.slottedCanvases = slotted;
2894
+ };
2895
+ var takeComposition = (live, made) => {
2896
+ for (const [name, contract] of Object.entries(made.components)) {
2897
+ if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
2898
+ }
2899
+ for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
2900
+ for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
2901
+ live.actionIds = new Set(Object.keys(made.actions));
2902
+ live.entries = made.entries;
2903
+ takeLayouts(live, made);
2904
+ takeCanvases(live, made);
2905
+ holdGranted(live.functions, made.grantedFunctions);
2906
+ };
2907
+ var adoptDraft = async (host, live, next) => {
2908
+ for (; ; ) {
2909
+ const cell = host.living.get(live);
2910
+ if (cell === void 0 || cell.live !== live) throw new Error(SHELL_GONE);
2911
+ const changes = host.changes;
2912
+ const made = await host.config.composition(cell.principal, draftedIn(next));
2913
+ if (live.ended || cell.live !== live) throw new Error(SHELL_GONE);
2914
+ if (changes < cell.changes) continue;
2915
+ cell.changes = changes;
2916
+ live.draft = next;
2917
+ takeComposition(live, made);
2918
+ return;
2919
+ }
2920
+ };
2148
2921
  var adopt = (host, cell) => {
2149
2922
  const adopting = async () => {
2150
- if (cell.live.ended) return;
2923
+ const asked = cell.live;
2924
+ if (asked.ended) return;
2925
+ const drafted = asked.draft;
2151
2926
  const changes = host.changes;
2152
- const made = await host.config.composition(cell.principal);
2153
- const live = cell.live;
2154
- if (live.ended || changes <= cell.changes) return;
2155
- cell.changes = changes;
2156
- for (const [name, contract] of Object.entries(made.components)) {
2157
- if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
2927
+ const made = await host.config.composition(cell.principal, draftedIn(drafted));
2928
+ if (asked.ended || changes <= cell.changes) return;
2929
+ if (asked.draft !== drafted) {
2930
+ adopt(host, cell);
2931
+ return;
2158
2932
  }
2159
- for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
2160
- for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
2161
- live.actionIds = new Set(Object.keys(made.actions));
2162
- live.entries = made.entries;
2163
- takeLayouts(live, made);
2933
+ cell.changes = changes;
2934
+ takeComposition(asked, made);
2164
2935
  };
2165
2936
  adopting().catch((error) => {
2166
2937
  console.error(`[moss/shells] the shell of ${cell.principal ?? "nobody"} could not adopt what changed, and keeps what it held:`, error);
@@ -2170,6 +2941,10 @@ var adoptAll = (host) => {
2170
2941
  host.changes += 1;
2171
2942
  for (const cell of [...host.living.values()]) adopt(host, cell);
2172
2943
  };
2944
+ var adoptFor = (host, principal) => {
2945
+ host.changes += 1;
2946
+ for (const cell of shellsOf(host, principal)) adopt(host, cell);
2947
+ };
2173
2948
  var build = (host, asked, wanted = () => true) => {
2174
2949
  const changes = host.changes;
2175
2950
  const limit = host.config.limits?.endpointTimeoutMs ?? DEFAULT_BUILD_TIMEOUT_MS;
@@ -2294,7 +3069,8 @@ var createShellHost = (config) => {
2294
3069
  durable: /* @__PURE__ */ new Map(),
2295
3070
  building: /* @__PURE__ */ new Map(),
2296
3071
  living: /* @__PURE__ */ new Map(),
2297
- changes: 0
3072
+ changes: 0,
3073
+ adoptDraft: (live, next) => adoptDraft(host, live, next)
2298
3074
  };
2299
3075
  const reset = (cell) => resetCell(host, cell);
2300
3076
  const handedOut = {
@@ -2308,25 +3084,38 @@ var createShellHost = (config) => {
2308
3084
  deliver: deliverTo(host),
2309
3085
  list: () => rosterOf(host.durable),
2310
3086
  reset: (principal) => {
2311
- const theirs = shellsOf(host, principal);
2312
- for (const cell of theirs) reset(cell);
2313
- return theirs.length > 0;
3087
+ const theirs2 = shellsOf(host, principal);
3088
+ for (const cell of theirs2) reset(cell);
3089
+ return theirs2.length > 0;
2314
3090
  }
2315
3091
  };
2316
- return { host: handedOut, adopt: () => adoptAll(host), stop: startSweep(host) };
3092
+ return { host: handedOut, adopt: () => adoptAll(host), adoptFor: (principal) => adoptFor(host, principal), stop: startSweep(host) };
2317
3093
  };
2318
3094
 
2319
3095
  // src/server/hosts.ts
2320
- var hostConfig = (deps, shell2, kept) => {
3096
+ var hostConfig = (deps, shell, kept) => {
2321
3097
  const { app, runtime, identity, running, data } = deps;
3098
+ const callerOf = async (principal) => {
3099
+ const resolved = await identity.resolve(principal);
3100
+ return {
3101
+ resolved,
3102
+ roles: resolved.roles,
3103
+ installed: resolved.installed,
3104
+ saved: deps.savedAs(identity.composeScope(principal, resolved)),
3105
+ replayable: () => data.fingerprintsFor(resolved)
3106
+ };
3107
+ };
2322
3108
  return {
2323
- composition: async (principal) => {
2324
- const resolved = await identity.resolve(principal);
2325
- return { roles: resolved.roles, scope: resolved.scope, ...running.artifactsFor(shell2, resolved.roles, resolved.installed) };
3109
+ composition: async (principal, drafted) => {
3110
+ const { resolved, saved, ...held } = await callerOf(principal);
3111
+ const who = { principal, ...held, ...principal === null ? {} : { saved, ...drafted === void 0 ? {} : { drafted } } };
3112
+ return { roles: resolved.roles, scope: resolved.scope, ...await running.artifactsFor(shell, who) };
2326
3113
  },
3114
+ artifacts: (principal) => running.sessionArtifacts(principal, () => callerOf(principal)),
3115
+ draftSaving: (principal) => running.draftSavingFor(shell, principal, () => callerOf(principal)),
2327
3116
  hooks: {
2328
- ...shell2.inputs !== void 0 ? { inputs: shell2.inputs } : {},
2329
- ...shell2.seeds !== void 0 ? { seeds: shell2.seeds } : {},
3117
+ ...shell.inputs !== void 0 ? { inputs: shell.inputs } : {},
3118
+ ...shell.seeds !== void 0 ? { seeds: shell.seeds } : {},
2330
3119
  ...app.phrases !== void 0 ? { phrases: app.phrases } : {},
2331
3120
  ...app.functions !== void 0 ? { functions: app.functions } : {},
2332
3121
  ...app.onSession !== void 0 ? { onSession: app.onSession } : {},
@@ -2338,7 +3127,7 @@ var hostConfig = (deps, shell2, kept) => {
2338
3127
  wrapWire: deps.wrapWire,
2339
3128
  answerIntent: async (principal, writers, asked) => {
2340
3129
  const resolved = await identity.resolve(principal);
2341
- return data.answerIntent(writers, asked, resolved, identity.composeScope(principal, resolved));
3130
+ return data.answerIntent(writers, asked, resolved, callerScope(identity.composeScope(principal, resolved)));
2342
3131
  },
2343
3132
  ...deps.revokeSessions !== void 0 ? { revokeSessions: deps.revokeSessions } : {},
2344
3133
  ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
@@ -2349,12 +3138,24 @@ var hostConfig = (deps, shell2, kept) => {
2349
3138
  }
2350
3139
  };
2351
3140
  };
3141
+ var checkedOnce = (functions, written) => {
3142
+ let checked2 = false;
3143
+ return (session) => {
3144
+ const given = functions(session);
3145
+ if (!checked2) {
3146
+ written(given);
3147
+ checked2 = true;
3148
+ }
3149
+ return given;
3150
+ };
3151
+ };
2352
3152
  var buildShellHosts = (deps) => {
2353
3153
  const { app } = deps;
3154
+ const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: checkedOnce(app.functions, deps.running.functionsWritten) } };
2354
3155
  const pageManifests = app.pages ?? {};
2355
3156
  const pageRouter = createPageRouter(pageManifests);
2356
- const shells = app.shell !== void 0 ? createShellHost(hostConfig(deps, app.shell, true)) : void 0;
2357
- const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(deps, manifest, false))]));
3157
+ const shells = app.shell !== void 0 ? createShellHost(hostConfig(wired, app.shell, true)) : void 0;
3158
+ const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(wired, manifest, false))]));
2358
3159
  const owned = [...shells !== void 0 ? [shells] : [], ...pageHosts.values()];
2359
3160
  const every = owned.map((made) => made.host);
2360
3161
  return {
@@ -2368,9 +3169,17 @@ var buildShellHosts = (deps) => {
2368
3169
  return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
2369
3170
  },
2370
3171
  pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
3172
+ buildForNobody: async () => {
3173
+ if (app.functions === void 0) deps.running.functionsWritten([]);
3174
+ else await every[0]?.snapshot(null, null, { waitMs: 0 });
3175
+ await deps.running.readPublished();
3176
+ },
2371
3177
  adopt: () => {
2372
3178
  for (const made of owned) made.adopt();
2373
3179
  },
3180
+ adoptFor: (principal) => {
3181
+ for (const made of owned) made.adoptFor(principal);
3182
+ },
2374
3183
  // `map`, not `some`: each host is asked, whatever the one before answered.
2375
3184
  reset: (principal) => every.map((host) => host.reset(principal)).includes(true),
2376
3185
  deliver: (principal, channel, payload) => every.map((host) => host.deliver(principal, channel, payload)).includes(true),
@@ -2418,7 +3227,7 @@ var mountRoutes = (server, { app, session, credentials, identity, running, data
2418
3227
  "/",
2419
3228
  data.routes({
2420
3229
  resources: app.resources,
2421
- scope: (c) => identity.composeScope(c.get("principal"), c.get("resolved")),
3230
+ scope: (c) => callerScope(identity.composeScope(c.get("principal"), c.get("resolved"))),
2422
3231
  caller: (c) => c.get("resolved")
2423
3232
  })
2424
3233
  );
@@ -2475,7 +3284,7 @@ var operatorPrefix = (runtime) => {
2475
3284
  guardOperator(operator, { key: runtime.operatorKey ?? "", gate: runtime.operatorGate });
2476
3285
  return operator;
2477
3286
  };
2478
- var buildSignals = ({ fabric, identity, reset, deliver }) => {
3287
+ var buildSignals = ({ fabric, identity, reset, adopt: adopt2, deliver }) => {
2479
3288
  const origin = randomBytes(8).toString("hex");
2480
3289
  const applyInvalidateIdentity = (principal) => {
2481
3290
  const held = identity.invalidate(principal);
@@ -2489,7 +3298,8 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
2489
3298
  const publish = wireFabric(fabric, origin, {
2490
3299
  invalidateIdentity: applyInvalidateIdentity,
2491
3300
  invalidateTag: applyInvalidateTag,
2492
- nudge: applyNudge
3301
+ nudge: applyNudge,
3302
+ adopt: adopt2
2493
3303
  });
2494
3304
  return {
2495
3305
  invalidateIdentity: (principal) => {
@@ -2506,6 +3316,10 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
2506
3316
  applyNudge(principal, channel);
2507
3317
  publish({ kind: "nudge", principal, channel });
2508
3318
  },
3319
+ adopt: (principal) => {
3320
+ adopt2(principal);
3321
+ publish({ kind: "adopt", principal });
3322
+ },
2509
3323
  // The payload stays in this process. Across processes only the channel is
2510
3324
  // said, and a shell there reads again under its own policy.
2511
3325
  deliver: (principal, channel, payload) => {
@@ -2541,6 +3355,9 @@ var wireFabric = (fabric, origin, apply) => {
2541
3355
  case "nudge":
2542
3356
  apply.nudge(message.principal, message.channel);
2543
3357
  break;
3358
+ case "adopt":
3359
+ apply.adopt(message.principal);
3360
+ break;
2544
3361
  }
2545
3362
  } catch (err) {
2546
3363
  console.error("[moss:fabric] a remote signal failed to apply", err);
@@ -2564,6 +3381,15 @@ var createServerWith = async (app, runtime, dataOf) => {
2564
3381
  return assembleServer({ app, runtime, session, revokeSessions, data });
2565
3382
  };
2566
3383
  var createServer = (app, runtime) => createServerWith(app, runtime, buildData);
3384
+ var rowRulesBeside = (behaviors) => {
3385
+ const declared = Object.keys(SAVE_ROW_RULES).filter((table) => Object.hasOwn(behaviors ?? {}, table));
3386
+ if (declared.length > 0) {
3387
+ throw new Error(
3388
+ `moss: the app\u2019s \`behaviors\` say what a caller reads and writes of ${declared.map((table) => `"${table}"`).join(" and ")}. Those rows are whoever saved them: moss keeps every read and write of them to the caller\u2019s own, and an app does not say otherwise.`
3389
+ );
3390
+ }
3391
+ return SAVE_ROW_RULES;
3392
+ };
2567
3393
  var buildData = (app, runtime) => createData({
2568
3394
  pool: runtime.pool,
2569
3395
  db: runtime.db,
@@ -2576,6 +3402,7 @@ var buildData = (app, runtime) => createData({
2576
3402
  grammars: app.grammars,
2577
3403
  charter: app.charter,
2578
3404
  behaviors: app.behaviors,
3405
+ rowRules: rowRulesBeside(app.behaviors),
2579
3406
  telemetry: runtime.telemetry
2580
3407
  });
2581
3408
  var assembleServer = async (deps) => {
@@ -2588,25 +3415,36 @@ var assembleServer = async (deps) => {
2588
3415
  }
2589
3416
  };
2590
3417
  var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) => {
2591
- const running = await buildRunningManifest(app, runtime, data);
3418
+ const saved = savedRowsOver(await data.artifactEntries(SAVE_ENTRIES, SAVE_ROW_RULES), data.grammars);
3419
+ const running = await buildRunningManifest(app, runtime, data, saved);
2592
3420
  stops.push(running.stop);
3421
+ if (runtime.artifactsUnusedMs !== void 0) {
3422
+ if (!Number.isSafeInteger(runtime.artifactsUnusedMs) || runtime.artifactsUnusedMs < 2 * TOUCH_EVERY_MS) {
3423
+ throw new Error(
3424
+ `moss: \`runtime.artifactsUnusedMs\` is how long what a person generated may go unused before it is deleted: a whole number of milliseconds, at least ${2 * TOUCH_EVERY_MS} (two hours), or left out, and nothing is deleted.`
3425
+ );
3426
+ }
3427
+ stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs));
3428
+ }
2593
3429
  const identity = buildIdentity(app, runtime, data);
2594
3430
  stops.push(identity.stop);
2595
3431
  const server = new Hono();
2596
3432
  const registered = emptyRegister();
2597
3433
  mountRoutes(server, { app, session, credentials: registered.credentials, identity, running, data });
2598
- const hosts = buildShellHosts({ app, runtime, identity, running, data, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
3434
+ const hosts = buildShellHosts({ app, runtime, identity, running, data, savedAs: saved.of, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
2599
3435
  stops.push(hosts.stop);
2600
- const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, deliver: hosts.deliver });
3436
+ const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, adopt: hosts.adoptFor, deliver: hosts.deliver });
2601
3437
  running.onChange(() => {
2602
3438
  identity.invalidateAll();
2603
3439
  hosts.adopt();
2604
3440
  });
3441
+ running.onChangeFor(signals.adopt);
2605
3442
  const operator = operatorPrefix(runtime);
2606
3443
  await startFeatures(app.features ?? [], { app, runtime, server, operator, registered, identity, running, data });
2607
3444
  server.route("/operator", operator);
2608
3445
  subscribeReactions({ app, onWrite: data.onWrite, deliver: signals.deliver });
2609
3446
  running.watch();
3447
+ await running.readPublished();
2610
3448
  const socket = buildSocket({ runtime, session, identity, running, hosts });
2611
3449
  stops.push(socket.stop);
2612
3450
  return Object.assign(server, {
@@ -2614,10 +3452,21 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
2614
3452
  principalOf: async (token) => session(token),
2615
3453
  page: hosts.pageAt,
2616
3454
  pages: hosts.pages,
3455
+ checkFunctions: hosts.buildForNobody,
2617
3456
  ...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
2618
3457
  refresh: running.refresh,
2619
3458
  replaceActions: running.replace,
3459
+ replaceEntries: running.replaceEntries,
2620
3460
  actions: running.actions,
3461
+ defaults: (publisher) => {
3462
+ if (typeof publisher !== "string" || publisher === "") {
3463
+ throw new Error("moss: `defaults` is handed who publishes. What is published is everybody\u2019s, and who published it is kept with it.");
3464
+ }
3465
+ return running.publishedArtifacts(saved.published(publisher), async () => {
3466
+ const resolved = await identity.resolve(publisher);
3467
+ return { roles: resolved.roles, replayable: () => data.fingerprintsFor(resolved) };
3468
+ });
3469
+ },
2621
3470
  catalogOf: async (principal) => {
2622
3471
  const resolved = await identity.resolve(principal);
2623
3472
  return running.catalogFor(resolved.roles, resolved.installed);
@@ -2638,15 +3487,18 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
2638
3487
  ...identity.roster !== void 0 ? { identities: identity.roster } : {}
2639
3488
  });
2640
3489
  };
2641
- var buildRunningManifest = async (app, runtime, data) => {
3490
+ var buildRunningManifest = async (app, runtime, data, saved) => {
2642
3491
  const running = createRunningManifest({
2643
3492
  shipped: app,
2644
3493
  grants: data.grants,
2645
3494
  // Polled on the clock a socket's credential is re-verified on.
2646
- pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} }
3495
+ pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} },
3496
+ shells: [...app.shell !== void 0 ? [app.shell] : [], ...Object.values(app.pages ?? {})],
3497
+ ...saved !== void 0 ? { published: saved.published().inForce, reads: { written: data.vexEntry, compile: data.compileQuery, savedOf: saved.of } } : {}
2647
3498
  });
2648
3499
  data.dropOnChange(running.onChange);
2649
- await data.seed(running.entries());
3500
+ data.entriesHeldBy({ get: running.cacheEntry, entries: running.cacheEntries });
3501
+ await running.cacheEntries();
2650
3502
  return running;
2651
3503
  };
2652
3504
  var buildIdentity = (app, runtime, data) => createIdentity({
@@ -2699,6 +3551,6 @@ var subscribeReactions = ({ app, onWrite, deliver }) => {
2699
3551
  });
2700
3552
  };
2701
3553
 
2702
- export { MOSS_SEQUENCE, createServer, defineApp, exportDocuments, migrateTables, mintDevToken, mintSession, renderDocument, revokeAllFor, sessionCookies, verifyApp };
2703
- //# sourceMappingURL=chunk-V5YMJL7Z.js.map
2704
- //# sourceMappingURL=chunk-V5YMJL7Z.js.map
3554
+ export { MOSS_SEQUENCE, createServer, exportDocuments, migrateTables, mintDevToken, mintSession, renderDocument, revokeAllFor, sessionCookies };
3555
+ //# sourceMappingURL=chunk-YZILOVCR.js.map
3556
+ //# sourceMappingURL=chunk-YZILOVCR.js.map