@open-document/core 0.9.1 → 0.10.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 (83) hide show
  1. package/dist/{build-B0GJXy8I.js → build-DJMLK50m.js} +1 -1
  2. package/dist/{check-CuDIWsPT.js → check-CUKuufBm.js} +3 -3
  3. package/dist/cli/bin.js +10 -6
  4. package/dist/{config-CAZ7Z_va.js → config-CvzpyAUA.js} +558 -546
  5. package/dist/{context-PWAh9qbf.js → context-B4ip7SoI.js} +1 -1
  6. package/dist/{dev-CYqppXDI.js → dev-dnH7DTlD.js} +1 -1
  7. package/dist/{diagram-CCaUUnRe.js → diagram-BK4jTZr4.js} +146 -146
  8. package/dist/diff-QTo0A5Rx.js +44 -0
  9. package/dist/{export-1JtO2OMC.js → export-BrRFrexj.js} +3 -3
  10. package/dist/{import-CsrdBOZ8.js → import-C14Vn9ER.js} +2 -2
  11. package/dist/index.d.ts +53 -2
  12. package/dist/index.js +457 -18
  13. package/dist/ops/index.d.ts +72 -17
  14. package/dist/ops/index.js +3 -3
  15. package/dist/{ops-B2y9BMpk.js → ops-DKidjLXP.js} +642 -124
  16. package/dist/{preview-DW3PM-JV.js → preview-wKM4C6Uk.js} +1 -1
  17. package/dist/{sdk-BqU6mwD_.d.ts → sdk-CpDEGRIo.d.ts} +2 -0
  18. package/dist/vite/index.js +1 -1
  19. package/package.json +2 -2
  20. package/skills/doc-authoring/SKILL.md +9 -4
  21. package/skills/doc-authoring/references/pagination.md +1 -1
  22. package/skills/doc-authoring/references/tables-and-charts.md +18 -1
  23. package/src/app/components/browser/browser-ui.tsx +105 -0
  24. package/src/app/components/chart.tsx +239 -0
  25. package/src/app/components/command-palette.tsx +284 -0
  26. package/src/app/components/design-panel/design-panel.tsx +22 -20
  27. package/src/app/components/design-panel/design-provider.tsx +4 -2
  28. package/src/app/components/diagram.tsx +11 -1
  29. package/src/app/components/doc-assets.tsx +6 -5
  30. package/src/app/components/doc-search.tsx +12 -10
  31. package/src/app/components/doc-sidebar.tsx +24 -18
  32. package/src/app/components/flow-page.tsx +2 -0
  33. package/src/app/components/inspector/inspector.tsx +75 -48
  34. package/src/app/components/language-toggle.tsx +38 -0
  35. package/src/app/components/palette-items.ts +128 -0
  36. package/src/app/components/panel/edit-save-card.tsx +4 -2
  37. package/src/app/components/panel/fields.tsx +5 -2
  38. package/src/app/components/panel/save-card.tsx +18 -10
  39. package/src/app/components/sidebar/folder-item.tsx +10 -8
  40. package/src/app/components/sidebar/icon-picker.tsx +3 -1
  41. package/src/app/components/sidebar/sidebar.tsx +44 -13
  42. package/src/app/components/theme-toggle.tsx +5 -3
  43. package/src/app/components/ui/menu.tsx +5 -0
  44. package/src/app/lib/agent-bridge.ts +8 -2
  45. package/src/app/lib/chart.test.ts +108 -0
  46. package/src/app/lib/chart.ts +343 -0
  47. package/src/app/lib/doc-preview.tsx +0 -10
  48. package/src/app/lib/docs.ts +3 -0
  49. package/src/app/lib/docx/from-dom.ts +11 -11
  50. package/src/app/lib/docx/ooxml.test.ts +25 -9
  51. package/src/app/lib/docx/ooxml.ts +58 -37
  52. package/src/app/lib/export-docx.ts +13 -8
  53. package/src/app/lib/flow.ts +1 -1
  54. package/src/app/lib/i18n-ja/browser.ts +88 -0
  55. package/src/app/lib/i18n-ja/doc.ts +65 -0
  56. package/src/app/lib/i18n-ja/index.ts +5 -0
  57. package/src/app/lib/i18n-ja/panels.ts +104 -0
  58. package/src/app/lib/i18n-ko/browser.ts +87 -0
  59. package/src/app/lib/i18n-ko/doc.ts +65 -0
  60. package/src/app/lib/i18n-ko/index.ts +5 -0
  61. package/src/app/lib/i18n-ko/panels.ts +102 -0
  62. package/src/app/lib/i18n-zh-cn/browser.ts +84 -0
  63. package/src/app/lib/i18n-zh-cn/doc.ts +64 -0
  64. package/src/app/lib/i18n-zh-cn/index.ts +5 -0
  65. package/src/app/lib/i18n-zh-cn/panels.ts +98 -0
  66. package/src/app/lib/i18n-zh-tw/browser.ts +84 -0
  67. package/src/app/lib/i18n-zh-tw/doc.ts +64 -0
  68. package/src/app/lib/i18n-zh-tw/index.ts +5 -0
  69. package/src/app/lib/i18n-zh-tw/panels.ts +99 -0
  70. package/src/app/lib/i18n.test.ts +24 -0
  71. package/src/app/lib/i18n.tsx +109 -0
  72. package/src/app/lib/outline.ts +23 -0
  73. package/src/app/lib/page-range.test.ts +10 -1
  74. package/src/app/lib/page-range.ts +26 -0
  75. package/src/app/lib/sdk.ts +2 -0
  76. package/src/app/main.tsx +4 -1
  77. package/src/app/routes/assets.tsx +193 -132
  78. package/src/app/routes/doc.tsx +666 -310
  79. package/src/app/routes/home-shell.tsx +115 -88
  80. package/src/app/routes/home.tsx +200 -67
  81. package/src/app/routes/themes.tsx +42 -35
  82. package/src/app/styles.css +84 -5
  83. package/src/app/virtual.d.ts +1 -0
@@ -1,4 +1,4 @@
1
- import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-CCaUUnRe.js";
1
+ import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
2
2
  import chalk from "chalk";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -6,10 +6,10 @@ import fs from "node:fs/promises";
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
  import fg from "fast-glob";
8
8
  import { loadConfigFromFile, normalizePath } from "vite";
