@niscorp/moss 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/DOCS.md +95 -58
  3. package/dist/{chunk-F45SFR7W.cjs → chunk-3DCTQKPQ.cjs} +56 -16
  4. package/dist/chunk-3DCTQKPQ.cjs.map +1 -0
  5. package/dist/{chunk-X2Q546EB.js → chunk-3T422CCN.js} +9 -3
  6. package/dist/chunk-3T422CCN.js.map +1 -0
  7. package/dist/{chunk-MYGVHWS5.js → chunk-6XC2MD7S.js} +51 -15
  8. package/dist/chunk-6XC2MD7S.js.map +1 -0
  9. package/dist/{chunk-Z2VA6AOE.cjs → chunk-I4UOWER3.cjs} +11 -5
  10. package/dist/chunk-I4UOWER3.cjs.map +1 -0
  11. package/dist/{chunk-C2DNDIQX.cjs → chunk-PVZMCEBX.cjs} +2 -2
  12. package/dist/chunk-PVZMCEBX.cjs.map +1 -0
  13. package/dist/{chunk-IMZZB4JE.js → chunk-QAHDSRPK.js} +2 -2
  14. package/dist/chunk-QAHDSRPK.js.map +1 -0
  15. package/dist/{chunk-DSTHFSTO.cjs → chunk-TMDKNZYL.cjs} +349 -159
  16. package/dist/chunk-TMDKNZYL.cjs.map +1 -0
  17. package/dist/{chunk-MTC46PGQ.js → chunk-YZILOVCR.js} +301 -111
  18. package/dist/chunk-YZILOVCR.js.map +1 -0
  19. package/dist/{document-AbQUbQaP.d.ts → document-BYAY-Qle.d.ts} +9 -9
  20. package/dist/{document-wHHxIXJz.d.cts → document-DAE71J27.d.cts} +9 -9
  21. package/dist/{index-Dml1klpZ.d.cts → index-CSEo7Tys.d.cts} +1 -0
  22. package/dist/{index-Dml1klpZ.d.ts → index-CSEo7Tys.d.ts} +1 -0
  23. package/dist/index.cjs +14 -14
  24. package/dist/index.d.cts +5 -5
  25. package/dist/index.d.ts +5 -5
  26. package/dist/index.js +3 -3
  27. package/dist/integrations.cjs +3 -3
  28. package/dist/integrations.d.cts +1 -1
  29. package/dist/integrations.d.ts +1 -1
  30. package/dist/integrations.js +1 -1
  31. package/dist/node.cjs +8 -8
  32. package/dist/node.d.cts +2 -2
  33. package/dist/node.d.ts +2 -2
  34. package/dist/node.js +4 -4
  35. package/dist/tide.d.cts +1 -1
  36. package/dist/tide.d.ts +1 -1
  37. package/dist/unverified.cjs +3 -3
  38. package/dist/unverified.js +2 -2
  39. package/dist/vite.cjs +9 -9
  40. package/dist/vite.d.cts +2 -2
  41. package/dist/vite.d.ts +2 -2
  42. package/dist/vite.js +4 -4
  43. package/package.json +8 -8
  44. package/dist/chunk-C2DNDIQX.cjs.map +0 -1
  45. package/dist/chunk-DSTHFSTO.cjs.map +0 -1
  46. package/dist/chunk-F45SFR7W.cjs.map +0 -1
  47. package/dist/chunk-IMZZB4JE.js.map +0 -1
  48. package/dist/chunk-MTC46PGQ.js.map +0 -1
  49. package/dist/chunk-MYGVHWS5.js.map +0 -1
  50. package/dist/chunk-X2Q546EB.js.map +0 -1
  51. package/dist/chunk-Z2VA6AOE.cjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkF45SFR7W_cjs = require('./chunk-F45SFR7W.cjs');
4
- var chunkC2DNDIQX_cjs = require('./chunk-C2DNDIQX.cjs');
3
+ var chunk3DCTQKPQ_cjs = require('./chunk-3DCTQKPQ.cjs');
4
+ var chunkPVZMCEBX_cjs = require('./chunk-PVZMCEBX.cjs');
5
5
  var chunk3RIWTXGI_cjs = require('./chunk-3RIWTXGI.cjs');
6
6
  var zod = require('zod');
7
7
  var crypto$1 = require('crypto');
@@ -538,6 +538,10 @@ var MOSS_SEQUENCE = {
538
538
  // What is in force for an artifact is its latest row, and that is asked at every shell.
539
539
  { kind: "sql", sql: `CREATE INDEX artifacts_latest ON artifacts (principal, kind, id, created_at)` }
540
540
  ]
541
+ },
542
+ {
543
+ description: "When a version of an artifact was last loaded into a shell, for the sweep over what is unused",
544
+ steps: [{ kind: "sql", sql: `ALTER TABLE artifacts ADD COLUMN last_used_at timestamptz` }]
541
545
  }
542
546
  ]
543
547
  };
@@ -609,7 +613,7 @@ var oneAtATime = (query) => {
609
613
  };
610
614
  };
611
615
  var migrateTables = async (runtime, app, options = {}) => {
612
- const entries = chunkF45SFR7W_cjs.entriesOf(app);
616
+ const entries = chunk3DCTQKPQ_cjs.entriesOf(app);
613
617
  const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
614
618
  const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
615
619
  const misfitsBefore = misfitsOf(entries, before);
@@ -646,6 +650,38 @@ var featureTablesOf = (app) => {
646
650
  return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
647
651
  });
648
652
  };
653
+
654
+ // src/data/aging.ts
655
+ var UNUSED_VERSIONS = (
656
+ /* sql */
657
+ `DELETE FROM artifacts a
658
+ WHERE a.principal <> '*'
659
+ AND (SELECT max(coalesce(b.last_used_at, b.created_at)) FROM artifacts b WHERE b.principal = a.principal AND b.kind = a.kind AND b.id = a.id) < now() - ($1::bigint * interval '1 millisecond')
660
+ RETURNING a.save`
661
+ );
662
+ var EMPTY_SAVES = (
663
+ /* sql */
664
+ `DELETE FROM artifact_saves s WHERE NOT EXISTS (SELECT 1 FROM artifacts a WHERE a.save = s.id) RETURNING s.id`
665
+ );
666
+ var sweepUnused = async (pool, unusedMs) => {
667
+ const versions = (await pool.query(UNUSED_VERSIONS, [unusedMs])).rows.length;
668
+ const saves = (await pool.query(EMPTY_SAVES)).rows.length;
669
+ return { versions, saves };
670
+ };
671
+ var AGING_EVERY_MS = 36e5;
672
+ var startAging = (pool, unusedMs, everyMs = AGING_EVERY_MS) => {
673
+ const sweep2 = async () => {
674
+ try {
675
+ const swept = await sweepUnused(pool, unusedMs);
676
+ if (swept.versions > 0) console.log(`[moss] aging: ${swept.versions} version(s) of what was generated and unused for ${unusedMs} ms deleted, and ${swept.saves} save(s) left empty`);
677
+ } catch (error) {
678
+ console.error("[moss] aging: the sweep failed, and is tried again at the next:", error);
679
+ }
680
+ };
681
+ void sweep2();
682
+ const timer = setInterval(() => void sweep2(), everyMs);
683
+ return () => clearInterval(timer);
684
+ };
649
685
  var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
