@open-document/core 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/{build-U81g9Hnk.js → build-C3pMGxJN.js} +1 -1
  2. package/dist/check-Dtwb1wvU.js +42 -0
  3. package/dist/cli/bin.js +24 -3
  4. package/dist/config-Dg1AMP0r.js +2461 -0
  5. package/dist/context-FoX0afRf.js +26 -0
  6. package/dist/{dev-DwwFT6uX.js → dev-Cdd7NZRQ.js} +1 -1
  7. package/dist/diagram-xlVDekYk.js +763 -0
  8. package/dist/export-ClJ4T1uU.js +36 -0
  9. package/dist/import-D7Psi8WK.js +25 -0
  10. package/dist/index.d.ts +235 -90
  11. package/dist/index.js +515 -49
  12. package/dist/ops/index.d.ts +96 -1
  13. package/dist/ops/index.js +3 -199
  14. package/dist/ops-Ci5Xw6QG.js +1270 -0
  15. package/dist/{preview-C_jbySle.js → preview-BhbCiAKC.js} +1 -1
  16. package/dist/sdk-CWMsH9Ms.d.ts +123 -0
  17. package/dist/vite/index.d.ts +6 -0
  18. package/dist/vite/index.js +1 -2
  19. package/env.d.ts +33 -1
  20. package/package.json +10 -1
  21. package/skills/create-doc/SKILL.md +6 -2
  22. package/skills/doc-authoring/SKILL.md +79 -0
  23. package/skills/doc-authoring/references/long-form.md +131 -0
  24. package/src/app/components/data-table.tsx +196 -0
  25. package/src/app/components/diagram.tsx +76 -0
  26. package/src/app/components/flow-page.tsx +20 -3
  27. package/src/app/components/footnote.tsx +196 -0
  28. package/src/app/components/numbering.tsx +208 -0
  29. package/src/app/lib/agent-bridge.ts +128 -0
  30. package/src/app/lib/diagnostics.ts +282 -0
  31. package/src/app/lib/export-html.ts +35 -11
  32. package/src/app/lib/export-pdf.ts +54 -19
  33. package/src/app/lib/flow-measure.ts +100 -31
  34. package/src/app/lib/flow.test.ts +46 -0
  35. package/src/app/lib/flow.ts +28 -3
  36. package/src/app/lib/footnotes.test.tsx +102 -0
  37. package/src/app/lib/footnotes.ts +94 -0
  38. package/src/app/lib/labels.ts +175 -0
  39. package/src/app/lib/page-context.tsx +6 -1
  40. package/src/app/lib/scan.ts +26 -0
  41. package/src/app/lib/sdk.ts +3 -0
  42. package/src/app/lib/use-doc-pages.ts +50 -15
  43. package/src/app/routes/doc.tsx +7 -4
  44. package/dist/config-8zkUElGq.js +0 -1169
  45. package/dist/design-IyRSwCtK.js +0 -52
  46. package/dist/edit-ops-D2W2plpc.js +0 -1190