9
- import { parse } from "@babel/parser";
10
- import { randomUUID } from "node:crypto";
11
9
  import tailwindcss from "@tailwindcss/vite";
12
10
  import react from "@vitejs/plugin-react";
11
+ import { parse } from "@babel/parser";
12
+ import { randomUUID } from "node:crypto";
13
13
  //#region src/vite/open-doc-plugin.ts
14
14
  const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
15
15
  const CONFIG_FILE = "open-doc.config.ts";
@@ -48,15 +48,18 @@ function toId(absFile, docsRoot) {
48
48
  }
49
49
  const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
50
50
  const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
51
+ const META_TITLE_RE = /(?:^|[\s,{])title\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/;
51
52
  /**
52
53
  * 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.
54
+ * every discovery pass, and the fields it needs (sort order, theme back-link,
55
+ * the title search and sorting use without loading every document) are
56
+ * contractually string literals.
55
57
  */
56
58
  function extractMeta(src) {
57
59
  const empty = {
58
60
  theme: null,
59
- createdAt: null
61
+ createdAt: null,
62
+ title: null
60
63
  };
61
64
  const metaStart = src.search(/export\s+const\s+meta\b/);
62
65
  if (metaStart === -1) return empty;
@@ -79,9 +82,13 @@ function extractMeta(src) {
79
82
  const body = src.slice(openBrace + 1, closeBrace);
80
83
  return {
81
84
  theme: body.match(META_THEME_RE)?.[1] ?? null,
82
- createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null
85
+ createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null,
86
+ title: unescapeLiteral(body.match(META_TITLE_RE)?.[2] ?? null)
83
87
  };
84
88
  }
89
+ function unescapeLiteral(raw) {
90
+ return raw === null ? null : raw.replace(/\\(.)/g, "$1");
91
+ }
85
92
  function parseCreatedAtMs(iso) {
86
93
  if (!iso) return null;
87
94
  const ms = Date.parse(iso);
@@ -93,7 +100,8 @@ async function readMeta(abs) {
93
100
  } catch {
94
101
  return {
95
102
  theme: null,
96
- createdAt: null
103
+ createdAt: null,
104
+ title: null
97
105
  };
98
106
  }
99
107
  }
@@ -105,6 +113,7 @@ async function generateDocsModule(files, docsRoot, isDev) {
105
113
  id: toId(abs, docsRoot),
106
114
  importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
107
115
  theme: meta.theme,
116
+ title: meta.title,
108
117
  createdAt: parseCreatedAtMs(meta.createdAt)
109
118
  };
110
119
  }));
