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