@@ -0,0 +1,2461 @@
1
+ import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-xlVDekYk.js";
2
+ import chalk from "chalk";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import fg from "fast-glob";
8
+ import { loadConfigFromFile, normalizePath } from "vite";
9
+ import { parse } from "@babel/parser";
10
+ import { randomUUID } from "node:crypto";
11
+ import tailwindcss from "@tailwindcss/vite";
12
+ import react from "@vitejs/plugin-react";
13
+ //#region src/vite/open-doc-plugin.ts
14
+ const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
15
+ const CONFIG_FILE = "open-doc.config.ts";
16
+ const DOCS_VMOD = "virtual:open-doc/docs";
17
+ const CONFIG_VMOD = "virtual:open-doc/config";
18
+ const FOLDERS_VMOD = "virtual:open-doc/folders";
19
+ async function readFoldersManifest(file) {
20
+ try {
21
+ const parsed = JSON.parse(await fs.readFile(file, "utf8"));
22
+ return {
23
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
24
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
25
+ };
26
+ } catch (err) {
27
+ if (err.code === "ENOENT") return {
28
+ folders: [],
29
+ assignments: {}
30
+ };
31
+ throw err;
32
+ }
33
+ }
34
+ function resolved$1(id) {
35
+ return `\0${id}`;
36
+ }
37
+ async function findDocs(userCwd, docsDir) {
38
+ const abs = path.resolve(userCwd, docsDir);
39
+ if (!existsSync(abs)) return [];
40
+ return (await fg("*/index.{tsx,jsx,ts,js}", {
41
+ cwd: abs,
42
+ absolute: true,
43
+ onlyFiles: true
44
+ })).sort();
45
+ }
46
+ function toId(absFile, docsRoot) {
47
+ return path.relative(docsRoot, absFile).split(path.sep)[0];
48
+ }
49
+ const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
50
+ const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
51
+ /**
52
+ * Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
53
+ * every discovery pass, and the two fields it needs (sort order, theme back-link)
54
+ * are contractually string literals.
55
+ */
56
+ function extractMeta(src) {
57
+ const empty = {
58
+ theme: null,
59
+ createdAt: null
60
+ };
61
+ const metaStart = src.search(/export\s+const\s+meta\b/);
62
+ if (metaStart === -1) return empty;
63
+ const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
64
+ if (openBrace === -1) return empty;
65
+ let depth = 0;
66
+ let closeBrace = -1;
67
+ for (let i = openBrace; i < src.length; i++) {
68
+ const ch = src[i];
69
+ if (ch === "{") depth++;
70
+ else if (ch === "}") {
71
+ depth--;
72
+ if (depth === 0) {
73
+ closeBrace = i;
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ if (closeBrace === -1) return empty;
79
+ const body = src.slice(openBrace + 1, closeBrace);
80
+ return {
81
+ theme: body.match(META_THEME_RE)?.[1] ?? null,
82
+ createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null
83
+ };
84
+ }
85
+ function parseCreatedAtMs(iso) {
86
+ if (!iso) return null;
87
+ const ms = Date.parse(iso);
88
+ return Number.isFinite(ms) ? ms : null;
89
+ }
90
+ async function readMeta(abs) {
91
+ try {
92
+ return extractMeta(await fs.readFile(abs, "utf8"));
93
+ } catch {
94
+ return {
95
+ theme: null,
96
+ createdAt: null
97
+ };
98
+ }
99
+ }
100
+ const warnedInvalidDocIds = /* @__PURE__ */ new Set();
101
+ async function generateDocsModule(files, docsRoot, isDev) {
102
+ const scanned = await Promise.all(files.map(async (abs) => {
103
+ const meta = await readMeta(abs);
104
+ return {
105
+ id: toId(abs, docsRoot),
106
+ importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
107
+ theme: meta.theme,
108
+ createdAt: parseCreatedAtMs(meta.createdAt)
109
+ };
110
+ }));
111
+ const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
112
+ const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
113
+ const ids = JSON.stringify(entries.map((e) => e.id).sort());
114
+ const createdAtMap = {};
115
+ const themesMap = {};
116
+ for (const e of entries) {
117
+ if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
118
+ if (e.theme) themesMap[e.id] = e.theme;
119
+ }
120
+ const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
121
+ const devRuntime = isDev ? `
122
+ const docImportTokens = ${importTokens};
123
+ if (import.meta.hot) {
124
+ import.meta.hot.on('open-doc:doc-changed', (data) => {
125
+ const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
126
+ const token = Date.now();
127
+ for (const id of ids) {
128
+ if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
129
+ }
130
+ });
131
+ }
132
+ ` : "";
133
+ const cases = entries.map((e) => {
134
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + docImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
135
+ return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
136
+ }).join("\n");
137
+ return {
138
+ code: `// virtual:open-doc/docs — generated
139
+ export const docIds = ${ids};
140
+ export const docCreatedAt = ${JSON.stringify(createdAtMap)};
141
+ export const docThemes = ${JSON.stringify(themesMap)};
142
+ ${devRuntime}
143
+
144
+ export async function loadDoc(id) {
145
+ switch (id) {
146
+ ${cases}
147
+ default: throw new Error('Document not found: ' + id);
148
+ }
149
+ }
150
+ `,
151
+ ignored
152
+ };
153
+ }
154
+ function openDocPlugin(opts) {
155
+ const { userCwd, config, coreVersion } = opts;
156
+ const docsDir = config.docsDir ?? "docs";
157
+ const docsRoot = path.resolve(userCwd, docsDir);
158
+ const foldersManifestPath = path.join(docsRoot, ".folders.json");
159
+ let isDev = false;
160
+ const docIdForEntry = (p) => {
161
+ const rel = path.relative(docsRoot, p);
162
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
163
+ const parts = rel.split(path.sep);
164
+ if (parts.length !== 2) return null;
165
+ if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
166
+ return parts[0];
167
+ };
168
+ let docChangeTimer = null;
169
+ const pendingDocChanges = /* @__PURE__ */ new Set();
170
+ const queueDocChanged = (server, id) => {
171
+ pendingDocChanges.add(id);
172
+ if (docChangeTimer) clearTimeout(docChangeTimer);
173
+ docChangeTimer = setTimeout(() => {
174
+ docChangeTimer = null;
175
+ const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
176
+ if (mod) server.moduleGraph.invalidateModule(mod);
177
+ const docIds = Array.from(pendingDocChanges);
178
+ pendingDocChanges.clear();
179
+ server.ws.send({
180
+ type: "custom",
181
+ event: "open-doc:doc-changed",
182
+ data: { docIds }
183
+ });
184
+ }, 100);
185
+ };
186
+ return {
187
+ name: "open-doc",
188
+ config(_c, env) {
189
+ isDev = env.command === "serve";
190
+ return { server: { fs: { allow: [userCwd] } } };
191
+ },
192
+ resolveId(id) {
193
+ if (id === DOCS_VMOD) return resolved$1(DOCS_VMOD);
194
+ if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
195
+ if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
196
+ return null;
197
+ },
198
+ async load(id) {
199
+ if (id === resolved$1(DOCS_VMOD)) {
200
+ const { code, ignored } = await generateDocsModule(await findDocs(userCwd, docsDir), docsRoot, isDev);
201
+ for (const docId of ignored) {
202
+ if (warnedInvalidDocIds.has(docId)) continue;
203
+ warnedInvalidDocIds.add(docId);
204
+ this.warn(`Ignoring document folder "${docId}": ids must match ${DOC_ID_RE} (letters, digits, "-", "_"). Rename it under "${docsDir}/" to a kebab-case id so it shows up.`);
205
+ }
206
+ return code;
207
+ }
208
+ if (id === resolved$1(CONFIG_VMOD)) {
209
+ const userBuild = config.build ?? {};
210
+ const build = isDev ? {
211
+ showDocBrowser: true,
212
+ allowHtmlExport: true
213
+ } : {
214
+ showDocBrowser: userBuild.showDocBrowser ?? true,
215
+ allowHtmlExport: userBuild.allowHtmlExport ?? true
216
+ };
217
+ return `export default ${JSON.stringify({
218
+ ...config,
219
+ build,
220
+ version: coreVersion
221
+ })};\n`;
222
+ }
223
+ if (id === resolved$1(FOLDERS_VMOD)) {
224
+ const manifest = await readFoldersManifest(foldersManifestPath);
225
+ return `export default ${JSON.stringify(manifest)};\n`;
226
+ }
227
+ return null;
228
+ },
229
+ handleHotUpdate(ctx) {
230
+ const docId = docIdForEntry(ctx.file);
231
+ if (!docId) return;
232
+ queueDocChanged(ctx.server, docId);
233
+ return [];
234
+ },
235
+ configureServer(server) {
236
+ const isDocEntry = (p) => docIdForEntry(p) !== null;
237
+ let reloadTimer = null;
238
+ const reload = () => {
239
+ if (reloadTimer) clearTimeout(reloadTimer);
240
+ reloadTimer = setTimeout(() => {
241
+ reloadTimer = null;
242
+ const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
243
+ if (mod) server.moduleGraph.invalidateModule(mod);
244
+ server.ws.send({ type: "full-reload" });
245
+ }, 150);
246
+ };
247
+ server.watcher.add(docsRoot);
248
+ server.watcher.on("add", (p) => {
249
+ if (isDocEntry(p)) reload();
250
+ });
251
+ server.watcher.on("unlink", (p) => {
252
+ if (isDocEntry(p)) reload();
253
+ });
254
+ server.watcher.on("unlinkDir", (p) => {
255
+ if (path.dirname(p) === docsRoot) reload();
256
+ });
257
+ let foldersTimer = null;
258
+ const foldersChanged = () => {
259
+ if (foldersTimer) clearTimeout(foldersTimer);
260
+ foldersTimer = setTimeout(() => {
261
+ foldersTimer = null;
262
+ const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
263
+ if (mod) server.moduleGraph.invalidateModule(mod);
264
+ server.ws.send({
265
+ type: "custom",
266
+ event: "open-doc:files-changed",
267
+ data: {}
268
+ });
269
+ }, 100);
270
+ };
271
+ server.watcher.add(foldersManifestPath);
272
+ for (const event of [
273
+ "add",
274
+ "change",
275
+ "unlink"
276
+ ]) server.watcher.on(event, (p) => {
277
+ if (p === foldersManifestPath) foldersChanged();
278
+ });
279
+ }
280
+ };
281
+ }
282
+ async function loadUserConfig(userCwd) {
283
+ const file = path.join(userCwd, CONFIG_FILE);
284
+ if (!existsSync(file)) return {};
285
+ return (await loadConfigFromFile({
286
+ command: "serve",
287
+ mode: "development"
288
+ }, file, userCwd, "silent"))?.config ?? {};
289
+ }
290
+ //#endregion
291
+ //#region src/vite/routes/context.ts
292
+ function makeContext(opts) {
293
+ const userCwd = opts.userCwd;
294
+ const docsDir = opts.docsDir ?? "docs";
295
+ const assetsDir = opts.assetsDir ?? "assets";
296
+ const docsRoot = path.resolve(userCwd, docsDir);
297
+ return {
298
+ userCwd,
299
+ docsDir,
300
+ docsRoot,
301
+ globalAssetsRoot: path.resolve(userCwd, assetsDir),
302
+ manifestPath: path.join(docsRoot, ".folders.json"),
303
+ coreVersion: opts.coreVersion,
304
+ ...opts.serverOrigin !== void 0 ? { serverOrigin: opts.serverOrigin } : {}
305
+ };
306
+ }
307
+ async function readBody(req) {
308
+ return await new Promise((resolve, reject) => {
309
+ const chunks = [];
310
+ req.on("data", (c) => chunks.push(c));
311
+ req.on("end", () => {
312
+ const raw = Buffer.concat(chunks).toString("utf8");
313
+ if (!raw) return resolve({});
314
+ try {
315
+ resolve(JSON.parse(raw));
316
+ } catch (e) {
317
+ reject(e);
318
+ }
319
+ });
320
+ req.on("error", reject);
321
+ });
322
+ }
323
+ function json(res, status, body) {
324
+ res.statusCode = status;
325
+ res.setHeader("content-type", "application/json");
326
+ res.end(JSON.stringify(body));
327
+ }
328
+ const ENTRY_NAMES$1 = [
329
+ "index.tsx",
330
+ "index.jsx",
331
+ "index.ts",
332
+ "index.js"
333
+ ];
334
+ /** Absolute path of a document's entry file, or null when the id is unusable. */
335
+ function resolveDocPath(userCwd, docsDir, docId) {
336
+ if (!DOC_ID_RE.test(docId)) return null;
337
+ const docsRoot = path.resolve(userCwd, docsDir);
338
+ const full = path.resolve(docsRoot, docId, ENTRY_NAMES$1[0]);
339
+ if (!full.startsWith(docsRoot + path.sep)) return null;
340
+ return full;
341
+ }
342
+ /** The entry file that actually exists on disk for a document, or null. */
343
+ function resolveDocEntry(docsRoot, docId) {
344
+ if (!DOC_ID_RE.test(docId)) return null;
345
+ const docDir = path.resolve(docsRoot, docId);
346
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
347
+ for (const name of ENTRY_NAMES$1) {
348
+ const candidate = path.join(docDir, name);
349
+ if (existsSync(candidate)) return candidate;
350
+ }
351
+ return null;
352
+ }
353
+ //#endregion
354
+ //#region src/editing/doc-ops.ts
355
+ function parseSource$2(source) {
356
+ try {
357
+ return parse(source, {
358
+ sourceType: "module",
359
+ plugins: ["typescript", "jsx"],
360
+ errorRecovery: true
361
+ });
362
+ } catch {
363
+ return null;
364
+ }
365
+ }
366
+ function programBody$1(ast) {
367
+ return ast.program?.body ?? [];
368
+ }
369
+ function metaObjectOf(node) {
370
+ if (node.type !== "ExportNamedDeclaration") return null;
371
+ const decl = node.declaration;
372
+ if (decl?.type !== "VariableDeclaration") return null;
373
+ const declarations = decl.declarations ?? [];
374
+ for (const d of declarations) {
375
+ const id = d.id;
376
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
377
+ let init = d.init;
378
+ if (!init) return null;
379
+ if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
380
+ const expr = init.expression;
381
+ if (expr) init = expr;
382
+ }
383
+ return init.type === "ObjectExpression" ? init : null;
384
+ }
385
+ return null;
386
+ }
387
+ function findMetaObject(ast) {
388
+ for (const node of programBody$1(ast)) {
389
+ const object = metaObjectOf(node);
390
+ if (object) return object;
391
+ }
392
+ return null;
393
+ }
394
+ function jsString$1(value) {
395
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
396
+ }
397
+ function validateDocTitle(v) {
398
+ if (typeof v !== "string") return null;
399
+ const trimmed = v.trim();
400
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
401
+ return trimmed;
402
+ }
403
+ /**
404
+ * Rewrites `meta.title` in place, adding the property when the meta object
405
+ * exists without one. Returns null when there is no meta object to edit —
406
+ * the caller reports that rather than inventing an export.
407
+ */
408
+ function setMetaTitle(source, title) {
409
+ const ast = parseSource$2(source);
410
+ if (!ast) return null;
411
+ const object = findMetaObject(ast);
412
+ if (!object) return null;
413
+ const properties = object.properties ?? [];
414
+ for (const prop of properties) {
415
+ if (prop.type !== "ObjectProperty") continue;
416
+ const p = prop;
417
+ if (p.computed) continue;
418
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
419
+ return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
420
+ }
421
+ const open = object.start + 1;
422
+ const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
423
+ return source.slice(0, open) + inserted + source.slice(open);
424
+ }
425
+ function readMetaTitle(source) {
426
+ const ast = parseSource$2(source);
427
+ if (!ast) return null;
428
+ const object = findMetaObject(ast);
429
+ if (!object) return null;
430
+ const properties = object.properties ?? [];
431
+ for (const prop of properties) {
432
+ if (prop.type !== "ObjectProperty") continue;
433
+ const p = prop;
434
+ if (p.computed) continue;
435
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
436
+ if (p.value.type !== "StringLiteral") return null;
437
+ return typeof p.value.value === "string" ? p.value.value : null;
438
+ }
439
+ return null;
440
+ }
441
+ /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
442
+ function nextCopyId(baseId, taken) {
443
+ const stem = baseId.replace(/-copy(-\d+)?$/, "");
444
+ let candidate = `${stem}-copy`;
445
+ let n = 2;
446
+ while (taken.has(candidate)) {
447
+ candidate = `${stem}-copy-${n}`;
448
+ n++;
449
+ }
450
+ return candidate;
451
+ }
452
+ function copyTitle(title) {
453
+ return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
454
+ }
455
+ //#endregion
456
+ //#region src/files/folders.ts
457
+ const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
458
+ const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
459
+ function emptyManifest() {
460
+ return {
461
+ folders: [],
462
+ assignments: {}
463
+ };
464
+ }
465
+ async function readManifest(file) {
466
+ try {
467
+ const raw = await fs.readFile(file, "utf8");
468
+ const parsed = JSON.parse(raw);
469
+ return {
470
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
471
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
472
+ };
473
+ } catch (err) {
474
+ if (err.code === "ENOENT") return emptyManifest();
475
+ throw err;
476
+ }
477
+ }
478
+ async function writeManifest(file, manifest) {
479
+ await fs.mkdir(path.dirname(file), { recursive: true });
480
+ await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
481
+ }
482
+ function newFolderId() {
483
+ return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
484
+ }
485
+ function validateName(v) {
486
+ if (typeof v !== "string") return null;
487
+ const trimmed = v.trim();
488
+ if (trimmed.length < 1 || trimmed.length > 40) return null;
489
+ return trimmed;
490
+ }
491
+ function validateReorder(v, current) {
492
+ if (!Array.isArray(v) || v.length !== current.length) return null;
493
+ const known = new Set(current.map((f) => f.id));
494
+ const seen = /* @__PURE__ */ new Set();
495
+ const out = [];
496
+ for (const id of v) {
497
+ if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
498
+ if (!known.has(id) || seen.has(id)) return null;
499
+ seen.add(id);
500
+ out.push(id);
501
+ }
502
+ return out;
503
+ }
504
+ function validateIcon(v) {
505
+ if (!v || typeof v !== "object") return null;
506
+ const icon = v;
507
+ if (icon.type === "emoji") {
508
+ if (typeof icon.value !== "string") return null;
509
+ if (icon.value.length < 1 || icon.value.length > 8) return null;
510
+ return {
511
+ type: "emoji",
512
+ value: icon.value
513
+ };
514
+ }
515
+ if (icon.type === "color") {
516
+ if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
517
+ return {
518
+ type: "color",
519
+ value: icon.value
520
+ };
521
+ }
522
+ return null;
523
+ }
524
+ //#endregion
525
+ //#region src/ops/documents.ts
526
+ /**
527
+ * Operations shared by the dev API and the MCP server. Everything here takes an
528
+ * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
529
+ * and a browser calling `/__docs` end up in exactly the same code.
530
+ */
531
+ var OpsError = class extends Error {
532
+ status;
533
+ constructor(status, message) {
534
+ super(message);
535
+ this.status = status;
536
+ this.name = "OpsError";
537
+ }
538
+ };
539
+ const ENTRY_NAMES = [
540
+ "index.tsx",
541
+ "index.jsx",
542
+ "index.ts",
543
+ "index.js"
544
+ ];
545
+ function docDir(ctx, docId) {
546
+ if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
547
+ const dir = path.resolve(ctx.docsRoot, docId);
548
+ if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
549
+ return dir;
550
+ }
551
+ function resolveEntry(ctx, docId) {
552
+ const dir = docDir(ctx, docId);
553
+ for (const name of ENTRY_NAMES) {
554
+ const file = path.join(dir, name);
555
+ if (existsSync(file)) return file;
556
+ }
557
+ return null;
558
+ }
559
+ async function listDocIds$1(ctx) {
560
+ try {
561
+ return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
562
+ } catch {
563
+ return [];
564
+ }
565
+ }
566
+ /** Reads what the doc declares without executing it — a regex over `export const meta`. */
567
+ function readMetaField(source, field) {
568
+ const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
569
+ return source.slice(source.indexOf("export const meta")).match(re)?.[2];
570
+ }
571
+ async function listDocuments(ctx) {
572
+ const ids = await listDocIds$1(ctx);
573
+ const manifest = await readManifest(ctx.manifestPath);
574
+ const out = [];
575
+ for (const id of ids) {
576
+ const entry = resolveEntry(ctx, id);
577
+ const source = entry ? await fs.readFile(entry, "utf8") : "";
578
+ out.push({
579
+ id,
580
+ title: source ? readMetaTitle(source) : null,
581
+ subtitle: source ? readMetaField(source, "subtitle") : void 0,
582
+ theme: source ? readMetaField(source, "theme") : void 0,
583
+ createdAt: source ? readMetaField(source, "createdAt") : void 0,
584
+ folder: manifest.assignments[id],
585
+ entry: entry ? path.relative(ctx.userCwd, entry) : null
586
+ });
587
+ }
588
+ return out;
589
+ }
590
+ async function readDocument(ctx, docId) {
591
+ const entry = resolveEntry(ctx, docId);
592
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
593
+ return {
594
+ id: docId,
595
+ entry: path.relative(ctx.userCwd, entry),
596
+ source: await fs.readFile(entry, "utf8")
597
+ };
598
+ }
599
+ async function createDocument(ctx, docId, source) {
600
+ const dir = docDir(ctx, docId);
601
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
602
+ await fs.mkdir(dir, { recursive: true });
603
+ const entry = path.join(dir, "index.tsx");
604
+ await fs.writeFile(entry, source, "utf8");
605
+ return {
606
+ id: docId,
607
+ entry: path.relative(ctx.userCwd, entry)
608
+ };
609
+ }
610
+ /**
611
+ * Whole-file overwrite. `expected` is the source the caller believes is on
612
+ * disk; passing it turns a blind overwrite into a conflict check, which is what
613
+ * keeps two agents (or an agent and a person) from clobbering each other.
614
+ */
615
+ async function writeDocument(ctx, docId, source, expected) {
616
+ const entry = resolveEntry(ctx, docId);
617
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
618
+ if (expected !== void 0) {
619
+ if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
620
+ }
621
+ await fs.writeFile(entry, source, "utf8");
622
+ return {
623
+ id: docId,
624
+ entry: path.relative(ctx.userCwd, entry)
625
+ };
626
+ }
627
+ async function renameDocument(ctx, docId, rawTitle) {
628
+ const title = validateDocTitle(rawTitle);
629
+ if (!title) throw new OpsError(400, "invalid title");
630
+ const entry = resolveEntry(ctx, docId);
631
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
632
+ const source = await fs.readFile(entry, "utf8");
633
+ const next = setMetaTitle(source, title);
634
+ if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
635
+ if (next !== source) await fs.writeFile(entry, next, "utf8");
636
+ return {
637
+ id: docId,
638
+ title
639
+ };
640
+ }
641
+ async function duplicateDocument(ctx, docId, newId) {
642
+ const dir = docDir(ctx, docId);
643
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
644
+ const taken = new Set(await listDocIds$1(ctx));
645
+ let targetId;
646
+ if (newId) {
647
+ if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
648
+ if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
649
+ targetId = newId;
650
+ } else targetId = nextCopyId(docId, taken);
651
+ await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
652
+ const entry = resolveEntry(ctx, targetId);
653
+ if (entry) {
654
+ const source = await fs.readFile(entry, "utf8");
655
+ const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
656
+ if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
657
+ }
658
+ const manifest = await readManifest(ctx.manifestPath);
659
+ const folderId = manifest.assignments[docId];
660
+ if (folderId) {
661
+ manifest.assignments[targetId] = folderId;
662
+ await writeManifest(ctx.manifestPath, manifest);
663
+ }
664
+ return { id: targetId };
665
+ }
666
+ async function deleteDocument(ctx, docId) {
667
+ const dir = docDir(ctx, docId);
668
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
669
+ await fs.rm(dir, {
670
+ recursive: true,
671
+ force: true
672
+ });
673
+ const manifest = await readManifest(ctx.manifestPath);
674
+ if (manifest.assignments[docId]) {
675
+ delete manifest.assignments[docId];
676
+ await writeManifest(ctx.manifestPath, manifest);
677
+ }
678
+ }
679
+ //#endregion
680
+ //#region src/files/assets.ts
681
+ const GLOBAL_SCOPE = "@global";
682
+ const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
683
+ const MIME_BY_EXT = {
684
+ png: "image/png",
685
+ jpg: "image/jpeg",
686
+ jpeg: "image/jpeg",
687
+ gif: "image/gif",
688
+ svg: "image/svg+xml",
689
+ webp: "image/webp",
690
+ avif: "image/avif",
691
+ ico: "image/x-icon",
692
+ pdf: "application/pdf",
693
+ woff: "font/woff",
694
+ woff2: "font/woff2",
695
+ ttf: "font/ttf",
696
+ otf: "font/otf",
697
+ csv: "text/csv; charset=utf-8",
698
+ json: "application/json",
699
+ txt: "text/plain; charset=utf-8",
700
+ md: "text/markdown; charset=utf-8"
701
+ };
702
+ function mimeForFilename(name) {
703
+ const dot = name.lastIndexOf(".");
704
+ if (dot < 0) return "application/octet-stream";
705
+ return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
706
+ }
707
+ function assetCreatedAt(birthtimeMs, mtimeMs) {
708
+ return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
709
+ }
710
+ function validateAssetName(v) {
711
+ if (typeof v !== "string") return null;
712
+ const trimmed = v.trim();
713
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
714
+ if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
715
+ if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
716
+ if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
717
+ const dot = trimmed.lastIndexOf(".");
718
+ if (dot <= 0 || dot === trimmed.length - 1) return null;
719
+ return trimmed;
720
+ }
721
+ function resolveAssetsDir(docsRoot, docId) {
722
+ if (!DOC_ID_RE.test(docId)) return null;
723
+ const docDir = path.resolve(docsRoot, docId);
724
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
725
+ const assetsDir = path.resolve(docDir, "assets");
726
+ if (assetsDir !== path.join(docDir, "assets")) return null;
727
+ return assetsDir;
728
+ }
729
+ function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
730
+ if (scope === "@global") return globalAssetsRoot;
731
+ return resolveAssetsDir(docsRoot, scope);
732
+ }
733
+ function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
734
+ if (!validateAssetName(filename)) return null;
735
+ const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
736
+ if (!dir) return null;
737
+ const file = path.resolve(dir, filename);
738
+ if (!file.startsWith(dir + path.sep)) return null;
739
+ return file;
740
+ }
741
+ /** How a document imports an asset — the string we look for when counting usages. */
742
+ function assetImportPath(scope, filename) {
743
+ return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
744
+ }
745
+ function escapeRegExp(value) {
746
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
747
+ }
748
+ /**
749
+ * Counts references to an asset in a document's source. Matches the quoted path
750
+ * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
751
+ * which is every form the authoring skill sanctions.
752
+ */
753
+ function countAssetUsages(source, importPath) {
754
+ const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
755
+ return source.match(quoted)?.length ?? 0;
756
+ }
757
+ function findReferencedAssets(source, importPaths) {
758
+ return importPaths.filter((p) => countAssetUsages(source, p) > 0);
759
+ }
760
+ //#endregion
761
+ //#region src/http/request-guard.ts
762
+ function firstHeaderValue(value) {
763
+ if (Array.isArray(value)) return value[0] ?? null;
764
+ return value ?? null;
765
+ }
766
+ function headerValue(req, name) {
767
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
768
+ }
769
+ function firstCommaToken(value) {
770
+ if (!value) return null;
771
+ const [first] = value.split(",", 1);
772
+ return first?.trim() || null;
773
+ }
774
+ function requestProto(req) {
775
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
776
+ if (forwarded === "http" || forwarded === "https") return forwarded;
777
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
778
+ }
779
+ function normalizedOrigin(origin) {
780
+ try {
781
+ const url = new URL(origin);
782
+ return `${url.protocol}//${url.host}`.toLowerCase();
783
+ } catch {
784
+ return null;
785
+ }
786
+ }
787
+ /**
788
+ * The dev server writes to the user's filesystem, so every mutating endpoint is
789
+ * guarded against a page on another origin driving it through the browser.
790
+ */
791
+ function validateMutationRequest(req, opts = {}) {
792
+ if (opts.requireJsonBody) {
793
+ if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
794
+ ok: false,
795
+ status: 415,
796
+ error: "content-type must be application/json"
797
+ };
798
+ }
799
+ if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
800
+ ok: false,
801
+ status: 403,
802
+ error: "cross-site request blocked"
803
+ };
804
+ const originRaw = headerValue(req, "origin");
805
+ if (!originRaw) return { ok: true };
806
+ if (originRaw.toLowerCase() === "null") return {
807
+ ok: false,
808
+ status: 403,
809
+ error: "opaque origin is not allowed"
810
+ };
811
+ const actualOrigin = normalizedOrigin(originRaw);
812
+ if (!actualOrigin) return {
813
+ ok: false,
814
+ status: 403,
815
+ error: "invalid origin header"
816
+ };
817
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
818
+ if (!host) return {
819
+ ok: false,
820
+ status: 400,
821
+ error: "missing host header"
822
+ };
823
+ if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
824
+ ok: false,
825
+ status: 403,
826
+ error: "origin mismatch"
827
+ };
828
+ return { ok: true };
829
+ }
830
+ //#endregion
831
+ //#region src/vite/routes/assets.ts
832
+ async function listDocIds(docsRoot) {
833
+ try {
834
+ return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
835
+ } catch {
836
+ return [];
837
+ }
838
+ }
839
+ async function readDocSource(docsRoot, docId) {
840
+ const entry = resolveDocEntry(docsRoot, docId);
841
+ if (!entry) return null;
842
+ try {
843
+ return await fs.readFile(entry, "utf8");
844
+ } catch {
845
+ return null;
846
+ }
847
+ }
848
+ function registerAssetRoutes(server, ctx) {
849
+ server.middlewares.use("/__assets", async (req, res, next) => {
850
+ const url = new URL(req.url ?? "/", "http://local");
851
+ const method = req.method ?? "GET";
852
+ try {
853
+ const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
854
+ const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
855
+ const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
856
+ if (usagesMatch && method === "GET") {
857
+ const scope = decodeURIComponent(usagesMatch[1]);
858
+ const filename = decodeURIComponent(usagesMatch[2]);
859
+ if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
860
+ const isGlobal = scope === GLOBAL_SCOPE;
861
+ if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
862
+ const importPath = assetImportPath(scope, filename);
863
+ const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
864
+ const usages = [];
865
+ let totalCount = 0;
866
+ for (const docId of docIds) {
867
+ const source = await readDocSource(ctx.docsRoot, docId);
868
+ if (source === null) continue;
869
+ const count = countAssetUsages(source, importPath);
870
+ if (count > 0) {
871
+ usages.push({
872
+ docId,
873
+ count
874
+ });
875
+ totalCount += count;
876
+ }
877
+ }
878
+ return json(res, 200, {
879
+ usages,
880
+ totalCount
881
+ });
882
+ }
883
+ if (listMatch && method === "GET") {
884
+ const scope = decodeURIComponent(listMatch[1]);
885
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
886
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
887
+ let entries;
888
+ try {
889
+ entries = await fs.readdir(scopedDir);
890
+ } catch (err) {
891
+ if (err.code === "ENOENT") return json(res, 200, { assets: [] });
892
+ throw err;
893
+ }
894
+ const assets = [];
895
+ for (const name of entries) {
896
+ if (!validateAssetName(name)) continue;
897
+ const stat = await fs.stat(path.join(scopedDir, name));
898
+ if (!stat.isFile()) continue;
899
+ assets.push({
900
+ name,
901
+ size: stat.size,
902
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
903
+ mtime: stat.mtimeMs,
904
+ mime: mimeForFilename(name),
905
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
906
+ importPath: assetImportPath(scope, name),
907
+ unused: true
908
+ });
909
+ }
910
+ assets.sort((a, b) => a.name.localeCompare(b.name));
911
+ if (assets.length > 0) {
912
+ const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
913
+ const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
914
+ const paths = assets.map((a) => a.importPath);
915
+ for (const docId of scanIds) {
916
+ const source = await readDocSource(ctx.docsRoot, docId);
917
+ if (source === null) continue;
918
+ for (const p of findReferencedAssets(source, paths)) {
919
+ const asset = pathToAsset.get(p);
920
+ if (asset) asset.unused = false;
921
+ }
922
+ }
923
+ }
924
+ return json(res, 200, { assets });
925
+ }
926
+ if (fileMatch) {
927
+ const scope = decodeURIComponent(fileMatch[1]);
928
+ const filename = decodeURIComponent(fileMatch[2]);
929
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
930
+ if (!file) return json(res, 400, { error: "invalid path" });
931
+ if (method === "GET") try {
932
+ const buf = await fs.readFile(file);
933
+ res.statusCode = 200;
934
+ res.setHeader("content-type", mimeForFilename(filename));
935
+ res.setHeader("cache-control", "no-store");
936
+ res.end(buf);
937
+ return;
938
+ } catch (err) {
939
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
940
+ throw err;
941
+ }
942
+ if (method === "POST") {
943
+ const requestCheck = validateMutationRequest(req);
944
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
945
+ const overwrite = url.searchParams.get("overwrite") === "1";
946
+ const lenHeader = req.headers["content-length"];
947
+ const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
948
+ if (Number.isFinite(len) && len > 26214400) return json(res, 413, { error: "file too large" });
949
+ if (!overwrite) try {
950
+ await fs.access(file);
951
+ return json(res, 409, { error: "asset exists" });
952
+ } catch {}
953
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
954
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
955
+ await fs.mkdir(scopedDir, { recursive: true });
956
+ const chunks = [];
957
+ let total = 0;
958
+ let oversized = false;
959
+ await new Promise((resolve, reject) => {
960
+ req.on("data", (c) => {
961
+ total += c.length;
962
+ if (total > 26214400) {
963
+ oversized = true;
964
+ req.destroy();
965
+ return;
966
+ }
967
+ chunks.push(c);
968
+ });
969
+ req.on("end", () => resolve());
970
+ req.on("error", reject);
971
+ });
972
+ if (oversized) return json(res, 413, { error: "file too large" });
973
+ await fs.writeFile(file, Buffer.concat(chunks));
974
+ const stat = await fs.stat(file);
975
+ return json(res, 200, {
976
+ ok: true,
977
+ name: filename,
978
+ size: stat.size,
979
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
980
+ mtime: stat.mtimeMs,
981
+ mime: mimeForFilename(filename),
982
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
983
+ importPath: assetImportPath(scope, filename)
984
+ });
985
+ }
986
+ if (method === "PATCH") {
987
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
988
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
989
+ const target = validateAssetName((await readBody(req)).name);
990
+ if (!target) return json(res, 400, { error: "invalid name" });
991
+ if (target === filename) return json(res, 200, {
992
+ ok: true,
993
+ name: filename
994
+ });
995
+ const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
996
+ if (!dest) return json(res, 400, { error: "invalid name" });
997
+ try {
998
+ await fs.access(dest);
999
+ return json(res, 409, { error: "target exists" });
1000
+ } catch {}
1001
+ try {
1002
+ await fs.rename(file, dest);
1003
+ } catch (err) {
1004
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1005
+ throw err;
1006
+ }
1007
+ return json(res, 200, {
1008
+ ok: true,
1009
+ name: target
1010
+ });
1011
+ }
1012
+ if (method === "DELETE") {
1013
+ const requestCheck = validateMutationRequest(req);
1014
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1015
+ try {
1016
+ await fs.unlink(file);
1017
+ } catch (err) {
1018
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1019
+ throw err;
1020
+ }
1021
+ return json(res, 200, { ok: true });
1022
+ }
1023
+ }
1024
+ return next();
1025
+ } catch (err) {
1026
+ json(res, 500, { error: String(err.message ?? err) });
1027
+ }
1028
+ });
1029
+ }
1030
+ //#endregion
1031
+ //#region src/vite/routes/docs.ts
1032
+ function registerDocRoutes(server, ctx) {
1033
+ server.middlewares.use("/__docs", async (req, res, next) => {
1034
+ const url = new URL(req.url ?? "/", "http://local");
1035
+ const method = req.method ?? "GET";
1036
+ try {
1037
+ const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
1038
+ const idMatch = url.pathname.match(/^\/([^/]+)$/);
1039
+ if (duplicateMatch && method === "POST") {
1040
+ const requestCheck = validateMutationRequest(req);
1041
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1042
+ const docId = decodeURIComponent(duplicateMatch[1]);
1043
+ const body = await readBody(req).catch(() => ({}));
1044
+ return json(res, 200, {
1045
+ ok: true,
1046
+ docId: (await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0)).id
1047
+ });
1048
+ }
1049
+ if (idMatch) {
1050
+ const docId = decodeURIComponent(idMatch[1]);
1051
+ if (method === "PATCH") {
1052
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1053
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1054
+ return json(res, 200, {
1055
+ ok: true,
1056
+ title: (await renameDocument(ctx, docId, (await readBody(req)).title)).title
1057
+ });
1058
+ }
1059
+ if (method === "DELETE") {
1060
+ const requestCheck = validateMutationRequest(req);
1061
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1062
+ await deleteDocument(ctx, docId);
1063
+ return json(res, 200, { ok: true });
1064
+ }
1065
+ }
1066
+ next();
1067
+ } catch (err) {
1068
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1069
+ json(res, 500, { error: String(err.message ?? err) });
1070
+ }
1071
+ });
1072
+ }
1073
+ //#endregion
1074
+ //#region src/editing/babel-walk.ts
1075
+ function parseSource$1(code) {
1076
+ try {
1077
+ return parse(code, {
1078
+ sourceType: "module",
1079
+ plugins: ["typescript", "jsx"],
1080
+ errorRecovery: true
1081
+ });
1082
+ } catch {
1083
+ return null;
1084
+ }
1085
+ }
1086
+ function isNode(value) {
1087
+ return typeof value === "object" && value !== null && typeof value.type === "string";
1088
+ }
1089
+ /** Depth-first walk over every node; the visitor decides what it cares about. */
1090
+ function walkAst(node, visit) {
1091
+ if (Array.isArray(node)) {
1092
+ for (const child of node) walkAst(child, visit);
1093
+ return;
1094
+ }
1095
+ if (!isNode(node)) return;
1096
+ visit(node);
1097
+ for (const key of Object.keys(node)) {
1098
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
1099
+ walkAst(node[key], visit);
1100
+ }
1101
+ }
1102
+ function walkJsx(ast, visit) {
1103
+ walkAst(ast, (node) => {
1104
+ if (node.type === "JSXElement") visit(node);
1105
+ });
1106
+ }
1107
+ /**
1108
+ * The JSX element whose opening tag starts at this source position.
1109
+ *
1110
+ * The match is exact on both line and column. Anything looser can resolve to a
1111
+ * different element on the same line, and this location decides where an edit
1112
+ * gets written — a near miss silently rewrites the wrong text.
1113
+ */
1114
+ function findJsxAt(ast, line, column) {
1115
+ let found = null;
1116
+ walkJsx(ast, (node) => {
1117
+ if (found) return;
1118
+ const start = node.loc?.start;
1119
+ if (start && start.line === line && start.column === column) found = node;
1120
+ });
1121
+ return found;
1122
+ }
1123
+ /**
1124
+ * Every JSX element that starts on a line, nearest column first.
1125
+ *
1126
+ * Columns cannot be trusted for locations derived from React's `_debugSource`:
1127
+ * injecting the loc attribute shifts the columns of anything later on the same
1128
+ * line, so the offset differs per element. The line survives that, so callers
1129
+ * scan the line and pick by content instead.
1130
+ */
1131
+ function findJsxOnLine(ast, line, column) {
1132
+ const hits = [];
1133
+ walkJsx(ast, (node) => {
1134
+ const start = node.loc?.start;
1135
+ if (!start || start.line !== line) return;
1136
+ hits.push({
1137
+ node,
1138
+ distance: Math.abs(start.column - column)
1139
+ });
1140
+ });
1141
+ return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
1142
+ }
1143
+ //#endregion
1144
+ //#region src/editing/comments.ts
1145
+ const MARKER_RE = /\{\/\*\s*@doc-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
1146
+ function b64urlEncode(value) {
1147
+ return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1148
+ }
1149
+ function b64urlDecode(value) {
1150
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
1151
+ return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
1152
+ }
1153
+ function parseMarkers(source) {
1154
+ const comments = [];
1155
+ source.split("\n").forEach((line, index) => {
1156
+ const match = MARKER_RE.exec(line);
1157
+ if (!match) return;
1158
+ const [, id, ts, payload] = match;
1159
+ try {
1160
+ const decoded = JSON.parse(b64urlDecode(payload));
1161
+ comments.push({
1162
+ id,
1163
+ line: index + 1,
1164
+ ts,
1165
+ note: decoded.note,
1166
+ hint: decoded.hint
1167
+ });
1168
+ } catch {}
1169
+ });
1170
+ return comments;
1171
+ }
1172
+ function newCommentId() {
1173
+ return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1174
+ }
1175
+ function markerFor(id, ts, note, hint) {
1176
+ return `{/* @doc-comment id="${id}" ts="${ts}" text="${b64urlEncode(JSON.stringify(hint ? {
1177
+ note,
1178
+ hint
1179
+ } : { note }))}" */}`;
1180
+ }
1181
+ function markerPattern(id) {
1182
+ return `\\{\\/\\*\\s*@doc-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text="[A-Za-z0-9_\\-]+={0,2}"\\s*\\*\\/\\}`;
1183
+ }
1184
+ /**
1185
+ * Removes a marker and the whitespace the insertion added — whichever side it
1186
+ * landed on — so deleting a comment restores the file byte for byte.
1187
+ */
1188
+ function removeMarker(source, id) {
1189
+ const pattern = markerPattern(id);
1190
+ for (const re of [
1191
+ new RegExp(`[ \\t]*${pattern}\\n`),
1192
+ new RegExp(`\\n[ \\t]*${pattern}`),
1193
+ new RegExp(pattern)
1194
+ ]) if (re.test(source)) return source.replace(re, "");
1195
+ return null;
1196
+ }
1197
+ function indentOfLine(source, offset) {
1198
+ const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
1199
+ return /^[ \t]*/.exec(source.slice(lineStart, offset))?.[0] ?? "";
1200
+ }
1201
+ /**
1202
+ * Splices the marker in as the **first child** of the target element. A
1203
+ * JSX-comment token outside a JSX child position parses as an empty object
1204
+ * literal and breaks the surrounding expression, so this never puts one before
1205
+ * an element.
1206
+ */
1207
+ function insertMarker(source, target, note, hint) {
1208
+ const ast = parseSource$1(source);
1209
+ if (!ast) return null;
1210
+ const element = findJsxAt(ast, target.line, target.column);
1211
+ if (!element) return null;
1212
+ const opening = element.openingElement;
1213
+ if (!opening) return null;
1214
+ if (opening.selfClosing === true) return null;
1215
+ const offset = opening.end;
1216
+ const id = newCommentId();
1217
+ const marker = markerFor(id, (/* @__PURE__ */ new Date()).toISOString(), note, hint);
1218
+ const indent = indentOfLine(source, element.start ?? offset);
1219
+ return {
1220
+ source: `${source.slice(0, offset)}\n${indent} ${marker}${source.slice(offset)}`,
1221
+ id
1222
+ };
1223
+ }
1224
+ //#endregion
1225
+ //#region src/editing/edit-ops.ts
1226
+ /** JSX text is written literally; only these characters have to be escaped. */
1227
+ function escapeJsxText(text) {
1228
+ return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
1229
+ }
1230
+ function normalizeText(value) {
1231
+ return value.replace(/\s+/g, " ").trim();
1232
+ }
1233
+ function jsxChildren(element) {
1234
+ return element.children ?? [];
1235
+ }
1236
+ function labelOf(node) {
1237
+ if (node.type === "JSXExpressionContainer") return "{…}";
1238
+ if (node.type === "JSXElement") return `<${(node.openingElement?.name)?.name ?? "element"}>`;
1239
+ return "…";
1240
+ }
1241
+ /** Text children with content, in document order. */
1242
+ function textNodes(element) {
1243
+ return jsxChildren(element).filter((child) => child.type === "JSXText" && child.value.trim() !== "");
1244
+ }
1245
+ function partsOf(element) {
1246
+ const parts = [];
1247
+ let index = 0;
1248
+ for (const child of jsxChildren(element)) {
1249
+ if (child.type === "JSXText") {
1250
+ const value = child.value;
1251
+ if (value.trim() === "") continue;
1252
+ parts.push({
1253
+ kind: "text",
1254
+ index: index++,
1255
+ value: value.trim()
1256
+ });
1257
+ continue;
1258
+ }
1259
+ parts.push({
1260
+ kind: "markup",
1261
+ label: labelOf(child)
1262
+ });
1263
+ }
1264
+ return parts;
1265
+ }
1266
+ function describe(element) {
1267
+ const parts = partsOf(element);
1268
+ const texts = parts.filter((part) => part.kind === "text");
1269
+ if (texts.length === 0) return {
1270
+ editable: false,
1271
+ text: "",
1272
+ parts,
1273
+ reason: parts.some((part) => part.kind === "markup" && part.label === "{…}") ? "text is produced by code — edit whatever feeds it" : "element has no text of its own"
1274
+ };
1275
+ return {
1276
+ editable: true,
1277
+ text: texts.map((part) => part.value).join(" "),
1278
+ parts
1279
+ };
1280
+ }
1281
+ /**
1282
+ * Picks the element an inspector click meant.
1283
+ *
1284
+ * Coordinates alone are not enough: fallback candidates come from React's
1285
+ * `_debugSource`, whose columns drift once the loc-tag transform has widened
1286
+ * the line. The rendered text the user is looking at is the tiebreaker — an
1287
+ * element only wins if its source text is part of what is on screen.
1288
+ */
1289
+ function resolveTextTarget(source, candidates, expected) {
1290
+ const ast = parseSource$1(source);
1291
+ if (!ast) return null;
1292
+ const shown = expected ? normalizeText(expected) : null;
1293
+ const matches = (info) => {
1294
+ if (!shown) return true;
1295
+ const runs = info.parts.filter((part) => part.kind === "text");
1296
+ if (runs.length === 0) return false;
1297
+ return runs.every((part) => part.kind === "text" && shown.includes(normalizeText(part.value)));
1298
+ };
1299
+ for (const candidate of candidates) {
1300
+ const exact = findJsxAt(ast, candidate.line, candidate.column);
1301
+ if (exact) {
1302
+ const info = describe(exact);
1303
+ if (info.editable && matches(info)) return {
1304
+ ...info,
1305
+ ...candidate
1306
+ };
1307
+ }
1308
+ if (!shown) continue;
1309
+ for (const node of findJsxOnLine(ast, candidate.line, candidate.column)) {
1310
+ const info = describe(node);
1311
+ const start = node.loc?.start;
1312
+ if (!info.editable || !matches(info) || !start) continue;
1313
+ return {
1314
+ ...info,
1315
+ line: start.line,
1316
+ column: start.column
1317
+ };
1318
+ }
1319
+ }
1320
+ const first = candidates[0];
1321
+ if (!first) return null;
1322
+ const clicked = findJsxAt(ast, first.line, first.column);
1323
+ return clicked ? {
1324
+ ...describe(clicked),
1325
+ ...first
1326
+ } : null;
1327
+ }
1328
+ /**
1329
+ * Replaces one text run of an element, leaving its markup and every other run
1330
+ * untouched. `expected` is the text the caller believes is there; a mismatch
1331
+ * means the source moved under us and the write is refused.
1332
+ */
1333
+ function replaceTextAt(source, target, text, opts = {}) {
1334
+ const ast = parseSource$1(source);
1335
+ if (!ast) return {
1336
+ ok: false,
1337
+ status: 422,
1338
+ error: "could not parse document source"
1339
+ };
1340
+ const element = findJsxAt(ast, target.line, target.column);
1341
+ if (!element) return {
1342
+ ok: false,
1343
+ status: 404,
1344
+ error: "no element at that source location"
1345
+ };
1346
+ const nodes = textNodes(element);
1347
+ if (nodes.length === 0) return {
1348
+ ok: false,
1349
+ status: 422,
1350
+ error: "element has no text to replace"
1351
+ };
1352
+ const child = nodes[opts.index ?? 0];
1353
+ if (!child) return {
1354
+ ok: false,
1355
+ status: 404,
1356
+ error: "no such text run in this element"
1357
+ };
1358
+ const raw = child.value;
1359
+ if (opts.expected !== void 0 && normalizeText(raw) !== normalizeText(opts.expected)) return {
1360
+ ok: false,
1361
+ status: 409,
1362
+ error: "source changed since this was opened — reselect it"
1363
+ };
1364
+ const leading = raw.match(/^\s*/)?.[0] ?? "";
1365
+ const trailing = raw.match(/\s*$/)?.[0] ?? "";
1366
+ return {
1367
+ ok: true,
1368
+ source: source.slice(0, child.start) + leading + escapeJsxText(text) + trailing + source.slice(child.end)
1369
+ };
1370
+ }
1371
+ //#endregion
1372
+ //#region src/vite/routes/edit.ts
1373
+ function readLoc(body) {
1374
+ const { docId, line, column } = body;
1375
+ if (typeof docId !== "string") return null;
1376
+ if (typeof line !== "number" || typeof column !== "number") return null;
1377
+ return {
1378
+ docId,
1379
+ line,
1380
+ column
1381
+ };
1382
+ }
1383
+ function registerEditRoutes(server, ctx) {
1384
+ const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
1385
+ server.middlewares.use("/__edit", async (req, res, next) => {
1386
+ const url = new URL(req.url ?? "/", "http://local");
1387
+ const method = req.method ?? "GET";
1388
+ try {
1389
+ if (method === "GET" && url.pathname === "/text") {
1390
+ const docId = url.searchParams.get("docId") ?? "";
1391
+ const entry = entryFor(docId);
1392
+ const locs = (url.searchParams.get("locs") ?? "").split(",").map((pair) => pair.split(":").map(Number)).filter(([line, column]) => Number.isFinite(line) && Number.isFinite(column)).map(([line, column]) => ({
1393
+ line,
1394
+ column
1395
+ }));
1396
+ if (!entry || locs.length === 0) return json(res, 400, { error: "invalid target" });
1397
+ const resolved = resolveTextTarget(await fs.readFile(entry, "utf8"), locs, url.searchParams.get("shown") ?? void 0);
1398
+ if (!resolved) return json(res, 404, { error: "element not found" });
1399
+ return json(res, 200, resolved);
1400
+ }
1401
+ if (method === "PUT" && url.pathname === "/text") {
1402
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1403
+ if (!check.ok) return json(res, check.status, { error: check.error });
1404
+ const body = await readBody(req);
1405
+ const loc = readLoc(body);
1406
+ const text = body.text;
1407
+ if (!loc || typeof text !== "string") return json(res, 400, { error: "invalid payload" });
1408
+ const entry = entryFor(loc.docId);
1409
+ if (!entry) return json(res, 404, { error: "document not found" });
1410
+ const source = await fs.readFile(entry, "utf8");
1411
+ const result = replaceTextAt(source, loc, text, {
1412
+ index: typeof body.index === "number" ? body.index : void 0,
1413
+ expected: typeof body.expected === "string" ? body.expected : void 0
1414
+ });
1415
+ if (!result.ok) return json(res, result.status, { error: result.error });
1416
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
1417
+ return json(res, 200, { ok: true });
1418
+ }
1419
+ if (method === "POST" && url.pathname === "/comment") {
1420
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1421
+ if (!check.ok) return json(res, check.status, { error: check.error });
1422
+ const body = await readBody(req);
1423
+ const loc = readLoc(body);
1424
+ const note = body.note;
1425
+ if (!loc || typeof note !== "string" || note.trim() === "") return json(res, 400, { error: "invalid payload" });
1426
+ const entry = entryFor(loc.docId);
1427
+ if (!entry) return json(res, 404, { error: "document not found" });
1428
+ const inserted = insertMarker(await fs.readFile(entry, "utf8"), loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
1429
+ if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
1430
+ await fs.writeFile(entry, inserted.source, "utf8");
1431
+ return json(res, 200, {
1432
+ ok: true,
1433
+ id: inserted.id
1434
+ });
1435
+ }
1436
+ return next();
1437
+ } catch (err) {
1438
+ json(res, 500, { error: String(err.message ?? err) });
1439
+ }
1440
+ });
1441
+ server.middlewares.use("/__comments", async (req, res, next) => {
1442
+ const url = new URL(req.url ?? "/", "http://local");
1443
+ const method = req.method ?? "GET";
1444
+ const docId = url.searchParams.get("docId") ?? "";
1445
+ const entry = entryFor(docId);
1446
+ try {
1447
+ if (method === "GET") {
1448
+ if (!entry) return json(res, 200, { comments: [] });
1449
+ return json(res, 200, { comments: parseMarkers(await fs.readFile(entry, "utf8")) });
1450
+ }
1451
+ if (method === "DELETE") {
1452
+ const check = validateMutationRequest(req);
1453
+ if (!check.ok) return json(res, check.status, { error: check.error });
1454
+ const id = url.searchParams.get("id") ?? "";
1455
+ if (!entry || !/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
1456
+ const next = removeMarker(await fs.readFile(entry, "utf8"), id);
1457
+ if (next === null) return json(res, 404, { error: "comment not found" });
1458
+ await fs.writeFile(entry, next, "utf8");
1459
+ return json(res, 200, { ok: true });
1460
+ }
1461
+ return next();
1462
+ } catch (err) {
1463
+ json(res, 500, { error: String(err.message ?? err) });
1464
+ }
1465
+ });
1466
+ }
1467
+ //#endregion
1468
+ //#region src/vite/routes/folders.ts
1469
+ function registerFolderRoutes(server, ctx) {
1470
+ server.middlewares.use("/__folders", async (req, res, next) => {
1471
+ const url = new URL(req.url ?? "/", "http://local");
1472
+ const method = req.method ?? "GET";
1473
+ try {
1474
+ if (method === "GET" && url.pathname === "/") return json(res, 200, await readManifest(ctx.manifestPath));
1475
+ if (method === "POST" && url.pathname === "/") {
1476
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1477
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1478
+ const body = await readBody(req);
1479
+ const name = validateName(body.name);
1480
+ if (!name) return json(res, 400, { error: "invalid name" });
1481
+ const icon = validateIcon(body.icon);
1482
+ if (!icon) return json(res, 400, { error: "invalid icon" });
1483
+ const manifest = await readManifest(ctx.manifestPath);
1484
+ const folder = {
1485
+ id: newFolderId(),
1486
+ name,
1487
+ icon
1488
+ };
1489
+ manifest.folders.push(folder);
1490
+ await writeManifest(ctx.manifestPath, manifest);
1491
+ return json(res, 200, folder);
1492
+ }
1493
+ if (method === "PUT" && url.pathname === "/assign") {
1494
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1495
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1496
+ const body = await readBody(req);
1497
+ if (typeof body.docId !== "string" || !DOC_ID_RE.test(body.docId)) return json(res, 400, { error: "invalid docId" });
1498
+ const docId = body.docId;
1499
+ let folderId;
1500
+ if (body.folderId === null) folderId = null;
1501
+ else if (typeof body.folderId === "string" && FOLDER_ID_RE.test(body.folderId)) folderId = body.folderId;
1502
+ else return json(res, 400, { error: "invalid folderId" });
1503
+ const manifest = await readManifest(ctx.manifestPath);
1504
+ if (folderId && !manifest.folders.some((f) => f.id === folderId)) return json(res, 404, { error: "folder not found" });
1505
+ if (folderId === null) delete manifest.assignments[docId];
1506
+ else manifest.assignments[docId] = folderId;
1507
+ await writeManifest(ctx.manifestPath, manifest);
1508
+ return json(res, 200, { ok: true });
1509
+ }
1510
+ if (method === "PUT" && url.pathname === "/reorder") {
1511
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1512
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1513
+ const body = await readBody(req);
1514
+ const manifest = await readManifest(ctx.manifestPath);
1515
+ const ids = validateReorder(body.ids, manifest.folders);
1516
+ if (!ids) return json(res, 400, { error: "invalid ids" });
1517
+ const byId = new Map(manifest.folders.map((f) => [f.id, f]));
1518
+ manifest.folders = ids.map((id) => byId.get(id));
1519
+ await writeManifest(ctx.manifestPath, manifest);
1520
+ return json(res, 200, { ok: true });
1521
+ }
1522
+ const idMatch = url.pathname.match(/^\/([^/]+)$/);
1523
+ if (idMatch) {
1524
+ const id = idMatch[1];
1525
+ if (!FOLDER_ID_RE.test(id)) return json(res, 400, { error: "invalid id" });
1526
+ if (method === "PATCH") {
1527
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1528
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1529
+ const body = await readBody(req);
1530
+ const manifest = await readManifest(ctx.manifestPath);
1531
+ const folder = manifest.folders.find((f) => f.id === id);
1532
+ if (!folder) return json(res, 404, { error: "folder not found" });
1533
+ if (body.name !== void 0) {
1534
+ const name = validateName(body.name);
1535
+ if (!name) return json(res, 400, { error: "invalid name" });
1536
+ folder.name = name;
1537
+ }
1538
+ if (body.icon !== void 0) {
1539
+ const icon = validateIcon(body.icon);
1540
+ if (!icon) return json(res, 400, { error: "invalid icon" });
1541
+ folder.icon = icon;
1542
+ }
1543
+ await writeManifest(ctx.manifestPath, manifest);
1544
+ return json(res, 200, folder);
1545
+ }
1546
+ if (method === "DELETE") {
1547
+ const requestCheck = validateMutationRequest(req);
1548
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1549
+ const manifest = await readManifest(ctx.manifestPath);
1550
+ const before = manifest.folders.length;
1551
+ manifest.folders = manifest.folders.filter((f) => f.id !== id);
1552
+ if (manifest.folders.length === before) return json(res, 404, { error: "folder not found" });
1553
+ for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
1554
+ await writeManifest(ctx.manifestPath, manifest);
1555
+ return json(res, 200, { ok: true });
1556
+ }
1557
+ }
1558
+ next();
1559
+ } catch (err) {
1560
+ json(res, 500, { error: String(err.message ?? err) });
1561
+ }
1562
+ });
1563
+ }
1564
+ //#endregion
1565
+ //#region src/vite/api-plugin.ts
1566
+ function apiPlugin(opts) {
1567
+ return {
1568
+ name: "open-doc:api",
1569
+ apply: "serve",
1570
+ configureServer(server) {
1571
+ const ctx = makeContext(opts);
1572
+ registerAssetRoutes(server, ctx);
1573
+ registerFolderRoutes(server, ctx);
1574
+ registerDocRoutes(server, ctx);
1575
+ registerEditRoutes(server, ctx);
1576
+ }
1577
+ };
1578
+ }
1579
+ //#endregion
1580
+ //#region src/vite/current-plugin.ts
1581
+ const TEXT_SNIPPET_MAX = 120;
1582
+ function parseSelection(raw) {
1583
+ if (raw == null || typeof raw !== "object") return null;
1584
+ const sel = raw;
1585
+ if (typeof sel.line !== "number" || !Number.isFinite(sel.line)) return null;
1586
+ if (typeof sel.column !== "number" || !Number.isFinite(sel.column)) return null;
1587
+ const tagName = typeof sel.tagName === "string" ? sel.tagName.toLowerCase().slice(0, 32) : "unknown";
1588
+ const text = typeof sel.text === "string" ? sel.text.replace(/\s+/g, " ").trim().slice(0, TEXT_SNIPPET_MAX) : "";
1589
+ return {
1590
+ line: Math.max(1, Math.floor(sel.line)),
1591
+ column: Math.max(0, Math.floor(sel.column)),
1592
+ tagName,
1593
+ text
1594
+ };
1595
+ }
1596
+ /**
1597
+ * Writes `node_modules/.open-doc/current.json` whenever the viewer navigates or
1598
+ * the inspector picks an element, so an agent can resolve "this page" without
1599
+ * asking. Dev only — a static build has no cursor to report.
1600
+ */
1601
+ function currentPlugin(opts) {
1602
+ const userCwd = opts.userCwd;
1603
+ const docsDir = opts.docsDir ?? "docs";
1604
+ const outDir = path.join(userCwd, "node_modules", ".open-doc");
1605
+ const outFile = path.join(outDir, "current.json");
1606
+ const tmpFile = `${outFile}.tmp`;
1607
+ let cached = null;
1608
+ return {
1609
+ name: "open-doc:current",
1610
+ apply: "serve",
1611
+ configureServer(server) {
1612
+ server.ws.on("open-doc:current", async (raw) => {
1613
+ const next = cached ? { ...cached } : {
1614
+ docId: "",
1615
+ pageIndex: 0,
1616
+ pageNumber: 1,
1617
+ totalPages: 1,
1618
+ docTitle: "",
1619
+ pagePath: "",
1620
+ selection: null
1621
+ };
1622
+ if (typeof raw?.docId === "string") {
1623
+ if (!DOC_ID_RE.test(raw.docId)) return;
1624
+ const totalPages = typeof raw.totalPages === "number" && Number.isFinite(raw.totalPages) && raw.totalPages > 0 ? Math.floor(raw.totalPages) : 1;
1625
+ const rawIndex = typeof raw.pageIndex === "number" && Number.isFinite(raw.pageIndex) ? Math.floor(raw.pageIndex) : 0;
1626
+ const pageIndex = Math.max(0, Math.min(totalPages - 1, rawIndex));
1627
+ const docTitle = typeof raw.docTitle === "string" ? raw.docTitle : raw.docId;
1628
+ const pagePath = path.join(docsDir, raw.docId, "index.tsx").split(path.sep).join("/");
1629
+ if (cached?.docId !== raw.docId || cached?.pageIndex !== pageIndex) next.selection = null;
1630
+ next.docId = raw.docId;
1631
+ next.pageIndex = pageIndex;
1632
+ next.pageNumber = pageIndex + 1;
1633
+ next.totalPages = totalPages;
1634
+ next.docTitle = docTitle;
1635
+ next.pagePath = pagePath;
1636
+ }
1637
+ if ("selection" in raw) next.selection = parseSelection(raw.selection);
1638
+ if (!next.docId) return;
1639
+ cached = next;
1640
+ const body = {
1641
+ ...next,
1642
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1643
+ };
1644
+ try {
1645
+ await fs.mkdir(outDir, { recursive: true });
1646
+ await fs.writeFile(tmpFile, `${JSON.stringify(body, null, 2)}\n`, "utf8");
1647
+ await fs.rename(tmpFile, outFile);
1648
+ } catch {}
1649
+ });
1650
+ }
1651
+ };
1652
+ }
1653
+ //#endregion
1654
+ //#region src/vite/data-plugin.ts
1655
+ const DATA_RE = /\.(csv|tsv)$/i;
1656
+ /**
1657
+ * Makes `import rows from './data/q3.csv'` an array of objects at build time.
1658
+ *
1659
+ * Fetching data at render time is not an option here: the flow packer measures
1660
+ * the real DOM to decide where pages break, and both exporters serialize what
1661
+ * is on screen. Data that arrives a tick later arrives after the layout is
1662
+ * already decided. Resolving it as a module keeps a table's numbers as
1663
+ * synchronous as the prose around them, in the dev server and in a static build
1664
+ * alike.
1665
+ *
1666
+ * `?raw` and `?url` are left to Vite.
1667
+ */
1668
+ function dataPlugin() {
1669
+ return {
1670
+ name: "open-doc:data",
1671
+ enforce: "pre",
1672
+ async load(id) {
1673
+ const [file, query] = id.split("?");
1674
+ if (query !== void 0) return null;
1675
+ if (!DATA_RE.test(file)) return null;
1676
+ let text;
1677
+ try {
1678
+ text = await fs.readFile(file, "utf8");
1679
+ } catch {
1680
+ return null;
1681
+ }
1682
+ const table = parseDelimited(text, { delimiter: /\.tsv$/i.test(file) ? " " : "," });
1683
+ return [
1684
+ `export const columns = ${JSON.stringify(table.columns)};`,
1685
+ `export const rows = ${JSON.stringify(table.rows)};`,
1686
+ "export default rows;"
1687
+ ].join("\n");
1688
+ }
1689
+ };
1690
+ }
1691
+ //#endregion
1692
+ //#region src/vite/design-plugin.ts
1693
+ function parseSource(source) {
1694
+ try {
1695
+ return parse(source, {
1696
+ sourceType: "module",
1697
+ plugins: ["typescript", "jsx"],
1698
+ errorRecovery: true
1699
+ });
1700
+ } catch {
1701
+ return null;
1702
+ }
1703
+ }
1704
+ function programBody(ast) {
1705
+ return ast.program?.body ?? [];
1706
+ }
1707
+ function designObjectOf(node) {
1708
+ let varDecl = null;
1709
+ if (node.type === "VariableDeclaration") varDecl = node;
1710
+ else if (node.type === "ExportNamedDeclaration") {
1711
+ const decl = node.declaration;
1712
+ if (decl?.type === "VariableDeclaration") varDecl = decl;
1713
+ }
1714
+ if (!varDecl) return null;
1715
+ const declarations = varDecl.declarations ?? [];
1716
+ for (const d of declarations) {
1717
+ const id = d.id;
1718
+ if (id?.type !== "Identifier" || id.name !== "design") continue;
1719
+ const init = d.init;
1720
+ if (!init) return "unsupported";
1721
+ let inner = init;
1722
+ if (inner.type === "TSSatisfiesExpression" || inner.type === "TSAsExpression") {
1723
+ const expr = inner.expression;
1724
+ if (expr) inner = expr;
1725
+ }
1726
+ if (inner.type !== "ObjectExpression") return "unsupported";
1727
+ return {
1728
+ decl: node,
1729
+ object: inner
1730
+ };
1731
+ }
1732
+ return null;
1733
+ }
1734
+ function findDesign(ast) {
1735
+ for (const node of programBody(ast)) {
1736
+ const hit = designObjectOf(node);
1737
+ if (hit === null) continue;
1738
+ if (hit === "unsupported") return null;
1739
+ return {
1740
+ loc: {
1741
+ declStart: hit.decl.start,
1742
+ declEnd: hit.decl.end,
1743
+ objectStart: hit.object.start,
1744
+ objectEnd: hit.object.end
1745
+ },
1746
+ object: hit.object
1747
+ };
1748
+ }
1749
+ return null;
1750
+ }
1751
+ function literalToValue(node) {
1752
+ switch (node.type) {
1753
+ case "StringLiteral": return node.value;
1754
+ case "NumericLiteral": return node.value;
1755
+ case "BooleanLiteral": return node.value;
1756
+ case "NullLiteral": return null;
1757
+ case "UnaryExpression": {
1758
+ const op = node.operator;
1759
+ const arg = node.argument;
1760
+ const v = literalToValue(arg);
1761
+ if (op === "-" && typeof v === "number") return -v;
1762
+ if (op === "+" && typeof v === "number") return v;
1763
+ throw new Error(`unsupported unary operator ${op}`);
1764
+ }
1765
+ case "TemplateLiteral": {
1766
+ const quasis = node.quasis;
1767
+ if (node.expressions.length > 0) throw new Error("template literal has expressions");
1768
+ const value = quasis[0].value;
1769
+ return value.cooked ?? value.raw;
1770
+ }
1771
+ case "ObjectExpression": {
1772
+ const properties = node.properties;
1773
+ const out = {};
1774
+ for (const prop of properties) {
1775
+ if (prop.type !== "ObjectProperty") throw new Error("object has spread or method");
1776
+ const p = prop;
1777
+ if (p.computed) throw new Error("object has computed key");
1778
+ let key;
1779
+ if (p.key.type === "Identifier" && typeof p.key.name === "string") key = p.key.name;
1780
+ else if (p.key.type === "StringLiteral" && typeof p.key.value === "string") key = p.key.value;
1781
+ else throw new Error("unsupported object key");
1782
+ out[key] = literalToValue(p.value);
1783
+ }
1784
+ return out;
1785
+ }
1786
+ default: throw new Error(`unsupported node type ${node.type}`);
1787
+ }
1788
+ }
1789
+ function isPlainObject(v) {
1790
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1791
+ }
1792
+ function mergeDesign(base, patch) {
1793
+ const out = JSON.parse(JSON.stringify(base));
1794
+ const apply = (target, src) => {
1795
+ for (const [k, v] of Object.entries(src)) if (isPlainObject(v) && isPlainObject(target[k])) apply(target[k], v);
1796
+ else target[k] = v;
1797
+ };
1798
+ if (isPlainObject(patch)) apply(out, patch);
1799
+ return out;
1800
+ }
1801
+ function indent(level) {
1802
+ return " ".repeat(level);
1803
+ }
1804
+ function jsString(s) {
1805
+ return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
1806
+ }
1807
+ function isValidIdentifier(name) {
1808
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
1809
+ }
1810
+ function serializeValue(value, level) {
1811
+ if (value === null) return "null";
1812
+ if (typeof value === "string") return jsString(value);
1813
+ if (typeof value === "number") {
1814
+ if (!Number.isFinite(value)) throw new Error("non-finite number");
1815
+ return String(value);
1816
+ }
1817
+ if (typeof value === "boolean") return value ? "true" : "false";
1818
+ if (isPlainObject(value)) {
1819
+ const entries = Object.entries(value);
1820
+ if (entries.length === 0) return "{}";
1821
+ const childIndent = indent(level + 1);
1822
+ return `{\n${entries.map(([k, v]) => {
1823
+ const key = isValidIdentifier(k) ? k : jsString(k);
1824
+ return `${childIndent}${key}: ${serializeValue(v, level + 1)},`;
1825
+ }).join("\n")}\n${indent(level)}}`;
1826
+ }
1827
+ throw new Error(`unsupported value type ${typeof value}`);
1828
+ }
1829
+ function serializeDesign(design) {
1830
+ return serializeValue(design, 0);
1831
+ }
1832
+ function parseDocDesign(source) {
1833
+ const ast = parseSource(source);
1834
+ if (!ast) return {
1835
+ ok: false,
1836
+ exists: true,
1837
+ error: "could not parse document source"
1838
+ };
1839
+ const found = findDesign(ast);
1840
+ if (!found) {
1841
+ if (programBody(ast).some((node) => designObjectOf(node) !== null)) return {
1842
+ ok: false,
1843
+ exists: true,
1844
+ error: "design has an unsupported initializer"
1845
+ };
1846
+ return {
1847
+ ok: false,
1848
+ exists: false
1849
+ };
1850
+ }
1851
+ let value;
1852
+ try {
1853
+ value = literalToValue(found.object);
1854
+ } catch (err) {
1855
+ return {
1856
+ ok: false,
1857
+ exists: true,
1858
+ error: err.message
1859
+ };
1860
+ }
1861
+ return {
1862
+ ok: true,
1863
+ design: mergeDesign(defaultDesign, value),
1864
+ loc: found.loc
1865
+ };
1866
+ }
1867
+ function findImports(ast) {
1868
+ const out = [];
1869
+ for (const node of programBody(ast)) {
1870
+ if (node.type !== "ImportDeclaration") continue;
1871
+ const src = node.source?.value;
1872
+ if (typeof src !== "string") continue;
1873
+ out.push({
1874
+ node,
1875
+ source: src,
1876
+ specifiers: node.specifiers ?? []
1877
+ });
1878
+ }
1879
+ return out;
1880
+ }
1881
+ function ensureDesignSystemImport(source, ast) {
1882
+ const imports = findImports(ast);
1883
+ const coreImport = imports.find((imp) => imp.source === "@open-document/core");
1884
+ if (coreImport) {
1885
+ if (coreImport.specifiers.some((spec) => {
1886
+ if (spec.type !== "ImportSpecifier") return false;
1887
+ return spec.imported?.name === "DesignSystem";
1888
+ })) return source;
1889
+ const node = coreImport.node;
1890
+ const braceClose = source.slice(node.start, node.end).lastIndexOf("}");
1891
+ if (braceClose === -1) return source;
1892
+ const absoluteBrace = node.start + braceClose;
1893
+ const insertText = coreImport.specifiers.length > 0 ? ", type DesignSystem" : "type DesignSystem";
1894
+ return source.slice(0, absoluteBrace) + insertText + source.slice(absoluteBrace);
1895
+ }
1896
+ const stmt = `import type { DesignSystem } from '@open-document/core';\n`;
1897
+ if (imports.length > 0) {
1898
+ const insertAt = imports[imports.length - 1].node.end;
1899
+ const trail = source[insertAt] === "\n" ? "" : "\n";
1900
+ return `${source.slice(0, insertAt)}\n${stmt.slice(0, -1)}${trail}${source.slice(insertAt)}`;
1901
+ }
1902
+ return `${stmt}\n${source}`;
1903
+ }
1904
+ function findInsertionPoint(source, ast) {
1905
+ const imports = findImports(ast);
1906
+ if (imports.length === 0) return 0;
1907
+ let off = imports[imports.length - 1].node.end;
1908
+ while (off < source.length && source[off] !== "\n") off++;
1909
+ if (off < source.length) off++;
1910
+ return off;
1911
+ }
1912
+ function applyDesignWrite(source, next) {
1913
+ let body;
1914
+ try {
1915
+ body = serializeDesign(next);
1916
+ } catch (err) {
1917
+ return {
1918
+ ok: false,
1919
+ status: 422,
1920
+ error: `serialize failed: ${err.message}`
1921
+ };
1922
+ }
1923
+ const ast = parseSource(source);
1924
+ if (!ast) return {
1925
+ ok: false,
1926
+ status: 422,
1927
+ error: "could not parse document source"
1928
+ };
1929
+ const found = findDesign(ast);
1930
+ if (found) return {
1931
+ ok: true,
1932
+ source: source.slice(0, found.loc.objectStart) + body + source.slice(found.loc.objectEnd),
1933
+ created: false
1934
+ };
1935
+ const withImport = ensureDesignSystemImport(source, ast);
1936
+ const ast2 = parseSource(withImport);
1937
+ if (!ast2) return {
1938
+ ok: false,
1939
+ status: 422,
1940
+ error: "failed to re-parse after adding import"
1941
+ };
1942
+ const insertAt = findInsertionPoint(withImport, ast2);
1943
+ const block = `\nexport const design: DesignSystem = ${body};\n`;
1944
+ return {
1945
+ ok: true,
1946
+ source: withImport.slice(0, insertAt) + block + withImport.slice(insertAt),
1947
+ created: true
1948
+ };
1949
+ }
1950
+ function designPlugin(opts) {
1951
+ const userCwd = opts.userCwd;
1952
+ const docsDir = opts.docsDir ?? "docs";
1953
+ return {
1954
+ name: "open-doc:design",
1955
+ apply: "serve",
1956
+ configureServer(server) {
1957
+ server.middlewares.use("/__design", async (req, res, next) => {
1958
+ const url = new URL(req.url ?? "/", "http://local");
1959
+ const method = req.method ?? "GET";
1960
+ const docId = url.searchParams.get("docId") ?? "";
1961
+ const file = resolveDocPath(userCwd, docsDir, docId);
1962
+ if (!file) return json(res, 400, { error: "invalid docId" });
1963
+ try {
1964
+ if (method === "GET" && url.pathname === "/") {
1965
+ let source;
1966
+ try {
1967
+ source = await fs.readFile(file, "utf8");
1968
+ } catch {
1969
+ return json(res, 404, { error: "document not found" });
1970
+ }
1971
+ const parsed = parseDocDesign(source);
1972
+ if (parsed.ok) return json(res, 200, {
1973
+ design: parsed.design,
1974
+ exists: true,
1975
+ warning: null
1976
+ });
1977
+ if (parsed.exists === false) return json(res, 200, {
1978
+ design: defaultDesign,
1979
+ exists: false,
1980
+ warning: null
1981
+ });
1982
+ return json(res, 200, {
1983
+ design: defaultDesign,
1984
+ exists: true,
1985
+ warning: parsed.error
1986
+ });
1987
+ }
1988
+ if (method === "PUT" && url.pathname === "/") {
1989
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1990
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1991
+ const patch = (await readBody(req)).patch;
1992
+ if (!patch || typeof patch !== "object") return json(res, 400, { error: "missing patch object" });
1993
+ let source;
1994
+ try {
1995
+ source = await fs.readFile(file, "utf8");
1996
+ } catch {
1997
+ return json(res, 404, { error: "document not found" });
1998
+ }
1999
+ const parsed = parseDocDesign(source);
2000
+ if (!parsed.ok && parsed.exists) return json(res, 422, { error: parsed.error });
2001
+ const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
2002
+ const written = applyDesignWrite(source, merged);
2003
+ if (!written.ok) return json(res, written.status, { error: written.error });
2004
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
2005
+ return json(res, 200, {
2006
+ ok: true,
2007
+ design: merged,
2008
+ created: written.created
2009
+ });
2010
+ }
2011
+ if (method === "POST" && url.pathname === "/reset") {
2012
+ const requestCheck = validateMutationRequest(req);
2013
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
2014
+ let source;
2015
+ try {
2016
+ source = await fs.readFile(file, "utf8");
2017
+ } catch {
2018
+ return json(res, 404, { error: "document not found" });
2019
+ }
2020
+ const written = applyDesignWrite(source, defaultDesign);
2021
+ if (!written.ok) return json(res, written.status, { error: written.error });
2022
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
2023
+ return json(res, 200, {
2024
+ ok: true,
2025
+ design: defaultDesign,
2026
+ created: written.created
2027
+ });
2028
+ }
2029
+ return next();
2030
+ } catch (err) {
2031
+ json(res, 500, { error: String(err.message ?? err) });
2032
+ }
2033
+ });
2034
+ }
2035
+ };
2036
+ }
2037
+ //#endregion
2038
+ //#region src/vite/diagram-plugin.ts
2039
+ const DIAGRAM_RE = /\.(mmd|mermaid)$/i;
2040
+ /**
2041
+ * Makes `import chart from './architecture.mmd'` a themed SVG at build time.
2042
+ *
2043
+ * The same rule as `data-plugin` applies, and for the same reason: the flow
2044
+ * packer measures the real DOM to decide where pages break, so a drawing that
2045
+ * renders a tick later renders after the layout is decided. Compiling in the
2046
+ * plugin also means no diagram library reaches the browser bundle — the SVG
2047
+ * arrives as text, already sized.
2048
+ *
2049
+ * `?raw` and `?url` are left to Vite.
2050
+ */
2051
+ function diagramPlugin() {
2052
+ return {
2053
+ name: "open-doc:diagram",
2054
+ enforce: "pre",
2055
+ async load(id) {
2056
+ const [file, query] = id.split("?");
2057
+ if (query !== void 0) return null;
2058
+ if (!DIAGRAM_RE.test(file)) return null;
2059
+ let text;
2060
+ try {
2061
+ text = await fs.readFile(file, "utf8");
2062
+ } catch {
2063
+ return null;
2064
+ }
2065
+ try {
2066
+ const suffix = path.basename(file).replace(/[^a-zA-Z0-9]/g, "");
2067
+ const compiled = compileDiagram(text, { idSuffix: suffix });
2068
+ return [
2069
+ `export const svg = ${JSON.stringify(compiled.svg)};`,
2070
+ `export const width = ${compiled.width};`,
2071
+ `export const height = ${compiled.height};`,
2072
+ "export default { svg, width, height };"
2073
+ ].join("\n");
2074
+ } catch (err) {
2075
+ if (err instanceof DiagramSyntaxError) this.error(`${path.relative(process.cwd(), file)}: ${err.message}`);
2076
+ throw err;
2077
+ }
2078
+ }
2079
+ };
2080
+ }
2081
+ //#endregion
2082
+ //#region src/vite/loc-tags-plugin.ts
2083
+ const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set(["ImagePlaceholder"]);
2084
+ function taggableName(opening) {
2085
+ const name = opening.name;
2086
+ if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
2087
+ if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
2088
+ return null;
2089
+ }
2090
+ function alreadyTagged(opening) {
2091
+ return (opening.attributes ?? []).some((attr) => {
2092
+ if (attr.type !== "JSXAttribute") return false;
2093
+ return attr.name?.name === "data-od-loc";
2094
+ });
2095
+ }
2096
+ function injectLocTags(code) {
2097
+ const ast = parseSource$1(code);
2098
+ if (!ast) return null;
2099
+ const insertions = [];
2100
+ walkJsx(ast, (node) => {
2101
+ const opening = node.openingElement;
2102
+ if (!opening || !node.loc) return;
2103
+ if (!taggableName(opening) || alreadyTagged(opening)) return;
2104
+ const nameNode = opening.name;
2105
+ insertions.push({
2106
+ offset: nameNode.end,
2107
+ text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
2108
+ });
2109
+ });
2110
+ if (insertions.length === 0) return null;
2111
+ insertions.sort((a, b) => b.offset - a.offset);
2112
+ let next = code;
2113
+ for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
2114
+ return next;
2115
+ }
2116
+ function isDocSourceFile(id, docsRootPosix) {
2117
+ const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
2118
+ if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
2119
+ if (!filePath.endsWith(".tsx")) return false;
2120
+ if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
2121
+ return filePath.slice(docsRootPosix.length + 1).includes("/");
2122
+ }
2123
+ function locTagsPlugin(opts) {
2124
+ const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
2125
+ return {
2126
+ name: "open-doc:loc-tags",
2127
+ apply: "serve",
2128
+ enforce: "pre",
2129
+ transform(code, id) {
2130
+ if (!isDocSourceFile(id, docsRoot)) return null;
2131
+ const next = injectLocTags(code);
2132
+ return next === null ? null : {
2133
+ code: next,
2134
+ map: null
2135
+ };
2136
+ }
2137
+ };
2138
+ }
2139
+ //#endregion
2140
+ //#region src/vite/mcp-plugin.ts
2141
+ /**
2142
+ * Finds a package's ESM entry by walking `node_modules` up from the user's
2143
+ * workspace. Node's own resolver is not used here for two reasons: the package
2144
+ * belongs to whoever opted into the endpoint rather than to core, and
2145
+ * `require.resolve` cannot read an exports map that only declares ESM
2146
+ * conditions.
2147
+ */
2148
+ function resolveEsmEntry(userCwd, name) {
2149
+ let dir = path.resolve(userCwd);
2150
+ for (;;) {
2151
+ const manifest = path.join(dir, "node_modules", name, "package.json");
2152
+ if (existsSync(manifest)) {
2153
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
2154
+ const entry = pkg.exports?.["."]?.import ?? pkg.module ?? pkg.main;
2155
+ return entry ? path.join(path.dirname(manifest), entry) : null;
2156
+ }
2157
+ const parent = path.dirname(dir);
2158
+ if (parent === dir) return null;
2159
+ dir = parent;
2160
+ }
2161
+ }
2162
+ /**
2163
+ * Mounts `@open-document/mcp` on the dev server so an agent and the browser act on
2164
+ * one workspace — a tool call lands on disk and the page hot-reloads.
2165
+ *
2166
+ * The package is imported dynamically and is *not* a dependency of core: the
2167
+ * MCP SDK is sizeable and only matters to people wiring up agents, so it stays
2168
+ * opt-in. A missing install is reported, never fatal.
2169
+ */
2170
+ function mcpPlugin(opts) {
2171
+ const endpoint = opts.endpoint ?? "/mcp";
2172
+ return {
2173
+ name: "open-doc:mcp",
2174
+ apply: "serve",
2175
+ async configureServer(server) {
2176
+ let mod;
2177
+ try {
2178
+ const specifier = "@open-document/mcp";
2179
+ const entry = resolveEsmEntry(opts.userCwd, specifier);
2180
+ mod = await (entry ? import(pathToFileURL(entry).href) : import(specifier));
2181
+ } catch {
2182
+ server.config.logger.warn(chalk.yellow(" MCP endpoint disabled — run `pnpm add -D @open-document/mcp` to enable it.\n"));
2183
+ return;
2184
+ }
2185
+ const originOf = () => {
2186
+ const local = server.resolvedUrls?.local?.[0];
2187
+ return local ? local.replace(/\/$/, "") : void 0;
2188
+ };
2189
+ let middleware;
2190
+ server.middlewares.use(endpoint, (req, res, next) => {
2191
+ middleware ??= mod.createOpenDocMcpMiddleware({
2192
+ userCwd: opts.userCwd,
2193
+ docsDir: opts.docsDir,
2194
+ assetsDir: opts.assetsDir,
2195
+ version: opts.coreVersion,
2196
+ serverOrigin: originOf()
2197
+ });
2198
+ return middleware(req, res, next);
2199
+ });
2200
+ server.httpServer?.once("listening", () => {
2201
+ const address = server.httpServer?.address();
2202
+ const port = typeof address === "object" && address ? address.port : "";
2203
+ server.config.logger.info(` ${chalk.green("➜")} ${chalk.bold("MCP")}: ${chalk.cyan(`http://localhost:${port}${endpoint}`)}`);
2204
+ });
2205
+ }
2206
+ };
2207
+ }
2208
+ //#endregion
2209
+ //#region src/vite/themes-plugin.ts
2210
+ const THEMES_VMOD = "virtual:open-doc/themes";
2211
+ function resolved(id) {
2212
+ return `\0${id}`;
2213
+ }
2214
+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
2215
+ function parseFrontmatter(raw, themeId) {
2216
+ const match = raw.match(FM_RE);
2217
+ const fmText = match ? match[1] : "";
2218
+ const body = match ? match[2] : raw;
2219
+ const data = {};
2220
+ for (const line of fmText.split(/\r?\n/)) {
2221
+ const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
2222
+ if (!m) continue;
2223
+ let value = m[2].trim();
2224
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2225
+ data[m[1]] = value;
2226
+ }
2227
+ return {
2228
+ fm: {
2229
+ name: data.name || themeId,
2230
+ description: data.description || "",
2231
+ pageSize: data.pageSize || "",
2232
+ mode: data.mode || ""
2233
+ },
2234
+ body: body.trim()
2235
+ };
2236
+ }
2237
+ async function findThemes(userCwd, themesDir) {
2238
+ const abs = path.resolve(userCwd, themesDir);
2239
+ if (!existsSync(abs)) return [];
2240
+ return (await fg("*.md", {
2241
+ cwd: abs,
2242
+ absolute: true,
2243
+ onlyFiles: true
2244
+ })).sort();
2245
+ }
2246
+ async function readTheme(mdAbs, themesRoot) {
2247
+ const id = path.basename(mdAbs, ".md");
2248
+ const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
2249
+ let demoAbs = null;
2250
+ for (const cand of [
2251
+ `${id}.demo.tsx`,
2252
+ `${id}.demo.jsx`,
2253
+ `${id}.demo.ts`,
2254
+ `${id}.demo.js`
2255
+ ]) {
2256
+ const p = path.join(themesRoot, cand);
2257
+ if (existsSync(p)) {
2258
+ demoAbs = p;
2259
+ break;
2260
+ }
2261
+ }
2262
+ return {
2263
+ id,
2264
+ frontmatter: fm,
2265
+ body,
2266
+ demoAbs
2267
+ };
2268
+ }
2269
+ function generateThemesModule(themes, isDev) {
2270
+ const meta = themes.map((t) => ({
2271
+ id: t.id,
2272
+ name: t.frontmatter.name,
2273
+ description: t.frontmatter.description,
2274
+ pageSize: t.frontmatter.pageSize,
2275
+ mode: t.frontmatter.mode,
2276
+ body: t.body,
2277
+ hasDemo: t.demoAbs !== null
2278
+ }));
2279
+ const cases = themes.flatMap((t) => {
2280
+ const abs = t.demoAbs;
2281
+ if (!abs) return [];
2282
+ const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
2283
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
2284
+ return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
2285
+ }).join("\n");
2286
+ return `// virtual:open-doc/themes — generated
2287
+ export const themes = ${JSON.stringify(meta)};
2288
+
2289
+ export async function loadThemeDemo(id) {
2290
+ switch (id) {
2291
+ ${cases}
2292
+ default: throw new Error('Theme demo not found: ' + id);
2293
+ }
2294
+ }
2295
+ `;
2296
+ }
2297
+ function themesPlugin(opts) {
2298
+ const { userCwd, config } = opts;
2299
+ const themesDir = config.themesDir ?? "themes";
2300
+ const themesRoot = path.resolve(userCwd, themesDir);
2301
+ let isDev = false;
2302
+ return {
2303
+ name: "open-doc:themes",
2304
+ config(_c, env) {
2305
+ isDev = env.command === "serve";
2306
+ },
2307
+ resolveId(id) {
2308
+ if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
2309
+ return null;
2310
+ },
2311
+ async load(id) {
2312
+ if (id !== resolved(THEMES_VMOD)) return null;
2313
+ const files = await findThemes(userCwd, themesDir);
2314
+ return generateThemesModule(await Promise.all(files.map((f) => readTheme(f, themesRoot))), isDev);
2315
+ },
2316
+ configureServer(server) {
2317
+ const isThemeFile = (p) => {
2318
+ const rel = path.relative(themesRoot, p);
2319
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
2320
+ if (rel.includes(path.sep)) return false;
2321
+ return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
2322
+ };
2323
+ let reloadTimer = null;
2324
+ const reload = () => {
2325
+ if (reloadTimer) clearTimeout(reloadTimer);
2326
+ reloadTimer = setTimeout(() => {
2327
+ reloadTimer = null;
2328
+ const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
2329
+ if (mod) server.moduleGraph.invalidateModule(mod);
2330
+ server.ws.send({ type: "full-reload" });
2331
+ }, 150);
2332
+ };
2333
+ server.watcher.add(themesRoot);
2334
+ for (const event of [
2335
+ "add",
2336
+ "unlink",
2337
+ "change"
2338
+ ]) server.watcher.on(event, (p) => {
2339
+ if (isThemeFile(p)) reload();
2340
+ });
2341
+ }
2342
+ };
2343
+ }
2344
+ //#endregion
2345
+ //#region src/vite/config.ts
2346
+ function findPackageRoot(fromFile) {
2347
+ let dir = path.dirname(fromFile);
2348
+ while (dir !== path.dirname(dir)) {
2349
+ if (existsSync(path.join(dir, "package.json"))) return dir;
2350
+ dir = path.dirname(dir);
2351
+ }
2352
+ throw new Error(`Could not find package.json walking up from ${fromFile}`);
2353
+ }
2354
+ const PKG_ROOT = findPackageRoot(fileURLToPath(import.meta.url));
2355
+ const APP_ROOT = path.join(PKG_ROOT, "src", "app");
2356
+ function readCoreVersion() {
2357
+ try {
2358
+ const raw = readFileSync(path.join(PKG_ROOT, "package.json"), "utf8");
2359
+ return JSON.parse(raw).version ?? "0.0.0";
2360
+ } catch {
2361
+ return "0.0.0";
2362
+ }
2363
+ }
2364
+ const CORE_VERSION = readCoreVersion();
2365
+ async function createViteConfig(opts) {
2366
+ const userCwd = path.resolve(opts.userCwd);
2367
+ const config = opts.config ?? await loadUserConfig(userCwd);
2368
+ const docsDir = config.docsDir ?? "docs";
2369
+ const assetsDir = config.assetsDir ?? "assets";
2370
+ const docsAbs = path.resolve(userCwd, docsDir);
2371
+ const themesAbs = path.resolve(userCwd, config.themesDir ?? "themes");
2372
+ const assetsAbs = path.resolve(userCwd, assetsDir);
2373
+ return {
2374
+ base: config.base ?? "/",
2375
+ root: APP_ROOT,
2376
+ configFile: false,
2377
+ envDir: userCwd,
2378
+ plugins: [
2379
+ dataPlugin(),
2380
+ diagramPlugin(),
2381
+ locTagsPlugin({
2382
+ userCwd,
2383
+ docsDir
2384
+ }),
2385
+ react(),
2386
+ tailwindcss(),
2387
+ openDocPlugin({
2388
+ userCwd,
2389
+ config,
2390
+ coreVersion: CORE_VERSION
2391
+ }),
2392
+ themesPlugin({
2393
+ userCwd,
2394
+ config
2395
+ }),
2396
+ designPlugin({
2397
+ userCwd,
2398
+ docsDir
2399
+ }),
2400
+ apiPlugin({
2401
+ userCwd,
2402
+ docsDir,
2403
+ assetsDir,
2404
+ coreVersion: CORE_VERSION
2405
+ }),
2406
+ ...opts.headless ? [] : [currentPlugin({
2407
+ userCwd,
2408
+ docsDir
2409
+ })],
2410
+ ...opts.mcp ? [mcpPlugin({
2411
+ userCwd,
2412
+ docsDir,
2413
+ assetsDir,
2414
+ coreVersion: CORE_VERSION
2415
+ })] : []
2416
+ ],
2417
+ resolve: { alias: {
2418
+ "@": APP_ROOT,
2419
+ "@assets": assetsAbs
2420
+ } },
2421
+ optimizeDeps: {
2422
+ entries: [path.join(APP_ROOT, "main.tsx")],
2423
+ include: [
2424
+ "react",
2425
+ "react-dom",
2426
+ "react-dom/client",
2427
+ "react-router-dom",
2428
+ "next-themes",
2429
+ "lucide-react",
2430
+ "clsx",
2431
+ "tailwind-merge"
2432
+ ],
2433
+ esbuildOptions: { plugins: [{
2434
+ name: "open-doc:virtual-externals",
2435
+ setup(build) {
2436
+ build.onResolve({ filter: /^virtual:open-doc\// }, (args) => ({
2437
+ path: args.path,
2438
+ external: true
2439
+ }));
2440
+ }
2441
+ }] }
2442
+ },
2443
+ server: {
2444
+ port: config.port ?? 5273,
2445
+ ...config.allowedHosts !== void 0 ? { allowedHosts: config.allowedHosts } : {},
2446
+ fs: { allow: [
2447
+ APP_ROOT,
2448
+ userCwd,
2449
+ docsAbs,
2450
+ themesAbs,
2451
+ assetsAbs
2452
+ ] }
2453
+ },
2454
+ build: {
2455
+ outDir: path.resolve(userCwd, "dist"),
2456
+ emptyOutDir: true
2457
+ }
2458
+ };
2459
+ }
2460
+ //#endregion
2461
+ export { openDocPlugin as A, readManifest as C, makeContext as D, writeManifest as E, DOC_ID_RE as O, newFolderId as S, validateName as T, listDocuments as _, insertMarker as a, resolveEntry as b, resolveScopedAssetFile as c, OpsError as d, createDocument as f, listDocIds$1 as g, duplicateDocument as h, resolveTextTarget as i, loadUserConfig as k, resolveScopedAssetsDir as l, docDir as m, parseFrontmatter as n, assetImportPath as o, deleteDocument as p, replaceTextAt as r, countAssetUsages as s, createViteConfig as t, validateAssetName as u, readDocument as v, validateIcon as w, writeDocument as x, renameDocument as y };