@marver-design/marver 0.27.0 → 0.28.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 (111) hide show
  1. package/CHANGELOG.md +195 -0
  2. package/README.md +9 -4
  3. package/dist/{anchor-check-ChdDqL5z.mjs → anchor-check-PHUOFj1N.mjs} +1 -1
  4. package/dist/{audio-Dw1lfMdb.mjs → audio-DX4POHAj.mjs} +39 -4
  5. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  6. package/dist/{boards-DlTcpF47.mjs → boards-BeWtjGUM.mjs} +50 -5
  7. package/dist/boards-EH2onUXM.mjs +995 -0
  8. package/dist/{build-DZnFysGU.mjs → build-BsAyLMT1.mjs} +9 -22
  9. package/dist/{capture-vadKjuCo.mjs → capture-DdZ6xgoz.mjs} +92 -30
  10. package/dist/cli.mjs +56 -21
  11. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  12. package/dist/{comments-DxOkCSNE.mjs → comments-CrBHPEQl.mjs} +4 -4
  13. package/dist/config-BezZTiov.mjs +182 -0
  14. package/dist/conn-BMiHS42T.mjs +222 -0
  15. package/dist/connectors-MR9d-EBP.mjs +290 -0
  16. package/dist/{context-HQ4Giw58.mjs → context-BUnFiyA3.mjs} +3 -3
  17. package/dist/{daemon-BSA0lV8d.mjs → daemon-C5dg2R-V.mjs} +2188 -183
  18. package/dist/{dev-eQJhWsqg.mjs → dev-D7YS7iT2.mjs} +25 -14
  19. package/dist/{init-COD0x48i.mjs → init-WE5lQkQL.mjs} +8 -3
  20. package/dist/jam-Cj5gBvwD.mjs +373 -0
  21. package/dist/{link-DDXZVGtv.mjs → link-BFFRgrMt.mjs} +4 -4
  22. package/dist/listener-DdLEM79A.mjs +80 -0
  23. package/dist/{ls-D7O1G505.mjs → ls-BZ5TAtd5.mjs} +1 -1
  24. package/dist/{manifest-Nl3KSVOk.mjs → manifest-DPZ3WNg_.mjs} +2 -2
  25. package/dist/{marks-CWM3WJjc.mjs → marks-Dyn6tmjp.mjs} +3 -3
  26. package/dist/{marks-CKgzucHZ.mjs → marks-Kmdab_5w.mjs} +3 -3
  27. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  28. package/dist/perf-Cn5LiRaY.mjs +1319 -0
  29. package/dist/perf-jam-QxD_UnzN.mjs +635 -0
  30. package/dist/permit-DDa6wqOs.mjs +187 -0
  31. package/dist/plugin-C_0yb-Fq.mjs +5089 -0
  32. package/dist/{poster-Bx83ZYVK.mjs → poster-DHi6I1fO.mjs} +1 -1
  33. package/dist/{profile-Bh5Y5zpW.mjs → profile-jIS6BcAs.mjs} +1 -1
  34. package/dist/{publish-bakes-aljgm45S.mjs → publish-bakes-r4PEZuPl.mjs} +3 -3
  35. package/dist/{queue-CAM_vNmX.mjs → queue-c-6aTHEz.mjs} +164 -25
  36. package/dist/{recover-t9Pno3u9.mjs → recover-nrLEVLyJ.mjs} +2 -2
  37. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  38. package/dist/{session-BAaJsK5c.mjs → session-DyVE7cCk.mjs} +1 -1
  39. package/dist/{share-W5H3BNvP.mjs → share-Ce4tP7ji.mjs} +1 -1
  40. package/dist/{shot-LFhC-WYD.mjs → shot-BrRtqaiS.mjs} +34 -8
  41. package/dist/{shot-DoHLl6ig.mjs → shot-DBWN8hPP.mjs} +1 -1
  42. package/dist/sizes-wjXDev3b.mjs +139 -0
  43. package/dist/{slots-DCDo3N0x.mjs → slots-CFNnegCc.mjs} +8 -1
  44. package/dist/speech-worker.mjs +23 -3
  45. package/dist/{sync-BQVlHZpx.mjs → sync-CQdGARJ9.mjs} +1 -1
  46. package/dist/transport-C5FnY9ni.mjs +203 -0
  47. package/dist/{work-BroFwnup.mjs → work-BYWD_1Zf.mjs} +3 -3
  48. package/dist/{work-Bp1p39kq.mjs → work-DJxH7cCX.mjs} +1 -1
  49. package/docs/jam-session.md +42 -16
  50. package/docs/live-jam.md +92 -10
  51. package/docs/performance.md +197 -35
  52. package/package.json +1 -1
  53. package/src/client/content/video.tsx +10 -2
  54. package/src/client/shell/App.tsx +10 -3
  55. package/src/client/shell/Comments.tsx +5 -3
  56. package/src/client/shell/ContextMenu.tsx +5 -3
  57. package/src/client/shell/JamSurface.tsx +56 -21
  58. package/src/client/shell/LockedApp.tsx +3 -0
  59. package/src/client/shell/Play.tsx +4 -2
  60. package/src/client/shell/Tip.tsx +3 -1
  61. package/src/client/shell/api.ts +47 -20
  62. package/src/client/shell/app-bridge.ts +254 -0
  63. package/src/client/shell/app-perf.ts +92 -0
  64. package/src/client/shell/canvas/Canvas.tsx +115 -22
  65. package/src/client/shell/canvas/FrameNode.tsx +10 -6
  66. package/src/client/shell/canvas/admission.ts +23 -8
  67. package/src/client/shell/canvas/ctl.ts +6 -0
  68. package/src/client/shell/canvas/sleep.ts +57 -17
  69. package/src/client/shell/canvas/updates.ts +2 -1
  70. package/src/client/shell/icons.tsx +1 -0
  71. package/src/client/shell/inset.ts +44 -0
  72. package/src/client/shell/jam-capture.ts +113 -33
  73. package/src/client/shell/jam-keys.ts +40 -9
  74. package/src/client/shell/jam-lane.tsx +14 -5
  75. package/src/client/shell/jam-lines.ts +66 -9
  76. package/src/client/shell/jam-panel.tsx +61 -6
  77. package/src/client/shell/jam-queue.ts +50 -8
  78. package/src/client/shell/jam-session.tsx +53 -4
  79. package/src/client/shell/jam-surface-parts.tsx +6 -3
  80. package/src/client/shell/jam-ui.tsx +6 -1
  81. package/src/client/shell/jam-voice-wait.ts +21 -0
  82. package/src/client/shell/jam-voice.ts +62 -15
  83. package/src/client/shell/main.tsx +14 -1
  84. package/src/client/shell/marks-ui.tsx +5 -3
  85. package/src/client/shell/marver-app.ts +21 -0
  86. package/src/client/shell/perf-run-probe.ts +34 -0
  87. package/src/client/shell/perf-run.ts +70 -0
  88. package/src/client/shell/perf.ts +11 -0
  89. package/src/client/shell/recorder.ts +45 -3
  90. package/src/client/shell/store.ts +52 -24
  91. package/src/client/shell/styles.css +65 -17
  92. package/src/client/shell/tidy.ts +3 -2
  93. package/src/client/shell/unsaved.ts +81 -0
  94. package/src/client/shell/whiteout-probes.ts +141 -0
  95. package/src/shared/app-api.ts +205 -0
  96. package/src/shared/app-perf.ts +308 -0
  97. package/src/shared/approval.ts +20 -0
  98. package/src/shared/events.ts +1 -1
  99. package/src/shared/logo-sniff.ts +86 -0
  100. package/src/shared/machine.ts +132 -0
  101. package/src/shared/perf-run.ts +177 -0
  102. package/templates/AGENTS-embedded.md +31 -1
  103. package/templates/AGENTS-studio.md +31 -1
  104. package/templates/instructions/boards.md +10 -2
  105. package/templates/instructions/jam.md +90 -0
  106. package/dist/bake-DM_uWgAA.mjs +0 -786
  107. package/dist/boards-CGg6piKF.mjs +0 -342
  108. package/dist/perf-BWzQwZqj.mjs +0 -369
  109. package/dist/perf-BoDSkbEb.mjs +0 -429
  110. package/dist/perf-jam-D55U3FZK.mjs +0 -242
  111. package/dist/plugin-C-E7omsh.mjs +0 -2762