@@ -113,9 +122,11 @@ async function generateDocsModule(files, docsRoot, isDev) {
113
122
  const ids = JSON.stringify(entries.map((e) => e.id).sort());
114
123
  const createdAtMap = {};
115
124
  const themesMap = {};
125
+ const titlesMap = {};
116
126
  for (const e of entries) {
117
127
  if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
118
128
  if (e.theme) themesMap[e.id] = e.theme;
129
+ if (e.title) titlesMap[e.id] = e.title;
119
130
  }
120
131
  const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
121
132
  const devRuntime = isDev ? `
@@ -139,6 +150,7 @@ if (import.meta.hot) {
139
150
  export const docIds = ${ids};
140
151
  export const docCreatedAt = ${JSON.stringify(createdAtMap)};
141
152
  export const docThemes = ${JSON.stringify(themesMap)};
153
+ export const docTitles = ${JSON.stringify(titlesMap)};
142
154
  ${devRuntime}
143
155
 
144
156
  export async function loadDoc(id) {
@@ -351,567 +363,172 @@ function resolveDocEntry(docsRoot, docId) {
351
363
  return null;
352
364
  }
353
365
  //#endregion
354
- //#region src/editing/babel-walk.ts
355
- function parseSource(code) {
356
- try {
357
- return parse(code, {
358
- sourceType: "module",
359
- plugins: ["typescript", "jsx"],
360
- errorRecovery: true
361
- });
362
- } catch {
363
- return null;
364
- }
366
+ //#region src/files/assets.ts
367
+ const GLOBAL_SCOPE = "@global";
368
+ const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
369
+ const MIME_BY_EXT = {
370
+ png: "image/png",
371
+ jpg: "image/jpeg",
372
+ jpeg: "image/jpeg",
373
+ gif: "image/gif",
374
+ svg: "image/svg+xml",
375
+ webp: "image/webp",
376
+ avif: "image/avif",
377
+ ico: "image/x-icon",
378
+ pdf: "application/pdf",
379
+ woff: "font/woff",
380
+ woff2: "font/woff2",
381
+ ttf: "font/ttf",
382
+ otf: "font/otf",
383
+ csv: "text/csv; charset=utf-8",
384
+ json: "application/json",
385
+ txt: "text/plain; charset=utf-8",
386
+ md: "text/markdown; charset=utf-8"
387
+ };
388
+ function mimeForFilename(name) {
389
+ const dot = name.lastIndexOf(".");
390
+ if (dot < 0) return "application/octet-stream";
391
+ return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
365
392
  }
366
- /**
367
- * `parseSource`, but a source with any recovered error is refused. Reading
368
- * tolerates a document mid-edit; writing splices text in by AST offset, and a
369
- * best-guess tree recovered from a syntax error must never decide where.
370
- */
371
- function parseStrict(code) {
372
- const ast = parseSource(code);
373
- if (!ast) return null;
374
- return ast.errors && ast.errors.length > 0 ? null : ast;
393
+ function assetCreatedAt(birthtimeMs, mtimeMs) {
394
+ return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
375
395
  }
376
- function isNode(value) {
377
- return typeof value === "object" && value !== null && typeof value.type === "string";
396
+ function validateAssetName(v) {
397
+ if (typeof v !== "string") return null;
398
+ const trimmed = v.trim();
399
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
400
+ if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
401
+ if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
402
+ if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
403
+ const dot = trimmed.lastIndexOf(".");
404
+ if (dot <= 0 || dot === trimmed.length - 1) return null;
405
+ return trimmed;
378
406
  }
379
- /** Depth-first walk over every node; the visitor decides what it cares about. */
380
- function walkAst(node, visit) {
381
- if (Array.isArray(node)) {
382
- for (const child of node) walkAst(child, visit);
383
- return;
384
- }
385
- if (!isNode(node)) return;
386
- visit(node);
387
- for (const key of Object.keys(node)) {
388
- if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
389
- walkAst(node[key], visit);
390
- }
407
+ function resolveAssetsDir(docsRoot, docId) {
408
+ if (!DOC_ID_RE.test(docId)) return null;
409
+ const docDir = path.resolve(docsRoot, docId);
410
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
411
+ const assetsDir = path.resolve(docDir, "assets");
412
+ if (assetsDir !== path.join(docDir, "assets")) return null;
413
+ return assetsDir;
391
414
  }
392
- function walkJsx(ast, visit) {
393
- walkAst(ast, (node) => {
394
- if (node.type === "JSXElement") visit(node);
395
- });
415
+ function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
416
+ if (scope === "@global") return globalAssetsRoot;
417
+ return resolveAssetsDir(docsRoot, scope);
396
418
  }
397
- /**
398
- * The JSX element whose opening tag starts at this source position.
399
- *
400
- * The match is exact on both line and column. Anything looser can resolve to a
401
- * different element on the same line, and this location decides where an edit
402
- * gets written — a near miss silently rewrites the wrong text.
403
- */
404
- function findJsxAt(ast, line, column) {
405
- let found = null;
406
- walkJsx(ast, (node) => {
407
- if (found) return;
408
- const start = node.loc?.start;
409
- if (start && start.line === line && start.column === column) found = node;
410
- });
411
- return found;
419
+ function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
420
+ if (!validateAssetName(filename)) return null;
421
+ const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
422
+ if (!dir) return null;
423
+ const file = path.resolve(dir, filename);
424
+ if (!file.startsWith(dir + path.sep)) return null;
425
+ return file;
426
+ }
427
+ /** How a document imports an asset — the string we look for when counting usages. */
428
+ function assetImportPath(scope, filename) {
429
+ return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
430
+ }
431
+ function escapeRegExp(value) {
432
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
412
433
  }
413
434
  /**
414
- * Every JSX element that starts on a line, nearest column first.
415
- *
416
- * Columns cannot be trusted for locations derived from React's `_debugSource`:
417
- * injecting the loc attribute shifts the columns of anything later on the same
418
- * line, so the offset differs per element. The line survives that, so callers
419
- * scan the line and pick by content instead.
435
+ * Counts references to an asset in a document's source. Matches the quoted path
436
+ * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
437
+ * which is every form the authoring skill sanctions.
420
438
  */
421
- function findJsxOnLine(ast, line, column) {
422
- const hits = [];
423
- walkJsx(ast, (node) => {
424
- const start = node.loc?.start;
425
- if (!start || start.line !== line) return;
426
- hits.push({
427
- node,
428
- distance: Math.abs(start.column - column)
429
- });
430
- });
431
- return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
439
+ function countAssetUsages(source, importPath) {
440
+ const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
441
+ return source.match(quoted)?.length ?? 0;
442
+ }
443
+ function findReferencedAssets(source, importPaths) {
444
+ return importPaths.filter((p) => countAssetUsages(source, p) > 0);
432
445
  }
433
446
  //#endregion
434
- //#region src/editing/doc-ops.ts
435
- function programBody$1(ast) {
436
- return ast.program?.body ?? [];
447
+ //#region src/http/request-guard.ts
448
+ function firstHeaderValue(value) {
449
+ if (Array.isArray(value)) return value[0] ?? null;
450
+ return value ?? null;
437
451
  }
438
- function metaObjectOf(node) {
439
- if (node.type !== "ExportNamedDeclaration") return null;
440
- const decl = node.declaration;
441
- if (decl?.type !== "VariableDeclaration") return null;
442
- const declarations = decl.declarations ?? [];
443
- for (const d of declarations) {
444
- const id = d.id;
445
- if (id?.type !== "Identifier" || id.name !== "meta") continue;
446
- let init = d.init;
447
- if (!init) return null;
448
- if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
449
- const expr = init.expression;
450
- if (expr) init = expr;
451
- }
452
- return init.type === "ObjectExpression" ? init : null;
453
- }
454
- return null;
452
+ function headerValue(req, name) {
453
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
455
454
  }
456
- function findMetaObject(ast) {
457
- for (const node of programBody$1(ast)) {
458
- const object = metaObjectOf(node);
459
- if (object) return object;
460
- }
461
- return null;
455
+ function firstCommaToken(value) {
456
+ if (!value) return null;
457
+ const [first] = value.split(",", 1);
458
+ return first?.trim() || null;
462
459
  }
463
- function jsString$1(value) {
464
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
460
+ function requestProto(req) {
461
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
462
+ if (forwarded === "http" || forwarded === "https") return forwarded;
463
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
465
464
  }
466
- function validateDocTitle(v) {
467
- if (typeof v !== "string") return null;
468
- const trimmed = v.trim();
469
- if (trimmed.length < 1 || trimmed.length > 120) return null;
470
- return trimmed;
465
+ function normalizedOrigin(origin) {
466
+ try {
467
+ const url = new URL(origin);
468
+ return `${url.protocol}//${url.host}`.toLowerCase();
469
+ } catch {
470
+ return null;
471
+ }
471
472
  }
472
473
  /**
473
- * Rewrites `meta.title` in place, adding the property when the meta object
474
- * exists without one. Returns null when there is no meta object to edit —
475
- * the caller reports that rather than inventing an export.
474
+ * The dev server writes to the user's filesystem, so every mutating endpoint is
475
+ * guarded against a page on another origin driving it through the browser.
476
476
  */
