@open-document/core 0.12.0 → 0.13.1

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 (48) hide show
  1. package/dist/{build-DfUfpeTR.js → build-CvsOak5B.js} +1 -1
  2. package/dist/{check-CHxiOkQG.js → check-CbUBwYmf.js} +3 -3
  3. package/dist/cli/bin.js +47 -10
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-9IdbhVuT.js → config-CltJJVsw.js} +398 -493
  6. package/dist/{context-BLI1-64_.js → context-CWgfsHoE.js} +2 -1
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-yNYKv5mm.js → dev-B8H2qT6G.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-Bs205mOx.js → diff-BvIjjgnc.js} +2 -2
  11. package/dist/{export-tkquS5O5.js → export-DX30_s2q.js} +3 -3
  12. package/dist/{sdk-CHEGeINh.d.ts → flow-CS5apebG.d.ts} +72 -3
  13. package/dist/{import-D1hIKIr3.js → import-DgsdJT5e.js} +2 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +896 -90
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +98 -13
  18. package/dist/ops/index.js +3 -3
  19. package/dist/{ops-Dgqujq5a.js → ops-CSR5RlrE.js} +2 -1
  20. package/dist/{preview-BImdTH6K.js → preview-DYMUNjXL.js} +1 -1
  21. package/dist/{templates-DT5zzqHq.js → templates-B5Tz0AKb.js} +3 -3
  22. package/dist/vite/index.d.ts +1 -1
  23. package/dist/vite/index.js +2 -1
  24. package/package.json +1 -1
  25. package/skills/doc-authoring/SKILL.md +15 -16
  26. package/skills/doc-authoring/references/long-form.md +43 -2
  27. package/skills/doc-authoring/references/pagination.md +14 -2
  28. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  29. package/src/app/components/callout.tsx +101 -0
  30. package/src/app/components/chart.tsx +191 -33
  31. package/src/app/components/code-block.tsx +249 -0
  32. package/src/app/components/data-table.tsx +146 -18
  33. package/src/app/components/flow-page.tsx +57 -8
  34. package/src/app/components/numbering.tsx +226 -12
  35. package/src/app/components/page-frame.tsx +42 -0
  36. package/src/app/lib/chart.test.ts +15 -0
  37. package/src/app/lib/chart.ts +134 -9
  38. package/src/app/lib/diagnostics.ts +45 -1
  39. package/src/app/lib/export-dom.ts +15 -2
  40. package/src/app/lib/export-pdf.ts +9 -1
  41. package/src/app/lib/flow-measure.ts +33 -4
  42. package/src/app/lib/flow.test.ts +20 -1
  43. package/src/app/lib/flow.ts +120 -20
  44. package/src/app/lib/labels.ts +29 -10
  45. package/src/app/lib/sdk.ts +6 -0
  46. package/src/app/lib/use-doc-pages.ts +23 -8
  47. package/src/app/routes/doc.tsx +1 -0
  48. package/dist/config-P61niZMf.d.ts +0 -24
@@ -1,318 +1,19 @@
1
- import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
1
+ import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-CKf3ptOE.js";
2
2
  import { t as corePackageRoot } from "./package-version-C89gtYSk.js";
