@marver-design/marver 0.26.1 → 0.27.2

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