477
- function setMetaTitle(source, title) {
478
- const ast = parseStrict(source);
479
- if (!ast) return null;
480
- const object = findMetaObject(ast);
481
- if (!object) return null;
482
- const properties = object.properties ?? [];
483
- for (const prop of properties) {
484
- if (prop.type !== "ObjectProperty") continue;
485
- const p = prop;
486
- if (p.computed) continue;
487
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
488
- return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
489
- }
490
- const open = object.start + 1;
491
- const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
492
- return source.slice(0, open) + inserted + source.slice(open);
493
- }
494
- function readMetaTitle(source) {
495
- const ast = parseSource(source);
496
- if (!ast) return null;
497
- const object = findMetaObject(ast);
498
- if (!object) return null;
499
- const properties = object.properties ?? [];
500
- for (const prop of properties) {
501
- if (prop.type !== "ObjectProperty") continue;
502
- const p = prop;
503
- if (p.computed) continue;
504
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
505
- if (p.value.type !== "StringLiteral") return null;
506
- return typeof p.value.value === "string" ? p.value.value : null;
507
- }
508
- return null;
509
- }
510
- /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
511
- function nextCopyId(baseId, taken) {
512
- const stem = baseId.replace(/-copy(-\d+)?$/, "");
513
- let candidate = `${stem}-copy`;
514
- let n = 2;
515
- while (taken.has(candidate)) {
516
- candidate = `${stem}-copy-${n}`;
517
- n++;
477
+ function validateMutationRequest(req, opts = {}) {
478
+ if (opts.requireJsonBody) {
479
+ if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
480
+ ok: false,
481
+ status: 415,
482
+ error: "content-type must be application/json"
483
+ };
518
484
  }
519
- return candidate;
520
- }
521
- function copyTitle(title) {
522
- return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
523
- }
524
- //#endregion
525
- //#region src/files/folders.ts
526
- const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
527
- const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
528
- function emptyManifest() {
529
- return {
530
- folders: [],
531
- assignments: {}
485
+ if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
486
+ ok: false,
487
+ status: 403,
488
+ error: "cross-site request blocked"
532
489
  };
533
- }
534
- async function readManifest(file) {
535
- try {
536
- const raw = await fs.readFile(file, "utf8");
537
- const parsed = JSON.parse(raw);
538
- return {
539
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
540
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
541
- };
542
- } catch (err) {
543
- if (err.code === "ENOENT") return emptyManifest();
544
- throw err;
545
- }
546
- }
547
- async function writeManifest(file, manifest) {
548
- await fs.mkdir(path.dirname(file), { recursive: true });
549
- await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
550
- }
551
- function newFolderId() {
552
- return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
553
- }
554
- function validateName(v) {
555
- if (typeof v !== "string") return null;
556
- const trimmed = v.trim();
557
- if (trimmed.length < 1 || trimmed.length > 40) return null;
558
- return trimmed;
559
- }
560
- function validateReorder(v, current) {
561
- if (!Array.isArray(v) || v.length !== current.length) return null;
562
- const known = new Set(current.map((f) => f.id));
563
- const seen = /* @__PURE__ */ new Set();
564
- const out = [];
565
- for (const id of v) {
566
- if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
567
- if (!known.has(id) || seen.has(id)) return null;
568
- seen.add(id);
569
- out.push(id);
570
- }
571
- return out;
572
- }
573
- function validateIcon(v) {
574
- if (!v || typeof v !== "object") return null;
575
- const icon = v;
576
- if (icon.type === "emoji") {
577
- if (typeof icon.value !== "string") return null;
578
- if (icon.value.length < 1 || icon.value.length > 8) return null;
579
- return {
580
- type: "emoji",
581
- value: icon.value
582
- };
583
- }
584
- if (icon.type === "color") {
585
- if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
586
- return {
587
- type: "color",
588
- value: icon.value
589
- };
590
- }
591
- return null;
592
- }
593
- //#endregion
594
- //#region src/ops/documents.ts
595
- /**
596
- * Operations shared by the dev API and the MCP server. Everything here takes an
597
- * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
598
- * and a browser calling `/__docs` end up in exactly the same code.
599
- */
600
- var OpsError = class extends Error {
601
- status;
602
- constructor(status, message) {
603
- super(message);
604
- this.status = status;
605
- this.name = "OpsError";
606
- }
607
- };
608
- const ENTRY_NAMES = [
609
- "index.tsx",
610
- "index.jsx",
611
- "index.ts",
612
- "index.js"
613
- ];
614
- function docDir(ctx, docId) {
615
- if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
616
- const dir = path.resolve(ctx.docsRoot, docId);
617
- if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
618
- return dir;
619
- }
620
- function resolveEntry(ctx, docId) {
621
- const dir = docDir(ctx, docId);
622
- for (const name of ENTRY_NAMES) {
623
- const file = path.join(dir, name);
624
- if (existsSync(file)) return file;
625
- }
626
- return null;
627
- }
628
- async function listDocIds$1(ctx) {
629
- try {
630
- return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
631
- } catch {
632
- return [];
633
- }
634
- }
635
- /** Reads what the doc declares without executing it — a regex over `export const meta`. */
636
- function readMetaField(source, field) {
637
- const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
638
- return source.slice(source.indexOf("export const meta")).match(re)?.[2];
639
- }
640
- async function listDocuments(ctx) {
641
- const ids = await listDocIds$1(ctx);
642
- const manifest = await readManifest(ctx.manifestPath);
643
- const out = [];
644
- for (const id of ids) {
645
- const entry = resolveEntry(ctx, id);
646
- const source = entry ? await fs.readFile(entry, "utf8") : "";
647
- out.push({
648
- id,
649
- title: source ? readMetaTitle(source) : null,
650
- subtitle: source ? readMetaField(source, "subtitle") : void 0,
651
- theme: source ? readMetaField(source, "theme") : void 0,
652
- createdAt: source ? readMetaField(source, "createdAt") : void 0,
653
- folder: manifest.assignments[id],
654
- entry: entry ? path.relative(ctx.userCwd, entry) : null
655
- });
656
- }
657
- return out;
658
- }
659
- async function readDocument(ctx, docId) {
660
- const entry = resolveEntry(ctx, docId);
661
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
662
- return {
663
- id: docId,
664
- entry: path.relative(ctx.userCwd, entry),
665
- source: await fs.readFile(entry, "utf8")
490
+ const originRaw = headerValue(req, "origin");
491
+ if (!originRaw) return { ok: true };
492
+ if (originRaw.toLowerCase() === "null") return {
493
+ ok: false,
494
+ status: 403,
495
+ error: "opaque origin is not allowed"
666
496
  };
667
- }
668
- async function createDocument(ctx, docId, source) {
669
- const dir = docDir(ctx, docId);
670
- if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
671
- await fs.mkdir(dir, { recursive: true });
672
- const entry = path.join(dir, "index.tsx");
673
- await fs.writeFile(entry, source, "utf8");
674
- return {
675
- id: docId,
676
- entry: path.relative(ctx.userCwd, entry)
497
+ const actualOrigin = normalizedOrigin(originRaw);
498
+ if (!actualOrigin) return {
499
+ ok: false,
500
+ status: 403,
501
+ error: "invalid origin header"
677
502
  };
678
- }
679
- /**
680
- * Whole-file overwrite. `expected` is the source the caller believes is on
681
- * disk; passing it turns a blind overwrite into a conflict check, which is what
682
- * keeps two agents (or an agent and a person) from clobbering each other.
683
- */
684
- async function writeDocument(ctx, docId, source, expected) {
685
- const entry = resolveEntry(ctx, docId);
686
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
687
- if (expected !== void 0) {
688
- if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
689
- }
690
- await fs.writeFile(entry, source, "utf8");
691
- return {
692
- id: docId,
693
- entry: path.relative(ctx.userCwd, entry)
503
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
504
+ if (!host) return {
505
+ ok: false,
506
+ status: 400,
507
+ error: "missing host header"
694
508
  };
695
- }
696
- async function renameDocument(ctx, docId, rawTitle) {
697
- const title = validateDocTitle(rawTitle);
698
- if (!title) throw new OpsError(400, "invalid title");
699
- const entry = resolveEntry(ctx, docId);
700
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
701
- const source = await fs.readFile(entry, "utf8");
702
- const next = setMetaTitle(source, title);
703
- if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
704
- if (next !== source) await fs.writeFile(entry, next, "utf8");
705
- return {
706
- id: docId,
707
- title
509
+ if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
510
+ ok: false,
511
+ status: 403,
512
+ error: "origin mismatch"
708
513
  };
514
+ return { ok: true };
709
515
  }
710
- async function duplicateDocument(ctx, docId, newId) {
711
- const dir = docDir(ctx, docId);
712
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
713
- const taken = new Set(await listDocIds$1(ctx));
714
- let targetId;
715
- if (newId) {
716
- if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
717
- if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
718
- targetId = newId;
719
- } else targetId = nextCopyId(docId, taken);
720
- await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
721
- const entry = resolveEntry(ctx, targetId);
722
- if (entry) {
723
- const source = await fs.readFile(entry, "utf8");
724
- const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
725
- if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
726
- }
727
- const manifest = await readManifest(ctx.manifestPath);
728
- const folderId = manifest.assignments[docId];
729
- if (folderId) {
730
- manifest.assignments[targetId] = folderId;
731
- await writeManifest(ctx.manifestPath, manifest);
516
+ //#endregion
517
+ //#region src/vite/routes/assets.ts
518
+ async function listDocIds$1(docsRoot) {
519
+ try {
520
+ return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
521
+ } catch {
522
+ return [];
732
523
  }
733
- return { id: targetId };
734
524
  }
735
- async function deleteDocument(ctx, docId) {
736
- const dir = docDir(ctx, docId);
737
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
738
- await fs.rm(dir, {
739
- recursive: true,
740
- force: true
741
- });
742
- const manifest = await readManifest(ctx.manifestPath);
743
- if (manifest.assignments[docId]) {
744
- delete manifest.assignments[docId];
745
- await writeManifest(ctx.manifestPath, manifest);
746
- }
747
- }
748
- //#endregion
749
- //#region src/files/assets.ts
750
- const GLOBAL_SCOPE = "@global";
751
- const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
752
- const MIME_BY_EXT = {
753
- png: "image/png",
754
- jpg: "image/jpeg",
755
- jpeg: "image/jpeg",
756
- gif: "image/gif",
757
- svg: "image/svg+xml",
758
- webp: "image/webp",
759
- avif: "image/avif",
760
- ico: "image/x-icon",
761
- pdf: "application/pdf",
762
- woff: "font/woff",
763
- woff2: "font/woff2",
764
- ttf: "font/ttf",
765
- otf: "font/otf",
766
- csv: "text/csv; charset=utf-8",
767
- json: "application/json",
768
- txt: "text/plain; charset=utf-8",
769
- md: "text/markdown; charset=utf-8"
770
- };
771
- function mimeForFilename(name) {
772
- const dot = name.lastIndexOf(".");
773
- if (dot < 0) return "application/octet-stream";
774
- return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
775
- }
776
- function assetCreatedAt(birthtimeMs, mtimeMs) {
777
- return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
778
- }
779
- function validateAssetName(v) {
780
- if (typeof v !== "string") return null;
781
- const trimmed = v.trim();
782
- if (trimmed.length < 1 || trimmed.length > 120) return null;
783
- if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
784
- if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
785
- if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
786
- const dot = trimmed.lastIndexOf(".");
787
- if (dot <= 0 || dot === trimmed.length - 1) return null;
788
- return trimmed;
789
- }
790
- function resolveAssetsDir(docsRoot, docId) {
791
- if (!DOC_ID_RE.test(docId)) return null;
792
- const docDir = path.resolve(docsRoot, docId);
793
- if (!docDir.startsWith(docsRoot + path.sep)) return null;
794
- const assetsDir = path.resolve(docDir, "assets");
795
- if (assetsDir !== path.join(docDir, "assets")) return null;
796
- return assetsDir;
797
- }
798
- function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
799
- if (scope === "@global") return globalAssetsRoot;
800
- return resolveAssetsDir(docsRoot, scope);
801
- }
802
- function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
803
- if (!validateAssetName(filename)) return null;
804
- const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
805
- if (!dir) return null;
806
- const file = path.resolve(dir, filename);
807
- if (!file.startsWith(dir + path.sep)) return null;
808
- return file;
809
- }
810
- /** How a document imports an asset — the string we look for when counting usages. */
811
- function assetImportPath(scope, filename) {
812
- return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
813
- }
814
- function escapeRegExp(value) {
815
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
816
- }
817
- /**
818
- * Counts references to an asset in a document's source. Matches the quoted path
819
- * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
820
- * which is every form the authoring skill sanctions.
821
- */
822
- function countAssetUsages(source, importPath) {
823
- const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
824
- return source.match(quoted)?.length ?? 0;
825
- }
826
- function findReferencedAssets(source, importPaths) {
827
- return importPaths.filter((p) => countAssetUsages(source, p) > 0);
828
- }
829
- //#endregion
830
- //#region src/http/request-guard.ts
831
- function firstHeaderValue(value) {
832
- if (Array.isArray(value)) return value[0] ?? null;
833
- return value ?? null;
834
- }
835
- function headerValue(req, name) {
836
- return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
837
- }
838
- function firstCommaToken(value) {
839
- if (!value) return null;
840
- const [first] = value.split(",", 1);
841
- return first?.trim() || null;
842
- }
843
- function requestProto(req) {
844
- const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
845
- if (forwarded === "http" || forwarded === "https") return forwarded;
846
- return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
847
- }
848
- function normalizedOrigin(origin) {
849
- try {
850
- const url = new URL(origin);
851
- return `${url.protocol}//${url.host}`.toLowerCase();
852
- } catch {
853
- return null;
854
- }
855
- }
856
- /**
857
- * The dev server writes to the user's filesystem, so every mutating endpoint is
858
- * guarded against a page on another origin driving it through the browser.
859
- */
860
- function validateMutationRequest(req, opts = {}) {
861
- if (opts.requireJsonBody) {
862
- if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
863
- ok: false,
864
- status: 415,
865
- error: "content-type must be application/json"
866
- };
867
- }
868
- if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
869
- ok: false,
870
- status: 403,
871
- error: "cross-site request blocked"
872
- };
873
- const originRaw = headerValue(req, "origin");
874
- if (!originRaw) return { ok: true };
875
- if (originRaw.toLowerCase() === "null") return {
876
- ok: false,
877
- status: 403,
878
- error: "opaque origin is not allowed"
879
- };
880
- const actualOrigin = normalizedOrigin(originRaw);
881
- if (!actualOrigin) return {
882
- ok: false,
883
- status: 403,
884
- error: "invalid origin header"
885
- };
886
- const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
887
- if (!host) return {
888
- ok: false,
889
- status: 400,
890
- error: "missing host header"
891
- };
892
- if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
893
- ok: false,
894
- status: 403,
895
- error: "origin mismatch"
896
- };
897
- return { ok: true };
898
- }
899
- //#endregion
900
- //#region src/vite/routes/assets.ts
901
- async function listDocIds(docsRoot) {
902
- try {
903
- return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
904
- } catch {
905
- return [];
906
- }
907
- }
908
- async function readDocSource(docsRoot, docId) {
909
- const entry = resolveDocEntry(docsRoot, docId);
910
- if (!entry) return null;
911
- try {
912
- return await fs.readFile(entry, "utf8");
913
- } catch {
914
- return null;
525
+ async function readDocSource(docsRoot, docId) {
526
+ const entry = resolveDocEntry(docsRoot, docId);
527
+ if (!entry) return null;
528
+ try {
529
+ return await fs.readFile(entry, "utf8");
530
+ } catch {
531
+ return null;
915
532
  }
916
533
  }
917
534
  function registerAssetRoutes(server, ctx) {
@@ -929,7 +546,7 @@ function registerAssetRoutes(server, ctx) {
929
546
  const isGlobal = scope === GLOBAL_SCOPE;
930
547
  if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
931
548
  const importPath = assetImportPath(scope, filename);
932
- const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
549
+ const docIds = isGlobal ? await listDocIds$1(ctx.docsRoot) : [scope];
933
550
  const usages = [];
934
551
  let totalCount = 0;
935
552
  for (const docId of docIds) {
@@ -978,7 +595,7 @@ function registerAssetRoutes(server, ctx) {
978
595
  }
979
596
  assets.sort((a, b) => a.name.localeCompare(b.name));
980
597
  if (assets.length > 0) {
981
- const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
598
+ const scanIds = scope === "@global" ? await listDocIds$1(ctx.docsRoot) : [scope];
982
599
  const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
983
600
  const paths = assets.map((a) => a.importPath);
984
601
  for (const docId of scanIds) {
@@ -1097,6 +714,401 @@ function registerAssetRoutes(server, ctx) {
1097
714
  });
1098
715
  }
1099
716
  //#endregion
717
+ //#region src/editing/babel-walk.ts
718
+ function parseSource(code) {
719
+ try {
720
+ return parse(code, {
721
+ sourceType: "module",
722
+ plugins: ["typescript", "jsx"],
723
+ errorRecovery: true
724
+ });
725
+ } catch {
726
+ return null;
727
+ }
728
+ }
729
+ /**
730
+ * `parseSource`, but a source with any recovered error is refused. Reading
731
+ * tolerates a document mid-edit; writing splices text in by AST offset, and a
732
+ * best-guess tree recovered from a syntax error must never decide where.
733
+ */
734
+ function parseStrict(code) {
735
+ const ast = parseSource(code);
736
+ if (!ast) return null;
737
+ return ast.errors && ast.errors.length > 0 ? null : ast;
738
+ }
739
+ function isNode(value) {
740
+ return typeof value === "object" && value !== null && typeof value.type === "string";
741
+ }
742
+ /** Depth-first walk over every node; the visitor decides what it cares about. */
743
+ function walkAst(node, visit) {
744
+ if (Array.isArray(node)) {
745
+ for (const child of node) walkAst(child, visit);
746
+ return;
747
+ }
748
+ if (!isNode(node)) return;
749
+ visit(node);
750
+ for (const key of Object.keys(node)) {
751
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
752
+ walkAst(node[key], visit);
753
+ }
754
+ }
755
+ function walkJsx(ast, visit) {
756
+ walkAst(ast, (node) => {
757
+ if (node.type === "JSXElement") visit(node);
758
+ });
759
+ }
760
+ /**
761
+ * The JSX element whose opening tag starts at this source position.
762
+ *
763
+ * The match is exact on both line and column. Anything looser can resolve to a
764
+ * different element on the same line, and this location decides where an edit
765
+ * gets written — a near miss silently rewrites the wrong text.
766
+ */
767
+ function findJsxAt(ast, line, column) {
768
+ let found = null;
769
+ walkJsx(ast, (node) => {
770
+ if (found) return;
771
+ const start = node.loc?.start;
772
+ if (start && start.line === line && start.column === column) found = node;
773
+ });
774
+ return found;
775
+ }
776
+ /**
777
+ * Every JSX element that starts on a line, nearest column first.
778
+ *
779
+ * Columns cannot be trusted for locations derived from React's `_debugSource`:
780
+ * injecting the loc attribute shifts the columns of anything later on the same
781
+ * line, so the offset differs per element. The line survives that, so callers
782
+ * scan the line and pick by content instead.
783
+ */
784
+ function findJsxOnLine(ast, line, column) {
785
+ const hits = [];
786
+ walkJsx(ast, (node) => {
787
+ const start = node.loc?.start;
788
+ if (!start || start.line !== line) return;
789
+ hits.push({
790
+ node,
791
+ distance: Math.abs(start.column - column)
792
+ });
793
+ });
794
+ return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
795
+ }
796
+ //#endregion
797
+ //#region src/editing/doc-ops.ts
798
+ function programBody$1(ast) {
799
+ return ast.program?.body ?? [];
800
+ }
801
+ function metaObjectOf(node) {
802
+ if (node.type !== "ExportNamedDeclaration") return null;
803
+ const decl = node.declaration;
804
+ if (decl?.type !== "VariableDeclaration") return null;
805
+ const declarations = decl.declarations ?? [];
806
+ for (const d of declarations) {
807
+ const id = d.id;
808
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
809
+ let init = d.init;
810
+ if (!init) return null;
811
+ if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
812
+ const expr = init.expression;
813
+ if (expr) init = expr;
814
+ }
815
+ return init.type === "ObjectExpression" ? init : null;
816
+ }
817
+ return null;
818
+ }
819
+ function findMetaObject(ast) {
820
+ for (const node of programBody$1(ast)) {
821
+ const object = metaObjectOf(node);
822
+ if (object) return object;
823
+ }
824
+ return null;
825
+ }
826
+ function jsString$1(value) {
827
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
828
+ }
829
+ function validateDocTitle(v) {
830
+ if (typeof v !== "string") return null;
831
+ const trimmed = v.trim();
832
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
833
+ return trimmed;
834
+ }
835
+ /**
836
+ * Rewrites `meta.title` in place, adding the property when the meta object
837
+ * exists without one. Returns null when there is no meta object to edit —
838
+ * the caller reports that rather than inventing an export.
839
+ */
840
+ function setMetaTitle(source, title) {
841
+ const ast = parseStrict(source);
842
+ if (!ast) return null;
843
+ const object = findMetaObject(ast);
844
+ if (!object) return null;
845
+ const properties = object.properties ?? [];
846
+ for (const prop of properties) {
847
+ if (prop.type !== "ObjectProperty") continue;
848
+ const p = prop;
849
+ if (p.computed) continue;
850
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
851
+ return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
852
+ }
853
+ const open = object.start + 1;
854
+ const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
855
+ return source.slice(0, open) + inserted + source.slice(open);
856
+ }
857
+ function readMetaTitle(source) {
858
+ const ast = parseSource(source);
859
+ if (!ast) return null;
860
+ const object = findMetaObject(ast);
861
+ if (!object) return null;
862
+ const properties = object.properties ?? [];
863
+ for (const prop of properties) {
864
+ if (prop.type !== "ObjectProperty") continue;
865
+ const p = prop;
866
+ if (p.computed) continue;
867
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
868
+ if (p.value.type !== "StringLiteral") return null;
869
+ return typeof p.value.value === "string" ? p.value.value : null;
870
+ }
871
+ return null;
872
+ }
873
+ /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
874
+ function nextCopyId(baseId, taken) {
875
+ const stem = baseId.replace(/-copy(-\d+)?$/, "");
876
+ let candidate = `${stem}-copy`;
877
+ let n = 2;
878
+ while (taken.has(candidate)) {
879
+ candidate = `${stem}-copy-${n}`;
880
+ n++;
881
+ }
882
+ return candidate;
883
+ }
884
+ function copyTitle(title) {
885
+ return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
886
+ }
887
+ //#endregion
888
+ //#region src/files/folders.ts
889
+ const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
890
+ const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
891
+ function emptyManifest() {
892
+ return {
893
+ folders: [],
894
+ assignments: {}
895
+ };
896
+ }
897
+ async function readManifest(file) {
898
+ try {
899
+ const raw = await fs.readFile(file, "utf8");
900
+ const parsed = JSON.parse(raw);
901
+ return {
902
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
903
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
904
+ };
905
+ } catch (err) {
906
+ if (err.code === "ENOENT") return emptyManifest();
907
+ throw err;
908
+ }
909
+ }
910
+ async function writeManifest(file, manifest) {
911
+ await fs.mkdir(path.dirname(file), { recursive: true });
912
+ await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
913
+ }
914
+ function newFolderId() {
915
+ return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
916
+ }
917
+ function validateName(v) {
918
+ if (typeof v !== "string") return null;
919
+ const trimmed = v.trim();
920
+ if (trimmed.length < 1 || trimmed.length > 40) return null;
921
+ return trimmed;
922
+ }
923
+ function validateReorder(v, current) {
924
+ if (!Array.isArray(v) || v.length !== current.length) return null;
925
+ const known = new Set(current.map((f) => f.id));
926
+ const seen = /* @__PURE__ */ new Set();
927
+ const out = [];
928
+ for (const id of v) {
929
+ if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
930
+ if (!known.has(id) || seen.has(id)) return null;
931
+ seen.add(id);
932
+ out.push(id);
933
+ }
934
+ return out;
935
+ }
936
+ function validateIcon(v) {
937
+ if (!v || typeof v !== "object") return null;
938
+ const icon = v;
939
+ if (icon.type === "emoji") {
940
+ if (typeof icon.value !== "string") return null;
941
+ if (icon.value.length < 1 || icon.value.length > 8) return null;
942
+ return {
943
+ type: "emoji",
944
+ value: icon.value
945
+ };
946
+ }
947
+ if (icon.type === "color") {
948
+ if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
949
+ return {
950
+ type: "color",
951
+ value: icon.value
952
+ };
953
+ }
954
+ return null;
955
+ }
956
+ //#endregion
957
+ //#region src/ops/documents.ts
958
+ /**
959
+ * Operations shared by the dev API and the MCP server. Everything here takes an
960
+ * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
961
+ * and a browser calling `/__docs` end up in exactly the same code.
962
+ */
963
+ var OpsError = class extends Error {
964
+ status;
965
+ constructor(status, message) {
966
+ super(message);
967
+ this.status = status;
968
+ this.name = "OpsError";
969
+ }
970
+ };
971
+ const ENTRY_NAMES = [
972
+ "index.tsx",
973
+ "index.jsx",
974
+ "index.ts",
975
+ "index.js"
976
+ ];
977
+ function docDir(ctx, docId) {
978
+ if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
979
+ const dir = path.resolve(ctx.docsRoot, docId);
980
+ if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
981
+ return dir;
982
+ }
983
+ function resolveEntry(ctx, docId) {
984
+ const dir = docDir(ctx, docId);
985
+ for (const name of ENTRY_NAMES) {
986
+ const file = path.join(dir, name);
987
+ if (existsSync(file)) return file;
988
+ }
989
+ return null;
990
+ }
991
+ async function listDocIds(ctx) {
992
+ try {
993
+ return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
994
+ } catch {
995
+ return [];
996
+ }
997
+ }
998
+ /** Reads what the doc declares without executing it — a regex over `export const meta`. */
999
+ function readMetaField(source, field) {
1000
+ const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
1001
+ return source.slice(source.indexOf("export const meta")).match(re)?.[2];
1002
+ }
1003
+ async function listDocuments(ctx) {
1004
+ const ids = await listDocIds(ctx);
1005
+ const manifest = await readManifest(ctx.manifestPath);
1006
+ const out = [];
1007
+ for (const id of ids) {
1008
+ const entry = resolveEntry(ctx, id);
1009
+ const source = entry ? await fs.readFile(entry, "utf8") : "";
1010
+ out.push({
1011
+ id,
1012
+ title: source ? readMetaTitle(source) : null,
1013
+ subtitle: source ? readMetaField(source, "subtitle") : void 0,
1014
+ theme: source ? readMetaField(source, "theme") : void 0,
1015
+ createdAt: source ? readMetaField(source, "createdAt") : void 0,
1016
+ folder: manifest.assignments[id],
1017
+ entry: entry ? path.relative(ctx.userCwd, entry) : null
1018
+ });
1019
+ }
1020
+ return out;
1021
+ }
1022
+ async function readDocument(ctx, docId) {
1023
+ const entry = resolveEntry(ctx, docId);
1024
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1025
+ return {
1026
+ id: docId,
1027
+ entry: path.relative(ctx.userCwd, entry),
1028
+ source: await fs.readFile(entry, "utf8")
1029
+ };
1030
+ }
1031
+ async function createDocument(ctx, docId, source) {
1032
+ const dir = docDir(ctx, docId);
1033
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
1034
+ await fs.mkdir(dir, { recursive: true });
1035
+ const entry = path.join(dir, "index.tsx");
1036
+ await fs.writeFile(entry, source, "utf8");
1037
+ return {
1038
+ id: docId,
1039
+ entry: path.relative(ctx.userCwd, entry)
1040
+ };
1041
+ }
1042
+ /**
1043
+ * Whole-file overwrite. `expected` is the source the caller believes is on
1044
+ * disk; passing it turns a blind overwrite into a conflict check, which is what
1045
+ * keeps two agents (or an agent and a person) from clobbering each other.
1046
+ */
1047
+ async function writeDocument(ctx, docId, source, expected) {
1048
+ const entry = resolveEntry(ctx, docId);
1049
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1050
+ if (expected !== void 0) {
1051
+ if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
1052
+ }
1053
+ await fs.writeFile(entry, source, "utf8");
1054
+ return {
1055
+ id: docId,
1056
+ entry: path.relative(ctx.userCwd, entry)
1057
+ };
1058
+ }
1059
+ async function renameDocument(ctx, docId, rawTitle) {
1060
+ const title = validateDocTitle(rawTitle);
1061
+ if (!title) throw new OpsError(400, "invalid title");
1062
+ const entry = resolveEntry(ctx, docId);
1063
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1064
+ const source = await fs.readFile(entry, "utf8");
1065
+ const next = setMetaTitle(source, title);
1066
+ if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
1067
+ if (next !== source) await fs.writeFile(entry, next, "utf8");
1068
+ return {
1069
+ id: docId,
1070
+ title
1071
+ };
1072
+ }
1073
+ async function duplicateDocument(ctx, docId, newId) {
1074
+ const dir = docDir(ctx, docId);
1075
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
1076
+ const taken = new Set(await listDocIds(ctx));
1077
+ let targetId;
1078
+ if (newId) {
1079
+ if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
1080
+ if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
1081
+ targetId = newId;
1082
+ } else targetId = nextCopyId(docId, taken);
1083
+ await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
1084
+ const entry = resolveEntry(ctx, targetId);
1085
+ if (entry) {
1086
+ const source = await fs.readFile(entry, "utf8");
1087
+ const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
1088
+ if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
1089
+ }
1090
+ const manifest = await readManifest(ctx.manifestPath);
1091
+ const folderId = manifest.assignments[docId];
1092
+ if (folderId) {
1093
+ manifest.assignments[targetId] = folderId;
1094
+ await writeManifest(ctx.manifestPath, manifest);
1095
+ }
1096
+ return { id: targetId };
1097
+ }
1098
+ async function deleteDocument(ctx, docId) {
1099
+ const dir = docDir(ctx, docId);
1100
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
1101
+ await fs.rm(dir, {
1102
+ recursive: true,
1103
+ force: true
1104
+ });
1105
+ const manifest = await readManifest(ctx.manifestPath);
1106
+ if (manifest.assignments[docId]) {
1107
+ delete manifest.assignments[docId];
1108
+ await writeManifest(ctx.manifestPath, manifest);
1109
+ }
1110
+ }
1111
+ //#endregion
1100
1112
  //#region src/vite/routes/docs.ts
1101
1113
  function registerDocRoutes(server, ctx) {
1102
1114
  server.middlewares.use("/__docs", async (req, res, next) => {
@@ -3198,4 +3210,4 @@ async function createViteConfig(opts) {
3198
3210
  };
3199
3211
  }
3200
3212
  //#endregion
3201
- export { loadUserConfig as A, newFolderId as C, writeManifest as D, validateName as E, makeContext as O, writeDocument as S, validateIcon as T, listDocIds$1 as _, writeText as a, renameDocument as b, countAssetUsages as c, validateAssetName as d, OpsError as f, duplicateDocument as g, docDir as h, readText as i, openDocPlugin as j, DOC_ID_RE as k, resolveScopedAssetFile as l, deleteDocument as m, parseFrontmatter as n, writeTexts as o, createDocument as p, addComment as r, assetImportPath as s, createViteConfig as t, resolveScopedAssetsDir as u, listDocuments as v, readManifest as w, resolveEntry as x, readDocument as y };
3213
+ export { loadUserConfig as A, assetImportPath as C, validateAssetName as D, resolveScopedAssetsDir as E, makeContext as O, writeManifest as S, resolveScopedAssetFile as T, writeDocument as _, writeText as a, validateIcon as b, createDocument as c, duplicateDocument as d, listDocIds as f, resolveEntry as g, renameDocument as h, readText as i, openDocPlugin as j, DOC_ID_RE as k, deleteDocument as l, readDocument as m, parseFrontmatter as n, writeTexts as o, listDocuments as p, addComment as r, OpsError as s, createViteConfig as t, docDir as u, newFolderId as v, countAssetUsages as w, validateName as x, readManifest as y };