650
686
  var createEntryCache = (table) => {
651
687
  let held;
@@ -952,7 +988,10 @@ var createIntentAnswers = (deps) => {
952
988
  engines.set(writers, created);
953
989
  return created;
954
990
  };
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 });
991
+ return async (writers, asked, caller) => (await engineFor(writers)).execute(
992
+ "fingerprint" in asked ? { fingerprint: asked.fingerprint, context: asked.context ?? {} } : { intent: asked.intent, shape: asked.shape, context: asked.context ?? {} },
993
+ { scope: caller.scope, scopePolicy: caller.policy }
994
+ );
956
995
  };
957
996
 
958
997
  // src/data/data.ts
@@ -1011,7 +1050,7 @@ var createDataWith = (prepared, config) => {
1011
1050
  const { grammars, engine, grants } = prepared;
1012
1051
  const governed = { charter: config.charter, behaviors: { ...config.behaviors, ...config.rowRules } };
1013
1052
  const policies = createPolicies({ ...governed, grants });
1014
- const emit = chunkC2DNDIQX_cjs.emitterOf(config.telemetry);
1053
+ const emit = chunkPVZMCEBX_cjs.emitterOf(config.telemetry);
1015
1054
  const onExecute = emit === void 0 ? void 0 : (record) => emit(vexRecordToSpan(record));
1016
1055
  const writes = createWriteNotifier();
1017
1056
  const answering = lazyIntentAnswers(prepared, config);
@@ -1212,15 +1251,15 @@ var isKept = (layout) => layout !== void 0 && layout !== null && typeof layout !
1212
1251
  var shellWithStoredLayouts = (shell) => {
1213
1252
  const layouts = {};
1214
1253
  const frame = shell.layout;
1215
- if (isKept(frame)) layouts[chunkF45SFR7W_cjs.FRAME_LAYOUT_REF] = frame;
1254
+ if (isKept(frame)) layouts[chunk3DCTQKPQ_cjs.FRAME_LAYOUT_REF] = frame;
1216
1255
  const canvases = shell.canvases.map((canvas) => {
1217
1256
  const layout = canvas.actionLayout;
1218
1257
  if (!isKept(layout)) return canvas;
1219
- const ref = chunkF45SFR7W_cjs.canvasLayoutRef(canvas.id);
1258
+ const ref = chunk3DCTQKPQ_cjs.canvasLayoutRef(canvas.id);
1220
1259
  layouts[ref] = layout;
1221
1260
  return { ...canvas, actionLayout: ref };
1222
1261
  });
1223
- return { canvases, ...isKept(frame) ? { frame: chunkF45SFR7W_cjs.FRAME_LAYOUT_REF } : typeof frame === "string" ? { frame } : {}, layouts };
1262
+ return { canvases, ...isKept(frame) ? { frame: chunk3DCTQKPQ_cjs.FRAME_LAYOUT_REF } : typeof frame === "string" ? { frame } : {}, layouts };
1224
1263
  };
1225
1264
  var slottedIn = /* @__PURE__ */ new WeakMap();
1226
1265
  var canvasesSlottedIn = (layout) => {
@@ -1253,8 +1292,29 @@ var shellComponents = (manifest, shell) => {
1253
1292
  for (const name of Object.keys(contracts)) names.add(name);
1254
1293
  return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
1255
1294
  };
1295
+ var createComponentNames = (read2) => {
1296
+ let components = /* @__PURE__ */ new WeakMap();
1297
+ return {
1298
+ of: (shell) => {
1299
+ const kept = components.get(shell);
1300
+ if (kept !== void 0) return kept;
1301
+ const names = read2(shell);
1302
+ components.set(shell, names);
1303
+ return names;
1304
+ },
1305
+ drop: () => {
1306
+ components = /* @__PURE__ */ new WeakMap();
1307
+ }
1308
+ };
1309
+ };
1256
1310
  var SavedLayoutSchema = zod.z.strictObject({ ref: zod.z.string(), layout: nova.LayoutNodeSchema, use: zod.z.boolean().optional() });
1257
1311
  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;
1312
+ var actionAtRef = (actions, layouts) => (ref) => {
1313
+ const id = chunk3DCTQKPQ_cjs.actionOfLayoutRef(ref);
1314
+ const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
1315
+ const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
1316
+ return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
1317
+ };
1258
1318
  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
1319
  var targetAt = (ref, heldTo) => {
1260
1320
  if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
@@ -1275,9 +1335,9 @@ var readLayout = (body, heldTo) => {
1275
1335
  const { ref, layout } = parsed.data;
1276
1336
  const target = targetAt(ref, heldTo);
1277
1337
  if (target === void 0) return { refusal: nothingKeptUnder(ref) };
1278
- const misfits = chunkF45SFR7W_cjs.layoutMisfits(layout, target.kit);
1338
+ const misfits = chunk3DCTQKPQ_cjs.layoutMisfits(layout, target.kit);
1279
1339
  if (misfits.length > 0) return { refusal: misfits.join("; ") };
1280
- const named = chunkF45SFR7W_cjs.layoutNameRefusal(layout);
1340
+ const named = chunk3DCTQKPQ_cjs.layoutNameRefusal(layout);
1281
1341
  if (named !== void 0) return { refusal: `it ${named}` };
1282
1342
  const { action } = target;
1283
1343
  if (action === void 0) return { layout: parsed.data };
@@ -1311,7 +1371,7 @@ var layoutsInUse = (inForce2, drawnFor) => {
1311
1371
  }
1312
1372
  return layouts;
1313
1373
  };
1314
- var generatedId = () => `${chunkF45SFR7W_cjs.GENERATED_ID_PREFIX}${crypto$1.randomUUID()}`;
1374
+ var generatedId = () => `${chunk3DCTQKPQ_cjs.GENERATED_ID_PREFIX}${crypto$1.randomUUID()}`;
1315
1375
  var VEX_ROUTE = /^\/api\/(?:[A-Za-z0-9_-]+\/)?vex$/;
1316
1376
  var endpointRefusals = async (endpoints, heldTo) => {
1317
1377
  const refusals = [];
@@ -1340,7 +1400,7 @@ var endpointRefusals = async (endpoints, heldTo) => {
1340
1400
  var parsedUnder = (schema, body, id, more = {}) => {
1341
1401
  if (strata.exceedsDepth(body)) return { refusal: strata.depthRefusal() };
1342
1402
  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.` };
1403
+ return { refusal: `it names the id "${String(body["id"])}", and is kept under "${id}": leave the id out of the body.` };
1344
1404
  }
1345
1405
  const parsed = schema.safeParse(reflect.isRecord(body) ? { ...more, ...body, id } : body);
1346
1406
  if (parsed.success) return { body: parsed.data };
@@ -1348,8 +1408,8 @@ var parsedUnder = (schema, body, id, more = {}) => {
1348
1408
  return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
1349
1409
  };
1350
1410
  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}`]];
1411
+ const named = chunk3DCTQKPQ_cjs.layoutNameRefusal(layout);
1412
+ return [...layout === void 0 || typeof layout === "string" ? [] : chunk3DCTQKPQ_cjs.layoutMisfits(layout, kit), ...named === void 0 ? [] : [`it ${named}`]];
1353
1413
  };
1354
1414
  var passedOrRefused = (body, refusals) => refusals.length > 0 ? { refusal: refusals.join("; ") } : { body };
1355
1415
  var readAction = async (body, id, heldTo) => {
@@ -1542,7 +1602,7 @@ var unmarked = (versions, inForce2) => {
1542
1602
  });
1543
1603
  };
1544
1604
  var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
1545
- var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1605
+ var savingFor = ({ holder, whose, kinds, written, defaults }, nobody) => {
1546
1606
  const requireHolder = () => {
1547
1607
  if (holder === void 0) throw new Error(nobody);
1548
1608
  return holder;
@@ -1559,12 +1619,14 @@ var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1559
1619
  };
1560
1620
  const checkedEach = async (asked, inForce2, held) => {
1561
1621
  const versions = [];
1562
- for (const { kind, id: named, body } of asked) {
1563
- const id = named ?? NEW_ID[kind]();
1622
+ for (const { kind, id: named2, body } of asked) {
1623
+ if (defaults !== void 0 && named2 === void 0 && kind !== "layout" && kind !== "read") throw new Error(`moss: a published ${kind} is given its id by whoever publishes it: name it.`);
1624
+ const id = named2 ?? NEW_ID[kind]();
1564
1625
  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
1626
  versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
1566
1627
  }
1567
- const notTheirs = asked.find(({ kind, id }) => id !== void 0 && kind !== "read" && !inForce2.some((version) => version.kind === kind && version.id === id));
1628
+ const named = (kind) => kind !== "read" && (defaults === void 0 || kind === "layout");
1629
+ const notTheirs = asked.find(({ kind, id }) => id !== void 0 && named(kind) && !inForce2.some((version) => version.kind === kind && version.id === id));
1568
1630
  if (notTheirs !== void 0) {
1569
1631
  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
1632
  }
@@ -1581,7 +1643,7 @@ var savingFor = ({ holder, whose, kinds, written }, nobody) => {
1581
1643
  return { requireHolder, ofKind, askedOf, checkedEach, write };
1582
1644
  };
1583
1645
  var savedArtifacts = (deps) => {
1584
- const { holder, whose, kinds } = deps;
1646
+ const { holder, whose, kinds, defaults } = deps;
1585
1647
  const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
1586
1648
  return {
1587
1649
  save: async (artifacts) => {
@@ -1590,6 +1652,7 @@ var savedArtifacts = (deps) => {
1590
1652
  const { saved, heldTo } = await holderOf();
1591
1653
  const inForce2 = await saved.inForce();
1592
1654
  const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
1655
+ await defaults?.verify(versions, inForce2);
1593
1656
  return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
1594
1657
  },
1595
1658
  list: async (kind) => {
@@ -1615,7 +1678,9 @@ var savedArtifacts = (deps) => {
1615
1678
  if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
1616
1679
  const inForce2 = await saved.inForce();
1617
1680
  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) };
1681
+ const restored = { kind: known, id, body, copiedFrom: version.save };
1682
+ await defaults?.verify([restored], inForce2);
1683
+ return { save: await write(saved, [restored], inForce2) };
1619
1684
  },
1620
1685
  reset: async (kind, id) => {
1621
1686
  const holderOf = requireHolder();
@@ -1637,22 +1702,22 @@ var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
1637
1702
  var draftSaving = (deps) => {
1638
1703
  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
1704
  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) => {
1705
+ // The draft with these added to it. Each is checked beside what is in force for its holder with the draft laid over.
1706
+ add: async (artifacts, drafted) => {
1642
1707
  const holderOf = requireHolder();
1643
1708
  const asked = askedOf(artifacts);
1644
1709
  const { saved, heldTo } = await holderOf();
1645
1710
  const inForce2 = laidOver(await saved.inForce(), drafted);
1646
1711
  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));
1712
+ const added = versions.map(({ kind, id, body }) => ({ kind, id, body }));
1713
+ const marked = new Set(markedRefs(added));
1649
1714
  const kept = drafted.flatMap((one) => {
1650
- if (put.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1715
+ if (added.some((other) => other.kind === one.kind && other.id === one.id)) return [];
1651
1716
  const ref = refOf(one.body);
1652
1717
  const loses = one.kind === "layout" && reflect.isRecord(one.body) && one.body["use"] === true && ref !== void 0 && marked.has(ref);
1653
1718
  return [loses && reflect.isRecord(one.body) ? { ...one, body: withoutMark(one.body) } : one];
1654
1719
  });
1655
- return { drafted: [...kept, ...put], put: idsOf(versions) };
1720
+ return { drafted: [...kept, ...added], added: idsOf(versions) };
1656
1721
  },
1657
1722
  save: async (drafted) => {
1658
1723
  const holderOf = requireHolder();
@@ -1741,6 +1806,51 @@ var createGeneration = (pointer, ctx) => {
1741
1806
  }
1742
1807
  };
1743
1808
  };
1809
+
1810
+ // src/artifactory/published.ts
1811
+ var NO_DEFAULTS = { actions: {}, fragments: {}, reads: /* @__PURE__ */ new Map() };
1812
+ var drawableIn = (fragments, kit, say) => Object.fromEntries(
1813
+ Object.entries(fragments).filter(([id, fragment]) => {
1814
+ const misfits = chunk3DCTQKPQ_cjs.layoutMisfits(fragment.layout, kit);
1815
+ if (misfits.length > 0) say(`[moss] the fragment "${id}" published for everybody is left out of a shell that cannot draw it: ${misfits.join("; ")}`);
1816
+ return misfits.length === 0;
1817
+ })
1818
+ );
1819
+ var createPublishedMemo = () => {
1820
+ let read2;
1821
+ let said = /* @__PURE__ */ new Set();
1822
+ return {
1823
+ held: () => read2,
1824
+ keep: (promise) => {
1825
+ read2 = promise;
1826
+ },
1827
+ drop: () => {
1828
+ read2 = void 0;
1829
+ said = /* @__PURE__ */ new Set();
1830
+ },
1831
+ sayOnce: (line) => {
1832
+ if (said.has(line)) return;
1833
+ said.add(line);
1834
+ console.error(line);
1835
+ }
1836
+ };
1837
+ };
1838
+ var hasDefaults = (defaults) => Object.keys(defaults.actions).length > 0 || Object.keys(defaults.fragments).length > 0 || defaults.reads.size > 0;
1839
+ var checkedDefaults = async (versions, heldTo, whose) => {
1840
+ const reads = heldTo.reads === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, heldTo.reads, whose);
1841
+ const checks = {
1842
+ kit: heldTo.kit,
1843
+ entryOf: (fingerprint) => {
1844
+ const read2 = reads.get(fingerprint);
1845
+ return heldTo.entryOf(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
1846
+ },
1847
+ replayable: async () => /* @__PURE__ */ new Set([...heldTo.fingerprints(), ...reads.keys()]),
1848
+ mayCall: () => true,
1849
+ catalog: () => [...Object.values(heldTo.built).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
1850
+ };
1851
+ const passed = await generatedInForce(versions, checks, whose);
1852
+ return { passed, reads, verified: chunk3DCTQKPQ_cjs.verifyManifest(heldTo.candidate({ ...heldTo.built, ...passed.actions }, passed.fragments)) };
1853
+ };
1744
1854
  var narrowedBy = (filter, ids, installed) => {
1745
1855
  const answered = new Set(filter(ids, installed));
1746
1856
  return ids.filter((id) => answered.has(id));
@@ -1752,9 +1862,9 @@ var catalogFor = (app, roles, installed, installedOnly) => {
1752
1862
  };
1753
1863
  var resolveVariantsForRoles = (app, roles) => {
1754
1864
  const variants = app.layouts ?? {};
1755
- return chunkF45SFR7W_cjs.variantLayouts(variants, charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
1865
+ return chunk3DCTQKPQ_cjs.variantLayouts(variants, charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
1756
1866
  };
1757
- var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(chunkF45SFR7W_cjs.withVariants(actions, ids, variants)));
1867
+ var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(chunk3DCTQKPQ_cjs.withVariants(actions, ids, variants)));
1758
1868
  var actionsWithStoredLayouts = (definitions) => {
1759
1869
  const actions = {};
1760
1870
  const layouts = {};
@@ -1764,7 +1874,7 @@ var actionsWithStoredLayouts = (definitions) => {
1764
1874
  actions[id] = definition;
1765
1875
  continue;
1766
1876
  }
1767
- const ref = chunkF45SFR7W_cjs.actionLayoutRef(id);
1877
+ const ref = chunk3DCTQKPQ_cjs.actionLayoutRef(id);
1768
1878
  layouts[ref] = layout;
1769
1879
  actions[id] = { ...definition, layout: { ref } };
1770
1880
  }
@@ -1807,15 +1917,7 @@ var versionToken = (ids) => {
1807
1917
  return h.toString(16).padStart(8, "0");
1808
1918
  };
1809
1919
 
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
- };
1920
+ // src/artifactory/sets.ts
1819
1921
  var createSetOwners = () => {
1820
1922
  const owners = /* @__PURE__ */ new Map();
1821
1923
  const ownerRefusalOf = (source) => {
@@ -1837,38 +1939,48 @@ var createSetOwners = () => {
1837
1939
  }
1838
1940
  };
1839
1941
  };
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;
1846
- };
1847
- var createComponentNames = (read2) => {
1848
- let components = /* @__PURE__ */ new WeakMap();
1942
+
1943
+ // src/artifactory/usage.ts
1944
+ var TOUCH_EVERY_MS = 36e5;
1945
+ var createUsage = (everyMs, now = Date.now) => {
1946
+ const stamped2 = /* @__PURE__ */ new Map();
1849
1947
  return {
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;
1856
- },
1857
- drop: () => {
1858
- components = /* @__PURE__ */ new WeakMap();
1948
+ touch: (principal, versions, rows) => {
1949
+ const at = now();
1950
+ for (const [key, when] of stamped2) if (when <= at - everyMs) stamped2.delete(key);
1951
+ const due = versions.filter((version) => version.body !== null && !stamped2.has(`${principal}\0${version.kind}\0${version.id}`));
1952
+ if (due.length === 0) return;
1953
+ for (const version of due) stamped2.set(`${principal}\0${version.kind}\0${version.id}`, at);
1954
+ rows.touch(
1955
+ due.map((version) => ({ kind: version.kind, id: version.id })),
1956
+ new Date(at).toISOString()
1957
+ ).catch((error) => console.error(`[moss] the artifacts of ${principal} could not be stamped as used:`, error));
1859
1958
  }
1860
1959
  };
1861
1960
  };
1961
+
1962
+ // src/artifactory/running.ts
1963
+ var mergedActions = (own, sets, over = {}) => Object.freeze([...sets.values(), over].reduce((all, set) => ({ ...all, ...set }), { ...own }));
1964
+ var tell = (listener, ...told) => {
1965
+ try {
1966
+ listener(...told);
1967
+ } catch (error) {
1968
+ console.error("[moss:manifest] a listener to a manifest change threw:", error);
1969
+ }
1970
+ };
1862
1971
  var createRunningManifest = (config) => {
1863
1972
  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);
1973
+ const entries = createEntriesInForce(chunk3DCTQKPQ_cjs.entriesOf(shipped));
1974
+ let defaults = NO_DEFAULTS;
1975
+ const usage = createUsage(config.touchEveryMs ?? TOUCH_EVERY_MS);
1976
+ let functionIds;
1977
+ const candidate = (actions, held = entries.list(), fragments = defaults.fragments) => chunk3DCTQKPQ_cjs.withFragments({ ...chunk3DCTQKPQ_cjs.candidateOf(shipped, { actions, entries: held }, config.grants), ...functionIds === void 0 ? {} : { functionIds } }, fragments);
1866
1978
  const own = shipped.actions;
1867
1979
  const loaders = /* @__PURE__ */ new Map();
1868
1980
  const owners = createSetOwners();
1869
1981
  let sets = /* @__PURE__ */ new Map();
1870
1982
  let inForce2 = mergedActions(own, sets);
1871
- let report = verifiedAtBoot(candidate(inForce2));
1983
+ let report = chunk3DCTQKPQ_cjs.verifiedAtBoot(candidate(inForce2));
1872
1984
  const components = createComponentNames((shell) => shellComponents({ actions: inForce2, layouts: shipped.layouts }, shell));
1873
1985
  const componentsOf2 = (shells) => {
1874
1986
  const kit = /* @__PURE__ */ new Map();
@@ -1878,6 +1990,11 @@ var createRunningManifest = (config) => {
1878
1990
  return kit;
1879
1991
  };
1880
1992
  let ofTheApp;
1993
+ const dropMemos = () => {
1994
+ roleMemo.drop();
1995
+ components.drop();
1996
+ ofTheApp = void 0;
1997
+ };
1881
1998
  const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
1882
1999
  const roleMemo = createRoleMemo({
1883
2000
  manifest: () => ({ charter: shipped.charter, actions: inForce2, layouts: shipped.layouts }),
@@ -1892,33 +2009,39 @@ var createRunningManifest = (config) => {
1892
2009
  kit,
1893
2010
  // A layout saved for the frame or a canvas is the app's own shell's, whichever shell it is saved from.
1894
2011
  ...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 };
1900
- }
2012
+ actionAt: actionAtRef(actions, layouts)
1901
2013
  };
1902
2014
  };
1903
2015
  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
- };
2016
+ const functionsWritten = (written) => {
2017
+ if (functionIds !== void 0) return;
2018
+ const ids = chunk3DCTQKPQ_cjs.functionsIn(written).map((definition) => definition.id);
2019
+ const charter = chunk3DCTQKPQ_cjs.charterOverFunctions(shipped.charter, { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) }, ids);
2020
+ if (charter.errors.length > 0) throw new Error(`Charter is incoherent over the app\u2019s functions \u2014 refusing to serve:
2021
+ ${charter.errors.join("\n ")}`);
2022
+ functionIds = new Set(ids);
2023
+ const built = mergedActions(own, sets);
2024
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(built, entries.list(), {}));
2025
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "boot");
2026
+ if (refusal !== void 0) {
2027
+ functionIds = void 0;
2028
+ throw new Error(refusal);
2029
+ }
2030
+ report = verified;
2031
+ defaults = NO_DEFAULTS;
2032
+ inForce2 = built;
2033
+ dropMemos();
2034
+ memo.drop();
2035
+ for (const warning2 of charter.warnings) console.warn(`[moss] charter: ${warning2}`);
2036
+ const warning = chunk3DCTQKPQ_cjs.functionsWarning(written);
2037
+ if (warning !== void 0) console.warn(warning);
2038
+ };
2039
+ const grantedFunctionsOf = (roles) => (names) => charter.resolvePrincipal(shipped.charter, names, roles, "functions");
1917
2040
  const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
1918
2041
  const heldWithGenerated = async (held, versions, who, shell, whose) => {
1919
2042
  let replayable;
1920
2043
  let catalog;
1921
- const reads = readsHeldTo === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, readsHeldTo, whose);
2044
+ const reads = new Map([...defaults.reads, ...readsHeldTo === void 0 ? [] : await readsInForce(versions, readsHeldTo, whose)]);
1922
2045
  const checks = {
1923
2046
  kit: kitOf2(shell),
1924
2047
  entryOf: (fingerprint) => {
@@ -1936,10 +2059,12 @@ var createRunningManifest = (config) => {
1936
2059
  };
1937
2060
  const listeners = /* @__PURE__ */ new Set();
1938
2061
  const listenersFor = /* @__PURE__ */ new Set();
2062
+ const kinds = readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"];
1939
2063
  const sessionDeps = (principal, callerOf, shell) => ({
1940
2064
  whose: "of yours",
1941
- kinds: readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"],
2065
+ kinds,
1942
2066
  holder: principal === null ? void 0 : async () => {
2067
+ await publishedNow();
1943
2068
  const caller = await callerOf();
1944
2069
  const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
1945
2070
  return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
@@ -1949,55 +2074,69 @@ var createRunningManifest = (config) => {
1949
2074
  }
1950
2075
  });
1951
2076
  let pointer;
1952
- let published;
1953
- let saidOfPublished = /* @__PURE__ */ new Set();
1954
- const dropPublished = () => {
1955
- published = void 0;
1956
- saidOfPublished = /* @__PURE__ */ new Set();
2077
+ const memo = createPublishedMemo();
2078
+ const defaultsHeldTo = () => ({
2079
+ kit: kitOf2(),
2080
+ entryOf: (fingerprint) => entries.byFingerprint().get(fingerprint),
2081
+ fingerprints: () => entries.byFingerprint().keys(),
2082
+ reads: readsHeldTo,
2083
+ built: mergedActions(own, sets),
2084
+ candidate: (actions, fragments) => candidate(actions, entries.list(), fragments)
2085
+ });
2086
+ const applyPublished = async (versions) => {
2087
+ const over = sets;
2088
+ const { passed, reads, verified } = await checkedDefaults(versions, defaultsHeldTo(), "published for everybody");
2089
+ if (sets !== over) return applyPublished(versions);
2090
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "boot");
2091
+ if (refusal !== void 0) memo.sayOnce(`[moss] what is published for everybody is left out, and the build\u2019s copies stand: ${refusal}`);
2092
+ const next = refusal === void 0 ? { actions: passed.actions, fragments: passed.fragments, reads } : { ...NO_DEFAULTS, reads };
2093
+ if (!hasDefaults(next) && !hasDefaults(defaults)) return;
2094
+ defaults = next;
2095
+ if (refusal === void 0) report = verified;
2096
+ inForce2 = mergedActions(own, sets, defaults.actions);
2097
+ dropMemos();
1957
2098
  };
1958
2099
  const publishedNow = () => {
1959
- if (published !== void 0) return published;
1960
- const read2 = (async () => await config.published?.() ?? [])();
1961
- published = read2;
1962
- read2.catch(dropPublished);
2100
+ const held = memo.held();
2101
+ if (held !== void 0) return held;
2102
+ const read2 = (async () => {
2103
+ const versions = await config.published?.() ?? [];
2104
+ await applyPublished(versions);
2105
+ return versions;
2106
+ })();
2107
+ memo.keep(read2);
2108
+ read2.catch(memo.drop);
1963
2109
  return read2;
1964
2110
  };
1965
- const sayOnce = (line) => {
1966
- if (saidOfPublished.has(line)) return;
1967
- saidOfPublished.add(line);
1968
- console.error(line);
1969
- };
1970
2111
  const applySets = (arrived, announce) => {
1971
2112
  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");
2113
+ const actions = mergedActions(own, next, defaults.actions);
2114
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(actions));
2115
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "refresh");
1975
2116
  if (refusal !== void 0) throw new Error(refusal);
1976
- for (const set of arrived.values()) chunkF45SFR7W_cjs.freezeDeep(set);
2117
+ for (const set of arrived.values()) chunk3DCTQKPQ_cjs.freezeDeep(set);
1977
2118
  sets = next;
1978
2119
  inForce2 = actions;
1979
2120
  report = verified;
1980
- roleMemo.drop();
1981
- components.drop();
1982
- ofTheApp = void 0;
2121
+ dropMemos();
1983
2122
  for (const listener of [...listeners]) tell(listener);
1984
2123
  if (announce) pointer?.bump();
1985
2124
  };
1986
2125
  const reload = async () => {
1987
2126
  const read2 = [];
1988
2127
  for (const [source, load] of loaders) read2.push([source, await load()]);
1989
- dropPublished();
2128
+ memo.drop();
1990
2129
  applySets(new Map(read2), false);
1991
2130
  };
1992
2131
  const takeEntries = async (source, handed) => {
1993
2132
  owners.assertAppOwned(source);
1994
- const misfits = chunkF45SFR7W_cjs.entryMisfits(handed);
2133
+ const misfits = chunk3DCTQKPQ_cjs.entryMisfits(handed);
1995
2134
  if (misfits.length > 0) throw new Error(["Refresh refused \u2014 entries that do not parse:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
1996
2135
  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");
2136
+ const verified = chunk3DCTQKPQ_cjs.verifyManifest(candidate(inForce2, entries.withSet(source, handed)));
2137
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf(verified, "refresh");
1999
2138
  if (refusal !== void 0) throw new Error(refusal);
2000
- chunkF45SFR7W_cjs.freezeDeep(handed);
2139
+ chunk3DCTQKPQ_cjs.freezeDeep(handed);
2001
2140
  entries.takeSet(source, handed, compiled);
2002
2141
  report = verified;
2003
2142
  for (const listener of [...listeners]) tell(listener);
@@ -2007,7 +2146,7 @@ var createRunningManifest = (config) => {
2007
2146
  return {
2008
2147
  actions: () => inForce2,
2009
2148
  entries: entries.list,
2010
- verify: (actions) => chunkF45SFR7W_cjs.verifyManifest(candidate(actions)),
2149
+ verify: (actions) => chunk3DCTQKPQ_cjs.verifyManifest(candidate(actions)),
2011
2150
  report: () => report,
2012
2151
  replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
2013
2152
  // In turn: a set is compiled before it is taken, and of two handed over
@@ -2019,11 +2158,15 @@ var createRunningManifest = (config) => {
2019
2158
  },
2020
2159
  cacheEntry: async (fingerprint, scope) => {
2021
2160
  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);
2161
+ if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0) return shippedEntry;
2162
+ const userId = scope["userId"];
2163
+ if (typeof userId === "string" && userId !== NOBODY_USER_ID) {
2164
+ const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
2165
+ if (newest !== void 0 && newest.body !== null && newest.unread === void 0) return answeredRead(fingerprint, newest.body);
2166
+ }
2167
+ await publishedNow();
2168
+ const everybodys = defaults.reads.get(fingerprint);
2169
+ return everybodys === void 0 ? void 0 : compiledRead(fingerprint, everybodys);
2027
2170
  },
2028
2171
  cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
2029
2172
  claim: (source, owner) => {
@@ -2037,6 +2180,7 @@ var createRunningManifest = (config) => {
2037
2180
  };
2038
2181
  },
2039
2182
  refresh: () => applySets(/* @__PURE__ */ new Map(), true),
2183
+ functionsWritten,
2040
2184
  watch: () => {
2041
2185
  const where = config.pointer;
2042
2186
  if (pointer !== void 0 || where === void 0) return;
@@ -2054,15 +2198,19 @@ var createRunningManifest = (config) => {
2054
2198
  },
2055
2199
  catalogFor: roleMemo.catalogFor,
2056
2200
  artifactsFor: async (shell, { principal, roles, installed, saved, replayable, drafted }) => {
2057
- const versions = saved === void 0 || principal === null ? [] : laidOver(await saved.inForce(), drafted);
2201
+ const own2 = saved === void 0 || principal === null ? [] : await saved.inForce();
2202
+ if (saved !== void 0 && principal !== null) usage.touch(principal, own2, saved);
2203
+ const versions = own2.length === 0 && drafted === void 0 ? [] : laidOver(own2, drafted);
2204
+ const everybodysVersions = await publishedNow();
2058
2205
  const whose = `of ${principal ?? "nobody"}`;
2059
2206
  const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
2060
2207
  const drawable = theirOwn.heldTo.layouts;
2061
2208
  const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
2062
2209
  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 };
2210
+ const underVariants = { ...drawable, actionAt: (ref) => variants.has(chunk3DCTQKPQ_cjs.actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
2211
+ const everybodys = layoutsInUse(everybodysVersions, { whose: "published for everybody", heldTo: underVariants, say: memo.sayOnce });
2212
+ const laidOverShell = { ...drawableIn(defaults.fragments, kitOf2(shell), memo.sayOnce), ...theirOwn.fragments };
2213
+ const fragments = Object.keys(laidOverShell).length === 0 ? shell.fragments : { ...shell.fragments, ...laidOverShell };
2066
2214
  const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
2067
2215
  const layoutStore = { ...shell.layoutStore, ...ofShell, ...theirOwn.all.layouts, ...everybodys, ...theirs2 };
2068
2216
  return {
@@ -2080,18 +2228,29 @@ var createRunningManifest = (config) => {
2080
2228
  draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
2081
2229
  // Held to every action in force with the layout it is built with: who holds
2082
2230
  // which is asked when a shell is built for them.
2083
- publishedArtifacts: (saved) => savedArtifacts({
2231
+ publishedArtifacts: (saved, publisher) => savedArtifacts({
2084
2232
  whose: "published for everybody",
2085
- kinds: ["layout"],
2086
- holder: async () => ({ saved, heldTo: async () => (await heldWithGenerated(actionsWithStoredLayouts(inForce2), [], {})).heldTo }),
2233
+ kinds,
2234
+ holder: async () => {
2235
+ const who = await publisher();
2236
+ return { saved, heldTo: async (inForce3) => (await heldWithGenerated(actionsWithStoredLayouts(mergedActions(own, sets)), inForce3, who)).heldTo };
2237
+ },
2238
+ defaults: {
2239
+ verify: async (versions, inForce3) => {
2240
+ const kept = inForce3.filter((held) => !versions.some((version) => version.kind === held.kind && version.id === held.id));
2241
+ const asked = versions.map((version) => ({ ...version, save: "", createdAt: "" }));
2242
+ const refusal = chunk3DCTQKPQ_cjs.refusalOf((await checkedDefaults([...kept, ...asked], defaultsHeldTo(), void 0)).verified, "publish");
2243
+ if (refusal !== void 0) throw new Error(refusal);
2244
+ }
2245
+ },
2087
2246
  written: () => {
2088
- dropPublished();
2247
+ memo.drop();
2089
2248
  for (const listener of [...listeners]) tell(listener);
2090
2249
  pointer?.bump();
2091
2250
  }
2092
2251
  }),
2093
2252
  readPublished: async () => {
2094
- dropPublished();
2253
+ memo.drop();
2095
2254
  await publishedNow();
2096
2255
  },
2097
2256
  onChangeFor: (listener) => {
@@ -2183,7 +2342,19 @@ var save = {
2183
2342
  }
2184
2343
  ]
2185
2344
  };
2186
- var SAVE_ENTRIES = [inForce, history, save];
2345
+ var touch = {
2346
+ fingerprint: "artifactory/touch",
2347
+ intent: "Mark one of the caller\u2019s artifacts as used now",
2348
+ mutation: [
2349
+ {
2350
+ op: "update",
2351
+ table: "artifacts",
2352
+ set: { last_used_at: { $context: "at" } },
2353
+ where: { and: [{ eq: ["artifacts.kind", { $context: "kind" }] }, { eq: ["artifacts.id", { $context: "id" }] }] }
2354
+ }
2355
+ ]
2356
+ };
2357
+ var SAVE_ENTRIES = [inForce, history, save, touch];
2187
2358
  var RowSchema2 = zod.z.object({
2188
2359
  save: zod.z.string(),
2189
2360
  kind: zod.z.string(),
@@ -2226,6 +2397,9 @@ var savedRowsOver = (replay, upgrader) => {
2226
2397
  write: async (saved) => {
2227
2398
  const versions = saved.versions.map((version) => ({ kind: version.kind, id: version.id, body: version.body, grammar: upgrader.stamp, copied_from: version.copiedFrom }));
2228
2399
  await replay(save.fingerprint, { save: saved.id, versions }, scope);
2400
+ },
2401
+ touch: async (artifacts, at) => {
2402
+ for (const { kind, id } of artifacts) await replay(touch.fingerprint, { kind, id, at }, scope);
2229
2403
  }
2230
2404
  };
2231
2405
  };
@@ -2455,7 +2629,7 @@ var refusalOf2 = (error) => {
2455
2629
  };
2456
2630
  var spanOf = (emit) => {
2457
2631
  if (emit === void 0) return void 0;
2458
- const clock = chunkC2DNDIQX_cjs.spanClock();
2632
+ const clock = chunkPVZMCEBX_cjs.spanClock();
2459
2633
  return (name, status, hasPrincipal) => emit({ name, startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status, attributes: { hasPrincipal } });
2460
2634
  };
2461
2635
  var openingOf = (config, { seed, path }) => {
@@ -2515,7 +2689,7 @@ var open = async (held, url, connection, send, span, found) => {
2515
2689
  connection.onMessage(messageHandler(attached, connection, send));
2516
2690
  };
2517
2691
  var createSocket = (config) => {
2518
- const emit = chunkC2DNDIQX_cjs.emitterOf(config.telemetry);
2692
+ const emit = chunkPVZMCEBX_cjs.emitterOf(config.telemetry);
2519
2693
  const revalidation = createRevalidation(config);
2520
2694
  const anonymousShells = createAnonymousShellLimit(config.anonymousShellMax ?? DEFAULT_ANONYMOUS_SHELL_MAX);
2521
2695
  const held = { config, foreignPageWarning: { warned: false }, revalidation, anonymousShells };
@@ -2563,13 +2737,13 @@ var seamsFor = (feature, owned, { app, runtime, server, operator, registered, id
2563
2737
  grantedActionIds: (roles, installed) => running.catalogFor(roles, installed).ids,
2564
2738
  actions: running.actions,
2565
2739
  replaceActions: owned.replace,
2566
- refusalOf: (actions) => chunkF45SFR7W_cjs.refusalOf(running.verify(actions), "refresh"),
2740
+ refusalOf: (actions) => chunk3DCTQKPQ_cjs.refusalOf(running.verify(actions), "refresh"),
2567
2741
  setActionsLoader: owned.setLoader,
2568
2742
  addCatalogFilter: running.addCatalogFilter,
2569
2743
  charter: app.charter,
2570
2744
  components: app.shell?.components ?? {},
2571
- layoutMisfits: (layout) => chunkF45SFR7W_cjs.layoutMisfits(layout, kitOf(app)),
2572
- endlessChains: chunkF45SFR7W_cjs.endlessChains,
2745
+ layoutMisfits: (layout) => chunk3DCTQKPQ_cjs.layoutMisfits(layout, kitOf(app)),
2746
+ endlessChains: chunk3DCTQKPQ_cjs.endlessChains,
2573
2747
  ownEntries: (entries) => data.ownEntries(feature.name, entries),
2574
2748
  grammars: data.grammars,
2575
2749
  upgradeStore: (store) => data.upgradeStore(feature.name, store),
@@ -2636,9 +2810,9 @@ var read = (live) => {
2636
2810
  console.error("[moss/shells] the shell frame failed to render for a snapshot \u2014 serving an empty arrangement:", error);
2637
2811
  }
2638
2812
  const trees = {};
2639
- for (const canvasId of chunkF45SFR7W_cjs.canvasesOf(live)) {
2813
+ for (const canvasId of chunk3DCTQKPQ_cjs.canvasesOf(live)) {
2640
2814
  try {
2641
- trees[canvasId] = chunkF45SFR7W_cjs.treeOf(live, canvasId);
2815
+ trees[canvasId] = chunk3DCTQKPQ_cjs.treeOf(live, canvasId);
2642
2816
  } catch (error) {
2643
2817
  console.error(`[moss/shells] canvas "${canvasId}" failed to render for a snapshot \u2014 leaving it out:`, error);
2644
2818
  }
@@ -2655,7 +2829,7 @@ var needOf = (live, principal, kept) => {
2655
2829
  for (const instance of canvas.stack) {
2656
2830
  const definition = live.shell.getRuntime(instance.id)?.definition;
2657
2831
  if (definition === void 0) continue;
2658
- const need = shellNeedOf(chunkF45SFR7W_cjs.withLayoutInPlace(definition, live.shell.layoutStore), entries);
2832
+ const need = shellNeedOf(chunk3DCTQKPQ_cjs.withLayoutInPlace(definition, live.shell.layoutStore), entries);
2659
2833
  for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
2660
2834
  for (const read2 of need.drawnWith) drawnWith.push(read2);
2661
2835
  }
@@ -2678,7 +2852,7 @@ var sweep = (host, idleMs) => {
2678
2852
  }
2679
2853
  if (live.connections.size > 0 || live.idleSince === null) continue;
2680
2854
  if (now - live.idleSince < idleMs) continue;
2681
- chunkF45SFR7W_cjs.endShell(host, live);
2855
+ chunk3DCTQKPQ_cjs.endShell(host, live);
2682
2856
  live.shell.dispose();
2683
2857
  durable.delete(principal);
2684
2858
  }
@@ -2700,7 +2874,7 @@ var rosterOf = (durable) => {
2700
2874
  var sameDocument = (one, other) => one === other || JSON.stringify(one) === JSON.stringify(other);
2701
2875
  var takeLayouts = (live, made) => {
2702
2876
  const taken = live.layouts;
2703
- const answered = chunkF45SFR7W_cjs.layoutsOf(made);
2877
+ const answered = chunk3DCTQKPQ_cjs.layoutsOf(made);
2704
2878
  for (const [ref, layout] of Object.entries(answered.layoutStore)) {
2705
2879
  if (!sameDocument(taken.layoutStore[ref], layout)) live.shell.setLayout(ref, layout);
2706
2880
  }
@@ -2730,15 +2904,15 @@ var takeComposition = (live, made) => {
2730
2904
  live.entries = made.entries;
2731
2905
  takeLayouts(live, made);
2732
2906
  takeCanvases(live, made);
2733
- chunkF45SFR7W_cjs.holdGranted(live.functions, made.grantedFunctions);
2907
+ chunk3DCTQKPQ_cjs.holdGranted(live.functions, made.grantedFunctions);
2734
2908
  };
2735
2909
  var adoptDraft = async (host, live, next) => {
2736
2910
  for (; ; ) {
2737
2911
  const cell = host.living.get(live);
2738
- if (cell === void 0 || cell.live !== live) throw new Error(chunkF45SFR7W_cjs.SHELL_GONE);
2912
+ if (cell === void 0 || cell.live !== live) throw new Error(chunk3DCTQKPQ_cjs.SHELL_GONE);
2739
2913
  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);
2914
+ const made = await host.config.composition(cell.principal, chunk3DCTQKPQ_cjs.draftedIn(next));
2915
+ if (live.ended || cell.live !== live) throw new Error(chunk3DCTQKPQ_cjs.SHELL_GONE);
2742
2916
  if (changes < cell.changes) continue;
2743
2917
  cell.changes = changes;
2744
2918
  live.draft = next;
@@ -2752,7 +2926,7 @@ var adopt = (host, cell) => {
2752
2926
  if (asked.ended) return;
2753
2927
  const drafted = asked.draft;
2754
2928
  const changes = host.changes;
2755
- const made = await host.config.composition(cell.principal, chunkF45SFR7W_cjs.draftedIn(drafted));
2929
+ const made = await host.config.composition(cell.principal, chunk3DCTQKPQ_cjs.draftedIn(drafted));
2756
2930
  if (asked.ended || changes <= cell.changes) return;
2757
2931
  if (asked.draft !== drafted) {
2758
2932
  adopt(host, cell);
@@ -2783,7 +2957,7 @@ var build = (host, asked, wanted = () => true) => {
2783
2957
  reject(new Error(`moss: the shell of ${asked.principal ?? "nobody"} was not built within ${limit}ms.`));
2784
2958
  }, limit);
2785
2959
  timer.unref?.();
2786
- chunkF45SFR7W_cjs.buildShell(host, { ...asked, wanted: () => inTime && wanted() }).then((live) => resolve2(live === void 0 ? void 0 : { live, changes }), reject).finally(() => clearTimeout(timer));
2960
+ chunk3DCTQKPQ_cjs.buildShell(host, { ...asked, wanted: () => inTime && wanted() }).then((live) => resolve2(live === void 0 ? void 0 : { live, changes }), reject).finally(() => clearTimeout(timer));
2787
2961
  });
2788
2962
  };
2789
2963
  var builtOrThrow = (built) => {
@@ -2823,18 +2997,18 @@ var replaceShell = async (host, cell) => {
2823
2997
  if (built === void 0) return;
2824
2998
  const old = cell.live;
2825
2999
  if (!stands()) {
2826
- chunkF45SFR7W_cjs.endShell(host, built.live);
3000
+ chunk3DCTQKPQ_cjs.endShell(host, built.live);
2827
3001
  built.live.shell.dispose();
2828
3002
  return;
2829
3003
  }
2830
3004
  const carried = [...old.connections].map((connection) => ({ connection, wants: old.deltaReady.has(connection) }));
2831
- chunkF45SFR7W_cjs.endShell(host, old);
3005
+ chunk3DCTQKPQ_cjs.endShell(host, old);
2832
3006
  old.connections.clear();
2833
3007
  old.shell.dispose();
2834
3008
  cell.live = built.live;
2835
3009
  cell.changes = built.changes;
2836
3010
  registerLiving(host, cell);
2837
- for (const { connection, wants } of carried) chunkF45SFR7W_cjs.attach(built.live, connection, host.delta && wants);
3011
+ for (const { connection, wants } of carried) chunk3DCTQKPQ_cjs.attach(built.live, connection, host.delta && wants);
2838
3012
  };
2839
3013
  var resetCell = (host, cell) => {
2840
3014
  const turn = (cell.resetting ?? Promise.resolve()).then(() => replaceShell(host, cell));
@@ -2872,7 +3046,7 @@ var snapshotOf = (host) => async (token, principal, options) => {
2872
3046
  const settled = await settle(live, waitMs);
2873
3047
  return { ...read(live), seed, settled, ...needOf(live, principal, kept) };
2874
3048
  } finally {
2875
- chunkF45SFR7W_cjs.endShell(host, live);
3049
+ chunk3DCTQKPQ_cjs.endShell(host, live);
2876
3050
  live.shell.dispose();
2877
3051
  }
2878
3052
  };
@@ -2891,7 +3065,7 @@ var deliverTo = (host) => (principal, channel, payload) => {
2891
3065
  var createShellHost = (config) => {
2892
3066
  const host = {
2893
3067
  config,
2894
- emit: chunkC2DNDIQX_cjs.emitterOf(config.telemetry),
3068
+ emit: chunkPVZMCEBX_cjs.emitterOf(config.telemetry),
2895
3069
  kept: config.kept ?? true,
2896
3070
  delta: config.limits?.delta ?? false,
2897
3071
  durable: /* @__PURE__ */ new Map(),
@@ -2904,9 +3078,9 @@ var createShellHost = (config) => {
2904
3078
  const handedOut = {
2905
3079
  session: async (token, principal, options) => {
2906
3080
  if (principal === null || !host.kept) {
2907
- return chunkF45SFR7W_cjs.sessionOn(host, await open2(host, { token, principal, ...options !== void 0 ? { opening: options } : {} }, false), true, reset);
3081
+ return chunk3DCTQKPQ_cjs.sessionOn(host, await open2(host, { token, principal, ...options !== void 0 ? { opening: options } : {} }, false), true, reset);
2908
3082
  }
2909
- return chunkF45SFR7W_cjs.sessionOn(host, await keptCell(host, token, principal), false, reset);
3083
+ return chunk3DCTQKPQ_cjs.sessionOn(host, await keptCell(host, token, principal), false, reset);
2910
3084
  },
2911
3085
  snapshot: snapshotOf(host),
2912
3086
  deliver: deliverTo(host),
@@ -2966,21 +3140,20 @@ var hostConfig = (deps, shell, kept) => {
2966
3140
  }
2967
3141
  };
2968
3142
  };
2969
- var sayingWhatToFix = (functions) => {
2970
- let said = false;
3143
+ var checkedOnce = (functions, written) => {
3144
+ let checked2 = false;
2971
3145
  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);
3146
+ const given = functions(session);
3147
+ if (!checked2) {
3148
+ written(given);
3149
+ checked2 = true;
2977
3150
  }
2978
- return written;
3151
+ return given;
2979
3152
  };
2980
3153
  };
2981
3154
  var buildShellHosts = (deps) => {
2982
3155
  const { app } = deps;
2983
- const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: sayingWhatToFix(app.functions) } };
3156
+ const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: checkedOnce(app.functions, deps.running.functionsWritten) } };
2984
3157
  const pageManifests = app.pages ?? {};
2985
3158
  const pageRouter = createPageRouter(pageManifests);
2986
3159
  const shells = app.shell !== void 0 ? createShellHost(hostConfig(wired, app.shell, true)) : void 0;
@@ -2998,6 +3171,11 @@ var buildShellHosts = (deps) => {
2998
3171
  return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
2999
3172
  },
3000
3173
  pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
3174
+ buildForNobody: async () => {
3175
+ if (app.functions === void 0) deps.running.functionsWritten([]);
3176
+ else await every[0]?.snapshot(null, null, { waitMs: 0 });
3177
+ await deps.running.readPublished();
3178
+ },
3001
3179
  adopt: () => {
3002
3180
  for (const made of owned) made.adopt();
3003
3181
  },
@@ -3158,7 +3336,7 @@ var wireFabric = (fabric, origin, apply) => {
3158
3336
  };
3159
3337
  let refusalSaid = false;
3160
3338
  fabric.subscribe((handed) => {
3161
- const parsed = chunkC2DNDIQX_cjs.FabricMessageSchema.safeParse(handed);
3339
+ const parsed = chunkPVZMCEBX_cjs.FabricMessageSchema.safeParse(handed);
3162
3340
  if (!parsed.success) {
3163
3341
  if (refusalSaid) return;
3164
3342
  refusalSaid = true;
@@ -3198,7 +3376,7 @@ var wireFabric = (fabric, origin, apply) => {
3198
3376
 
3199
3377
  // src/server/server.ts
3200
3378
  var createServerWith = async (app, runtime, dataOf) => {
3201
- chunkF45SFR7W_cjs.receiveManifest(app);
3379
+ chunk3DCTQKPQ_cjs.receiveManifest(app);
3202
3380
  const session = sessionVerifierOf(runtime);
3203
3381
  const revokeSessions = sessionRevokerOf(runtime);
3204
3382
  const data = await dataOf(app, runtime);
@@ -3242,6 +3420,14 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3242
3420
  const saved = savedRowsOver(await data.artifactEntries(SAVE_ENTRIES, SAVE_ROW_RULES), data.grammars);
3243
3421
  const running = await buildRunningManifest(app, runtime, data, saved);
3244
3422
  stops.push(running.stop);
3423
+ if (runtime.artifactsUnusedMs !== void 0) {
3424
+ if (!Number.isSafeInteger(runtime.artifactsUnusedMs) || runtime.artifactsUnusedMs < 2 * TOUCH_EVERY_MS) {
3425
+ throw new Error(
3426
+ `moss: \`runtime.artifactsUnusedMs\` is how long what a person generated may go unused before it is deleted: a whole number of milliseconds, at least ${2 * TOUCH_EVERY_MS} (two hours), or left out, and nothing is deleted.`
3427
+ );
3428
+ }
3429
+ stops.push(startAging(runtime.pool, runtime.artifactsUnusedMs));
3430
+ }
3245
3431
  const identity = buildIdentity(app, runtime, data);
3246
3432
  stops.push(identity.stop);
3247
3433
  const server = new hono.Hono();
@@ -3268,6 +3454,7 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3268
3454
  principalOf: async (token) => session(token),
3269
3455
  page: hosts.pageAt,
3270
3456
  pages: hosts.pages,
3457
+ checkFunctions: hosts.buildForNobody,
3271
3458
  ...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
3272
3459
  refresh: running.refresh,
3273
3460
  replaceActions: running.replace,
@@ -3277,7 +3464,10 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
3277
3464
  if (typeof publisher !== "string" || publisher === "") {
3278
3465
  throw new Error("moss: `defaults` is handed who publishes. What is published is everybody\u2019s, and who published it is kept with it.");
3279
3466
  }
3280
- return running.publishedArtifacts(saved.published(publisher));
3467
+ return running.publishedArtifacts(saved.published(publisher), async () => {
3468
+ const resolved = await identity.resolve(publisher);
3469
+ return { roles: resolved.roles, replayable: () => data.fingerprintsFor(resolved) };
3470
+ });
3281
3471
  },
3282
3472
  catalogOf: async (principal) => {
3283
3473
  const resolved = await identity.resolve(principal);
@@ -3372,5 +3562,5 @@ exports.mintSession = mintSession;
3372
3562
  exports.renderDocument = renderDocument;
3373
3563
  exports.revokeAllFor = revokeAllFor;
3374
3564
  exports.sessionCookies = sessionCookies;
3375
- //# sourceMappingURL=chunk-DSTHFSTO.cjs.map
3376
- //# sourceMappingURL=chunk-DSTHFSTO.cjs.map
3565
+ //# sourceMappingURL=chunk-TMDKNZYL.cjs.map
3566
+ //# sourceMappingURL=chunk-TMDKNZYL.cjs.map