3
+ import { n as loadUserConfig, r as openDocPlugin, t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
4
  import chalk from "chalk";
4
5
  import path from "node:path";
5
6
  import { fileURLToPath, pathToFileURL } from "node:url";
6
7
  import fs from "node:fs/promises";
7
- import { existsSync, readFileSync } from "node:fs";
8
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
8
9
  import fg from "fast-glob";
9
- import { loadConfigFromFile, normalizePath } from "vite";
10
+ import { normalizePath } from "vite";
10
11
  import { execFile } from "node:child_process";
11
12
  import { promisify } from "node:util";
12
13
  import { parse } from "@babel/parser";
13
14
  import { createHash, randomUUID } from "node:crypto";
14
15
  import tailwindcss from "@tailwindcss/vite";
15
16
  import react from "@vitejs/plugin-react";
16
- //#region src/vite/open-doc-plugin.ts
17
- const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
18
- const CONFIG_FILE = "open-doc.config.ts";
19
- const DOCS_VMOD = "virtual:open-doc/docs";
20
- const CONFIG_VMOD = "virtual:open-doc/config";
21
- const FOLDERS_VMOD = "virtual:open-doc/folders";
22
- async function readFoldersManifest(file) {
23
- try {
24
- const parsed = JSON.parse(await fs.readFile(file, "utf8"));
25
- return {
26
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
27
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
28
- };
29
- } catch (err) {
30
- if (err.code === "ENOENT") return {
31
- folders: [],
32
- assignments: {}
33
- };
34
- throw err;
35
- }
36
- }
37
- function resolved$1(id) {
38
- return `\0${id}`;
39
- }
40
- async function findDocs(userCwd, docsDir) {
41
- const abs = path.resolve(userCwd, docsDir);
42
- if (!existsSync(abs)) return [];
43
- return (await fg("*/index.{tsx,jsx,ts,js}", {
44
- cwd: abs,
45
- absolute: true,
46
- onlyFiles: true
47
- })).sort();
48
- }
49
- function toId(absFile, docsRoot) {
50
- return path.relative(docsRoot, absFile).split(path.sep)[0];
51
- }
52
- const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
53
- const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
54
- const META_TITLE_RE = /(?:^|[\s,{])title\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/;
55
- /**
56
- * Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
57
- * every discovery pass, and the fields it needs (sort order, theme back-link,
58
- * the title search and sorting use without loading every document) are
59
- * contractually string literals.
60
- */
61
- function extractMeta(src) {
62
- const empty = {
63
- theme: null,
64
- createdAt: null,
65
- title: null
66
- };
67
- const metaStart = src.search(/export\s+const\s+meta\b/);
68
- if (metaStart === -1) return empty;
69
- const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
70
- if (openBrace === -1) return empty;
71
- let depth = 0;
72
- let closeBrace = -1;
73
- for (let i = openBrace; i < src.length; i++) {
74
- const ch = src[i];
75
- if (ch === "{") depth++;
76
- else if (ch === "}") {
77
- depth--;
78
- if (depth === 0) {
79
- closeBrace = i;
80
- break;
81
- }
82
- }
83
- }
84
- if (closeBrace === -1) return empty;
85
- const body = src.slice(openBrace + 1, closeBrace);
86
- return {
87
- theme: body.match(META_THEME_RE)?.[1] ?? null,
88
- createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null,
89
- title: unescapeLiteral(body.match(META_TITLE_RE)?.[2] ?? null)
90
- };
91
- }
92
- function unescapeLiteral(raw) {
93
- return raw === null ? null : raw.replace(/\\(.)/g, "$1");
94
- }
95
- function parseCreatedAtMs(iso) {
96
- if (!iso) return null;
97
- const ms = Date.parse(iso);
98
- return Number.isFinite(ms) ? ms : null;
99
- }
100
- async function readMeta(abs) {
101
- try {
102
- return extractMeta(await fs.readFile(abs, "utf8"));
103
- } catch {
104
- return {
105
- theme: null,
106
- createdAt: null,
107
- title: null
108
- };
109
- }
110
- }
111
- const warnedInvalidDocIds = /* @__PURE__ */ new Set();
112
- async function generateDocsModule(files, docsRoot, isDev) {
113
- const scanned = await Promise.all(files.map(async (abs) => {
114
- const meta = await readMeta(abs);
115
- return {
116
- id: toId(abs, docsRoot),
117
- importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
118
- theme: meta.theme,
119
- title: meta.title,
120
- createdAt: parseCreatedAtMs(meta.createdAt)
121
- };
122
- }));
123
- const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
124
- const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
125
- const ids = JSON.stringify(entries.map((e) => e.id).sort());
126
- const createdAtMap = {};
127
- const themesMap = {};
128
- const titlesMap = {};
129
- for (const e of entries) {
130
- if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
131
- if (e.theme) themesMap[e.id] = e.theme;
132
- if (e.title) titlesMap[e.id] = e.title;
133
- }
134
- const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
135
- const devRuntime = isDev ? `
136
- const docImportTokens = ${importTokens};
137
- if (import.meta.hot) {
138
- import.meta.hot.on('open-doc:doc-changed', (data) => {
139
- const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
140
- const token = Date.now();
141
- for (const id of ids) {
142
- if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
143
- }
144
- });
145
- }
146
- ` : "";
147
- const cases = entries.map((e) => {
148
- 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)})`;
149
- return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
150
- }).join("\n");
151
- return {
152
- code: `// virtual:open-doc/docs — generated
153
- export const docIds = ${ids};
154
- export const docCreatedAt = ${JSON.stringify(createdAtMap)};
155
- export const docThemes = ${JSON.stringify(themesMap)};
156
- export const docTitles = ${JSON.stringify(titlesMap)};
157
- ${devRuntime}
158
-
159
- export async function loadDoc(id) {
160
- switch (id) {
161
- ${cases}
162
- default: throw new Error('Document not found: ' + id);
163
- }
164
- }
165
- `,
166
- ignored
167
- };
168
- }
169
- function openDocPlugin(opts) {
170
- const { userCwd, config, coreVersion } = opts;
171
- const docsDir = config.docsDir ?? "docs";
172
- const docsRoot = path.resolve(userCwd, docsDir);
173
- const foldersManifestPath = path.join(docsRoot, ".folders.json");
174
- let isDev = false;
175
- let listedIds = "";
176
- const docIdForEntry = (p) => {
177
- const rel = path.relative(docsRoot, p);
178
- if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
179
- const parts = rel.split(path.sep);
180
- if (parts.length !== 2) return null;
181
- if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
182
- return parts[0];
183
- };
184
- let docChangeTimer = null;
185
- const pendingDocChanges = /* @__PURE__ */ new Set();
186
- const queueDocChanged = (server, id) => {
187
- pendingDocChanges.add(id);
188
- if (docChangeTimer) clearTimeout(docChangeTimer);
189
- docChangeTimer = setTimeout(() => {
190
- docChangeTimer = null;
191
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
192
- if (mod) server.moduleGraph.invalidateModule(mod);
193
- const docIds = Array.from(pendingDocChanges);
194
- pendingDocChanges.clear();
195
- server.ws.send({
196
- type: "custom",
197
- event: "open-doc:doc-changed",
198
- data: { docIds }
199
- });
200
- }, 100);
201
- };
202
- return {
203
- name: "open-doc",
204
- config(_c, env) {
205
- isDev = env.command === "serve";
206
- return { server: { fs: { allow: [userCwd] } } };
207
- },
208
- resolveId(id) {
209
- if (id === DOCS_VMOD) return resolved$1(DOCS_VMOD);
210
- if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
211
- if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
212
- return null;
213
- },
214
- async load(id) {
215
- if (id === resolved$1(DOCS_VMOD)) {
216
- const files = await findDocs(userCwd, docsDir);
217
- listedIds = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort());
218
- const { code, ignored } = await generateDocsModule(files, docsRoot, isDev);
219
- for (const docId of ignored) {
220
- if (warnedInvalidDocIds.has(docId)) continue;
221
- warnedInvalidDocIds.add(docId);
222
- 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.`);
223
- }
224
- return code;
225
- }
226
- if (id === resolved$1(CONFIG_VMOD)) {
227
- const userBuild = config.build ?? {};
228
- const build = isDev ? {
229
- showDocBrowser: true,
230
- allowHtmlExport: true
231
- } : {
232
- showDocBrowser: userBuild.showDocBrowser ?? true,
233
- allowHtmlExport: userBuild.allowHtmlExport ?? true
234
- };
235
- return `export default ${JSON.stringify({
236
- ...config,
237
- build,
238
- version: coreVersion
239
- })};\n`;
240
- }
241
- if (id === resolved$1(FOLDERS_VMOD)) {
242
- const manifest = await readFoldersManifest(foldersManifestPath);
243
- return `export default ${JSON.stringify(manifest)};\n`;
244
- }
245
- return null;
246
- },
247
- handleHotUpdate(ctx) {
248
- const docId = docIdForEntry(ctx.file);
249
- if (!docId) return;
250
- queueDocChanged(ctx.server, docId);
251
- return [];
252
- },
253
- configureServer(server) {
254
- const isDocEntry = (p) => docIdForEntry(p) !== null;
255
- let reloadTimer = null;
256
- const reload = () => {
257
- if (reloadTimer) clearTimeout(reloadTimer);
258
- reloadTimer = setTimeout(() => {
259
- reloadTimer = null;
260
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
261
- if (mod) server.moduleGraph.invalidateModule(mod);
262
- server.ws.send({ type: "full-reload" });
263
- }, 150);
264
- };
265
- server.watcher.add(docsRoot);
266
- server.watcher.on("add", (p) => {
267
- if (isDocEntry(p)) reload();
268
- });
269
- server.middlewares.use("/__docs-rescan", async (_req, res) => {
270
- const files = await findDocs(userCwd, docsDir);
271
- const changed = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort()) !== listedIds;
272
- if (changed) reload();
273
- res.setHeader("content-type", "application/json");
274
- res.end(JSON.stringify({ changed }));
275
- });
276
- server.watcher.on("unlink", (p) => {
277
- if (isDocEntry(p)) reload();
278
- });
279
- server.watcher.on("unlinkDir", (p) => {
280
- if (path.dirname(p) === docsRoot) reload();
281
- });
282
- let foldersTimer = null;
283
- const foldersChanged = () => {
284
- if (foldersTimer) clearTimeout(foldersTimer);
285
- foldersTimer = setTimeout(() => {
286
- foldersTimer = null;
287
- const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
288
- if (mod) server.moduleGraph.invalidateModule(mod);
289
- server.ws.send({
290
- type: "custom",
291
- event: "open-doc:files-changed",
292
- data: {}
293
- });
294
- }, 100);
295
- };
296
- server.watcher.add(foldersManifestPath);
297
- for (const event of [
298
- "add",
299
- "change",
300
- "unlink"
301
- ]) server.watcher.on(event, (p) => {
302
- if (p === foldersManifestPath) foldersChanged();
303
- });
304
- }
305
- };
306
- }
307
- async function loadUserConfig(userCwd) {
308
- const file = path.join(userCwd, CONFIG_FILE);
309
- if (!existsSync(file)) return {};
310
- return (await loadConfigFromFile({
311
- command: "serve",
312
- mode: "development"
313
- }, file, userCwd, "silent"))?.config ?? {};
314
- }
315
- //#endregion
316
17
  //#region src/vite/routes/context.ts