@@ -1,2762 +0,0 @@
1
- import { a as ROUTE, i as PKG, r as NAME } from "./cli.mjs";
2
- import { c as nodeExists, d as readMembership, f as readRegistry, h as hash, i as checkBoardsDir, l as parseBoard, m as withRegistryLock, o as isRegularFile, r as boardFields, s as listBoardFiles, t as AUTHOR_FIELDS, u as pinFrames } from "./boards-CGg6piKF.mjs";
3
- import { A as settableStatuses, D as readStatusWord, E as readReason, O as readType, T as readCapability, _ as wireKids, a as buildTree, c as folderMap, g as validateWire, h as readTitle, k as resolveType, m as readDescription, n as BOARD_NAME, r as FOLDERS_FILE, t as ALL_SCENES, x as HAS_STATUS } from "./board-tree-DRioF94d.mjs";
4
- import { c as setSceneTitle, d as annotateBoards, f as planNames, m as readContextFacts, n as isNoteFile, o as rendersDoc, p as planWithStage, r as layoutDocSource, s as scanFrames, t as affectedFrameIds, u as writeManifest } from "./manifest-Nl3KSVOk.mjs";
5
- import { r as boardsChanged } from "./work-Bp1p39kq.mjs";
6
- import { h as workspaceId, o as originOf } from "./slots-DCDo3N0x.mjs";
7
- import { n as localProfile, t as isConnected } from "./profile-Bh5Y5zpW.mjs";
8
- import { i as onPath, n as AGENT_NAMES, r as detectAgent, t as AGENT_BIN } from "./agent-BsieQGTD.mjs";
9
- import { a as observe, n as docRevs, r as initMarks, s as recordChanged, t as docRev } from "./marks-CKgzucHZ.mjs";
10
- import { n as logPage, r as logReload, s as tidyPerfDir, t as PAGE_BODY_MAX } from "./perf-BWzQwZqj.mjs";
11
- import { closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
12
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
13
- import { fileURLToPath, pathToFileURL } from "node:url";
14
- import { createHmac, randomBytes } from "node:crypto";
15
- //#region src/server/config.ts
16
- const DEFAULTS = {
17
- mode: "studio",
18
- theme: null,
19
- viewports: {
20
- mobile: {
21
- width: 390,
22
- height: 844
23
- },
24
- tablet: {
25
- width: 768,
26
- height: 1024
27
- },
28
- laptop: {
29
- width: 1280,
30
- height: 800
31
- },
32
- monitor: {
33
- width: 1920,
34
- height: 1080
35
- }
36
- },
37
- themes: ["light", "dark"],
38
- port: 5199,
39
- zoomSpeed: 1,
40
- share: { branding: true }
41
- };
42
- /** Load design/config.ts via native TS import (Node >= 22.18). Missing or broken fields fall back to defaults. */
43
- async function loadConfig(root) {
44
- const file = join(root, "design", "config.ts");
45
- if (!existsSync(file)) return {
46
- ...DEFAULTS,
47
- ...jamFields(void 0)
48
- };
49
- try {
50
- const user = (await import(`${pathToFileURL(file).href}?t=${Date.now()}`)).default ?? {};
51
- return {
52
- ...DEFAULTS,
53
- ...user,
54
- viewports: validViewports(user.viewports) ?? DEFAULTS.viewports,
55
- themes: Array.isArray(user.themes) && user.themes.length ? user.themes.map(String) : DEFAULTS.themes,
56
- port: validPort(user.port) ?? DEFAULTS.port,
57
- zoomSpeed: validZoom(user.zoomSpeed) ?? DEFAULTS.zoomSpeed,
58
- description: readDescription(user.description),
59
- share: {
60
- branding: user.share?.branding !== false,
61
- name: typeof user.share?.name === "string" ? user.share.name : void 0,
62
- logo: typeof user.share?.logo === "string" ? user.share.logo : void 0,
63
- frontDoor: user.share?.frontDoor !== false && user.share?.front_door !== false,
64
- notify: user.share?.notify !== false
65
- },
66
- ...jamFields(user.jam)
67
- };
68
- } catch (err) {
69
- console.error(`[marver] design/config.ts failed to load, using defaults and leaving Live Jam OFF:\n ${err.message}`);
70
- return {
71
- ...DEFAULTS,
72
- jamOff: "unreadable"
73
- };
74
- }
75
- }
76
- const validDim = (n) => typeof n === "number" && Number.isFinite(n) && n >= 1 && n <= 2e4;
77
- function validPort(n) {
78
- return typeof n === "number" && Number.isInteger(n) && n > 0 && n < 65536 ? n : null;
79
- }
80
- function validZoom(n) {
81
- return typeof n === "number" && Number.isFinite(n) && n >= .1 && n <= 10 ? n : null;
82
- }
83
- /** Six frames at once is what a jam actually feels like - at 3, half of a multi-frame
84
- * ask sat waiting on the other half while the human watched. */
85
- const DEFAULT_CONCURRENCY = 6;
86
- /** A config value, printable in a warning. Never throws - a formatter that can crash inside an
87
- * error path (JSON.stringify does, on a BigInt) turns a clear message into a mystery. */
88
- const show = (v) => {
89
- try {
90
- return JSON.stringify(v) ?? String(v);
91
- } catch {
92
- return String(v);
93
- }
94
- };
95
- /** A `{...}` written by hand, not a Date/Map/class instance that merely types as "object". */
96
- const plainObject = (v) => {
97
- if (!v || typeof v !== "object") return false;
98
- const proto = Object.getPrototypeOf(v);
99
- return proto === Object.prototype || proto === null;
100
- };
101
- /** The agent to arm with - or, when the human NAMED one we cannot use, why not (said once,
102
- * here, because a bad `jam.agent` is a config-file error like any other).
103
- *
104
- * A named agent is never quietly swapped for another: running a different tool than the one
105
- * asked for is worse than not running. Nor is one armed that cannot be spawned - that would
106
- * claim every @marver mention, fail it, and never retry. */
107
- function resolveAgent(named) {
108
- if (named === void 0) return detectAgent() ?? "no-agent";
109
- if (typeof named !== "string" || !Object.hasOwn(AGENT_BIN, named)) {
110
- console.warn(`[marver] design/config.ts: jam.agent ${show(named)} is not an agent marver can spawn - Live Jam is off. Use ${AGENT_NAMES}.`);
111
- return "bad-agent";
112
- }
113
- const agent = named;
114
- if (!onPath(AGENT_BIN[agent])) {
115
- console.warn(`[marver] design/config.ts names jam.agent "${agent}", but \`${AGENT_BIN[agent]}\` is not on PATH - Live Jam is off until it is installed.`);
116
- return "bad-agent";
117
- }
118
- return agent;
119
- }
120
- /** Resolve the jam block. Live Jam is ON by default: an absent or partial `jam` resolves
121
- * to whatever agent CLI this machine has, so a fresh workspace jams with nothing
122
- * configured and an old one needs no re-init. `jam: false` is the off switch. */
123
- function resolveJam(v) {
124
- if (v === false) return "opted-out";
125
- const shape = v === void 0 || v === true ? {} : typeof v === "string" ? { agent: v } : plainObject(v) ? v : null;
126
- if (!shape) {
127
- console.warn(`[marver] design/config.ts: jam must be false, an agent name, or an options object - got ${show(v)}. Live Jam is off.`);
128
- return "bad-agent";
129
- }
130
- const j = shape;
131
- const agent = resolveAgent(j.agent);
132
- if (agent === "no-agent" || agent === "bad-agent") return agent;
133
- const c = j.concurrency;
134
- const pick = (key, v, ok, fallback, want) => {
135
- if (v === void 0) return fallback;
136
- if (ok(v)) return v;
137
- console.warn(`[marver] design/config.ts: jam.${key} must be ${want} - got ${show(v)}. Using ${JSON.stringify(fallback)}.`);
138
- return fallback;
139
- };
140
- const bool = (v) => typeof v === "boolean";
141
- return {
142
- agent,
143
- concurrency: typeof c === "number" && Number.isInteger(c) && c >= 1 && c <= 16 ? c : DEFAULT_CONCURRENCY,
144
- subagents: j.subagents !== false,
145
- proactive: j.proactive === true,
146
- chime: pick("chime", j.chime, bool, true, "true or false"),
147
- capture: pick("capture", j.capture, (v) => v === "confirm" || v === "at-once", "confirm", `'confirm' or 'at-once'`),
148
- loc: pick("loc", j.loc, bool, true, "true or false"),
149
- names: pick("names", j.names, bool, true, "true or false")
150
- };
151
- }
152
- /** Exactly one of `jam` (armed) or `jamOff` (why not) - so the dev server can speak up about
153
- * the one off-state nothing has reported yet, and stay quiet about the rest. BOTH keys are
154
- * always written: these spread over the user's own `jam`, and a raw `jam: false` reaching the
155
- * server as config would arm the daemon against a truthy object check. */
156
- function jamFields(v) {
157
- const r = resolveJam(v);
158
- return typeof r === "string" ? {
159
- jam: void 0,
160
- jamOff: r
161
- } : {
162
- jam: r,
163
- jamOff: void 0
164
- };
165
- }
166
- function validViewports(v) {
167
- if (!v || typeof v !== "object") return null;
168
- const out = {};
169
- for (const [k, val] of Object.entries(v)) {
170
- const vp = val;
171
- if (validDim(vp?.width) && validDim(vp?.height)) out[k] = {
172
- width: Math.round(vp.width),
173
- height: Math.round(vp.height)
174
- };
175
- }
176
- return Object.keys(out).length ? out : null;
177
- }
178
- //#endregion
179
- //#region src/shared/frames.ts
180
- /** A canvas made of content frames alone (Doc, Md, Diagram ship their own styling) needs no theme -
181
- * only an app frame does (#4). Empty counts as not content-only: the warning still helps there. */
182
- const contentOnly = (frames) => frames.length > 0 && frames.every((f) => !!f.intent);
183
- //#endregion
184
- //#region src/server/updates.ts
185
- /**
186
- * Calm updates, the dev server's half (spec 26 Part 2). Frame documents take no updates from Vite:
187
- * Fast Refresh is off under design/ (dev.ts) and the frame host's registry accepts every update and
188
- * ignores it. Marver decides which frames an edit touched, before Vite's update collapses into that
189
- * shared registry, and the shell reloads exactly those - a few at a time, on screen first.
190
- *
191
- * Which frames, two answers united:
192
- * - by path: the edited file mapped directly - a frame, or a wrapper the frame host puts around
193
- * frames (providers -> every TSX frame, a _layout or _fixtures file -> every TSX frame below it),
194
- * which also covers a wrapper just created, before Vite has a module for it;
195
- * - by graph: the edit's modules walked up their importers to frame modules, exact for every loaded
196
- * document, the wrapper mapping applied wherever the walk reaches a wrapper.
197
- * A walk that passes a module accepting its own updates (an app component under src/**, a stylesheet)
198
- * has been applied in place: the frames past it are touched (marked) but not reloaded.
199
- *
200
- * Every other `full-reload` Vite or Tailwind sends is dropped and becomes reloads of the frames it
201
- * names (or every frame, when it names none) - the shell never reloads for a design edit. The one
202
- * that passes is the dependency optimiser's: module URLs changed, every document must reload.
203
- */
204
- const safeReal = (p) => {
205
- try {
206
- return realpathSync(p);
207
- } catch {
208
- return p;
209
- }
210
- };
211
- /** The frames an edit reaches: `doc` must reload to show it; `touched` saw it applied in place. */
212
- function framesFor(root, manifest, file, modules, skipFirst = false) {
213
- const real = safeReal(root);
214
- const byFile = new Map(manifest.frames.flatMap((f) => [[join(root, f.file), f], [join(real, f.file), f]]));
215
- const doc = /* @__PURE__ */ new Set(), touched = /* @__PURE__ */ new Set();
216
- const wrapper = (f) => /(^|[/\\])(providers\.(tsx|jsx)|_layout\.(tsx|jsx)|_fixtures\.(ts|tsx|js|jsx|json))$/.test(f);
217
- const add = (ids, inPlace) => {
218
- for (const id of ids) (inPlace ? touched : doc).add(id);
219
- };
220
- add(affectedFrameIds(file, root, manifest) ?? [], false);
221
- const seen = /* @__PURE__ */ new Map();
222
- const queue = [];
223
- for (const m of modules) {
224
- if (skipFirst) {
225
- for (const up of m.importers) queue.push([up, false]);
226
- continue;
227
- }
228
- queue.push([m, false]);
229
- }
230
- while (queue.length) {
231
- const [m, inPlace] = queue.shift();
232
- const had = seen.get(m);
233
- if (had === false || had === inPlace) continue;
234
- seen.set(m, inPlace);
235
- const f = m.file ? byFile.get(m.file) : void 0;
236
- if (f) (inPlace ? touched : doc).add(f.id);
237
- if (m.file && wrapper(m.file)) add(affectedFrameIds(m.file, root, manifest) ?? [], inPlace);
238
- const accepts = m.isSelfAccepting === true;
239
- for (const up of m.importers) queue.push([up, inPlace || accepts]);
240
- }
241
- for (const id of doc) touched.delete(id);
242
- return {
243
- file,
244
- doc: [...doc],
245
- touched: [...touched]
246
- };
247
- }
248
- /** The hook that runs last on every hot update of the client environment. */
249
- function updatesPlugin(root, manifest, hooks, landed) {
250
- return {
251
- name: "marver:updates",
252
- hotUpdate: {
253
- order: "post",
254
- handler(opts) {
255
- landed(opts.file);
256
- if (this.environment.name !== "client") return;
257
- const h = hooks();
258
- if (!h) return;
259
- const t = framesFor(root, manifest(), opts.file, opts.modules);
260
- if (t.doc.length || t.touched.length) h.onFrames(t, "update");
261
- }
262
- }
263
- };
264
- }
265
- /** Wraps the client's hot channel: the reload guard and refused refreshes. */
266
- function guardUpdates(server, root, manifest, hooks) {
267
- const env = server.environments.client;
268
- const wrap = (ch) => {
269
- const send = ch.send.bind(ch);
270
- ch.send = (...a) => {
271
- const p = a[0];
272
- if (typeof p === "object" && p?.type === "full-reload") {
273
- const passed = p.path === "*" && !p.triggeredBy;
274
- hooks.onReload({
275
- triggeredBy: p.triggeredBy,
276
- path: p.path
277
- }, passed);
278
- if (!passed) {
279
- const by = p.triggeredBy ?? (p.path && p.path !== "*" ? join(root, p.path.replace(/^\//, "")) : void 0);
280
- const mods = by ? env.moduleGraph.getModulesByFile(by) : void 0;
281
- const all = manifest().frames.map((f) => f.id);
282
- const t = by ? framesFor(root, manifest(), by, mods ?? []) : {
283
- file: "",
284
- doc: all,
285
- touched: [],
286
- unattributed: true
287
- };
288
- if (t.doc.length || t.touched.length) hooks.onFrames(t, "reload");
289
- return;
290
- }
291
- }
292
- send(...a);
293
- };
294
- };
295
- wrap(env.hot);
296
- if (server.ws !== env.hot) wrap(server.ws);
297
- const refused = /* @__PURE__ */ new Map();
298
- env.hot.on("vite:invalidate", (payload) => {
299
- const mod = payload?.path ? env.moduleGraph.urlToModuleMap.get(payload.path) : void 0;
300
- if (!mod?.file) return;
301
- if (refused.get(mod.url) === mod.lastHMRTimestamp) return;
302
- refused.set(mod.url, mod.lastHMRTimestamp);
303
- const t = framesFor(root, manifest(), mod.file, [mod], true);
304
- if (t.doc.length || t.touched.length) hooks.onFrames(t, "invalidate");
305
- });
306
- }
307
- //#endregion
308
- //#region src/server/sizes.ts
309
- /**
310
- * Content-frame heights - `design/boards/_sizes.json`, committed.
311
- *
312
- * A content frame (a Doc: markdown, diagrams, images) is as tall as its content, which only a
313
- * render can tell. Measured live, every load started from a guess (3/4 of the width) and grew
314
- * frame by frame, and each growth re-flowed the rows below - the board swam for seconds. The
315
- * height a frame measured at its own width is a fact about the FRAME at that width, not about a
316
- * board (one doc sits on several boards) and not something to write into the frame's source: so
317
- * it lives here, one line per `scene/frame@width`, written by the dev server when the shell
318
- * reports a settled measurement, read before the first layout - dev, `marver build` and the
319
- * published canvas alike. A stale entry is still the best first guess; the live measurement
320
- * corrects it and the file follows. Underscore = infrastructure, never a board (board-tree.ts).
321
- */
322
- const SIZES_FILE = "_sizes.json";
323
- /** `scene/frame@width` - the frame id grammar the focus route accepts, then the width it was measured at. */
324
- const SIZE_KEY = /^([\w./-]{1,200})@(\d{2,4})$/;
325
- const ABOUT = "Written by marver dev: the height each content frame measured at its width, so boards open at their final size. Commit it; never edit it by hand.";
326
- const sizesPath = (root) => join(root, "design", "boards", SIZES_FILE);
327
- /** A valid entry: a well-formed key whose frame is not a traversal, and a height in the shell's clamp. */
328
- function validEntry(key, h) {
329
- if (typeof key !== "string" || typeof h !== "number" || !Number.isInteger(h) || h < 80 || h > 4e4) return false;
330
- const m = SIZE_KEY.exec(key);
331
- return !!m && !m[1].split("/").some((p) => p === ".." || p === "." || p === "");
332
- }
333
- function readSizesFile(root) {
334
- const file = sizesPath(root);
335
- if (!existsSync(file)) return {
336
- state: "absent",
337
- heights: {}
338
- };
339
- try {
340
- const raw = JSON.parse(readFileSync(file, "utf8"));
341
- if (!raw || typeof raw !== "object" || !raw.heights || typeof raw.heights !== "object" || Array.isArray(raw.heights)) return {
342
- state: "invalid",
343
- heights: {}
344
- };
345
- const out = {};
346
- for (const [k, v] of Object.entries(raw.heights)) if (validEntry(k, v)) out[k] = v;
347
- return {
348
- state: "ok",
349
- heights: out
350
- };
351
- } catch {
352
- return {
353
- state: "invalid",
354
- heights: {}
355
- };
356
- }
357
- }
358
- /** Lenient read for the readers (the shell's first layout, the build): an absent or invalid file is
359
- * no heights - every frame opens at its placeholder, as before. Never throws. */
360
- const readSizes = (root) => readSizesFile(root).heights;
361
- /** The file's text for a set of heights: sorted keys, one entry per line - a changed height is a
362
- * one-line diff, and two branches that measured different frames merge without a conflict. */
363
- function serializeSizes(heights) {
364
- const sorted = {};
365
- for (const k of Object.keys(heights).sort()) sorted[k] = heights[k];
366
- return JSON.stringify({
367
- about: ABOUT,
368
- heights: sorted
369
- }, null, 2) + "\n";
370
- }
371
- const keeps = (key, autoWidth) => {
372
- const m = SIZE_KEY.exec(key);
373
- return !!m && autoWidth(m[1]) === Number(m[2]);
374
- };
375
- /** Merge incoming heights into the current ones, keeping only what a board can use: a content frame
376
- * that still exists, at the width it measures at on its own. Everything else is pruned - a deleted
377
- * frame, a Doc that went from document to wide. Returns the next map and the keys taken. Pruning
378
- * reads only the manifest: whether a frame still renders a Doc is asked on READ (keptSizes), so a
379
- * source caught mid-write can hide an entry for one load, never delete it. */
380
- function mergeSizes(current, incoming, autoWidth) {
381
- const next = Object.fromEntries(Object.entries(current).filter(([k]) => keeps(k, autoWidth)));
382
- const accepted = [];
383
- for (const [k, v] of Object.entries(incoming)) {
384
- if (!validEntry(k, v) || !keeps(k, autoWidth)) continue;
385
- next[k] = v;
386
- accepted.push(k);
387
- }
388
- return {
389
- next,
390
- accepted
391
- };
392
- }
393
- /** The entries a board can use - what the GET and the build hand the shell: a content frame at its
394
- * own width that MEASURES (renders a Doc). A frame that went from a Doc to a bare Md keeps the size
395
- * its board gives it, never an old measurement. */
396
- const keptSizes = (heights, autoWidth, measuring) => Object.fromEntries(Object.entries(heights).filter(([k]) => keeps(k, autoWidth) && measuring.has(k.slice(0, k.lastIndexOf("@")))));
397
- /** The auto width rule over a manifest's frames (the shell's defaultSize, store.ts). */
398
- function autoWidthOf(frames, viewports) {
399
- const byId = new Map(frames.map((f) => [f.id, f]));
400
- return (id) => {
401
- const f = byId.get(id);
402
- if (!f?.contentWidth) return null;
403
- return viewports[f.viewport ?? ""]?.width ?? f.contentWidth;
404
- };
405
- }
406
- /** The content frames that measure: the frame renders a Doc, or a `_layout` it renders inside does
407
- * (manifest.ts layoutDocSource - the same rule the manifest's width follows). A source that cannot
408
- * be read, or reads empty (an editor mid-write), gets the benefit of the doubt - this only decides
409
- * what a load is handed, never what the file keeps. */
410
- function measuringFrames(root, frames) {
411
- const out = /* @__PURE__ */ new Set();
412
- const memo = /* @__PURE__ */ new Map();
413
- for (const f of frames) {
414
- if (!f.contentWidth || f.kind === "html" || !f.file || f.file.split("/").includes("..")) continue;
415
- let src = "";
416
- try {
417
- src = readFileSync(join(root, f.file), "utf8");
418
- } catch {}
419
- if (!src.trim() || rendersDoc(src) || layoutDocSource(root, f.file, memo) !== null) out.add(f.id);
420
- }
421
- return out;
422
- }
423
- //#endregion
424
- //#region src/server/api.ts
425
- const BODY_LIMIT = 1e6;
426
- const CSRF_MAX_AGE = 2592e3;
427
- /** Read one cookie value off the request. */
428
- function cookie(req, name) {
429
- const m = new RegExp(`(?:^|;\\s*)${name}=([^;]+)`).exec(String(req.headers.cookie ?? ""));
430
- return m ? m[1] : "";
431
- }
432
- /** The owner gate. The dev server is 127.0.0.1-only, so the live threat is a
433
- * cross-origin drive-by page firing a POST at localhost. Two defenses, mirroring the published
434
- * side (collab.ts:206): a double-submit cookie (mv_c is JS-readable same-origin, so a cross-origin
435
- * page cannot read it to echo x-mv-c), plus an Origin allowlist. Only a POST that passes this is
436
- * eligible to be ledgered, so a forged @marver can never authorize the local agent. */
437
- function ownerGated(req) {
438
- const c = cookie(req, "mv_c");
439
- if (!c || req.headers["x-mv-c"] !== c) return false;
440
- const origin = req.headers.origin;
441
- if (origin) try {
442
- if (new URL(String(origin)).host !== String(req.headers.host ?? "")) return false;
443
- } catch {
444
- return false;
445
- }
446
- return true;
447
- }
448
- function json(res, status, body) {
449
- res.statusCode = status;
450
- res.setHeader("content-type", "application/json");
451
- res.end(JSON.stringify(body));
452
- }
453
- function readBody(req, limit = BODY_LIMIT) {
454
- return new Promise((done) => {
455
- let size = 0;
456
- const chunks = [];
457
- req.on("data", (c) => {
458
- size += c.length;
459
- if (size > limit) {
460
- done(null);
461
- req.destroy();
462
- } else chunks.push(c);
463
- });
464
- req.on("end", () => done(Buffer.concat(chunks).toString("utf8")));
465
- req.on("error", () => done(null));
466
- });
467
- }
468
- /** Atomic write: random temp name (no predictable symlink target), rename, and a
469
- * copy-fallback only for the Windows rename errors - anything else rethrows. */
470
- function atomicWrite(file, content) {
471
- const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
472
- writeFileSync(tmp, content, { flag: "wx" });
473
- try {
474
- renameSync(tmp, file);
475
- } catch (err) {
476
- const code = err.code;
477
- if (code !== "EEXIST" && code !== "EPERM") {
478
- rmSync(tmp, { force: true });
479
- throw err;
480
- }
481
- copyFileSync(tmp, file);
482
- try {
483
- rmSync(tmp, { force: true });
484
- } catch {}
485
- }
486
- }
487
- /** A replacement that is whole or not at all, in two steps: `stageWrite` puts the new content in a temp
488
- * file beside the destination; `rename` swaps it in - one syscall, so a caller can look at the
489
- * destination right before it and nothing but that rename stands between the look and the write.
490
- * Never the copy fallback: a copy can fail part way, or not at all, and nothing tells which. For the
491
- * status write, which writes several files and must say exactly what it changed. */
492
- function stageWrite(file, content) {
493
- const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
494
- const fd = openSync(tmp, "wx");
495
- let open = true;
496
- try {
497
- writeFileSync(fd, content);
498
- open = false;
499
- closeSync(fd);
500
- } catch (err) {
501
- if (open) try {
502
- closeSync(fd);
503
- } catch {}
504
- discard(tmp);
505
- throw err;
506
- }
507
- return tmp;
508
- }
509
- const discard = (tmp) => {
510
- try {
511
- rmSync(tmp, { force: true });
512
- } catch {}
513
- };
514
- /** Containment beyond string prefixes: the realpath of the parent dir must stay inside base. */
515
- function contained(target, base) {
516
- try {
517
- const realBase = realpathSync(base);
518
- const parent = realpathSync(resolve(target, ".."));
519
- if (parent !== realBase && !parent.startsWith(realBase + sep)) return false;
520
- if (existsSync(target)) {
521
- const real = realpathSync(target);
522
- return real === realBase || real.startsWith(realBase + sep);
523
- }
524
- return true;
525
- } catch {
526
- return false;
527
- }
528
- }
529
- function apiMiddleware(root, opts = {}) {
530
- const ws = opts.workspace ?? workspaceId(root);
531
- const devManifest = () => {
532
- if (opts.manifest) return opts.manifest();
533
- try {
534
- return JSON.parse(readFileSync(join(root, "design", "manifest.json"), "utf8"));
535
- } catch {
536
- return scanFrames(root);
537
- }
538
- };
539
- const devFrames = () => devManifest().frames;
540
- const boardsDir = join(root, "design", "boards");
541
- const foldersPath = join(boardsDir, FOLDERS_FILE);
542
- const boardPath = (name) => {
543
- if (!validName(name)) return null;
544
- if (checkBoardsDir(root, boardsDir)) return null;
545
- mkdirSync(boardsDir, { recursive: true });
546
- const p = resolve(boardsDir, `${name}.json`);
547
- return contained(p, boardsDir) ? p : null;
548
- };
549
- const validName = (n) => typeof n === "string" && n.length >= 1 && n.length <= 64 && BOARD_NAME.test(n);
550
- const dirError = () => checkBoardsDir(root, boardsDir);
551
- const notSymlink = (p) => !nodeExists(p) || isRegularFile(p);
552
- const nodeExists$1 = nodeExists;
553
- let sizesWarned = false;
554
- try {
555
- for (const f of readdirSync(boardsDir)) if (f.endsWith(".tmp")) rmSync(join(boardsDir, f), { force: true });
556
- } catch {}
557
- return async (req, res, next) => {
558
- const url = new URL(req.url ?? "/", "http://x");
559
- if (!url.pathname.startsWith(`/__mv/api/`)) return next();
560
- const path = url.pathname.slice(`${ROUTE}/api/`.length);
561
- if (req.method === "GET" && !cookie(req, "mv_c")) res.setHeader("set-cookie", `mv_c=${randomBytes(16).toString("base64url")}; Path=/; Max-Age=${CSRF_MAX_AGE}; SameSite=Lax`);
562
- try {
563
- if (path === "policy" && req.method === "GET") try {
564
- const raw = JSON.parse(readFileSync(join(root, "design", "publish.json"), "utf8"));
565
- const boards = {};
566
- for (const [n, level] of Object.entries(raw?.boards ?? {})) {
567
- if (typeof level !== "object" || level === null) continue;
568
- const p2 = level;
569
- boards[n] = {
570
- ...typeof p2.type === "string" ? { type: p2.type } : {},
571
- ...typeof p2.open === "string" ? { open: p2.open } : {},
572
- ...p2.lock === true ? { lock: true } : {},
573
- ...typeof p2.transition === "string" ? { transition: p2.transition } : {},
574
- ...typeof p2.chrome === "string" ? { chrome: p2.chrome } : {}
575
- };
576
- }
577
- return json(res, 200, { boards });
578
- } catch {
579
- return json(res, 200, { boards: {} });
580
- }
581
- if (path === "boards" && req.method === "GET") {
582
- const de = dirError();
583
- if (de) return json(res, 422, { error: de });
584
- mkdirSync(boardsDir, { recursive: true });
585
- const files = listBoardFiles(boardsDir).boards;
586
- const rows = files.map((b) => ({
587
- name: b.name,
588
- ...boardFields(b.json, validName),
589
- ...b.error ? { error: b.error } : {}
590
- }));
591
- const reg = readRegistry(boardsDir);
592
- const regFolders = reg.state === "ok" ? reg.folders : [];
593
- const tree = buildTree(rows, regFolders);
594
- const fm = folderMap(tree);
595
- const facts = readContextFacts(root);
596
- const notes = annotateBoards(root, files, regFolders, (n) => fm.get(n) ?? null, facts);
597
- const settableFor = (cap) => settableStatuses(facts.present, !!facts.plans.get(cap)?.length);
598
- return json(res, 200, files.map((b, i) => {
599
- const n = notes.get(b.name);
600
- return {
601
- ...rows[i],
602
- sha256: b.sha256,
603
- ...n ?? {},
604
- ...n?.status ? { settable: settableFor(n.status.capability) } : {}
605
- };
606
- }));
607
- }
608
- if (path === "boards/status" && req.method === "POST") {
609
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
610
- const raw = await readBody(req);
611
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
612
- let parsed;
613
- try {
614
- parsed = JSON.parse(raw);
615
- } catch {
616
- return json(res, 400, { error: "malformed JSON" });
617
- }
618
- if (!parsed || typeof parsed !== "object") return json(res, 400, { error: "expected an object" });
619
- const { name, status: statusRaw, reason: reasonRaw, baseHash } = parsed;
620
- if (!validName(name) || name === "all-scenes") return json(res, 400, { error: "invalid board name" });
621
- if (baseHash !== void 0 && typeof baseHash !== "string") return json(res, 400, { error: "invalid baseHash" });
622
- const status = statusRaw === null ? null : readStatusWord(statusRaw);
623
- if (status === void 0) return json(res, 400, { error: "invalid status" });
624
- const reason = readReason(reasonRaw);
625
- if (status === "blocked" && !reason) return json(res, 400, { error: "a blocked board says why - give a reason" });
626
- {
627
- const de = dirError();
628
- if (de) return json(res, 400, { error: de });
629
- }
630
- const file = boardPath(name);
631
- if (!file) return json(res, 400, { error: "invalid board name" });
632
- if (!existsSync(file)) return json(res, 404, { error: `board "${name}" does not exist` });
633
- if (!notSymlink(file)) return json(res, 400, { error: "refusing to write a symlinked board file" });
634
- const current = readFileSync(file, "utf8");
635
- if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
636
- error: "board changed on disk",
637
- sha256: hash(current)
638
- });
639
- let obj;
640
- try {
641
- obj = JSON.parse(current);
642
- } catch {
643
- return json(res, 422, { error: `board "${name}" is not valid JSON - fix the file` });
644
- }
645
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) return json(res, 422, { error: `board "${name}" is not a JSON object - fix the file` });
646
- const reg = readRegistry(boardsDir);
647
- const regFolders = reg.state === "ok" ? reg.folders : [];
648
- const all = listBoardFiles(boardsDir).boards;
649
- const fm = folderMap(buildTree(all.map((b) => ({
650
- name: b.name,
651
- ...boardFields(b.json, validName)
652
- })), regFolders));
653
- const folder = regFolders.find((f) => f.name === fm.get(name));
654
- const parent = folder?.parent ? regFolders.find((f) => f.name === folder.parent) : void 0;
655
- const type = resolveType(obj.type, folder?.type, parent?.type);
656
- if (!HAS_STATUS.includes(type)) return json(res, 422, { error: `a ${type} board carries no status - only feature and project boards do` });
657
- const facts = readContextFacts(root);
658
- const capability = readCapability(obj.capability) ?? name;
659
- const plans = facts.present ? facts.plans.get(capability) ?? [] : [];
660
- if (status !== null && !settableStatuses(facts.present, plans.length > 0).includes(status)) return json(res, 422, { error: status === "done" ? "Done is never set by hand - it comes from context/shipped.md" : status === "building" || status === "in-progress" ? `${status === "building" ? "Building" : "In progress"} needs an open plan naming ${capability} - context/plans/` : `with context/, ${status} is read from the evidence - a plan, a contract, the shipped record` });
661
- const writes = [];
662
- if (facts.present && (status === "building" || status === "in-progress")) {
663
- for (const p of plans.filter((x, i) => plans.findIndex((y) => y.where === x.where) === i)) {
664
- const file = join(root, p.where);
665
- if (!notSymlink(file)) return json(res, 400, { error: `refusing to write a symlinked plan (${p.where})` });
666
- const raw = readFileSync(file, "utf8");
667
- if (!planNames(raw, capability)) return json(res, 409, { error: `${p.where} changed on disk - try again` });
668
- const r = planWithStage(raw, status === "building" ? "build" : null);
669
- if ("error" in r) return json(res, 422, { error: `${p.where} ${r.error} - fix the file` });
670
- writes.push({
671
- file,
672
- raw,
673
- next: r.text,
674
- plan: p.where
675
- });
676
- }
677
- delete obj.status;
678
- delete obj.reason;
679
- } else {
680
- if (status === null) delete obj.status;
681
- else obj.status = status;
682
- if (status === "blocked") obj.reason = reason;
683
- else delete obj.reason;
684
- }
685
- const next = JSON.stringify(obj, null, 2) + "\n";
686
- writes.push({
687
- file,
688
- raw: current,
689
- next
690
- });
691
- const current_ = (f) => {
692
- try {
693
- return readFileSync(f, "utf8");
694
- } catch {
695
- return null;
696
- }
697
- };
698
- const done = [];
699
- const undo = () => {
700
- const stuck = [];
701
- for (const w of done.reverse()) {
702
- const label = w.plan ?? `design/boards/${name}.json`;
703
- let tmp;
704
- try {
705
- tmp = stageWrite(w.file, w.raw);
706
- } catch {
707
- stuck.push(label);
708
- continue;
709
- }
710
- if (current_(w.file) !== w.next) {
711
- discard(tmp);
712
- stuck.push(`${label} (edited since - kept)`);
713
- continue;
714
- }
715
- try {
716
- renameSync(tmp, w.file);
717
- } catch {
718
- discard(tmp);
719
- stuck.push(label);
720
- }
721
- }
722
- return stuck;
723
- };
724
- for (const w of writes) {
725
- if (w.next === w.raw) continue;
726
- let tmp = null;
727
- try {
728
- tmp = stageWrite(w.file, w.next);
729
- const now = current_(w.file);
730
- if (now !== w.raw) {
731
- discard(tmp);
732
- const stuck = undo();
733
- if (stuck.length) return json(res, 500, { error: `${w.plan ?? `board "${name}"`} changed on disk mid-write, and ${stuck.join(", ")} still ${stuck.length === 1 ? "holds" : "hold"} this change - check by hand` });
734
- return json(res, 409, {
735
- error: `${w.plan ?? `board "${name}"`} changed on disk - try again`,
736
- ...w.plan || now === null ? {} : { sha256: hash(now) }
737
- });
738
- }
739
- renameSync(tmp, w.file);
740
- done.push(w);
741
- } catch (err) {
742
- if (tmp) discard(tmp);
743
- const stuck = undo();
744
- const off = writes.filter((x) => x.next !== x.raw && current_(x.file) !== x.raw).map((x) => x.plan ?? `design/boards/${name}.json`);
745
- const named = [.../* @__PURE__ */ new Set([...stuck, ...off.filter((o) => !stuck.some((s) => s.startsWith(o)))])];
746
- return json(res, 500, { error: named.length ? `could not write the status (${err.message}), and ${named.join(", ")} ${named.length === 1 ? "is" : "are"} not as before - check by hand` : `could not write the status (${err.message}) - nothing changed` });
747
- }
748
- }
749
- return json(res, 200, {
750
- name,
751
- sha256: hash(next)
752
- });
753
- }
754
- const readManifestFrames = () => {
755
- try {
756
- const m = JSON.parse(readFileSync(join(root, "design", "manifest.json"), "utf8"));
757
- return Array.isArray(m?.frames) ? m.frames : null;
758
- } catch {
759
- return null;
760
- }
761
- };
762
- if (path === "perf/reload" && req.method === "POST") {
763
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
764
- const raw = await readBody(req);
765
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
766
- let b;
767
- try {
768
- b = JSON.parse(raw);
769
- } catch {
770
- return json(res, 400, { error: "malformed JSON" });
771
- }
772
- const str = (v) => typeof v === "string" ? v.slice(0, 200) : void 0;
773
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
774
- if (!str(b?.kind)) return json(res, 400, { error: "kind required" });
775
- (await import("./perf-BWzQwZqj.mjs").then((n) => n.i)).logReload(root, {
776
- kind: str(b.kind),
777
- tab: str(b.tab),
778
- node: str(b.node),
779
- frame: str(b.frame),
780
- cause: str(b.cause),
781
- shown: str(b.shown),
782
- ms: num(b.ms)
783
- });
784
- return json(res, 200, { ok: true });
785
- }
786
- if (path === "perf/jam" && req.method === "POST") {
787
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
788
- const raw = await readBody(req);
789
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
790
- let b;
791
- try {
792
- b = JSON.parse(raw);
793
- } catch {
794
- return json(res, 400, { error: "malformed JSON" });
795
- }
796
- if (!b || b.kind !== "capture" && b.kind !== "upload") return json(res, 400, { error: "kind must be capture or upload" });
797
- (await import("./perf-jam-D55U3FZK.mjs").then((n) => n.n)).logJam(root, b);
798
- return json(res, 200, { ok: true });
799
- }
800
- if (path === "perf/page" && req.method === "POST") {
801
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
802
- const raw = await readBody(req, PAGE_BODY_MAX);
803
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
804
- let b;
805
- try {
806
- b = JSON.parse(raw);
807
- } catch {
808
- return json(res, 400, { error: "malformed JSON" });
809
- }
810
- if (!Array.isArray(b?.records)) return json(res, 400, { error: "expected { records: [...] }" });
811
- return json(res, 200, {
812
- ok: true,
813
- accepted: logPage(root, b.records)
814
- });
815
- }
816
- if (path === "sizes" && req.method === "GET") {
817
- const frames = readManifestFrames();
818
- if (!frames) return json(res, 200, {
819
- heights: {},
820
- measuring: []
821
- });
822
- const measuring = measuringFrames(root, frames);
823
- return json(res, 200, {
824
- heights: keptSizes(readSizes(root), autoWidthOf(frames, opts.viewports ?? {}), measuring),
825
- measuring: [...measuring].sort()
826
- });
827
- }
828
- if (path === "sizes" && req.method === "POST") {
829
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
830
- const raw = await readBody(req);
831
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
832
- let body;
833
- try {
834
- body = JSON.parse(raw);
835
- } catch {
836
- return json(res, 400, { error: "malformed JSON" });
837
- }
838
- const incoming = body?.heights;
839
- if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) return json(res, 400, { error: "expected { heights: { \"scene/frame@width\": height } }" });
840
- if (Object.keys(incoming).length > 500) return json(res, 400, { error: `at most 500 heights per write` });
841
- {
842
- const de = dirError();
843
- if (de) return json(res, 400, { error: de });
844
- }
845
- const frames = readManifestFrames();
846
- if (!frames) return json(res, 409, { error: "design/manifest.json is missing or mid-rewrite - try again" });
847
- const file = sizesPath(root);
848
- if (!notSymlink(file)) return json(res, 400, { error: "refusing to write a symlinked sizes file" });
849
- const cur = readSizesFile(root);
850
- if (cur.state === "invalid") {
851
- if (!sizesWarned) {
852
- sizesWarned = true;
853
- console.warn(" marver: design/boards/_sizes.json is not valid JSON (a merge conflict?) - resolve it, either side is fine; heights are not saved until then");
854
- }
855
- return json(res, 409, { error: "design/boards/_sizes.json is not valid JSON - resolve it (either side is fine)" });
856
- }
857
- const { next, accepted } = mergeSizes(cur.heights, incoming, autoWidthOf(frames, opts.viewports ?? {}));
858
- const text = serializeSizes(next);
859
- const current = existsSync(file) ? readFileSync(file, "utf8") : "";
860
- if (text !== current && (Object.keys(next).length || current)) {
861
- mkdirSync(boardsDir, { recursive: true });
862
- atomicWrite(file, text);
863
- }
864
- return json(res, 200, { accepted });
865
- }
866
- if (path === "folders" && req.method === "GET") {
867
- const de = dirError();
868
- if (de) return json(res, 422, { error: de });
869
- const reg = readRegistry(boardsDir);
870
- if (reg.state === "malformed") return json(res, 422, { error: reg.error });
871
- return json(res, 200, {
872
- folders: reg.folders,
873
- sha256: reg.sha256
874
- });
875
- }
876
- if (path === "membership" && req.method === "GET") {
877
- const de = dirError();
878
- if (de) return json(res, 422, { error: de });
879
- return json(res, 200, readMembership(root, scanFrames(root).frames.map((f) => f.id)));
880
- }
881
- if (path === "boards/pin" && req.method === "POST") {
882
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
883
- const raw = await readBody(req);
884
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
885
- let parsed;
886
- try {
887
- parsed = JSON.parse(raw);
888
- } catch {
889
- return json(res, 400, { error: "malformed JSON" });
890
- }
891
- const live = scanFrames(root).frames.map((f) => f.id);
892
- const frames = Array.isArray(parsed?.frames) ? parsed.frames.filter((f) => typeof f === "string" && live.includes(f)) : [];
893
- if (!validName(parsed?.board) || !frames.length) return json(res, 400, { error: "a board and frames on this canvas" });
894
- try {
895
- return json(res, 200, pinFrames(root, parsed.board, frames, live));
896
- } catch (err) {
897
- return json(res, 409, { error: err.message });
898
- }
899
- }
900
- if (path === "boards/rename" && req.method === "POST") {
901
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
902
- const raw = await readBody(req);
903
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
904
- let parsed;
905
- try {
906
- parsed = JSON.parse(raw);
907
- } catch {
908
- return json(res, 400, { error: "malformed JSON" });
909
- }
910
- if (!parsed || typeof parsed !== "object") return json(res, 400, { error: "expected an object" });
911
- const { from, to: toRaw, title: titleRaw, baseHash } = parsed;
912
- const to = toRaw === void 0 ? from : toRaw;
913
- if (!validName(from) || !validName(to)) return json(res, 400, { error: "invalid board name" });
914
- if (titleRaw !== void 0 && (typeof titleRaw !== "string" || Array.from(titleRaw).length > 120)) return json(res, 400, { error: "invalid title" });
915
- if (baseHash !== void 0 && typeof baseHash !== "string") return json(res, 400, { error: "invalid baseHash" });
916
- if (to === "all-scenes" || from === "all-scenes") return json(res, 400, { error: "invalid rename" });
917
- if (to === from && titleRaw === void 0) return json(res, 400, { error: "invalid rename" });
918
- {
919
- const de = dirError();
920
- if (de) return json(res, 400, { error: de });
921
- }
922
- const fromPath = boardPath(from), toPath = boardPath(to);
923
- if (!fromPath || !toPath) return json(res, 400, { error: "invalid board name" });
924
- if (!existsSync(fromPath)) return json(res, 404, { error: `board "${from}" does not exist` });
925
- if (!notSymlink(fromPath)) return json(res, 400, { error: "refusing to rename a symlinked board file" });
926
- const current = readFileSync(fromPath, "utf8");
927
- if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
928
- error: "board changed on disk",
929
- sha256: hash(current)
930
- });
931
- let obj = null;
932
- if (titleRaw !== void 0) {
933
- let parsedBoard;
934
- try {
935
- parsedBoard = JSON.parse(current);
936
- } catch {
937
- return json(res, 422, { error: `board "${from}" is not valid JSON - fix the file` });
938
- }
939
- if (!parsedBoard || typeof parsedBoard !== "object" || Array.isArray(parsedBoard)) return json(res, 422, { error: `board "${from}" is not a JSON object - fix the file` });
940
- obj = parsedBoard;
941
- }
942
- let next;
943
- if (obj) {
944
- const title = readTitle(titleRaw);
945
- if (title) obj.title = title;
946
- else delete obj.title;
947
- next = JSON.stringify(obj, null, 2) + "\n";
948
- }
949
- if (to !== from) {
950
- if (isConnected(root)) return json(res, 409, { error: "disconnect before renaming boards - comment sync is board-keyed" });
951
- if (existsSync(join(root, "design", "comments", `${from}.jsonl`))) return json(res, 409, { error: "rename a board before commenting on it - this board has threads" });
952
- if (nodeExists$1(toPath)) return json(res, 409, { error: `a board named "${to}" already exists` });
953
- try {
954
- if (next !== void 0) writeFileSync(toPath, next, { flag: "wx" });
955
- else linkSync(fromPath, toPath);
956
- } catch (err) {
957
- const code = err.code;
958
- if (code === "EEXIST") return json(res, 409, { error: `a board named "${to}" already exists` });
959
- if (next !== void 0 || code !== "EPERM" && code !== "ENOSYS" && code !== "ENOTSUP" && code !== "EOPNOTSUPP") throw err;
960
- if (nodeExists$1(toPath)) return json(res, 409, { error: `a board named "${to}" already exists` });
961
- renameSync(fromPath, toPath);
962
- return json(res, 200, { name: to });
963
- }
964
- rmSync(fromPath);
965
- return json(res, 200, {
966
- name: to,
967
- ...next !== void 0 ? { sha256: hash(next) } : {}
968
- });
969
- }
970
- atomicWrite(toPath, next);
971
- return json(res, 200, {
972
- name: to,
973
- sha256: hash(next)
974
- });
975
- }
976
- if (path === "scenes/rename" && req.method === "POST") {
977
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
978
- const raw = await readBody(req);
979
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
980
- let parsed;
981
- try {
982
- parsed = JSON.parse(raw);
983
- } catch {
984
- return json(res, 400, { error: "malformed JSON" });
985
- }
986
- if (!parsed || typeof parsed !== "object") return json(res, 400, { error: "expected an object" });
987
- const { scene, title } = parsed;
988
- if (typeof scene !== "string" || !scene || scene.length > 128 || /[\\/]/.test(scene) || scene === "." || scene === "..") return json(res, 400, { error: "invalid scene name" });
989
- if (typeof title !== "string" || Array.from(title).length > 120) return json(res, 400, { error: "invalid title" });
990
- if (!scanFrames(root).scenes.some((sc) => sc.name === scene)) return json(res, 400, { error: `scene "${scene}" does not exist (no frames under design/scenes/${scene}/)` });
991
- const e = setSceneTitle(root, scene, readTitle(title) ?? "");
992
- if (e) return json(res, 400, { error: e });
993
- return json(res, 200, { ok: true });
994
- }
995
- if (path === "boards/reorder" && req.method === "POST") {
996
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
997
- const raw = await readBody(req);
998
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
999
- let parsed;
1000
- try {
1001
- parsed = JSON.parse(raw);
1002
- } catch {
1003
- return json(res, 400, { error: "malformed JSON" });
1004
- }
1005
- if (!parsed || typeof parsed !== "object") return json(res, 400, { error: "expected an object" });
1006
- const { tree, base } = parsed;
1007
- const bad = validateWire(tree);
1008
- if (bad) return json(res, 400, { error: bad });
1009
- const b = base;
1010
- if (!b || typeof b !== "object" || !b.boards || typeof b.boards !== "object" || b.folders !== null && typeof b.folders !== "string") return json(res, 400, { error: "expected base hashes" });
1011
- {
1012
- const de = dirError();
1013
- if (de) return json(res, 400, { error: de });
1014
- }
1015
- const reply = (status, body) => ({
1016
- status,
1017
- body
1018
- });
1019
- mkdirSync(boardsDir, { recursive: true });
1020
- const locked = withRegistryLock(boardsDir, 0, () => {
1021
- const reg = readRegistry(boardsDir);
1022
- if (reg.state === "malformed") return reply(422, { error: reg.error });
1023
- if (reg.state === "ok" && reg.folders.some((f) => f.parent) && parsed.protocol !== 2) return reply(422, { error: "this tab predates folders in folders - reload the canvas, then try again" });
1024
- if (reg.sha256 !== b.folders) return reply(409, {
1025
- error: "folders changed on disk",
1026
- stale: [FOLDERS_FILE]
1027
- });
1028
- const unseen = listBoardFiles(boardsDir).boards.map((x) => x.name).filter((n) => !(n in b.boards));
1029
- if (unseen.length) return reply(409, {
1030
- error: "boards changed on disk",
1031
- stale: unseen
1032
- });
1033
- const plan = [];
1034
- const stale = [];
1035
- const consider = (name, order, folder) => {
1036
- const p = boardPath(name);
1037
- if (!p || !isRegularFile(p)) {
1038
- stale.push(name);
1039
- return null;
1040
- }
1041
- const content = readFileSync(p, "utf8");
1042
- if (b.boards[name] !== hash(content)) {
1043
- stale.push(name);
1044
- return null;
1045
- }
1046
- let obj;
1047
- try {
1048
- obj = JSON.parse(content);
1049
- } catch {
1050
- return `board "${name}" is not valid JSON - fix the file`;
1051
- }
1052
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) return `board "${name}" is not a JSON object - fix the file`;
1053
- plan.push({
1054
- name,
1055
- path: p,
1056
- obj,
1057
- order,
1058
- folder
1059
- });
1060
- return null;
1061
- };
1062
- const onDisk = /* @__PURE__ */ new Map();
1063
- try {
1064
- const raw = JSON.parse(readFileSync(join(boardsDir, FOLDERS_FILE), "utf8"));
1065
- if (Array.isArray(raw.folders)) {
1066
- for (const r of raw.folders) if (r && typeof r === "object" && typeof r.name === "string") onDisk.set(r.name, r);
1067
- }
1068
- } catch {}
1069
- const MANAGED = /* @__PURE__ */ new Set([
1070
- "name",
1071
- "order",
1072
- "parent",
1073
- "title",
1074
- "description",
1075
- "type"
1076
- ]);
1077
- const folders = [];
1078
- const walk = (list, parent) => {
1079
- for (const [i, it] of list.entries()) {
1080
- if (typeof it === "string") {
1081
- const e = consider(it, i, parent);
1082
- if (e) return e;
1083
- continue;
1084
- }
1085
- const title = readTitle(it.title), description = readDescription(it.description);
1086
- const disk = onDisk.get(it.folder);
1087
- const type = readType(it.type) ?? readType(disk?.type);
1088
- const kept = disk ? Object.fromEntries(Object.entries(disk).filter(([k]) => !MANAGED.has(k))) : {};
1089
- folders.push({
1090
- ...kept,
1091
- name: it.folder,
1092
- order: i,
1093
- ...parent ? { parent } : {},
1094
- ...title ? { title } : {},
1095
- ...description ? { description } : {},
1096
- ...type ? { type } : {}
1097
- });
1098
- const e = walk(wireKids(it), it.folder);
1099
- if (e) return e;
1100
- }
1101
- return null;
1102
- };
1103
- {
1104
- const e = walk(tree, null);
1105
- if (e) return reply(422, { error: e });
1106
- }
1107
- if (stale.length) return reply(409, {
1108
- error: "boards changed on disk",
1109
- stale
1110
- });
1111
- const sha256 = {};
1112
- for (const w of plan) {
1113
- if (w.obj.order === w.order && (w.folder ? w.obj.folder === w.folder : w.obj.folder === void 0)) continue;
1114
- if (hash(readFileSync(w.path, "utf8")) !== b.boards[w.name]) return reply(409, {
1115
- error: "boards changed on disk",
1116
- stale: [w.name]
1117
- });
1118
- w.obj.order = w.order;
1119
- if (w.folder) w.obj.folder = w.folder;
1120
- else delete w.obj.folder;
1121
- const next = JSON.stringify(w.obj, null, 2) + "\n";
1122
- atomicWrite(w.path, next);
1123
- sha256[w.name] = hash(next);
1124
- }
1125
- mkdirSync(boardsDir, { recursive: true });
1126
- if ((nodeExists(foldersPath) ? hash(readFileSync(foldersPath, "utf8")) : null) !== b.folders) return reply(409, {
1127
- error: "folders changed on disk",
1128
- stale: [FOLDERS_FILE]
1129
- });
1130
- let foldersSha = null;
1131
- if (folders.length) {
1132
- const version = folders.some((f) => f.parent) ? 2 : 1;
1133
- const next = JSON.stringify({
1134
- version,
1135
- folders
1136
- }, null, 2) + "\n";
1137
- atomicWrite(foldersPath, next);
1138
- foldersSha = hash(next);
1139
- } else rmSync(foldersPath, { force: true });
1140
- return reply(200, {
1141
- ok: true,
1142
- sha256: {
1143
- boards: sha256,
1144
- folders: foldersSha
1145
- }
1146
- });
1147
- });
1148
- if (!locked) return json(res, 409, {
1149
- error: "folders changed on disk",
1150
- stale: [FOLDERS_FILE]
1151
- });
1152
- return json(res, locked.status, locked.body);
1153
- }
1154
- const boardMatch = /^boards\/([^/]+)$/.exec(path);
1155
- if (boardMatch) {
1156
- const p = boardPath(boardMatch[1]);
1157
- if (!p) return json(res, 400, { error: "invalid board name" });
1158
- if (req.method === "GET") {
1159
- if (!existsSync(p)) return json(res, 200, { board: null });
1160
- const content = readFileSync(p, "utf8");
1161
- const parsed = parseBoard(content);
1162
- if (parsed.error) return json(res, 422, { error: `design/boards/${boardMatch[1]}.json is not valid JSON - ${parsed.error}` });
1163
- return json(res, 200, {
1164
- board: parsed.json,
1165
- sha256: hash(content)
1166
- });
1167
- }
1168
- if (req.method === "PUT") {
1169
- if (boardMatch[1] === "all-scenes") return json(res, 400, { error: `"${ALL_SCENES}" is a reserved name` });
1170
- const raw = await readBody(req);
1171
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
1172
- let body;
1173
- try {
1174
- body = JSON.parse(raw);
1175
- } catch {
1176
- return json(res, 400, { error: "malformed JSON" });
1177
- }
1178
- if (body.mustExist && !existsSync(p)) return json(res, 409, {
1179
- error: "board no longer exists on disk",
1180
- gone: true
1181
- });
1182
- const current = existsSync(p) ? readFileSync(p, "utf8") : "";
1183
- if (current && body.baseHash !== hash(current)) {
1184
- let disk = null;
1185
- try {
1186
- disk = JSON.parse(current);
1187
- } catch {}
1188
- return json(res, 409, {
1189
- error: "board changed on disk",
1190
- board: disk,
1191
- sha256: hash(current)
1192
- });
1193
- }
1194
- mkdirSync(boardsDir, { recursive: true });
1195
- const incoming = body.board;
1196
- if (incoming && typeof incoming === "object" && current) try {
1197
- const disk = JSON.parse(current);
1198
- const valid = boardFields(disk, validName);
1199
- for (const k of AUTHOR_FIELDS) if (incoming[k] === void 0 && valid[k] !== void 0) incoming[k] = disk[k];
1200
- } catch {}
1201
- const next2 = JSON.stringify(body.board, null, 2) + "\n";
1202
- atomicWrite(p, next2);
1203
- return json(res, 200, { sha256: hash(next2) });
1204
- }
1205
- }
1206
- if (path === "shot" && req.method === "GET") {
1207
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
1208
- const token = readDevInfo(root)?.token;
1209
- if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1210
- const frameId = url.searchParams.get("frame") ?? "";
1211
- const theme = url.searchParams.get("theme") ?? "light";
1212
- const scale = url.searchParams.has("scale") ? Number(url.searchParams.get("scale")) : void 0;
1213
- const dim = (k) => {
1214
- const v = Math.round(Number(url.searchParams.get(k)));
1215
- return url.searchParams.has(k) && Number.isFinite(v) ? v : void 0;
1216
- };
1217
- const size = {
1218
- w: dim("w"),
1219
- h: dim("h")
1220
- };
1221
- const asPng = url.searchParams.get("format") === "png";
1222
- const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1223
- const { shootFrame } = await import("./shot-LFhC-WYD.mjs");
1224
- const r = await shootFrame({
1225
- root,
1226
- viewports: opts.viewports ?? {},
1227
- frameId,
1228
- theme,
1229
- origin,
1230
- scale,
1231
- size
1232
- });
1233
- if (!r.ok) return json(res, r.error.startsWith("unknown frame") ? 404 : r.error.startsWith("invalid ") ? 400 : 503, { error: r.error });
1234
- const summary = {
1235
- path: r.path,
1236
- frame: frameId,
1237
- theme,
1238
- width: r.width,
1239
- height: r.height,
1240
- scale: r.scale,
1241
- ...r.truncated ? { truncated: true } : {},
1242
- ...r.unsettled ? { unsettled: true } : {},
1243
- ...r.note ? { note: r.note } : {},
1244
- recaptures: r.recaptures
1245
- };
1246
- if (!asPng) return json(res, 200, summary);
1247
- const png = readFileSync(join(root, r.path));
1248
- res.writeHead(200, {
1249
- "content-type": "image/png",
1250
- "content-length": png.length,
1251
- "cache-control": "no-store",
1252
- "x-mv-shot": Buffer.from(JSON.stringify(summary)).toString("base64url")
1253
- });
1254
- return res.end(png);
1255
- }
1256
- if (path === "shots" && req.method === "POST") {
1257
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
1258
- const token = readDevInfo(root)?.token;
1259
- if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1260
- const raw = await readBody(req);
1261
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
1262
- let parsed;
1263
- try {
1264
- parsed = JSON.parse(raw);
1265
- } catch {
1266
- return json(res, 400, { error: "malformed JSON" });
1267
- }
1268
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return json(res, 400, { error: "expected an object" });
1269
- const body = parsed;
1270
- const theme = body.theme === void 0 ? "light" : body.theme;
1271
- if (typeof theme !== "string" || !/^[a-z0-9-]+$/i.test(theme)) return json(res, 400, { error: "invalid theme" });
1272
- const scale = body.scale === void 0 ? void 0 : body.scale;
1273
- if (scale !== void 0 && !(Number.isInteger(scale) && scale >= 1 && scale <= 4)) return json(res, 400, { error: "invalid scale" });
1274
- const { resolveFrames, shootBatch } = await import("./shot-LFhC-WYD.mjs");
1275
- const sel = resolveFrames(root, body);
1276
- if (!sel.ok) return json(res, sel.status, { error: sel.error });
1277
- const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1278
- try {
1279
- return json(res, 200, { results: await shootBatch({
1280
- root,
1281
- viewports: opts.viewports ?? {},
1282
- frames: sel.frames,
1283
- theme,
1284
- origin,
1285
- scale
1286
- }) });
1287
- } catch (err) {
1288
- return json(res, 503, { error: err.message });
1289
- }
1290
- }
1291
- if (path === "anchor" && req.method === "POST") {
1292
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
1293
- const token = readDevInfo(root)?.token;
1294
- if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1295
- const raw = await readBody(req);
1296
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
1297
- let b;
1298
- try {
1299
- b = JSON.parse(raw);
1300
- } catch {
1301
- return json(res, 400, { error: "malformed JSON" });
1302
- }
1303
- const { readTarget } = await import("./anchor-5H1vnoLu.mjs").then((n) => n.t);
1304
- const target = readTarget(b ?? {});
1305
- if (typeof target === "string") return json(res, 400, { error: target });
1306
- const others = Array.isArray(b.others) ? b.others.filter((o) => typeof o?.key === "string").slice(0, 200) : [];
1307
- const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1308
- const { checkAnchor, CheckInputError } = await import("./anchor-check-ChdDqL5z.mjs");
1309
- try {
1310
- return json(res, 200, await checkAnchor({
1311
- root,
1312
- viewports: opts.viewports ?? {},
1313
- origin,
1314
- frameId: String(b.frame ?? ""),
1315
- target,
1316
- others,
1317
- viewport: typeof b.viewport === "string" ? b.viewport : void 0,
1318
- theme: typeof b.theme === "string" ? b.theme : void 0
1319
- }));
1320
- } catch (err) {
1321
- if (err instanceof CheckInputError) return json(res, 400, { error: err.message });
1322
- throw err;
1323
- }
1324
- }
1325
- if (path === "bakes" && req.method === "POST") {
1326
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1327
- const raw = await readBody(req);
1328
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
1329
- let body;
1330
- try {
1331
- body = JSON.parse(raw);
1332
- } catch {
1333
- return json(res, 400, { error: "malformed JSON" });
1334
- }
1335
- if (!body || typeof body !== "object" || !Array.isArray(body.asks) || !body.asks.length || body.asks.length > 200) return json(res, 400, { error: "asks must list 1-200 frames" });
1336
- const { bakeBatch, ASK_MAX } = await import("./bake-DM_uWgAA.mjs");
1337
- let manifest = {};
1338
- try {
1339
- manifest = JSON.parse(readFileSync(join(root, "design", "manifest.json"), "utf8"));
1340
- } catch {}
1341
- const frames = new Map((manifest.frames ?? []).map((f) => [f.id, f]));
1342
- const asks = [];
1343
- const docs = [];
1344
- for (const a of body.asks) {
1345
- const frame = typeof a?.frame === "string" ? a.frame : "";
1346
- const theme = typeof a?.theme === "string" && /^[a-z0-9-]{1,32}$/i.test(a.theme) ? a.theme : "";
1347
- const w = Math.round(Number(a?.w)), h = Math.round(Number(a?.h));
1348
- if (!frames.has(frame) || !theme || !(w >= 120 && h >= 80 && w <= ASK_MAX.side && h <= ASK_MAX.side && w * h <= ASK_MAX.area)) return json(res, 400, { error: `invalid ask for "${frame}"` });
1349
- asks.push({
1350
- frame,
1351
- theme,
1352
- w,
1353
- h
1354
- });
1355
- docs.push(typeof a?.doc === "string" ? a.doc : void 0);
1356
- }
1357
- const { docRev } = await import("./marks-CKgzucHZ.mjs").then((n) => n.i);
1358
- const all = devManifest().frames;
1359
- const pending = opts.settled ? !opts.settled() : false;
1360
- const behind = docs.map((d, i) => d !== void 0 && (pending || d !== docRev(root, all, asks[i].frame)));
1361
- const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1362
- const { ROUTE } = await import("./cli.mjs").then((n) => n.t);
1363
- const gen = opts.bakeGen?.() ?? 0;
1364
- const baked = await bakeBatch({
1365
- root,
1366
- gen,
1367
- asks: asks.filter((_, i) => !behind[i]),
1368
- live: () => opts.bakeGen?.() ?? 0,
1369
- log: (a) => {
1370
- if (a.ok) console.log(` bake: ${a.frame} ${a.theme} ${a.w}x${a.h} - ${a.targets.length} effects, ${a.rejected} stay live, ${a.ms} ms`);
1371
- else console.log(` bake: ${a.frame} ${a.theme} ${a.w}x${a.h} - stays live: ${a.error}`);
1372
- },
1373
- urlFor: (ask) => {
1374
- const f = frames.get(ask.frame);
1375
- return f.kind === "html" ? `${origin}/${f.file}?theme=${encodeURIComponent(ask.theme)}` : `${origin}${ROUTE}/frame/?id=${encodeURIComponent(ask.frame)}&theme=${encodeURIComponent(ask.theme)}`;
1376
- },
1377
- urlBase: `${ROUTE}/bakes`,
1378
- waitMs: 2500
1379
- });
1380
- const after = docs.map((d, i) => d !== void 0 && (!!opts.settled && !opts.settled() || d !== docRev(root, devManifest().frames, asks[i].frame)));
1381
- let k = 0;
1382
- return json(res, 200, {
1383
- gen,
1384
- answers: asks.map((a, i) => {
1385
- const r = behind[i] ? null : baked[k++];
1386
- return {
1387
- ...r && !after[i] ? r : {
1388
- ...a,
1389
- ok: false,
1390
- error: "the document is behind its frame"
1391
- },
1392
- ...docs[i] ? { doc: docs[i] } : {}
1393
- };
1394
- })
1395
- });
1396
- }
1397
- if (path === "poster" && req.method === "POST") {
1398
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1399
- const raw = await readBody(req, 4096);
1400
- if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
1401
- let b;
1402
- try {
1403
- b = JSON.parse(raw);
1404
- } catch {
1405
- return json(res, 400, { error: "malformed JSON" });
1406
- }
1407
- const src = typeof b?.src === "string" ? b.src : "";
1408
- const { ensurePoster, isLocalClip } = await import("./poster-Bx83ZYVK.mjs");
1409
- const { isLocalAssetRef } = await import("./build-DZnFysGU.mjs");
1410
- if (!isLocalAssetRef(src) || !isLocalClip(src)) return json(res, 400, { error: "src must be a clip under design/assets/" });
1411
- const r = await ensurePoster(join(root, "design", "assets"), src);
1412
- if (!r.ok) return json(res, r.error.includes("does not exist") ? 404 : 503, { error: r.error });
1413
- return json(res, 200, {
1414
- path: `design/assets/${src}.poster.png`,
1415
- generated: r.generated
1416
- });
1417
- }
1418
- if (path === "me" && req.method === "GET") return json(res, 200, {
1419
- user: localProfile(root),
1420
- role: "owner",
1421
- local: true,
1422
- connected: isConnected(root)
1423
- });
1424
- if (path === "profile" && req.method === "POST") {
1425
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1426
- const raw = await readBody(req);
1427
- if (raw == null) return json(res, 400, { error: "body too large" });
1428
- let b;
1429
- try {
1430
- b = JSON.parse(raw);
1431
- } catch {
1432
- return json(res, 400, { error: "malformed JSON" });
1433
- }
1434
- const dir = join(root, "design", ".local");
1435
- mkdirSync(dir, { recursive: true });
1436
- const { validAvatar } = await import("./collab-Dxg2trOK.mjs");
1437
- let cur = {};
1438
- try {
1439
- cur = JSON.parse(readFileSync(join(dir, "profile.json"), "utf8"));
1440
- } catch {}
1441
- const prof = {
1442
- ...cur,
1443
- ...typeof b.name === "string" && b.name.trim() ? { name: b.name.trim() } : {},
1444
- ...typeof b.email === "string" ? { email: b.email.trim() } : {},
1445
- ...b.avatar === "" ? { avatar: void 0 } : validAvatar(b.avatar) ? { avatar: b.avatar } : {}
1446
- };
1447
- atomicWrite(join(dir, "profile.json"), JSON.stringify(prof, null, 2) + "\n");
1448
- return json(res, 200, { user: localProfile(root) });
1449
- }
1450
- if (path === "marks" || path === "marks/seen") {
1451
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1452
- const { readMarks, markSeen } = await import("./marks-CKgzucHZ.mjs").then((n) => n.i);
1453
- const manifest = devManifest();
1454
- if (path === "marks" && req.method === "GET") return json(res, 200, readMarks(root, manifest));
1455
- if (path === "marks/seen" && req.method === "POST") {
1456
- const raw = await readBody(req);
1457
- if (raw == null) return json(res, 400, { error: "body too large" });
1458
- let b;
1459
- try {
1460
- b = JSON.parse(raw);
1461
- } catch {
1462
- return json(res, 400, { error: "malformed JSON" });
1463
- }
1464
- if (!b?.frames || typeof b.frames !== "object" || Array.isArray(b.frames)) return json(res, 400, { error: "frames: { id: revision } required" });
1465
- if (!markSeen(root, manifest.frames, b.epoch, b.frames)) return json(res, 409, { error: "the marks started over - read them again" });
1466
- opts.notify?.("sh:marks");
1467
- return json(res, 200, { ok: true });
1468
- }
1469
- return json(res, 405, { error: "method not allowed" });
1470
- }
1471
- if (path === "work") {
1472
- const { workActivity, readDevInfo, WORK_TTL_DEFAULT, WORK_TTL_MAX } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
1473
- const tokenOk = () => {
1474
- const t = readDevInfo(root)?.token;
1475
- return !!t && req.headers["x-mv-work"] === t;
1476
- };
1477
- if (req.method === "GET") {
1478
- if (!ownerGated(req) && !tokenOk()) return json(res, 403, { error: "forbidden" });
1479
- const { boardsShowing, activityClock } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
1480
- const frames = workActivity.active();
1481
- return json(res, 200, {
1482
- frames,
1483
- boards: boardsShowing(root, frames),
1484
- seq: activityClock.seq
1485
- });
1486
- }
1487
- if (req.method === "POST") {
1488
- if (!ownerGated(req) && !tokenOk()) return json(res, 403, { error: "forbidden" });
1489
- const raw = await readBody(req);
1490
- if (raw == null) return json(res, 400, { error: "body too large" });
1491
- let b;
1492
- try {
1493
- b = JSON.parse(raw);
1494
- } catch {
1495
- return json(res, 400, { error: "malformed JSON" });
1496
- }
1497
- const frames = Array.isArray(b.frames) ? b.frames.filter((f) => typeof f === "string" && f) : [];
1498
- const on = b.on !== false;
1499
- if (!on && b.all === true) {
1500
- const done = workActivity.active().filter((f) => workActivity.has(f, "cli"));
1501
- if (done.length) {
1502
- (await import("./marks-CKgzucHZ.mjs").then((n) => n.i)).recordChanged(root, devFrames(), done, { doc: false });
1503
- opts.notify?.("sh:marks");
1504
- }
1505
- workActivity.clearAll("cli");
1506
- (await import("./reserve-BURNQ2Y3.mjs")).saveHolds(root, workActivity);
1507
- return json(res, 200, { frames: workActivity.active() });
1508
- }
1509
- if (!frames.length) return json(res, 400, { error: "frames required" });
1510
- const ttl = Math.min(Math.max(Number(b.ttlMs) || WORK_TTL_DEFAULT, 1e4), WORK_TTL_MAX);
1511
- const { refuseHold, saveHolds } = await import("./reserve-BURNQ2Y3.mjs");
1512
- if (on) {
1513
- const refused = frames.map((f) => refuseHold(f, workActivity.has(f, "cli"))).find(Boolean);
1514
- if (refused) return json(res, 409, {
1515
- error: refused,
1516
- frames: workActivity.active()
1517
- });
1518
- }
1519
- for (const f of frames) on ? workActivity.mark(f, ttl, "cli") : workActivity.clear(f, "cli");
1520
- saveHolds(root, workActivity);
1521
- if (!on) {
1522
- (await import("./marks-CKgzucHZ.mjs").then((n) => n.i)).recordChanged(root, devFrames(), frames, { doc: false });
1523
- opts.notify?.("sh:marks");
1524
- return json(res, 200, { frames: workActivity.active() });
1525
- }
1526
- let behind = [];
1527
- let contextPresent = false;
1528
- try {
1529
- const files = listBoardFiles(boardsDir).boards;
1530
- const want = new Set(frames);
1531
- const lit = new Set(files.filter((b) => {
1532
- const j = b.json;
1533
- return j?.auto === true || Array.isArray(j?.nodes) && j.nodes.some((n) => !!n && typeof n === "object" && want.has(n.frame));
1534
- }).map((b) => b.name));
1535
- const reg = readRegistry(boardsDir);
1536
- const regFolders = reg.state === "ok" ? reg.folders : [];
1537
- const fm = folderMap(buildTree(files.map((b) => ({
1538
- name: b.name,
1539
- ...boardFields(b.json, validName)
1540
- })), regFolders));
1541
- const facts = readContextFacts(root);
1542
- contextPresent = facts.present;
1543
- behind = [...annotateBoards(root, files.filter((b) => lit.has(b.name)), regFolders, (n) => fm.get(n) ?? null, facts)].filter(([, a]) => a.status && (a.status.status === "backlog" || a.status.status === "todo")).map(([board, a]) => ({
1544
- board,
1545
- status: a.status.status,
1546
- capability: a.status.capability
1547
- }));
1548
- } catch {}
1549
- return json(res, 200, {
1550
- frames: workActivity.active(),
1551
- behind,
1552
- context: contextPresent
1553
- });
1554
- }
1555
- }
1556
- if (path === "jam/queue" && req.method === "GET") {
1557
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1558
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1559
- return json(res, 200, jamLive.view?.() ?? {
1560
- agent: null,
1561
- cards: []
1562
- });
1563
- }
1564
- if (path === "jam/card" && req.method === "POST") {
1565
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1566
- const raw = await readBody(req);
1567
- if (raw == null) return json(res, 400, { error: "body too large" });
1568
- let b;
1569
- try {
1570
- b = JSON.parse(raw);
1571
- } catch {
1572
- return json(res, 400, { error: "malformed JSON" });
1573
- }
1574
- const { ACTIONS } = await import("./queue-CAM_vNmX.mjs");
1575
- if (!b || typeof b.id !== "string" || !Number.isInteger(b.rev) || !ACTIONS.includes(b.action) || b.body !== void 0 && typeof b.body !== "string") return json(res, 400, { error: "expected { id, rev, action, body? }" });
1576
- if ("kind" in b) return json(res, 400, { error: "a capture has no category" });
1577
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1578
- if (!jamLive.act) return json(res, 409, { error: "jam is not running here" });
1579
- const r = await jamLive.act(b.id, b.rev, b.action, b.body);
1580
- return json(res, r.ok ? 200 : 409, r);
1581
- }
1582
- if (path === "jam/audio-ticket" && req.method === "POST") {
1583
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1584
- const { issueTicket, speechLive } = await import("./audio-Dw1lfMdb.mjs");
1585
- if (!speechLive.svc) return json(res, 409, { error: "jam is not running here" });
1586
- return json(res, 200, { ticket: issueTicket() });
1587
- }
1588
- if (path === "jam/voice" && (req.method === "GET" || req.method === "POST")) {
1589
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1590
- const { speechLive } = await import("./audio-Dw1lfMdb.mjs");
1591
- const { downloadModels, downloadState, DOWNLOAD_MB } = await import("./speech-models-DomiLQcY.mjs");
1592
- if (!speechLive.svc) return json(res, 409, { error: "jam is not running here" });
1593
- if (req.method === "POST") {
1594
- const raw = await readBody(req);
1595
- if (raw == null) return json(res, 400, { error: "body too large" });
1596
- let b;
1597
- try {
1598
- b = JSON.parse(raw);
1599
- } catch {
1600
- return json(res, 400, { error: "malformed JSON" });
1601
- }
1602
- if (b?.retry === true) speechLive.svc.retry();
1603
- else if (b?.download === true) downloadModels();
1604
- else return json(res, 400, { error: "expected { download: true } or { retry: true }" });
1605
- }
1606
- return json(res, 200, {
1607
- ...await speechLive.svc.state(),
1608
- download: downloadState(),
1609
- mb: DOWNLOAD_MB,
1610
- busy: speechLive.svc.busy()
1611
- });
1612
- }
1613
- if (path === "jam/session" && (req.method === "GET" || req.method === "POST")) {
1614
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1615
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1616
- if (!jamLive.session || !jamLive.view) return json(res, 409, { error: "jam is not running here" });
1617
- if (req.method === "GET") {
1618
- const ses = jamLive.view().session ?? null;
1619
- const { readTalk, talkMinutes, recordFile } = await import("./session-BAaJsK5c.mjs").then((n) => n.s);
1620
- const folder = ses ? recordFile(root, ses.since, ses.id).replace(/[^/]+$/, "") : null;
1621
- return json(res, 200, {
1622
- session: ses,
1623
- talkMinutes: ses ? talkMinutes(readTalk(root, ses.id)) : 0,
1624
- tags: ses ? jamLive.tags?.(ses.id) ?? 0 : 0,
1625
- folder
1626
- });
1627
- }
1628
- const raw = await readBody(req);
1629
- if (raw == null) return json(res, 400, { error: "body too large" });
1630
- let b;
1631
- try {
1632
- b = JSON.parse(raw);
1633
- } catch {
1634
- return json(res, 400, { error: "malformed JSON" });
1635
- }
1636
- if (!b || typeof b.id !== "string" || ![
1637
- "start",
1638
- "end",
1639
- "wrapup"
1640
- ].includes(b.action)) return json(res, 400, { error: "expected { action, id }" });
1641
- if (b.action === "wrapup" && (typeof b.instructions !== "string" || typeof b.board !== "string")) return json(res, 400, { error: "expected { instructions, board }" });
1642
- if (b.action === "wrapup") {
1643
- const why = jamLive.canWrap?.(b.id);
1644
- if (why) return json(res, 409, {
1645
- ok: false,
1646
- error: why
1647
- });
1648
- }
1649
- if (b.action !== "start") {
1650
- const { speechLive } = await import("./audio-Dw1lfMdb.mjs");
1651
- if (!await (speechLive.svc?.finishTalk(b.id) ?? Promise.resolve(true)).catch(() => false) && b.action === "wrapup" && b.includeTalk !== false) return json(res, 409, {
1652
- ok: false,
1653
- error: "what was said is still being written down - write the record again in a moment (or leave what was said out)"
1654
- });
1655
- }
1656
- const r = await jamLive.session(b.action === "wrapup" ? {
1657
- action: "wrapup",
1658
- id: b.id,
1659
- instructions: b.instructions,
1660
- includeTalk: b.includeTalk !== false,
1661
- tags: Number(b.tags) || 0,
1662
- board: b.board
1663
- } : {
1664
- action: b.action,
1665
- id: b.id
1666
- });
1667
- return json(res, r.ok ? 200 : 409, r);
1668
- }
1669
- if (path === "jam/capture-open" && req.method === "POST") {
1670
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1671
- const raw = await readBody(req);
1672
- let b;
1673
- try {
1674
- b = JSON.parse(raw ?? "");
1675
- } catch {
1676
- return json(res, 400, { error: "malformed JSON" });
1677
- }
1678
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1679
- if (!jamLive.captureOpen) return json(res, 409, { error: "jam is not running here" });
1680
- if (typeof b?.capture !== "string" || typeof b?.session !== "string") return json(res, 400, { error: "expected { capture, session, on }" });
1681
- return jamLive.captureOpen(b.capture, b.session, b.on === true) === "ended" ? json(res, 409, {
1682
- ok: false,
1683
- ended: true,
1684
- error: "the session has ended"
1685
- }) : json(res, 200, { ok: true });
1686
- }
1687
- if (path === "jam/record" && req.method === "GET") {
1688
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1689
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1690
- const r = jamLive.record?.(url.searchParams.get("id") ?? "");
1691
- return r ? json(res, 200, r) : json(res, 404, { error: "no such record" });
1692
- }
1693
- if (path === "jam/capture" && req.method === "POST") {
1694
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1695
- const raw = await readBody(req, 4e6);
1696
- if (raw == null) return json(res, 400, { error: "body too large" });
1697
- let b;
1698
- try {
1699
- b = JSON.parse(raw);
1700
- } catch {
1701
- return json(res, 400, { error: "malformed JSON" });
1702
- }
1703
- if (b?.workspace !== void 0 && b.workspace !== ws) return json(res, 409, { error: "this capture was made in another workspace" });
1704
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1705
- if (!jamLive.capture) return json(res, 409, { error: "jam is not running here" });
1706
- const r = await jamLive.capture(b?.record);
1707
- return json(res, r.ok ? 200 : 400, r);
1708
- }
1709
- if (path === "jam/capture" && req.method === "GET") {
1710
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1711
- const { readCapture } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
1712
- const id = url.searchParams.get("id") ?? "";
1713
- const cap = readCapture(root, id);
1714
- if (!cap) return json(res, 404, { error: "no such capture" });
1715
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
1716
- const card = jamLive.view?.().cards.find((c) => c.id === id);
1717
- return json(res, 200, {
1718
- record: cap.record,
1719
- ...card?.edited !== void 0 ? { edited: card.edited } : {},
1720
- pictures: cap.record.pictures,
1721
- sealed: jamLive.sealed?.(id) ?? false
1722
- });
1723
- }
1724
- if (path === "jam/picture" && req.method === "POST") {
1725
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1726
- const raw = await readBody(req);
1727
- if (raw == null) return json(res, 400, { error: "body too large" });
1728
- let b;
1729
- try {
1730
- b = JSON.parse(raw);
1731
- } catch {
1732
- return json(res, 400, { error: "malformed JSON" });
1733
- }
1734
- const { CAPTURE_ID, readCapture, addPicture, sweepPictures } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
1735
- if (!b || typeof b.capture !== "string" || !CAPTURE_ID.test(b.capture) || typeof b.frame !== "string") return json(res, 400, { error: "expected { capture, frame, theme?, viewport? }" });
1736
- if (readCapture(root, b.capture)) return json(res, 409, { error: "that capture is sealed" });
1737
- const theme = typeof b.theme === "string" && /^[a-z0-9-]+$/i.test(b.theme) ? b.theme : "light";
1738
- const { shootFrame } = await import("./shot-LFhC-WYD.mjs");
1739
- const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1740
- const vp = typeof b.viewport === "string" ? opts.viewports?.[b.viewport] : void 0;
1741
- const dim = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
1742
- const size = dim(b.w) ? {
1743
- w: dim(b.w),
1744
- h: dim(b.h)
1745
- } : vp ? {
1746
- w: vp.width,
1747
- h: vp.height
1748
- } : void 0;
1749
- const r = await shootFrame({
1750
- root,
1751
- viewports: opts.viewports ?? {},
1752
- frameId: b.frame,
1753
- theme,
1754
- origin,
1755
- ...size ? { size } : {}
1756
- });
1757
- if (!r.ok) return json(res, r.error.startsWith("unknown frame") ? 404 : 503, { error: r.error });
1758
- sweepPictures(root);
1759
- const unchecked = /not checked for a stale surface/.test(r.note ?? "");
1760
- return json(res, 200, {
1761
- id: addPicture(root, r.path, {
1762
- frame: b.frame,
1763
- capture: b.capture,
1764
- ...unchecked ? { unchecked: true } : {}
1765
- }),
1766
- ...unchecked ? { unchecked: true } : {}
1767
- });
1768
- }
1769
- if (path === "jam/picture" && req.method === "GET") {
1770
- const site = String(req.headers["sec-fetch-site"] ?? "");
1771
- if (!ownerGated(req) && !(cookie(req, "mv_c") && (site === "same-origin" || site === "none"))) return json(res, 403, { error: "forbidden" });
1772
- const { picturePath } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
1773
- const p = picturePath(root, url.searchParams.get("id") ?? "");
1774
- if (!p) return json(res, 404, { error: "no such picture" });
1775
- const png = readFileSync(p.path);
1776
- res.writeHead(200, {
1777
- "content-type": "image/png",
1778
- "content-length": png.length,
1779
- "cache-control": "no-store"
1780
- });
1781
- return res.end(png);
1782
- }
1783
- if (path === "boards.rights" && req.method === "GET") {
1784
- const { listBoards } = await import("./comments-0BSbb04K.mjs").then((n) => n.n);
1785
- return json(res, 200, {
1786
- local: true,
1787
- stored: listBoards(join(root, "design", "comments"))
1788
- });
1789
- }
1790
- const cm = /^comments\/([a-z0-9][a-z0-9-]*)$/.exec(path);
1791
- if (cm) {
1792
- const { appendEvents, readLog } = await import("./comments-0BSbb04K.mjs").then((n) => n.n);
1793
- const dir = join(root, "design", "comments");
1794
- if (req.method === "GET") return json(res, 200, { events: readLog(dir, cm[1]) });
1795
- if (req.method === "POST") {
1796
- if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1797
- const raw = await readBody(req);
1798
- if (raw == null) return json(res, 400, { error: "body too large" });
1799
- let b;
1800
- try {
1801
- b = JSON.parse(raw);
1802
- } catch {
1803
- return json(res, 400, { error: "malformed JSON" });
1804
- }
1805
- const incoming = Array.isArray(b.events) ? b.events : [];
1806
- const me = localProfile(root);
1807
- const stamped = incoming.map((ev) => {
1808
- const { agent: _a, agentMeta: _am, origin: _o, ...clean } = ev;
1809
- return {
1810
- ...clean,
1811
- board: clean.board ?? cm[1],
1812
- author: clean.author ?? ([
1813
- "create",
1814
- "reply",
1815
- "react",
1816
- "edit"
1817
- ].includes(clean.type) ? me : void 0)
1818
- };
1819
- });
1820
- const fresh = appendEvents(dir, cm[1], stamped);
1821
- const { record } = await import("./ledger-D54iROST.mjs").then((n) => n.n);
1822
- for (const ev of fresh) if (ev.type === "create" || ev.type === "reply" || ev.type === "edit") record(root, cm[1], ev.id);
1823
- (await import("./live-Cgzsicwi.mjs")).jamLive.poke?.();
1824
- backgroundPush(root);
1825
- return json(res, 200, { accepted: fresh.length });
1826
- }
1827
- }
1828
- if (path === "sync" && req.method === "POST") {
1829
- const { loadCollab, syncOnce } = await import("./sync-BQVlHZpx.mjs").then((n) => n.o);
1830
- const collab = loadCollab(root);
1831
- if (!collab) return json(res, 200, { connected: false });
1832
- try {
1833
- return json(res, 200, {
1834
- connected: true,
1835
- boards: await syncOnce(root, collab)
1836
- });
1837
- } catch (err) {
1838
- return json(res, 502, {
1839
- connected: true,
1840
- error: err.message
1841
- });
1842
- }
1843
- }
1844
- json(res, 404, { error: "unknown endpoint" });
1845
- } catch (err) {
1846
- json(res, 500, { error: err.message });
1847
- }
1848
- };
1849
- }
1850
- let pushTimer = null;
1851
- /** Debounced fire-and-forget push after a local write; failures are silent - the
1852
- * 30s sync loop is the reliability layer, this is just latency. */
1853
- function backgroundPush(root) {
1854
- if (pushTimer) return;
1855
- pushTimer = setTimeout(async () => {
1856
- pushTimer = null;
1857
- try {
1858
- const { loadCollab, syncOnce } = await import("./sync-BQVlHZpx.mjs").then((n) => n.o);
1859
- const collab = loadCollab(root);
1860
- if (collab) await syncOnce(root, collab);
1861
- } catch {}
1862
- }, 1500);
1863
- }
1864
- //#endregion
1865
- //#region src/server/proof.ts
1866
- /**
1867
- * The document proof (spec 28 A1.4). The Mac app puts a fresh nonce on every main-frame request to a
1868
- * local canvas (`x-mv-nonce`) and checks the answer before the document commits; only the canvas
1869
- * holding the slot file's key can sign it, so the privileges the app grants belong to that exact
1870
- * document. The proof rides the very response the app commits - the check and the load can never
1871
- * reach different listeners.
1872
- *
1873
- * Pinned exactly, so the app (A2.3 `proof.ts`) computes the same: the key is the slot file's 32 bytes
1874
- * (base64url there), HMAC-SHA256 over UTF-8 `doc|<nonce>|<port>` (port in decimal), base64url without
1875
- * padding. Requests from the app itself carry `app|<port>` the same way.
1876
- */
1877
- /** 16-64 base64url characters - anything else is not a nonce, and is ignored. */
1878
- const NONCE = /^[A-Za-z0-9_-]{16,64}$/;
1879
- const sign$1 = (key, msg) => createHmac("sha256", key).update(msg, "utf8").digest("base64url");
1880
- const docProof = (key, nonce, port) => sign$1(key, `doc|${nonce}|${port}`);
1881
- /** The two headers for a request carrying a well-formed `x-mv-nonce`, else null. */
1882
- function proofHeaders(p, nonce) {
1883
- if (!p || typeof nonce !== "string" || !NONCE.test(nonce)) return null;
1884
- return {
1885
- "x-mv-instance": p.instance,
1886
- "x-mv-proof": docProof(p.key, nonce, p.port)
1887
- };
1888
- }
1889
- //#endregion
1890
- //#region src/server/routes.ts
1891
- function routesMiddleware(server, clientDir, stamps, proof) {
1892
- const page = (dir) => {
1893
- const html = readFileSync(join(clientDir, dir, "index.html"), "utf8");
1894
- const entry = "/@fs/" + join(clientDir, dir, "main.tsx").split("\\").join("/");
1895
- return html.replaceAll("{{ENTRY}}", entry).replaceAll("{{ROUTE}}", ROUTE);
1896
- };
1897
- const ICON_TYPES = {
1898
- png: "image/png",
1899
- ico: "image/x-icon",
1900
- webmanifest: "application/manifest+json"
1901
- };
1902
- return async (req, res, next) => {
1903
- const url = new URL(req.url ?? "/", "http://x");
1904
- const path = url.pathname;
1905
- let dir = null;
1906
- if (path === "/" || path === "/index.html") dir = "shell";
1907
- else if (path === `/__mv/frame/` || path === `/__mv/frame/index.html`) dir = "frame-host";
1908
- else if (path === `/__mv/stage/` || path === `/__mv/stage/index.html`) dir = "stage";
1909
- else if (path.startsWith(`/__mv/favicon/`)) {
1910
- const name = path.slice(`${ROUTE}/favicon/`.length);
1911
- const type = ICON_TYPES[name.split(".").pop() ?? ""];
1912
- if (!/^[\w@-]+(\.[\w]+)+$/.test(name) || !type) return next();
1913
- try {
1914
- res.setHeader("content-type", type);
1915
- res.setHeader("cache-control", "public, max-age=3600");
1916
- return res.end(readFileSync(join(clientDir, "shell", "favicon", name)));
1917
- } catch {
1918
- return next();
1919
- }
1920
- } else if (path.startsWith(`/__mv/bakes/`)) {
1921
- const m = /^\/(\d+)\/([a-f0-9]{16})\/(\d+)\.png$/.exec(path.slice(`${ROUTE}/bakes`.length));
1922
- if (!m) {
1923
- res.statusCode = 404;
1924
- return res.end();
1925
- }
1926
- try {
1927
- const base = realpathSync(join(server.config.root, "design", ".local", "bakes"));
1928
- const file = realpathSync(join(base, m[1], m[2], `${m[3]}.png`));
1929
- if (!file.startsWith(base + sep)) throw new Error("outside the cache");
1930
- const png = readFileSync(file);
1931
- res.setHeader("content-type", "image/png");
1932
- res.setHeader("cache-control", "public, max-age=31536000, immutable");
1933
- return res.end(png);
1934
- } catch {
1935
- res.statusCode = 404;
1936
- return res.end();
1937
- }
1938
- } else if (path === `/__mv/bridge.js`) {
1939
- res.setHeader("content-type", "text/javascript");
1940
- return res.end(readFileSync(join(clientDir, "frame-host", "bridge.js"), "utf8"));
1941
- }
1942
- if (!dir) return next();
1943
- try {
1944
- const stamp = dir === "frame-host" ? stamps?.doc(url.searchParams.get("id") ?? "") : dir === "stage" ? JSON.stringify(stamps?.docs() ?? null) : void 0;
1945
- let html = await server.transformIndexHtml(req.url ?? "/", page(dir));
1946
- if (stamp) html = html.replace("<head>", `<head><meta name="mv-doc" content="${stamp.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}">`);
1947
- res.setHeader("content-type", "text/html");
1948
- res.setHeader("cache-control", "no-store");
1949
- const signed = dir === "shell" && req.method === "GET" ? proofHeaders(proof, req.headers["x-mv-nonce"]) : null;
1950
- if (signed) for (const [k, v] of Object.entries(signed)) res.setHeader(k, v);
1951
- res.end(html);
1952
- } catch (err) {
1953
- res.statusCode = 500;
1954
- res.end(`marver route error: ${err.message}`);
1955
- }
1956
- };
1957
- }
1958
- //#endregion
1959
- //#region src/server/guard.ts
1960
- /** A workspace key as marver writes it: 16 hex. A frame's own `ws` query in another shape is the
1961
- * frame's business, never ours. */
1962
- const WS_KEY = /^[0-9a-f]{16}$/;
1963
- /** Marks the workspace refusal, so the page tells it from every other 409 without reading the body. */
1964
- const ELSEWHERE_HEADER = "x-mv-elsewhere";
1965
- /** What a frame gets when its URL names another workspace: no script, nothing of this project. The
1966
- * `mv-elsewhere` meta is how the shell, back on its own canvas, finds the frames to reload, and draws its own
1967
- * quiet placeholder over them meanwhile (shell/api.ts) - so this page is read on its own: a frame's address
1968
- * opened in a tab. It wears the frame's own theme (its URL's `theme`; a name with "dark" in it is dark), never
1969
- * the system's: a light frame stays light on a Mac in dark mode. */
1970
- function anotherCanvasPage(theme) {
1971
- const dark = /dark/i.test(theme ?? "");
1972
- const [bg, ink, dim, code] = dark ? [
1973
- "#0f1015",
1974
- "#ececf1",
1975
- "#a1a1aa",
1976
- "#1d1e26"
1977
- ] : [
1978
- "#ffffff",
1979
- "#18181b",
1980
- "#52525b",
1981
- "#f0f0f2"
1982
- ];
1983
- return `<!doctype html><html><head><meta charset="utf-8"><meta name="mv-elsewhere" content="1"><meta name="color-scheme" content="${dark ? "dark" : "light"}"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Another canvas</title><style>html,body{height:100%;margin:0;background:${bg}}body{display:flex;align-items:center;justify-content:center;padding:24px;box-sizing:border-box;font:400 13px/1.5 -apple-system,system-ui,sans-serif;color:${dim}}main{max-width:340px}h1{margin:0 0 6px;font-size:15px;font-weight:600;line-height:1.35;color:${ink}}p{margin:0}code{font:500 12px ui-monospace,SFMono-Regular,Menlo,monospace;color:${ink};background:${code};padding:1px 5px;border-radius:5px;white-space:nowrap}</style></head><body><main><h1>This frame's canvas stopped</h1><p>Another project runs on this address now. To bring this frame back, stop that project, run <code>npx marver dev</code> in this frame's own project, then reload.</p></main></body></html>`;
1984
- }
1985
- /**
1986
- * The first middleware of every dev server (spec 28 A1.11). A page left open after its canvas
1987
- * stopped may reach whatever listens on that port later; everything it sends names its workspace,
1988
- * and this answers before anything of this project is read, written or served:
1989
- * - `Service-Worker: script` (what the browser sends when it fetches a worker's script): 403 - no
1990
- * service worker ever runs on a canvas, whatever later takes the port;
1991
- * - `x-mv-ws` present and not ours: 409 `{ error: 'another workspace' }`;
1992
- * - a `ws` query not ours (frame and stage URLs, a Jam picture's <img>): the same 409 under
1993
- * /__mv/api/, else the "another canvas" page - a retained frame reloading its own URL never boots
1994
- * this project's frame;
1995
- * - `GET /__mv/api/hello`: `{ ok, ws }` - the stopped page asking "is my canvas back here?".
1996
- * A request naming no workspace (the CLI, a test, an older page) is served as before.
1997
- */
1998
- function guardMiddleware(workspace) {
1999
- return (req, res, next) => {
2000
- if (String(req.headers["service-worker"] ?? "").toLowerCase() === "script") {
2001
- res.statusCode = 403;
2002
- res.setHeader("content-type", "text/plain; charset=utf-8");
2003
- return res.end("marver canvases run no service workers");
2004
- }
2005
- let url;
2006
- try {
2007
- url = new URL(req.url ?? "/", "http://x");
2008
- } catch {
2009
- return next();
2010
- }
2011
- const api = url.pathname.startsWith(`${ROUTE}/api/`);
2012
- const said = req.headers["x-mv-ws"];
2013
- if (said !== void 0 && String(said) !== workspace) return elsewhere(res);
2014
- const q = url.searchParams.get("ws");
2015
- if (q !== null && WS_KEY.test(q) && q !== workspace) {
2016
- if (api) return elsewhere(res);
2017
- res.statusCode = 409;
2018
- res.setHeader("content-type", "text/html; charset=utf-8");
2019
- res.setHeader("cache-control", "no-store");
2020
- res.setHeader(ELSEWHERE_HEADER, "1");
2021
- return res.end(anotherCanvasPage(url.searchParams.get("theme")));
2022
- }
2023
- if (url.pathname === `/__mv/api/hello` && req.method === "GET") {
2024
- res.setHeader("content-type", "application/json");
2025
- res.setHeader("cache-control", "no-store");
2026
- return res.end(JSON.stringify({
2027
- ok: true,
2028
- ws: workspace
2029
- }));
2030
- }
2031
- next();
2032
- };
2033
- }
2034
- function elsewhere(res) {
2035
- res.statusCode = 409;
2036
- res.setHeader("content-type", "application/json");
2037
- res.setHeader("cache-control", "no-store");
2038
- res.setHeader(ELSEWHERE_HEADER, "1");
2039
- res.end(JSON.stringify({ error: "another workspace" }));
2040
- }
2041
- //#endregion
2042
- //#region src/server/update.ts
2043
- /**
2044
- * Update discovery - dev only, and deliberately boring about privacy: one anonymous
2045
- * registry metadata GET per day (the same request `npm view` makes), cached in
2046
- * design/.local/, nothing sent beyond the request itself. Offline, slow, or
2047
- * firewalled registries degrade to silence. MARVER_NO_UPDATE_CHECK=1 disables it.
2048
- * Published bundles never check anything - viewers are not the owner.
2049
- */
2050
- const TTL = 864e5;
2051
- /** Installed version: walk up from this module to the package's own package.json
2052
- * (one level from dist/, two from src/server/ - the walk covers both). */
2053
- function installedVersion() {
2054
- let dir = dirname(fileURLToPath(import.meta.url));
2055
- for (let i = 0; i < 4; i++) {
2056
- try {
2057
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
2058
- if (pkg.name === "@marver-design/marver") return pkg.version;
2059
- } catch {}
2060
- dir = dirname(dir);
2061
- }
2062
- return null;
2063
- }
2064
- /** Strictly-newer numeric compare; anything non-numeric (prerelease tags) compares false. */
2065
- const newer = (a, b) => {
2066
- const pa = a.split(".").map((n) => parseInt(n, 10));
2067
- const pb = b.split(".").map((n) => parseInt(n, 10));
2068
- for (let i = 0; i < 3; i++) {
2069
- const x = pa[i] ?? 0, y = pb[i] ?? 0;
2070
- if (!Number.isFinite(x) || !Number.isFinite(y)) return false;
2071
- if (x !== y) return x > y;
2072
- }
2073
- return false;
2074
- };
2075
- /** The latest published version when strictly newer than installed, else null. Never throws. */
2076
- async function checkUpdate(root) {
2077
- if (process.env.MARVER_NO_UPDATE_CHECK) return null;
2078
- const current = installedVersion();
2079
- if (!current) return null;
2080
- const latest = await latestVersion(root);
2081
- return latest && newer(latest, current) ? latest : null;
2082
- }
2083
- async function latestVersion(root) {
2084
- const cacheFile = join(root, "design", ".local", "update-check.json");
2085
- const wellFormed = (v) => typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v);
2086
- try {
2087
- const c = JSON.parse(readFileSync(cacheFile, "utf8"));
2088
- const age = Date.now() - c.checkedAt;
2089
- if (typeof c.checkedAt === "number" && age >= 0 && age < TTL) return wellFormed(c.latest) ? c.latest : null;
2090
- } catch {}
2091
- let latest = null;
2092
- try {
2093
- const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(PKG)}/latest`, { signal: AbortSignal.timeout(3e3) });
2094
- if (res.ok) {
2095
- const v = (await res.json())?.version;
2096
- if (wellFormed(v)) latest = v;
2097
- }
2098
- } catch {}
2099
- try {
2100
- mkdirSync(join(root, "design", ".local"), { recursive: true });
2101
- writeFileSync(cacheFile, JSON.stringify({
2102
- checkedAt: Date.now(),
2103
- latest
2104
- }) + "\n");
2105
- } catch {}
2106
- return latest;
2107
- }
2108
- //#endregion
2109
- //#region src/server/plugin.ts
2110
- const VIRTUAL_THEME = "virtual:sh-theme";
2111
- const VIRTUAL_CONFIG = "virtual:sh-config";
2112
- const VIRTUAL_DATA = "virtual:sh-data";
2113
- function marverPlugin(ctx) {
2114
- const { root, clientDir, config } = ctx;
2115
- const ws = ctx.workspace ?? workspaceId(root);
2116
- /** a watcher this plugin makes, handed to the start (its error is said, not Node's crash) - as it is, outside one */
2117
- const guarded = (w) => ctx.startup?.watch?.(w) ?? w;
2118
- let project = {
2119
- name: config.share.name || basename(root),
2120
- description: config.description
2121
- };
2122
- const projectInfo = () => project;
2123
- let manifest = scanFrames(root, projectInfo());
2124
- let devServer = null;
2125
- let served = 0;
2126
- const bootId = String(process.hrtime.bigint());
2127
- let invRev = 0;
2128
- const pendingInv = /* @__PURE__ */ new Set();
2129
- const flushInv = debounce(() => {
2130
- if (!devServer || !pendingInv.size) return;
2131
- const frameIds = [...pendingInv];
2132
- pendingInv.clear();
2133
- const docs = docRevs(root, manifest.frames);
2134
- devServer.ws.send("sh:frame-invalidated", {
2135
- frameIds,
2136
- revision: `${bootId}:${++invRev}`,
2137
- epoch: docs?.epoch,
2138
- docs: docs ? Object.fromEntries(frameIds.map((id) => [id, docs.doc[id] ?? 0])) : void 0
2139
- });
2140
- }, 120);
2141
- const inFlight = /* @__PURE__ */ new Map();
2142
- const late = /* @__PURE__ */ new Map();
2143
- const envs = () => Object.keys(devServer?.environments ?? { client: 1 }).length;
2144
- const waiting = [];
2145
- const settled = () => inFlight.size === 0;
2146
- const whenSettled = (fn) => {
2147
- if (settled()) fn();
2148
- else waiting.push(fn);
2149
- };
2150
- const drain = () => {
2151
- if (settled()) for (const fn of waiting.splice(0)) try {
2152
- fn();
2153
- } catch (e) {
2154
- console.warn(`[marver] ${e.message}`);
2155
- }
2156
- };
2157
- const done = (file) => {
2158
- const f = inFlight.get(file);
2159
- if (!f) return;
2160
- if (--f.events > 0) return;
2161
- clearTimeout(f.timer);
2162
- inFlight.delete(file);
2163
- drain();
2164
- };
2165
- const flying = (file) => {
2166
- const f = inFlight.get(file) ?? {
2167
- events: 0,
2168
- hits: 0,
2169
- timer: void 0
2170
- };
2171
- f.events++;
2172
- clearTimeout(f.timer);
2173
- f.timer = setTimeout(() => {
2174
- for (const env of Object.values(devServer?.environments ?? {})) env.moduleGraph.invalidateAll();
2175
- late.set(file, (late.get(file) ?? 0) + f.events * envs() - f.hits);
2176
- inFlight.delete(file);
2177
- drain();
2178
- }, 1e4);
2179
- inFlight.set(file, f);
2180
- };
2181
- ctx.startup?.defer(() => {
2182
- flushInv.cancel();
2183
- for (const f of inFlight.values()) clearTimeout(f.timer);
2184
- });
2185
- const landed = (file) => {
2186
- const owed = late.get(file);
2187
- if (owed) {
2188
- if (owed > 1) late.set(file, owed - 1);
2189
- else late.delete(file);
2190
- return;
2191
- }
2192
- const f = inFlight.get(file);
2193
- if (!f) return;
2194
- if (++f.hits < envs()) return;
2195
- f.hits = 0;
2196
- setTimeout(() => done(file), 0);
2197
- };
2198
- const observeMarks = () => observed(observe(root, manifest.frames));
2199
- const observeLater = () => whenSettled(() => {
2200
- if (observeMarks()) devServer?.ws.send("sh:marks", {});
2201
- });
2202
- const hooks = {
2203
- onFrames: (t, cause) => {
2204
- setTimeout(() => whenSettled(() => record(t, cause)), 0);
2205
- },
2206
- onReload(p, passed) {
2207
- logReload(root, {
2208
- kind: "full-reload",
2209
- passed,
2210
- triggeredBy: p.triggeredBy ?? null,
2211
- path: p.path ?? null
2212
- });
2213
- }
2214
- };
2215
- function record(t, cause) {
2216
- const seen = observe(root, manifest.frames, t.file ? { file: t.file } : {});
2217
- const doc = t.unattributed ? [] : t.doc.filter((id) => !seen.doc.includes(id));
2218
- const touched = t.touched.filter((id) => !seen.doc.includes(id) && !seen.note.includes(id) && !doc.includes(id));
2219
- if (doc.length) recordChanged(root, manifest.frames, doc, { doc: true });
2220
- if (touched.length) recordChanged(root, manifest.frames, touched, { doc: false });
2221
- const reload = [.../* @__PURE__ */ new Set([...seen.doc, ...t.doc])];
2222
- for (const id of reload) pendingInv.add(id);
2223
- flushInv();
2224
- if (reload.length || touched.length || seen.note.length) devServer?.ws.send("sh:marks", {});
2225
- logReload(root, {
2226
- kind: "update",
2227
- cause,
2228
- file: t.file ? relative(root, t.file).split(sep).join("/") : null,
2229
- reload,
2230
- inPlace: t.touched
2231
- });
2232
- }
2233
- /** No theme is only a problem for app frames: a canvas made of content frames alone (Doc, Md,
2234
- * Diagram ship their own styling) needs none (#4). The shell decides its banner from the live
2235
- * manifest; the config carries only whether a theme exists. */
2236
- const themeMissing = () => themeFile() == null && !contentOnly(manifest.frames);
2237
- /** Theme resolution: design/theme.css wrapper > configured > detected > empty (spec §5.4). */
2238
- const themeFile = () => {
2239
- const wrapper = join(root, "design", "theme.css");
2240
- if (existsSync(wrapper)) return wrapper;
2241
- if (config.theme && existsSync(join(root, config.theme))) return join(root, config.theme);
2242
- if (ctx.detectedThemeCss && existsSync(join(root, ctx.detectedThemeCss))) return join(root, ctx.detectedThemeCss);
2243
- return null;
2244
- };
2245
- return [{
2246
- name: "marver",
2247
- watchChange(id) {
2248
- if (devServer) flying(id);
2249
- },
2250
- enforce: "pre",
2251
- resolveId(id) {
2252
- if (id === VIRTUAL_THEME) return themeFile() ?? "\0virtual:sh-theme.css";
2253
- if (id === VIRTUAL_CONFIG) return "\0virtual:sh-config";
2254
- if (id === VIRTUAL_DATA) return "\0virtual:sh-data";
2255
- },
2256
- load(id) {
2257
- if (id === "\0virtual:sh-theme.css") {
2258
- if (themeMissing()) console.warn("[marver] no theme detected - frames render unstyled. Create design/theme.css importing your app's stylesheet (or set `theme` in design/config.ts).");
2259
- return "/* marver: no theme configured */";
2260
- }
2261
- if (id === "\0virtual:sh-config") {
2262
- const setupPending = (() => {
2263
- try {
2264
- const s = readFileSync(join(root, "design", "instructions", "setup.md"), "utf8");
2265
- return s.startsWith("# Setup required") && s.includes("marver init");
2266
- } catch {
2267
- return false;
2268
- }
2269
- })();
2270
- return `export default ${JSON.stringify({
2271
- viewports: config.viewports,
2272
- themes: config.themes,
2273
- zoomSpeed: config.zoomSpeed,
2274
- noTheme: themeFile() == null,
2275
- setup: setupPending,
2276
- projectName: config.share.name || basename(root),
2277
- branding: config.share.branding,
2278
- jam: config.jam ? {
2279
- chime: config.jam.chime,
2280
- capture: config.jam.capture,
2281
- names: config.jam.names && config.jam.agent === "claude"
2282
- } : null,
2283
- workspace: ws
2284
- })}`;
2285
- }
2286
- if (id === "\0virtual:sh-data") return "export default null";
2287
- },
2288
- /** HTML frames: inject theme + bridge into any design/**.html Vite serves.
2289
- * Inline scripts go through vite's html-proxy import-analysis: bare specifiers resolve
2290
- * through plugins (so `virtual:sh-theme` works); `/@id/` URLs are rejected there. */
2291
- transformIndexHtml: {
2292
- order: "pre",
2293
- handler(html, hctx) {
2294
- const path = (hctx.originalUrl ?? hctx.path ?? "").split("?")[0];
2295
- if (!path.startsWith("/design/")) return;
2296
- const bridge = "/@fs/" + join(clientDir, "frame-host", "bridge.js").split("\\").join("/") + "?html=1";
2297
- const frame = manifest.frames.find((f) => "/" + f.file === path);
2298
- const stamp = frame ? docRev(root, manifest.frames, frame.id) : "";
2299
- return {
2300
- html,
2301
- tags: [
2302
- {
2303
- tag: "script",
2304
- attrs: { type: "module" },
2305
- children: `import '${VIRTUAL_THEME}'`,
2306
- injectTo: "head-prepend"
2307
- },
2308
- {
2309
- tag: "script",
2310
- attrs: {
2311
- type: "module",
2312
- src: bridge
2313
- },
2314
- injectTo: "head-prepend"
2315
- },
2316
- ...stamp ? [{
2317
- tag: "meta",
2318
- attrs: {
2319
- name: "mv-doc",
2320
- content: stamp
2321
- },
2322
- injectTo: "head-prepend"
2323
- }] : []
2324
- ]
2325
- };
2326
- }
2327
- },
2328
- configureServer(server) {
2329
- const closers = [];
2330
- const onClose = (fn) => {
2331
- closers.push(fn);
2332
- };
2333
- const closeAll = () => {
2334
- for (const fn of closers.splice(0).reverse()) try {
2335
- fn();
2336
- } catch {}
2337
- };
2338
- const withdraw = ctx.startup?.defer(closeAll, server);
2339
- server.httpServer?.once("close", () => {
2340
- withdraw?.();
2341
- closeAll();
2342
- });
2343
- if (served++) {
2344
- manifest = scanFrames(root, projectInfo());
2345
- observeLater();
2346
- }
2347
- server.middlewares.use(guardMiddleware(ws));
2348
- let bakeGen = Date.now();
2349
- server.middlewares.use((req, res, next) => {
2350
- if (req.url && req.url.includes("/frame-host/registry.ts")) {
2351
- const orig = res.setHeader.bind(res);
2352
- res.setHeader = ((name, value) => orig(name, String(name).toLowerCase() === "cache-control" ? "no-cache" : value));
2353
- }
2354
- next();
2355
- });
2356
- const update = checkUpdate(root).catch(() => null);
2357
- update.then((latest) => {
2358
- if (latest) console.log(`\n update: ${PKG} ${latest} is out (installed ${installedVersion() ?? "?"}) → npm i -D ${PKG}@latest && npx ${NAME} init\n`);
2359
- });
2360
- server.middlewares.use((req, res, next) => {
2361
- if (new URL(req.url ?? "/", "http://x").pathname !== `/__mv/api/update`) return next();
2362
- update.then((latest) => {
2363
- res.setHeader("content-type", "application/json");
2364
- res.setHeader("cache-control", "no-store");
2365
- res.end(JSON.stringify({
2366
- latest,
2367
- current: installedVersion()
2368
- }));
2369
- });
2370
- });
2371
- const listeningOrigin = () => originOf(server.httpServer?.address());
2372
- initMarks(root, manifest.frames);
2373
- tidyPerfDir(root);
2374
- server.middlewares.use(apiMiddleware(root, {
2375
- viewports: config.viewports,
2376
- origin: listeningOrigin,
2377
- bakeGen: () => bakeGen,
2378
- notify: (event) => server.ws.send(event, {}),
2379
- manifest: () => manifest,
2380
- settled,
2381
- workspace: ws
2382
- }));
2383
- server.middlewares.use(routesMiddleware(server, clientDir, {
2384
- doc: (id) => docRev(root, manifest.frames, id),
2385
- docs: () => docRevs(root, manifest.frames)
2386
- }, ctx.proof));
2387
- const before = devServer;
2388
- devServer = server;
2389
- onClose(() => {
2390
- if (devServer === server) devServer = before;
2391
- });
2392
- guardUpdates(server, root, () => manifest, hooks);
2393
- let framesKey = JSON.stringify(manifest.frames);
2394
- let scenesKey = JSON.stringify(manifest.scenes);
2395
- let unplacedKey = "";
2396
- const sayUnplaced = () => {
2397
- const { unplaced } = readMembership(root, manifest.frames.map((f) => f.id));
2398
- const key = unplaced.join(",");
2399
- if (key && key !== unplacedKey) console.log(`[${NAME}] not on a board (${unplaced.length}): ${unplaced.join(", ")} - every frame goes on the board it belongs to: npx ${NAME} boards pin <board> <scene/frame ...>`);
2400
- unplacedKey = key;
2401
- };
2402
- sayUnplaced();
2403
- const regen = debounce(() => {
2404
- manifest = scanFrames(root, projectInfo());
2405
- sayUnplaced();
2406
- const changed = writeManifest(root, manifest);
2407
- observeLater();
2408
- const key = JSON.stringify(manifest.frames), sKey = JSON.stringify(manifest.scenes);
2409
- if (changed && key !== framesKey) server.ws.send("sh:manifest", manifest);
2410
- else if (changed && sKey !== scenesKey) server.ws.send("sh:scenes", { scenes: manifest.scenes });
2411
- framesKey = key;
2412
- scenesKey = sKey;
2413
- }, 150);
2414
- onClose(regen.cancel);
2415
- const watched = [join(root, "design", "scenes"), join(root, "design", "components")];
2416
- const inScope = (file) => watched.some((w) => file.startsWith(w));
2417
- const themeModules = () => {
2418
- const f = themeFile();
2419
- if (!f) return [];
2420
- const out = [];
2421
- const seen = /* @__PURE__ */ new Set();
2422
- const walk = (mod) => {
2423
- if (!mod || seen.has(mod)) return;
2424
- seen.add(mod);
2425
- out.push(mod);
2426
- for (const im of mod.clientImportedModules ?? mod.importedModules ?? []) if (String(im.id ?? "").split("?")[0].endsWith(".css")) walk(im);
2427
- };
2428
- for (const mod of server.moduleGraph.getModulesByFile(f) ?? []) walk(mod);
2429
- return out;
2430
- };
2431
- const pushTheme = debounce(() => {
2432
- for (const mod of themeModules()) server.reloadModule(mod).catch(() => {});
2433
- }, 150);
2434
- onClose(pushTheme.cancel);
2435
- const rescanTheme = () => {
2436
- for (const mod of themeModules()) server.moduleGraph.invalidateModule(mod);
2437
- pushTheme();
2438
- };
2439
- const localDir = join(root, "design", ".local"), boardsDirGen = join(root, "design", "boards"), manifestPath = join(root, "design", "manifest.json");
2440
- const bumpGen = (f) => {
2441
- if (f.startsWith(localDir) || f.startsWith(boardsDirGen) || f === manifestPath || f.includes("/node_modules/")) return;
2442
- bakeGen++;
2443
- prune();
2444
- };
2445
- const pruning = /* @__PURE__ */ new Set();
2446
- const prune = () => {
2447
- const t = setTimeout(async () => {
2448
- pruning.delete(t);
2449
- try {
2450
- (await import("./bake-DM_uWgAA.mjs")).pruneBakes(root, bakeGen);
2451
- } catch {}
2452
- }, 500);
2453
- pruning.add(t);
2454
- };
2455
- onClose(() => {
2456
- for (const t of pruning) clearTimeout(t);
2457
- });
2458
- prune();
2459
- server.watcher.on("add", bumpGen);
2460
- server.watcher.on("unlink", bumpGen);
2461
- server.watcher.on("change", bumpGen);
2462
- server.watcher.on("add", (f) => {
2463
- if (inScope(f)) {
2464
- regen();
2465
- rescanTheme();
2466
- }
2467
- });
2468
- server.watcher.on("unlink", (f) => {
2469
- if (inScope(f)) {
2470
- regen();
2471
- rescanTheme();
2472
- }
2473
- });
2474
- const contextDir = join(root, "context") + sep;
2475
- let statusTimer;
2476
- onClose(() => clearTimeout(statusTimer));
2477
- const restatus = (f) => {
2478
- if (!f.startsWith(contextDir) && !(inScope(f) && f.endsWith("_brief.md"))) return;
2479
- clearTimeout(statusTimer);
2480
- statusTimer = setTimeout(() => {
2481
- server.ws.send("sh:boards", {});
2482
- regen();
2483
- }, 150);
2484
- };
2485
- server.watcher.on("add", restatus);
2486
- server.watcher.on("unlink", restatus);
2487
- server.watcher.on("change", restatus);
2488
- server.watcher.on("change", (f) => inScope(f) && (/\.(tsx|jsx)$/.test(f) || f.endsWith("_brief.md") || isNoteFile(f)) && regen());
2489
- const marksChanged = debounce(observeLater, 300);
2490
- onClose(marksChanged.cancel);
2491
- for (const ev of [
2492
- "add",
2493
- "change",
2494
- "unlink"
2495
- ]) server.watcher.on(ev, (f) => {
2496
- if (!f.startsWith(localDir) && !f.startsWith(boardsDirGen)) marksChanged();
2497
- });
2498
- const configFile = join(root, "design", "config.ts");
2499
- server.watcher.on("change", (f) => {
2500
- if (f !== configFile) return;
2501
- loadConfig(root).then((c) => {
2502
- project = {
2503
- name: c.share.name || basename(root),
2504
- description: c.description
2505
- };
2506
- regen();
2507
- }).catch(() => {});
2508
- });
2509
- writeManifest(root, manifest);
2510
- const boardsDir = join(root, "design", "boards");
2511
- try {
2512
- mkdirSync(boardsDir, { recursive: true });
2513
- const timers = /* @__PURE__ */ new Map();
2514
- const badBoards = /* @__PURE__ */ new Map();
2515
- const reportBad = (file, content, error) => {
2516
- if (badBoards.get(file) === hash(content)) return;
2517
- badBoards.set(file, hash(content));
2518
- console.warn(`[marver] design/boards/${file} is not valid JSON - ${error}`);
2519
- };
2520
- if (!checkBoardsDir(root, boardsDir)) {
2521
- for (const b of listBoardFiles(boardsDir).boards) if (b.error) reportBad(`${b.name}.json`, b.content, b.error);
2522
- }
2523
- if (nodeExists(join(boardsDir, `all-scenes.json`))) console.log(`[${NAME}] design/boards/${ALL_SCENES}.json is left over from the All Scenes board, gone since 0.25 - nothing reads it any more; delete it when you like (its threads stay in design/comments/)`);
2524
- let listTimer;
2525
- const watcher = guarded(watch(boardsDir, (_event, file) => {
2526
- if (!file || !file.endsWith(".json") || file === "_sizes.json" || file === `all-scenes.json`) return;
2527
- clearTimeout(listTimer);
2528
- listTimer = setTimeout(() => {
2529
- server.ws.send("sh:boards", {});
2530
- regen();
2531
- boardsChanged(root);
2532
- }, 150);
2533
- clearTimeout(timers.get(file));
2534
- timers.set(file, setTimeout(() => {
2535
- timers.delete(file);
2536
- let content;
2537
- if (!isRegularFile(join(boardsDir, file))) return;
2538
- try {
2539
- content = readFileSync(join(boardsDir, file), "utf8");
2540
- } catch {
2541
- return;
2542
- }
2543
- const { error } = parseBoard(content);
2544
- if (error) {
2545
- if (!checkBoardsDir(root, boardsDir)) reportBad(file, content, error);
2546
- return;
2547
- }
2548
- badBoards.delete(file);
2549
- server.ws.send("sh:board", {
2550
- name: file.replace(/\.json$/, ""),
2551
- sha256: hash(content)
2552
- });
2553
- }, 120));
2554
- }));
2555
- onClose(() => {
2556
- watcher.close();
2557
- clearTimeout(listTimer);
2558
- for (const t of timers.values()) clearTimeout(t);
2559
- });
2560
- } catch {}
2561
- try {
2562
- const inbox = join(root, "design", ".local", "shots");
2563
- mkdirSync(inbox, { recursive: true });
2564
- const origin = listeningOrigin;
2565
- const inFlight = /* @__PURE__ */ new Set();
2566
- const processRequest = (file) => {
2567
- if (!file.endsWith(".request.json") || inFlight.has(file)) return;
2568
- const reqPath = join(inbox, file);
2569
- if (!existsSync(reqPath)) return;
2570
- inFlight.add(file);
2571
- setTimeout(async () => {
2572
- const base = file.replace(/\.request\.json$/, "");
2573
- const resultPath = join(inbox, `${base}.result.json`);
2574
- const claimed = join(inbox, `.${base}.${process.pid}.${Date.now().toString(36)}.claimed`);
2575
- try {
2576
- renameSync(reqPath, claimed);
2577
- } catch {
2578
- inFlight.delete(file);
2579
- return;
2580
- }
2581
- try {
2582
- const write = (r) => {
2583
- const tmp = join(inbox, `.${base}.${process.pid}.tmp`);
2584
- try {
2585
- writeFileSync(tmp, JSON.stringify(r, null, 2));
2586
- renameSync(tmp, resultPath);
2587
- } catch {
2588
- try {
2589
- rmSync(tmp, { force: true });
2590
- } catch {}
2591
- }
2592
- };
2593
- let spec;
2594
- try {
2595
- spec = JSON.parse(readFileSync(claimed, "utf8"));
2596
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new Error("expected an object");
2597
- } catch (err) {
2598
- write({
2599
- ok: false,
2600
- error: `malformed request - ${err.message}`
2601
- });
2602
- return;
2603
- }
2604
- const theme = spec.theme === void 0 ? "light" : spec.theme;
2605
- if (typeof theme !== "string" || !/^[a-z0-9-]+$/i.test(theme)) {
2606
- write({
2607
- ok: false,
2608
- error: "invalid theme"
2609
- });
2610
- return;
2611
- }
2612
- const scale = spec.scale === void 0 ? void 0 : spec.scale;
2613
- if (scale !== void 0 && !(Number.isInteger(scale) && scale >= 1 && scale <= 4)) {
2614
- write({
2615
- ok: false,
2616
- error: "invalid scale"
2617
- });
2618
- return;
2619
- }
2620
- const ways = [
2621
- "frame",
2622
- "frames",
2623
- "scene",
2624
- "all"
2625
- ].filter((k) => spec[k] !== void 0);
2626
- if (ways.length !== 1) {
2627
- write({
2628
- ok: false,
2629
- error: "name the frames one way: frame (an id), frames (an array of ids), scene (a name) or all (true)"
2630
- });
2631
- return;
2632
- }
2633
- const o = origin();
2634
- if (!o) {
2635
- write({
2636
- ok: false,
2637
- error: "dev server has no address yet - retry"
2638
- });
2639
- return;
2640
- }
2641
- const { shootFrame, shootBatch, resolveFrames } = await import("./shot-LFhC-WYD.mjs");
2642
- if (ways[0] === "frame") {
2643
- if (typeof spec.frame !== "string") {
2644
- write({
2645
- ok: false,
2646
- error: "frame must be a frame id"
2647
- });
2648
- return;
2649
- }
2650
- write(await shootFrame({
2651
- root,
2652
- viewports: config.viewports,
2653
- frameId: spec.frame,
2654
- theme,
2655
- origin: o,
2656
- scale
2657
- }));
2658
- return;
2659
- }
2660
- const sel = resolveFrames(root, spec);
2661
- if (!sel.ok) {
2662
- write({
2663
- ok: false,
2664
- error: sel.error
2665
- });
2666
- return;
2667
- }
2668
- try {
2669
- write({
2670
- ok: true,
2671
- results: await shootBatch({
2672
- root,
2673
- viewports: config.viewports,
2674
- frames: sel.frames,
2675
- theme,
2676
- origin: o,
2677
- scale
2678
- })
2679
- });
2680
- } catch (err) {
2681
- write({
2682
- ok: false,
2683
- error: err.message
2684
- });
2685
- }
2686
- } finally {
2687
- try {
2688
- rmSync(claimed, { force: true });
2689
- } catch {}
2690
- inFlight.delete(file);
2691
- }
2692
- }, 60);
2693
- };
2694
- const inboxWatcher = guarded(watch(inbox, { persistent: false }, (_e, file) => {
2695
- if (file) processRequest(file);
2696
- }));
2697
- const sweep = setInterval(() => {
2698
- try {
2699
- for (const f of readdirSync(inbox)) processRequest(f);
2700
- } catch {}
2701
- }, 1e3);
2702
- sweep.unref?.();
2703
- onClose(() => {
2704
- inboxWatcher.close();
2705
- clearInterval(sweep);
2706
- });
2707
- } catch {}
2708
- }
2709
- }, updatesPlugin(root, () => manifest, () => devServer && hooks, landed)];
2710
- }
2711
- /** The marks look at the frames on disk; true when they recorded something. */
2712
- function observed(r) {
2713
- return r.doc.length + r.note.length > 0;
2714
- }
2715
- function debounce(fn, ms) {
2716
- let t;
2717
- return Object.assign(((...a) => {
2718
- clearTimeout(t);
2719
- t = setTimeout(() => fn(...a), ms);
2720
- }), { cancel: () => clearTimeout(t) });
2721
- }
2722
- /** Extra vite plugin when the host runs Tailwind v4. The host's own @tailwindcss/vite
2723
- * wins (version-matched to their tailwindcss); the fallback is marver's bundled copy -
2724
- * Next.js hosts use @tailwindcss/postcss and never have the vite plugin (the blessed
2725
- * stack would otherwise render every frame without its utility classes). */
2726
- async function tailwind4Plugin(root) {
2727
- const factories = [() => import(join(root, "node_modules", "@tailwindcss", "vite", "dist", "index.mjs")), () => import("@tailwindcss/vite")];
2728
- for (const load of factories) try {
2729
- const mod = await load();
2730
- const result = (mod.default ?? mod)();
2731
- return Array.isArray(result) ? result : [result];
2732
- } catch {}
2733
- return null;
2734
- }
2735
- /** Tailwind v3: inline PostCSS config extending the host's tailwind config with design/ globs. Host files untouched. */
2736
- async function tailwind3Css(root) {
2737
- for (const name of [
2738
- "tailwind.config.ts",
2739
- "tailwind.config.js",
2740
- "tailwind.config.mjs",
2741
- "tailwind.config.cjs"
2742
- ]) {
2743
- const file = join(root, name);
2744
- if (!existsSync(file)) continue;
2745
- try {
2746
- const { pathToFileURL } = await import("node:url");
2747
- const twConfig = (await import(pathToFileURL(file).href)).default;
2748
- const tailwindcss = (await import(join(root, "node_modules", "tailwindcss", "lib", "index.js").replace(/\\/g, "/"))).default;
2749
- const content = Array.isArray(twConfig.content) ? twConfig.content : twConfig.content?.files ?? [];
2750
- return { postcss: { plugins: [tailwindcss({
2751
- ...twConfig,
2752
- content: [...content, "./design/**/*.{ts,tsx,html}"]
2753
- })] } };
2754
- } catch (err) {
2755
- console.warn(`[marver] could not extend Tailwind v3 config (${err.message}). Add './design/**/*.{ts,tsx,html}' to its content globs manually.`);
2756
- return null;
2757
- }
2758
- }
2759
- return null;
2760
- }
2761
- //#endregion
2762
- export { autoWidthOf as a, readSizes as c, installedVersion as i, loadConfig as l, tailwind3Css as n, keptSizes as o, tailwind4Plugin as r, measuringFrames as s, marverPlugin as t };