317
18
  function makeContext(opts) {
318
19
  const userCwd = opts.userCwd;
@@ -461,7 +162,9 @@ const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
461
162
  "ImagePlaceholder",
462
163
  "Figure",
463
164
  "DataTable",
464
- "Footnote"
165
+ "Footnote",
166
+ "CodeBlock",
167
+ "Callout"
465
168
  ]);
466
169
  function taggableName(opening) {
467
170
  const name = opening.name;
@@ -944,53 +647,67 @@ async function listDocuments(ctx) {
944
647
  async function readDocument(ctx, docId) {
945
648
  const entry = resolveEntry(ctx, docId);
946
649
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
650
+ const source = await fs.readFile(entry, "utf8");
947
651
  return {
948
652
  id: docId,
949
653
  entry: path.relative(ctx.userCwd, entry),
950
- source: await fs.readFile(entry, "utf8")
654
+ source,
655
+ hash: hashSource(source)
951
656
  };
952
657
  }
953
658
  async function createDocument(ctx, docId, source) {
954
659
  const dir = docDir(ctx, docId);
955
- if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
956
- await fs.mkdir(dir, { recursive: true });
957
660
  const entry = path.join(dir, "index.tsx");
958
- await fs.writeFile(entry, source, "utf8");
959
- return {
960
- id: docId,
961
- entry: path.relative(ctx.userCwd, entry)
962
- };
661
+ return withFileLock(entry, async () => {
662
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
663
+ await fs.mkdir(dir, { recursive: true });
664
+ await fs.writeFile(entry, source, "utf8");
665
+ return {
666
+ id: docId,
667
+ entry: path.relative(ctx.userCwd, entry),
668
+ hash: hashSource(source)
669
+ };
670
+ });
963
671
  }
964
672
  /**
965
- * Whole-file overwrite. `expected` is the source the caller believes is on
966
- * disk; passing it turns a blind overwrite into a conflict check, which is what
967
- * keeps two agents (or an agent and a person) from clobbering each other.
673
+ * Whole-file overwrite. `expected` (full source) or `expectedHash` (16-char
674
+ * SHA-256 digest from `readDocument`) turns a blind overwrite into an atomic
675
+ * conflict check inside a per-file write lock, keeping two agents (or an agent
676
+ * and a person on GCS FUSE) from clobbering each other.
968
677
  */
969
- async function writeDocument(ctx, docId, source, expected) {
678
+ async function writeDocument(ctx, docId, source, expected, expectedHash) {
970
679
  const entry = resolveEntry(ctx, docId);
971
680
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
972
- if (expected !== void 0) {
973
- if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
974
- }
975
- await fs.writeFile(entry, source, "utf8");
976
- return {
977
- id: docId,
978
- entry: path.relative(ctx.userCwd, entry)
979
- };
681
+ return withFileLock(entry, async () => {
682
+ if (expected !== void 0 || expectedHash !== void 0) assertExpectedSource(await fs.readFile(entry, "utf8"), {
683
+ expected,
684
+ expectedHash
685
+ });
686
+ await fs.writeFile(entry, source, "utf8");
687
+ return {
688
+ id: docId,
689
+ entry: path.relative(ctx.userCwd, entry),
690
+ hash: hashSource(source)
691
+ };
692
+ });
980
693
  }
981
- async function renameDocument(ctx, docId, rawTitle) {
694
+ async function renameDocument(ctx, docId, rawTitle, opts = {}) {
982
695
  const title = validateDocTitle(rawTitle);
983
696
  if (!title) throw new OpsError(400, "invalid title");
984
697
  const entry = resolveEntry(ctx, docId);
985
698
  if (!entry) throw new OpsError(404, `document not found: ${docId}`);
986
- const source = await fs.readFile(entry, "utf8");
987
- const next = setMetaTitle(source, title);
988
- if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
989
- if (next !== source) await fs.writeFile(entry, next, "utf8");
990
- return {
991
- id: docId,
992
- title
993
- };
699
+ return withFileLock(entry, async () => {
700
+ const source = await fs.readFile(entry, "utf8");
701
+ assertExpectedSource(source, opts);
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,
708
+ hash: hashSource(next)
709
+ };
710
+ });
994
711
  }
995
712
  async function duplicateDocument(ctx, docId, newId) {
996
713
  const dir = docDir(ctx, docId);
@@ -1004,17 +721,19 @@ async function duplicateDocument(ctx, docId, newId) {
1004
721
  } else targetId = nextCopyId(docId, taken);
1005
722
  await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
1006
723
  const entry = resolveEntry(ctx, targetId);
1007
- if (entry) {
724
+ if (entry) await withFileLock(entry, async () => {
1008
725
  const source = await fs.readFile(entry, "utf8");
1009
726
  const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
1010
727
  if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
1011
- }
1012
- const manifest = await readManifest(ctx.manifestPath);
1013
- const folderId = manifest.assignments[docId];
1014
- if (folderId) {
1015
- manifest.assignments[targetId] = folderId;
1016
- await writeManifest(ctx.manifestPath, manifest);
1017
- }
728
+ });
729
+ await withFileLock(ctx.manifestPath, async () => {
730
+ const manifest = await readManifest(ctx.manifestPath);
731
+ const folderId = manifest.assignments[docId];
732
+ if (folderId) {
733
+ manifest.assignments[targetId] = folderId;
734
+ await writeManifest(ctx.manifestPath, manifest);
735
+ }
736
+ });
1018
737
  return { id: targetId };
1019
738
  }
1020
739
  async function deleteDocument(ctx, docId) {
@@ -1024,10 +743,53 @@ async function deleteDocument(ctx, docId) {
1024
743
  recursive: true,
1025
744
  force: true
1026
745
  });
1027
- const manifest = await readManifest(ctx.manifestPath);
1028
- if (manifest.assignments[docId]) {
1029
- delete manifest.assignments[docId];
1030
- await writeManifest(ctx.manifestPath, manifest);
746
+ await withFileLock(ctx.manifestPath, async () => {
747
+ const manifest = await readManifest(ctx.manifestPath);
748
+ if (manifest.assignments[docId]) {
749
+ delete manifest.assignments[docId];
750
+ await writeManifest(ctx.manifestPath, manifest);
751
+ }
752
+ });
753
+ }
754
+ //#endregion
755
+ //#region src/ops/concurrency.ts
756
+ /**
757
+ * Deterministic 16-char SHA-256 hex digest of a document's UTF-8 source.
758
+ * Used as a lightweight optimistic concurrency token (`hash` / `expectedHash`)
759
+ * so clients and MCP agents do not need to re-send the full source string.
760
+ */
761
+ function hashSource(source) {
762
+ return createHash("sha256").update(source, "utf8").digest("hex").slice(0, 16);
763
+ }
764
+ /**
765
+ * Verifies that `current` on disk still matches what the caller last read,
766
+ * either via full-source comparison (`expected`) or SHA-256 digest (`expectedHash`).
767
+ */
768
+ function assertExpectedSource(current, opts) {
769
+ if (opts?.expected !== void 0 && current !== opts.expected) throw new OpsError(409, "document changed on disk since it was read");
770
+ if (opts?.expectedHash !== void 0 && hashSource(current) !== opts.expectedHash) throw new OpsError(409, "document changed on disk since it was read (hash mismatch)");
771
+ }
772
+ const fileQueues = /* @__PURE__ */ new Map();
773
+ /**
774
+ * Serializes async read-modify-write operations on the same file path in FIFO order.
775
+ * Prevents concurrent edits (e.g. over high-latency GCS FUSE mounts or parallel
776
+ * MCP tool calls) from reading the same stale snapshot and overwriting each other.
777
+ */
778
+ async function withFileLock(filePath, fn) {
779
+ const key = path.resolve(filePath);
780
+ const prev = fileQueues.get(key) ?? Promise.resolve();
781
+ let release;
782
+ const gate = new Promise((resolve) => {
783
+ release = resolve;
784
+ });
785
+ const tail = prev.then(() => gate);
786
+ fileQueues.set(key, tail);
787
+ await prev;
788
+ try {
789
+ return await fn();
790
+ } finally {
791
+ release();
792
+ if (fileQueues.get(key) === tail) fileQueues.delete(key);
1031
793
  }
1032
794
  }
1033
795
  //#endregion
@@ -1152,11 +914,13 @@ async function revertChange(ctx, docId, opts) {
1152
914
  if (!file || !hunk) throw new OpsError(409, "that change is no longer there — reload the changes");
1153
915
  if (file.binary) throw new OpsError(422, "a binary file cannot be reverted here");
1154
916
  const target = path.join(ctx.docsRoot, docId, file.path);
1155
- const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
1156
- if (next === null) throw new OpsError(409, "the file changed since the diff was read");
1157
- if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
1158
- await fs.writeFile(target, next, "utf8");
1159
- return { ok: true };
917
+ return withFileLock(target, async () => {
918
+ const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
919
+ if (next === null) throw new OpsError(409, "the file changed since the diff was read");
920
+ if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
921
+ await fs.writeFile(target, next, "utf8");
922
+ return { ok: true };
923
+ });
1160
924
  }
1161
925
  //#endregion
1162
926
  //#region src/files/assets.ts
@@ -1758,7 +1522,9 @@ async function writeAsset(ctx, scope, filename, data) {
1758
1522
  await fs.mkdir(dir, { recursive: true });
1759
1523
  const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1760
1524
  if (!file) throw new OpsError(400, "invalid filename");
1761
- await fs.writeFile(file, data);
1525
+ await withFileLock(file, async () => {
1526
+ await fs.writeFile(file, data);
1527
+ });
1762
1528
  return {
1763
1529
  scope,
1764
1530
  filename: name,
@@ -1770,7 +1536,9 @@ async function deleteAsset(ctx, scope, filename) {
1770
1536
  const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1771
1537
  if (!file) throw new OpsError(400, "invalid filename");
1772
1538
  if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1773
- await fs.rm(file);
1539
+ await withFileLock(file, async () => {
1540
+ await fs.rm(file);
1541
+ });
1774
1542
  }
1775
1543
  /** Which documents import this asset — check before deleting one. */
1776
1544
  async function findAssetUsages(ctx, scope, filename) {
@@ -1804,23 +1572,27 @@ async function createFolder(ctx, rawName, rawIcon) {
1804
1572
  if (!name) throw new OpsError(400, "invalid folder name");
1805
1573
  const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1806
1574
  if (!icon) throw new OpsError(400, "invalid icon");
1807
- const manifest = await readManifest(ctx.manifestPath);
1808
- const folder = {
1809
- id: newFolderId(),
1810
- name,
1811
- icon
1812
- };
1813
- manifest.folders.push(folder);
1814
- await writeManifest(ctx.manifestPath, manifest);
1815
- return folder;
1575
+ return withFileLock(ctx.manifestPath, async () => {
1576
+ const manifest = await readManifest(ctx.manifestPath);
1577
+ const folder = {
1578
+ id: newFolderId(),
1579
+ name,
1580
+ icon
1581
+ };
1582
+ manifest.folders.push(folder);
1583
+ await writeManifest(ctx.manifestPath, manifest);
1584
+ return folder;
1585
+ });
1816
1586
  }
1817
1587
  /** Filing only edits assignments — a document id never moves on disk. */
1818
1588
  async function fileDocument(ctx, docId, folderId) {
1819
- const manifest = await readManifest(ctx.manifestPath);
1820
- if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1821
- if (folderId === null) delete manifest.assignments[docId];
1822
- else manifest.assignments[docId] = folderId;
1823
- await writeManifest(ctx.manifestPath, manifest);
1589
+ await withFileLock(ctx.manifestPath, async () => {
1590
+ const manifest = await readManifest(ctx.manifestPath);
1591
+ if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1592
+ if (folderId === null) delete manifest.assignments[docId];
1593
+ else manifest.assignments[docId] = folderId;
1594
+ await writeManifest(ctx.manifestPath, manifest);
1595
+ });
1824
1596
  }
1825
1597
  //#endregion
1826
1598
  //#region src/ops/templates.ts
@@ -1984,15 +1756,18 @@ function registerDocRoutes(server, ctx) {
1984
1756
  if (method === "PATCH") {
1985
1757
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1986
1758
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1759
+ const result = await renameDocument(ctx, docId, (await readBody(req)).title);
1760
+ server.watcher.emit("change", `${ctx.docsRoot}/${docId}/index.tsx`);
1987
1761
  return json(res, 200, {
1988
1762
  ok: true,
1989
- title: (await renameDocument(ctx, docId, (await readBody(req)).title)).title
1763
+ title: result.title
1990
1764
  });
1991
1765
  }
1992
1766
  if (method === "DELETE") {
1993
1767
  const requestCheck = validateMutationRequest(req);
1994
1768
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1995
1769
  await deleteDocument(ctx, docId);
1770
+ server.watcher.emit("unlink", `${ctx.docsRoot}/${docId}/index.tsx`);
1996
1771
  return json(res, 200, { ok: true });
1997
1772
  }
1998
1773
  }
@@ -3451,21 +3226,31 @@ async function readText(ctx, docId, locs, shown, prop) {
3451
3226
  const { source } = await sourceOf(ctx, docId);
3452
3227
  const resolved = resolveTextTarget(source, locs, shown, prop);
3453
3228
  if (!resolved) throw new OpsError(404, "no editable text at that location");
3454
- return resolved;
3229
+ return {
3230
+ ...resolved,
3231
+ hash: hashSource(source)
3232
+ };
3455
3233
  }
3456
3234
  /**
3457
3235
  * `expected` is the text the caller believes is there; when it no longer
3458
3236
  * matches the write is refused rather than silently overwriting someone else's
3459
- * edit. `index` picks a run when the element mixes text and markup. A run that
3460
- * carries code, emphasis or links must be written as `segments`, or the write
3461
- * is refused rather than dropping the formatting.
3237
+ * edit. `expectedHash` optionally verifies the file-level SHA-256 digest.
3238
+ * All reads and writes on the same document are serialized via `withFileLock`.
3462
3239
  */
3463
3240
  async function writeText(ctx, docId, loc, text, opts = {}) {
3464
- const { entry, source } = await sourceOf(ctx, docId);
3465
- const result = replaceTextAt(source, loc, text, opts);
3466
- if (!result.ok) throw new OpsError(result.status, result.error);
3467
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3468
- return { ok: true };
3241
+ const entry = resolveEntry(ctx, docId);
3242
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3243
+ return withFileLock(entry, async () => {
3244
+ const source = await fs.readFile(entry, "utf8");
3245
+ assertExpectedSource(source, { expectedHash: opts.expectedHash });
3246
+ const result = replaceTextAt(source, loc, text, opts);
3247
+ if (!result.ok) throw new OpsError(result.status, result.error);
3248
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3249
+ return {
3250
+ ok: true,
3251
+ hash: hashSource(result.source)
3252
+ };
3253
+ });
3469
3254
  }
3470
3255
  /**
3471
3256
  * Several run replacements in one read and one write, so an editing session
@@ -3473,12 +3258,20 @@ async function writeText(ctx, docId, loc, text, opts = {}) {
3473
3258
  * that each re-paginate the document. Per-edit failures are reported, not
3474
3259
  * thrown: the edits that still apply are written.
3475
3260
  */
3476
- async function writeTexts(ctx, docId, edits) {
3261
+ async function writeTexts(ctx, docId, edits, opts = {}) {
3477
3262
  if (edits.length === 0) throw new OpsError(400, "at least one edit is required");
3478
- const { entry, source } = await sourceOf(ctx, docId);
3479
- const result = replaceTextsAt(source, edits);
3480
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3481
- return { results: result.results };
3263
+ const entry = resolveEntry(ctx, docId);
3264
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3265
+ return withFileLock(entry, async () => {
3266
+ const source = await fs.readFile(entry, "utf8");
3267
+ assertExpectedSource(source, opts);
3268
+ const result = replaceTextsAt(source, edits);
3269
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3270
+ return {
3271
+ results: result.results,
3272
+ hash: hashSource(result.source)
3273
+ };
3274
+ });
3482
3275
  }
3483
3276
  /** What the element at `loc` sets in its `style`, key by key, for the element panel's Format section. */
3484
3277
  async function readStyle(ctx, docId, loc, tag) {
@@ -3490,24 +3283,38 @@ async function readStyle(ctx, docId, loc, tag) {
3490
3283
  * against the same read of the file and written once. Per-edit failures are
3491
3284
  * reported, not thrown, like `writeTexts`.
3492
3285
  */
3493
- async function writeEdits(ctx, docId, texts, styles) {
3286
+ async function writeEdits(ctx, docId, texts, styles, opts = {}) {
3494
3287
  if (texts.length + styles.length === 0) throw new OpsError(400, "at least one edit is required");
3495
- const { entry, source } = await sourceOf(ctx, docId);
3496
- const result = replaceEditsAt(source, texts, styles);
3497
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3498
- return {
3499
- texts: result.texts,
3500
- styles: result.styles
3501
- };
3288
+ const entry = resolveEntry(ctx, docId);
3289
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3290
+ return withFileLock(entry, async () => {
3291
+ const source = await fs.readFile(entry, "utf8");
3292
+ assertExpectedSource(source, opts);
3293
+ const result = replaceEditsAt(source, texts, styles);
3294
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3295
+ return {
3296
+ texts: result.texts,
3297
+ styles: result.styles,
3298
+ hash: hashSource(result.source)
3299
+ };
3300
+ });
3502
3301
  }
3503
3302
  /** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
3504
- async function addComment(ctx, docId, loc, note, hint) {
3303
+ async function addComment(ctx, docId, loc, note, hint, opts = {}) {
3505
3304
  if (note.trim() === "") throw new OpsError(400, "note is empty");
3506
- const { entry, source } = await sourceOf(ctx, docId);
3507
- const inserted = insertMarker(source, loc, note.trim(), hint);
3508
- if (!inserted) throw new OpsError(422, "cannot anchor a comment here — pick the surrounding element");
3509
- await fs.writeFile(entry, inserted.source, "utf8");
3510
- return { id: inserted.id };
3305
+ const entry = resolveEntry(ctx, docId);
3306
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
3307
+ return withFileLock(entry, async () => {
3308
+ const source = await fs.readFile(entry, "utf8");
3309
+ assertExpectedSource(source, opts);
3310
+ const inserted = insertMarker(source, loc, note.trim(), hint);
3311
+ if (!inserted) throw new OpsError(422, "cannot anchor a comment here — pick the surrounding element");
3312
+ await fs.writeFile(entry, inserted.source, "utf8");
3313
+ return {
3314
+ id: inserted.id,
3315
+ hash: hashSource(inserted.source)
3316
+ };
3317
+ });
3511
3318
  }
3512
3319
  //#endregion
3513
3320
  //#region src/vite/routes/edit.ts
@@ -3598,9 +3405,13 @@ function registerEditRoutes(server, ctx) {
3598
3405
  column
3599
3406
  }));
3600
3407
  if (!entry || locs.length === 0) return json(res, 400, { error: "invalid target" });
3601
- const resolved = resolveTextTarget(await fs.readFile(entry, "utf8"), locs, url.searchParams.get("shown") ?? void 0, url.searchParams.get("prop") ?? void 0);
3408
+ const source = await fs.readFile(entry, "utf8");
3409
+ const resolved = resolveTextTarget(source, locs, url.searchParams.get("shown") ?? void 0, url.searchParams.get("prop") ?? void 0);
3602
3410
  if (!resolved) return json(res, 404, { error: "element not found" });
3603
- return json(res, 200, resolved);
3411
+ return json(res, 200, {
3412
+ ...resolved,
3413
+ hash: hashSource(source)
3414
+ });
3604
3415
  }
3605
3416
  if (method === "PUT" && url.pathname === "/text") {
3606
3417
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -3611,16 +3422,15 @@ function registerEditRoutes(server, ctx) {
3611
3422
  if (!loc || typeof text !== "string") return json(res, 400, { error: "invalid payload" });
3612
3423
  const entry = entryFor(loc.docId);
3613
3424
  if (!entry) return json(res, 404, { error: "document not found" });
3614
- const source = await fs.readFile(entry, "utf8");
3615
- const result = replaceTextAt(source, loc, text, {
3425
+ const out = await writeText(ctx, loc.docId, loc, text, {
3616
3426
  index: typeof body.index === "number" ? body.index : void 0,
3617
3427
  expected: typeof body.expected === "string" ? body.expected : void 0,
3428
+ expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0,
3618
3429
  shown: typeof body.shown === "string" ? body.shown : void 0,
3619
3430
  prop: typeof body.prop === "string" ? body.prop : void 0
3620
3431
  });
3621
- if (!result.ok) return json(res, result.status, { error: result.error });
3622
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3623
- return json(res, 200, { ok: true });
3432
+ server.watcher.emit("change", entry);
3433
+ return json(res, 200, out);
3624
3434
  }
3625
3435
  if (method === "PUT" && url.pathname === "/texts") {
3626
3436
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -3629,7 +3439,10 @@ function registerEditRoutes(server, ctx) {
3629
3439
  if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
3630
3440
  const edits = readTextEdits(body.docId, body.edits);
3631
3441
  if (!edits) return json(res, 400, { error: "invalid payload" });
3632
- return json(res, 200, await writeTexts(ctx, body.docId, edits));
3442
+ const out = await writeTexts(ctx, body.docId, edits, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3443
+ const entry = entryFor(body.docId);
3444
+ if (entry) server.watcher.emit("change", entry);
3445
+ return json(res, 200, out);
3633
3446
  }
3634
3447
  if (method === "GET" && url.pathname === "/style") {
3635
3448
  const loc = readLoc({
@@ -3649,7 +3462,10 @@ function registerEditRoutes(server, ctx) {
3649
3462
  const texts = readTextEdits(body.docId, body.texts ?? []);
3650
3463
  const styles = readStyleEdits(body.docId, body.styles ?? []);
3651
3464
  if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
3652
- return json(res, 200, await writeEdits(ctx, body.docId, texts, styles));
3465
+ const out = await writeEdits(ctx, body.docId, texts, styles, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3466
+ const entry = entryFor(body.docId);
3467
+ if (entry) server.watcher.emit("change", entry);
3468
+ return json(res, 200, out);
3653
3469
  }
3654
3470
  if (method === "POST" && url.pathname === "/comment") {
3655
3471
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -3660,12 +3476,12 @@ function registerEditRoutes(server, ctx) {
3660
3476
  if (!loc || typeof note !== "string" || note.trim() === "") return json(res, 400, { error: "invalid payload" });
3661
3477
  const entry = entryFor(loc.docId);
3662
3478
  if (!entry) return json(res, 404, { error: "document not found" });
3663
- const inserted = insertMarker(await fs.readFile(entry, "utf8"), loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
3664
- if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
3665
- await fs.writeFile(entry, inserted.source, "utf8");
3479
+ const inserted = await addComment(ctx, loc.docId, loc, note, typeof body.hint === "string" ? body.hint : void 0, { expectedHash: typeof body.expectedHash === "string" ? body.expectedHash : void 0 });
3480
+ server.watcher.emit("change", entry);
3666
3481
  return json(res, 200, {
3667
3482
  ok: true,
3668
- id: inserted.id
3483
+ id: inserted.id,
3484
+ hash: inserted.hash
3669
3485
  });
3670
3486
  }
3671
3487
  return next();
@@ -3690,9 +3506,13 @@ function registerEditRoutes(server, ctx) {
3690
3506
  if (!check.ok) return json(res, check.status, { error: check.error });
3691
3507
  const id = url.searchParams.get("id") ?? "";
3692
3508
  if (!entry || !/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
3693
- const next = removeMarker(await fs.readFile(entry, "utf8"), id);
3694
- if (next === null) return json(res, 404, { error: "comment not found" });
3695
- await fs.writeFile(entry, next, "utf8");
3509
+ if (!await withFileLock(entry, async () => {
3510
+ const nextSource = removeMarker(await fs.readFile(entry, "utf8"), id);
3511
+ if (nextSource === null) return false;
3512
+ await fs.writeFile(entry, nextSource, "utf8");
3513
+ return true;
3514
+ })) return json(res, 404, { error: "comment not found" });
3515
+ server.watcher.emit("change", entry);
3696
3516
  return json(res, 200, { ok: true });
3697
3517
  }
3698
3518
  return next();
@@ -3717,15 +3537,17 @@ function registerFolderRoutes(server, ctx) {
3717
3537
  if (!name) return json(res, 400, { error: "invalid name" });
3718
3538
  const icon = validateIcon(body.icon);
3719
3539
  if (!icon) return json(res, 400, { error: "invalid icon" });
3720
- const manifest = await readManifest(ctx.manifestPath);
3721
- const folder = {
3722
- id: newFolderId(),
3723
- name,
3724
- icon
3725
- };
3726
- manifest.folders.push(folder);
3727
- await writeManifest(ctx.manifestPath, manifest);
3728
- return json(res, 200, folder);
3540
+ return json(res, 200, await withFileLock(ctx.manifestPath, async () => {
3541
+ const manifest = await readManifest(ctx.manifestPath);
3542
+ const created = {
3543
+ id: newFolderId(),
3544
+ name,
3545
+ icon
3546
+ };
3547
+ manifest.folders.push(created);
3548
+ await writeManifest(ctx.manifestPath, manifest);
3549
+ return created;
3550
+ }));
3729
3551
  }
3730
3552
  if (method === "PUT" && url.pathname === "/assign") {
3731
3553
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
@@ -3737,23 +3559,29 @@ function registerFolderRoutes(server, ctx) {
3737
3559
  if (body.folderId === null) folderId = null;
3738
3560
  else if (typeof body.folderId === "string" && FOLDER_ID_RE.test(body.folderId)) folderId = body.folderId;
3739
3561
  else return json(res, 400, { error: "invalid folderId" });
3740
- const manifest = await readManifest(ctx.manifestPath);
3741
- if (folderId && !manifest.folders.some((f) => f.id === folderId)) return json(res, 404, { error: "folder not found" });
3742
- if (folderId === null) delete manifest.assignments[docId];
3743
- else manifest.assignments[docId] = folderId;
3744
- await writeManifest(ctx.manifestPath, manifest);
3562
+ if (!await withFileLock(ctx.manifestPath, async () => {
3563
+ const manifest = await readManifest(ctx.manifestPath);
3564
+ if (folderId && !manifest.folders.some((f) => f.id === folderId)) return false;
3565
+ if (folderId === null) delete manifest.assignments[docId];
3566
+ else manifest.assignments[docId] = folderId;
3567
+ await writeManifest(ctx.manifestPath, manifest);
3568
+ return true;
3569
+ })) return json(res, 404, { error: "folder not found" });
3745
3570
  return json(res, 200, { ok: true });
3746
3571
  }
3747
3572
  if (method === "PUT" && url.pathname === "/reorder") {
3748
3573
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3749
3574
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3750
3575
  const body = await readBody(req);
3751
- const manifest = await readManifest(ctx.manifestPath);
3752
- const ids = validateReorder(body.ids, manifest.folders);
3753
- if (!ids) return json(res, 400, { error: "invalid ids" });
3754
- const byId = new Map(manifest.folders.map((f) => [f.id, f]));
3755
- manifest.folders = ids.map((id) => byId.get(id));
3756
- await writeManifest(ctx.manifestPath, manifest);
3576
+ if (!await withFileLock(ctx.manifestPath, async () => {
3577
+ const manifest = await readManifest(ctx.manifestPath);
3578
+ const ids = validateReorder(body.ids, manifest.folders);
3579
+ if (!ids) return false;
3580
+ const byId = new Map(manifest.folders.map((f) => [f.id, f]));
3581
+ manifest.folders = ids.map((id) => byId.get(id));
3582
+ await writeManifest(ctx.manifestPath, manifest);
3583
+ return true;
3584
+ })) return json(res, 400, { error: "invalid ids" });
3757
3585
  return json(res, 200, { ok: true });
3758
3586
  }
3759
3587
  const idMatch = url.pathname.match(/^\/([^/]+)$/);
@@ -3764,31 +3592,50 @@ function registerFolderRoutes(server, ctx) {
3764
3592
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
3765
3593
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3766
3594
  const body = await readBody(req);
3767
- const manifest = await readManifest(ctx.manifestPath);
3768
- const folder = manifest.folders.find((f) => f.id === id);
3769
- if (!folder) return json(res, 404, { error: "folder not found" });
3770
- if (body.name !== void 0) {
3771
- const name = validateName(body.name);
3772
- if (!name) return json(res, 400, { error: "invalid name" });
3773
- folder.name = name;
3774
- }
3775
- if (body.icon !== void 0) {
3776
- const icon = validateIcon(body.icon);
3777
- if (!icon) return json(res, 400, { error: "invalid icon" });
3778
- folder.icon = icon;
3779
- }
3780
- await writeManifest(ctx.manifestPath, manifest);
3781
- return json(res, 200, folder);
3595
+ const outcome = await withFileLock(ctx.manifestPath, async () => {
3596
+ const manifest = await readManifest(ctx.manifestPath);
3597
+ const folder = manifest.folders.find((f) => f.id === id);
3598
+ if (!folder) return {
3599
+ status: 404,
3600
+ error: "folder not found"
3601
+ };
3602
+ if (body.name !== void 0) {
3603
+ const name = validateName(body.name);
3604
+ if (!name) return {
3605
+ status: 400,
3606
+ error: "invalid name"
3607
+ };
3608
+ folder.name = name;
3609
+ }
3610
+ if (body.icon !== void 0) {
3611
+ const icon = validateIcon(body.icon);
3612
+ if (!icon) return {
3613
+ status: 400,
3614
+ error: "invalid icon"
3615
+ };
3616
+ folder.icon = icon;
3617
+ }
3618
+ await writeManifest(ctx.manifestPath, manifest);
3619
+ return {
3620
+ status: 200,
3621
+ folder
3622
+ };
3623
+ });
3624
+ if (outcome.status !== 200) return json(res, outcome.status, { error: outcome.error });
3625
+ return json(res, 200, outcome.folder);
3782
3626
  }
3783
3627
  if (method === "DELETE") {
3784
3628
  const requestCheck = validateMutationRequest(req);
3785
3629
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
3786
- const manifest = await readManifest(ctx.manifestPath);
3787
- const before = manifest.folders.length;
3788
- manifest.folders = manifest.folders.filter((f) => f.id !== id);
3789
- if (manifest.folders.length === before) return json(res, 404, { error: "folder not found" });
3790
- for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
3791
- await writeManifest(ctx.manifestPath, manifest);
3630
+ if (!await withFileLock(ctx.manifestPath, async () => {
3631
+ const manifest = await readManifest(ctx.manifestPath);
3632
+ const before = manifest.folders.length;
3633
+ manifest.folders = manifest.folders.filter((f) => f.id !== id);
3634
+ if (manifest.folders.length === before) return false;
3635
+ for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
3636
+ await writeManifest(ctx.manifestPath, manifest);
3637
+ return true;
3638
+ })) return json(res, 404, { error: "folder not found" });
3792
3639
  return json(res, 200, { ok: true });
3793
3640
  }
3794
3641
  }
@@ -4226,41 +4073,68 @@ function designPlugin(opts) {
4226
4073
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4227
4074
  const patch = (await readBody(req)).patch;
4228
4075
  if (!patch || typeof patch !== "object") return json(res, 400, { error: "missing patch object" });
4229
- let source;
4230
- try {
4231
- source = await fs.readFile(file, "utf8");
4232
- } catch {
4233
- return json(res, 404, { error: "document not found" });
4234
- }
4235
- const parsed = parseDocDesign(source);
4236
- if (!parsed.ok && parsed.exists) return json(res, 422, { error: parsed.error });
4237
- const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
4238
- const written = applyDesignWrite(source, merged);
4239
- if (!written.ok) return json(res, written.status, { error: written.error });
4240
- if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4241
- return json(res, 200, {
4242
- ok: true,
4243
- design: merged,
4244
- created: written.created
4076
+ const outcome = await withFileLock(file, async () => {
4077
+ let source;
4078
+ try {
4079
+ source = await fs.readFile(file, "utf8");
4080
+ } catch {
4081
+ return {
4082
+ status: 404,
4083
+ payload: { error: "document not found" }
4084
+ };
4085
+ }
4086
+ const parsed = parseDocDesign(source);
4087
+ if (!parsed.ok && parsed.exists) return {
4088
+ status: 422,
4089
+ payload: { error: parsed.error }
4090
+ };
4091
+ const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
4092
+ const written = applyDesignWrite(source, merged);
4093
+ if (!written.ok) return {
4094
+ status: written.status,
4095
+ payload: { error: written.error }
4096
+ };
4097
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4098
+ return {
4099
+ status: 200,
4100
+ payload: {
4101
+ ok: true,
4102
+ design: merged,
4103
+ created: written.created
4104
+ }
4105
+ };
4245
4106
  });
4107
+ return json(res, outcome.status, outcome.payload);
4246
4108
  }
4247
4109
  if (method === "POST" && url.pathname === "/reset") {
4248
4110
  const requestCheck = validateMutationRequest(req);
4249
4111
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
4250
- let source;
4251
- try {
4252
- source = await fs.readFile(file, "utf8");
4253
- } catch {
4254
- return json(res, 404, { error: "document not found" });
4255
- }
4256
- const written = applyDesignWrite(source, defaultDesign);
4257
- if (!written.ok) return json(res, written.status, { error: written.error });
4258
- if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4259
- return json(res, 200, {
4260
- ok: true,
4261
- design: defaultDesign,
4262
- created: written.created
4112
+ const outcome = await withFileLock(file, async () => {
4113
+ let source;
4114
+ try {
4115
+ source = await fs.readFile(file, "utf8");
4116
+ } catch {
4117
+ return {
4118
+ status: 404,
4119
+ payload: { error: "document not found" }
4120
+ };
4121
+ }
4122
+ const written = applyDesignWrite(source, defaultDesign);
4123
+ if (!written.ok) return {
4124
+ status: written.status,
4125
+ payload: { error: written.error }
4126
+ };
4127
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
4128
+ return {
4129
+ status: 200,
4130
+ payload: {
4131
+ ok: true,
4132
+ design: defaultDesign,
4133
+ created: written.created
4134
+ }
4135
+ };
4263
4136
  });
4137
+ return json(res, outcome.status, outcome.payload);
4264
4138
  }
4265
4139
  return next();
4266
4140
  } catch (err) {
@@ -4371,7 +4245,11 @@ function mcpPlugin(opts) {
4371
4245
  docsDir: opts.docsDir,
4372
4246
  assetsDir: opts.assetsDir,
4373
4247
  version: opts.coreVersion,
4374
- serverOrigin: originOf()
4248
+ serverOrigin: originOf(),
4249
+ ...opts.allowedHosts !== void 0 ? { allowedHosts: opts.allowedHosts } : {},
4250
+ onFileChange: (event, filePath) => {
4251
+ server.watcher.emit(event, filePath);
4252
+ }
4375
4253
  });
4376
4254
  return middleware(req, res, next);
4377
4255
  });
@@ -4404,6 +4282,13 @@ function readCoreVersion() {
4404
4282
  }
4405
4283
  }
4406
4284
  const CORE_VERSION = readCoreVersion();
4285
+ function safeRealpath(target) {
4286
+ try {
4287
+ return existsSync(target) ? realpathSync(target) : null;
4288
+ } catch {
4289
+ return null;
4290
+ }
4291
+ }
4407
4292
  async function createViteConfig(opts) {
4408
4293
  const userCwd = path.resolve(opts.userCwd);
4409
4294
  const config = opts.config ?? await loadUserConfig(userCwd);
@@ -4412,6 +4297,25 @@ async function createViteConfig(opts) {
4412
4297
  const docsAbs = path.resolve(userCwd, docsDir);
4413
4298
  const themesAbs = path.resolve(userCwd, config.themesDir ?? "themes");
4414
4299
  const assetsAbs = path.resolve(userCwd, assetsDir);
4300
+ const isCloud = process.env.OPEN_DOC_CLOUD === "1" || Boolean(process.env.K_SERVICE);
4301
+ const allowedHosts = config.allowedHosts ?? (isCloud ? true : void 0);
4302
+ const fsAllow = /* @__PURE__ */ new Set([
4303
+ APP_ROOT,
4304
+ userCwd,
4305
+ docsAbs,
4306
+ themesAbs,
4307
+ assetsAbs
4308
+ ]);
4309
+ for (const candidate of [
4310
+ userCwd,
4311
+ docsAbs,
4312
+ themesAbs,
4313
+ assetsAbs
4314
+ ]) {
4315
+ const real = safeRealpath(candidate);
4316
+ if (real) fsAllow.add(real);
4317
+ }
4318
+ if (process.env.OPEN_DOC_MOUNT_DIR) fsAllow.add(path.resolve(process.env.OPEN_DOC_MOUNT_DIR));
4415
4319
  return {
4416
4320
  base: config.base ?? "/",
4417
4321
  root: APP_ROOT,
@@ -4453,7 +4357,8 @@ async function createViteConfig(opts) {
4453
4357
  userCwd,
4454
4358
  docsDir,
4455
4359
  assetsDir,
4456
- coreVersion: CORE_VERSION
4360
+ coreVersion: CORE_VERSION,
4361
+ ...allowedHosts !== void 0 ? { allowedHosts } : {}
4457
4362
  })] : []
4458
4363
  ],
4459
4364
  resolve: { alias: {
@@ -4464,6 +4369,8 @@ async function createViteConfig(opts) {
4464
4369
  entries: [path.join(APP_ROOT, "main.tsx")],
4465
4370
  include: [
4466
4371
  "react",
4372
+ "react/jsx-runtime",
4373
+ "react/jsx-dev-runtime",
4467
4374
  "react-dom",
4468
4375
  "react-dom/client",
4469
4376
  "react-router-dom",
@@ -4483,15 +4390,13 @@ async function createViteConfig(opts) {
4483
4390
  }] }
4484
4391
  },
4485
4392
  server: {
4486
- port: config.port ?? 5273,
4487
- ...config.allowedHosts !== void 0 ? { allowedHosts: config.allowedHosts } : {},
4488
- fs: { allow: [
4489
- APP_ROOT,
4490
- userCwd,
4491
- docsAbs,
4492
- themesAbs,
4493
- assetsAbs
4494
- ] }
4393
+ port: config.port ?? (process.env.PORT ? Number(process.env.PORT) : 5273),
4394
+ ...allowedHosts !== void 0 ? { allowedHosts } : {},
4395
+ ...isCloud ? { watch: {
4396
+ usePolling: true,
4397
+ interval: 1500
4398
+ } } : {},
4399
+ fs: { allow: [...fsAllow] }
4495
4400
  },
4496
4401
  build: {
4497
4402
  outDir: path.resolve(userCwd, "dist"),
@@ -4500,4 +4405,4 @@ async function createViteConfig(opts) {
4500
4405
  };
4501
4406
  }
4502
4407
  //#endregion
4503
- export { renameDocument as A, createDocument as C, listDocIds$1 as D, duplicateDocument as E, loadUserConfig as F, openDocPlugin as I, writeDocument as M, makeContext as N, listDocuments as O, DOC_ID_RE as P, OpsError as S, docDir as T, writeAsset as _, writeTexts as a, readChanges as b, suggestDocId as c, fileDocument as d, findAssetUsages as f, readTheme as g, listThemes as h, writeText as i, resolveEntry as j, readDocument as k, createFolder as l, listFolders as m, addComment as n, createFromTemplate as o, listAssets as p, readText as r, listTemplates as s, createViteConfig as t, deleteAsset as u, validateAssetName as v, deleteDocument as w, revertChange as x, listRevisions as y };
4408
+ export { duplicateDocument as A, assertExpectedSource as C, createDocument as D, OpsError as E, resolveEntry as F, writeDocument as I, makeContext as L, listDocuments as M, readDocument as N, deleteDocument as O, renameDocument as P, revertChange as S, withFileLock as T, readTheme as _, writeText as a, listRevisions as b, listTemplates as c, deleteAsset as d, fileDocument as f, listThemes as g, listFolders as h, writeEdits as i, listDocIds$1 as j, docDir as k, suggestDocId as l, listAssets as m, addComment as n, writeTexts as o, findAssetUsages as p, readText as r, createFromTemplate as s, createViteConfig as t, createFolder as u, writeAsset as v, hashSource as w, readChanges as x, validateAssetName as y };