@open-document/core 0.1.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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -0
  3. package/README.zh-TW.md +50 -0
  4. package/bin.js +2 -0
  5. package/dist/build-BWZJ1gvL.js +18 -0
  6. package/dist/cli/bin.d.ts +1 -0
  7. package/dist/cli/bin.js +86 -0
  8. package/dist/config-DBp4mOOf.js +1121 -0
  9. package/dist/config-EBFfKtWH.d.ts +17 -0
  10. package/dist/design-BJLvOcCO.js +53 -0
  11. package/dist/dev-CZtw1oqs.js +24 -0
  12. package/dist/edit-ops-DSdUroVO.js +1225 -0
  13. package/dist/index.d.ts +206 -0
  14. package/dist/index.js +240 -0
  15. package/dist/ops/index.d.ts +160 -0
  16. package/dist/ops/index.js +202 -0
  17. package/dist/preview-DUfQl7Ij.js +23 -0
  18. package/dist/sync-6GTPAt2t.js +86 -0
  19. package/dist/sync-C6CsPmyK.js +3 -0
  20. package/dist/vite/index.d.ts +22 -0
  21. package/dist/vite/index.js +5 -0
  22. package/env.d.ts +51 -0
  23. package/package.json +91 -0
  24. package/skills/apply-comments/SKILL.md +74 -0
  25. package/skills/create-doc/SKILL.md +102 -0
  26. package/skills/create-theme/SKILL.md +184 -0
  27. package/skills/doc-authoring/SKILL.md +354 -0
  28. package/skills/doc-authoring/references/assets.md +47 -0
  29. package/skills/doc-authoring/references/design-system.md +81 -0
  30. package/skills/doc-authoring/references/pagination.md +117 -0
  31. package/skills/doc-authoring/references/tables-and-charts.md +161 -0
  32. package/src/app/app.tsx +42 -0
  33. package/src/app/components/design-panel/design-panel.tsx +318 -0
  34. package/src/app/components/design-panel/design-provider.tsx +121 -0
  35. package/src/app/components/design-panel/use-design.ts +85 -0
  36. package/src/app/components/doc-assets.tsx +129 -0
  37. package/src/app/components/doc-sidebar.tsx +162 -0
  38. package/src/app/components/flow-page.tsx +50 -0
  39. package/src/app/components/image-placeholder.tsx +50 -0
  40. package/src/app/components/inspector/inspector.tsx +426 -0
  41. package/src/app/components/page-frame.tsx +70 -0
  42. package/src/app/components/sidebar/folder-item.tsx +212 -0
  43. package/src/app/components/sidebar/icon-picker.tsx +99 -0
  44. package/src/app/components/sidebar/sidebar.tsx +252 -0
  45. package/src/app/components/table-of-contents.tsx +81 -0
  46. package/src/app/components/theme-toggle.tsx +50 -0
  47. package/src/app/components/themes/markdown.tsx +249 -0
  48. package/src/app/components/themes/theme-preview.tsx +74 -0
  49. package/src/app/components/ui/menu.tsx +139 -0
  50. package/src/app/index.html +12 -0
  51. package/src/app/lib/assets.ts +151 -0
  52. package/src/app/lib/design-presets.ts +109 -0
  53. package/src/app/lib/design.ts +88 -0
  54. package/src/app/lib/doc-preview.tsx +29 -0
  55. package/src/app/lib/docs.ts +26 -0
  56. package/src/app/lib/export-html.ts +309 -0
  57. package/src/app/lib/export-pdf.ts +166 -0
  58. package/src/app/lib/flow-measure.ts +109 -0
  59. package/src/app/lib/flow.test.ts +64 -0
  60. package/src/app/lib/flow.ts +111 -0
  61. package/src/app/lib/folders.ts +192 -0
  62. package/src/app/lib/inspector/fiber.ts +99 -0
  63. package/src/app/lib/outline.ts +109 -0
  64. package/src/app/lib/page-context.tsx +38 -0
  65. package/src/app/lib/print-ready.ts +69 -0
  66. package/src/app/lib/sdk.test.ts +24 -0
  67. package/src/app/lib/sdk.ts +86 -0
  68. package/src/app/lib/themes.ts +31 -0
  69. package/src/app/lib/use-doc-module.ts +53 -0
  70. package/src/app/lib/use-doc-pages.ts +99 -0
  71. package/src/app/lib/utils.ts +6 -0
  72. package/src/app/main.tsx +14 -0
  73. package/src/app/routes/assets.tsx +257 -0
  74. package/src/app/routes/doc.tsx +480 -0
  75. package/src/app/routes/home-shell.tsx +203 -0
  76. package/src/app/routes/home.tsx +269 -0
  77. package/src/app/routes/themes.tsx +121 -0
  78. package/src/app/styles.css +72 -0
  79. package/src/app/virtual.d.ts +30 -0
@@ -0,0 +1,1121 @@
1
+ import { defaultDesign } from "./design-BJLvOcCO.js";
2
+ import { ASSET_MAX_BYTES, DOC_ID_RE, FOLDER_ID_RE, GLOBAL_SCOPE, OpsError, assetCreatedAt, assetImportPath, countAssetUsages, deleteDocument, duplicateDocument, findReferencedAssets, insertMarker, json, loadUserConfig, makeContext, mimeForFilename, newFolderId, openDocPlugin, parseMarkers, parseSource, readBody, readManifest, removeMarker, renameDocument, replaceTextAt, resolveDocEntry, resolveDocPath, resolveScopedAssetFile, resolveScopedAssetsDir, resolveTextTarget, themesPlugin, validateAssetName, validateIcon, validateName, validateReorder, walkJsx, writeManifest } from "./edit-ops-DSdUroVO.js";
3
+ import chalk from "chalk";
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { parse } from "@babel/parser";
9
+ import tailwindcss from "@tailwindcss/vite";
10
+ import react from "@vitejs/plugin-react";
11
+
12
+ //#region src/http/request-guard.ts
13
+ function firstHeaderValue(value) {
14
+ if (Array.isArray(value)) return value[0] ?? null;
15
+ return value ?? null;
16
+ }
17
+ function headerValue(req, name) {
18
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
19
+ }
20
+ function firstCommaToken(value) {
21
+ if (!value) return null;
22
+ const [first] = value.split(",", 1);
23
+ return first?.trim() || null;
24
+ }
25
+ function requestProto(req) {
26
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
27
+ if (forwarded === "http" || forwarded === "https") return forwarded;
28
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
29
+ }
30
+ function normalizedOrigin(origin) {
31
+ try {
32
+ const url = new URL(origin);
33
+ return `${url.protocol}//${url.host}`.toLowerCase();
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ /**
39
+ * The dev server writes to the user's filesystem, so every mutating endpoint is
40
+ * guarded against a page on another origin driving it through the browser.
41
+ */
42
+ function validateMutationRequest(req, opts = {}) {
43
+ if (opts.requireJsonBody) {
44
+ const contentType = headerValue(req, "content-type")?.toLowerCase();
45
+ if (!contentType?.startsWith("application/json")) return {
46
+ ok: false,
47
+ status: 415,
48
+ error: "content-type must be application/json"
49
+ };
50
+ }
51
+ const fetchSite = firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase();
52
+ if (fetchSite === "cross-site") return {
53
+ ok: false,
54
+ status: 403,
55
+ error: "cross-site request blocked"
56
+ };
57
+ const originRaw = headerValue(req, "origin");
58
+ if (!originRaw) return { ok: true };
59
+ if (originRaw.toLowerCase() === "null") return {
60
+ ok: false,
61
+ status: 403,
62
+ error: "opaque origin is not allowed"
63
+ };
64
+ const actualOrigin = normalizedOrigin(originRaw);
65
+ if (!actualOrigin) return {
66
+ ok: false,
67
+ status: 403,
68
+ error: "invalid origin header"
69
+ };
70
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
71
+ if (!host) return {
72
+ ok: false,
73
+ status: 400,
74
+ error: "missing host header"
75
+ };
76
+ const expectedOrigin = `${requestProto(req)}://${host}`.toLowerCase();
77
+ if (actualOrigin !== expectedOrigin) return {
78
+ ok: false,
79
+ status: 403,
80
+ error: "origin mismatch"
81
+ };
82
+ return { ok: true };
83
+ }
84
+
85
+ //#endregion
86
+ //#region src/vite/routes/assets.ts
87
+ async function listDocIds(docsRoot) {
88
+ try {
89
+ const entries = await fs.readdir(docsRoot, { withFileTypes: true });
90
+ return entries.filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
91
+ } catch {
92
+ return [];
93
+ }
94
+ }
95
+ async function readDocSource(docsRoot, docId) {
96
+ const entry = resolveDocEntry(docsRoot, docId);
97
+ if (!entry) return null;
98
+ try {
99
+ return await fs.readFile(entry, "utf8");
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+ function registerAssetRoutes(server, ctx) {
105
+ server.middlewares.use("/__assets", async (req, res, next) => {
106
+ const url = new URL(req.url ?? "/", "http://local");
107
+ const method = req.method ?? "GET";
108
+ try {
109
+ const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
110
+ const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
111
+ const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
112
+ if (usagesMatch && method === "GET") {
113
+ const scope = decodeURIComponent(usagesMatch[1]);
114
+ const filename = decodeURIComponent(usagesMatch[2]);
115
+ if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
116
+ const isGlobal = scope === GLOBAL_SCOPE;
117
+ if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
118
+ const importPath = assetImportPath(scope, filename);
119
+ const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
120
+ const usages = [];
121
+ let totalCount = 0;
122
+ for (const docId of docIds) {
123
+ const source = await readDocSource(ctx.docsRoot, docId);
124
+ if (source === null) continue;
125
+ const count = countAssetUsages(source, importPath);
126
+ if (count > 0) {
127
+ usages.push({
128
+ docId,
129
+ count
130
+ });
131
+ totalCount += count;
132
+ }
133
+ }
134
+ return json(res, 200, {
135
+ usages,
136
+ totalCount
137
+ });
138
+ }
139
+ if (listMatch && method === "GET") {
140
+ const scope = decodeURIComponent(listMatch[1]);
141
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
142
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
143
+ let entries;
144
+ try {
145
+ entries = await fs.readdir(scopedDir);
146
+ } catch (err) {
147
+ if (err.code === "ENOENT") return json(res, 200, { assets: [] });
148
+ throw err;
149
+ }
150
+ const assets = [];
151
+ for (const name of entries) {
152
+ if (!validateAssetName(name)) continue;
153
+ const stat = await fs.stat(path.join(scopedDir, name));
154
+ if (!stat.isFile()) continue;
155
+ assets.push({
156
+ name,
157
+ size: stat.size,
158
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
159
+ mtime: stat.mtimeMs,
160
+ mime: mimeForFilename(name),
161
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
162
+ importPath: assetImportPath(scope, name),
163
+ unused: true
164
+ });
165
+ }
166
+ assets.sort((a, b) => a.name.localeCompare(b.name));
167
+ if (assets.length > 0) {
168
+ const isGlobal = scope === GLOBAL_SCOPE;
169
+ const scanIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
170
+ const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
171
+ const paths = assets.map((a) => a.importPath);
172
+ for (const docId of scanIds) {
173
+ const source = await readDocSource(ctx.docsRoot, docId);
174
+ if (source === null) continue;
175
+ for (const p of findReferencedAssets(source, paths)) {
176
+ const asset = pathToAsset.get(p);
177
+ if (asset) asset.unused = false;
178
+ }
179
+ }
180
+ }
181
+ return json(res, 200, { assets });
182
+ }
183
+ if (fileMatch) {
184
+ const scope = decodeURIComponent(fileMatch[1]);
185
+ const filename = decodeURIComponent(fileMatch[2]);
186
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
187
+ if (!file) return json(res, 400, { error: "invalid path" });
188
+ if (method === "GET") try {
189
+ const buf = await fs.readFile(file);
190
+ res.statusCode = 200;
191
+ res.setHeader("content-type", mimeForFilename(filename));
192
+ res.setHeader("cache-control", "no-store");
193
+ res.end(buf);
194
+ return;
195
+ } catch (err) {
196
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
197
+ throw err;
198
+ }
199
+ if (method === "POST") {
200
+ const requestCheck = validateMutationRequest(req);
201
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
202
+ const overwrite = url.searchParams.get("overwrite") === "1";
203
+ const lenHeader = req.headers["content-length"];
204
+ const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
205
+ if (Number.isFinite(len) && len > ASSET_MAX_BYTES) return json(res, 413, { error: "file too large" });
206
+ if (!overwrite) try {
207
+ await fs.access(file);
208
+ return json(res, 409, { error: "asset exists" });
209
+ } catch {}
210
+ const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
211
+ if (!scopedDir) return json(res, 400, { error: "invalid scope" });
212
+ await fs.mkdir(scopedDir, { recursive: true });
213
+ const chunks = [];
214
+ let total = 0;
215
+ let oversized = false;
216
+ await new Promise((resolve, reject) => {
217
+ req.on("data", (c) => {
218
+ total += c.length;
219
+ if (total > ASSET_MAX_BYTES) {
220
+ oversized = true;
221
+ req.destroy();
222
+ return;
223
+ }
224
+ chunks.push(c);
225
+ });
226
+ req.on("end", () => resolve());
227
+ req.on("error", reject);
228
+ });
229
+ if (oversized) return json(res, 413, { error: "file too large" });
230
+ await fs.writeFile(file, Buffer.concat(chunks));
231
+ const stat = await fs.stat(file);
232
+ return json(res, 200, {
233
+ ok: true,
234
+ name: filename,
235
+ size: stat.size,
236
+ createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
237
+ mtime: stat.mtimeMs,
238
+ mime: mimeForFilename(filename),
239
+ url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
240
+ importPath: assetImportPath(scope, filename)
241
+ });
242
+ }
243
+ if (method === "PATCH") {
244
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
245
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
246
+ const body = await readBody(req);
247
+ const target = validateAssetName(body.name);
248
+ if (!target) return json(res, 400, { error: "invalid name" });
249
+ if (target === filename) return json(res, 200, {
250
+ ok: true,
251
+ name: filename
252
+ });
253
+ const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
254
+ if (!dest) return json(res, 400, { error: "invalid name" });
255
+ try {
256
+ await fs.access(dest);
257
+ return json(res, 409, { error: "target exists" });
258
+ } catch {}
259
+ try {
260
+ await fs.rename(file, dest);
261
+ } catch (err) {
262
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
263
+ throw err;
264
+ }
265
+ return json(res, 200, {
266
+ ok: true,
267
+ name: target
268
+ });
269
+ }
270
+ if (method === "DELETE") {
271
+ const requestCheck = validateMutationRequest(req);
272
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
273
+ try {
274
+ await fs.unlink(file);
275
+ } catch (err) {
276
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
277
+ throw err;
278
+ }
279
+ return json(res, 200, { ok: true });
280
+ }
281
+ }
282
+ return next();
283
+ } catch (err) {
284
+ json(res, 500, { error: String(err.message ?? err) });
285
+ }
286
+ });
287
+ }
288
+
289
+ //#endregion
290
+ //#region src/vite/routes/docs.ts
291
+ function registerDocRoutes(server, ctx) {
292
+ server.middlewares.use("/__docs", async (req, res, next) => {
293
+ const url = new URL(req.url ?? "/", "http://local");
294
+ const method = req.method ?? "GET";
295
+ try {
296
+ const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
297
+ const idMatch = url.pathname.match(/^\/([^/]+)$/);
298
+ if (duplicateMatch && method === "POST") {
299
+ const requestCheck = validateMutationRequest(req);
300
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
301
+ const docId = decodeURIComponent(duplicateMatch[1]);
302
+ const body = await readBody(req).catch(() => ({}));
303
+ const newId = typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0;
304
+ const result = await duplicateDocument(ctx, docId, newId);
305
+ return json(res, 200, {
306
+ ok: true,
307
+ docId: result.id
308
+ });
309
+ }
310
+ if (idMatch) {
311
+ const docId = decodeURIComponent(idMatch[1]);
312
+ if (method === "PATCH") {
313
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
314
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
315
+ const body = await readBody(req);
316
+ const result = await renameDocument(ctx, docId, body.title);
317
+ return json(res, 200, {
318
+ ok: true,
319
+ title: result.title
320
+ });
321
+ }
322
+ if (method === "DELETE") {
323
+ const requestCheck = validateMutationRequest(req);
324
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
325
+ await deleteDocument(ctx, docId);
326
+ return json(res, 200, { ok: true });
327
+ }
328
+ }
329
+ next();
330
+ } catch (err) {
331
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
332
+ json(res, 500, { error: String(err.message ?? err) });
333
+ }
334
+ });
335
+ }
336
+
337
+ //#endregion
338
+ //#region src/vite/routes/edit.ts
339
+ function readLoc(body) {
340
+ const { docId, line, column } = body;
341
+ if (typeof docId !== "string") return null;
342
+ if (typeof line !== "number" || typeof column !== "number") return null;
343
+ return {
344
+ docId,
345
+ line,
346
+ column
347
+ };
348
+ }
349
+ function registerEditRoutes(server, ctx) {
350
+ const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
351
+ server.middlewares.use("/__edit", async (req, res, next) => {
352
+ const url = new URL(req.url ?? "/", "http://local");
353
+ const method = req.method ?? "GET";
354
+ try {
355
+ if (method === "GET" && url.pathname === "/text") {
356
+ const docId = url.searchParams.get("docId") ?? "";
357
+ const entry = entryFor(docId);
358
+ const locs = (url.searchParams.get("locs") ?? "").split(",").map((pair) => pair.split(":").map(Number)).filter(([line, column]) => Number.isFinite(line) && Number.isFinite(column)).map(([line, column]) => ({
359
+ line,
360
+ column
361
+ }));
362
+ if (!entry || locs.length === 0) return json(res, 400, { error: "invalid target" });
363
+ const source = await fs.readFile(entry, "utf8");
364
+ const resolved = resolveTextTarget(source, locs, url.searchParams.get("shown") ?? void 0);
365
+ if (!resolved) return json(res, 404, { error: "element not found" });
366
+ return json(res, 200, resolved);
367
+ }
368
+ if (method === "PUT" && url.pathname === "/text") {
369
+ const check = validateMutationRequest(req, { requireJsonBody: true });
370
+ if (!check.ok) return json(res, check.status, { error: check.error });
371
+ const body = await readBody(req);
372
+ const loc = readLoc(body);
373
+ const text = body.text;
374
+ if (!loc || typeof text !== "string") return json(res, 400, { error: "invalid payload" });
375
+ const entry = entryFor(loc.docId);
376
+ if (!entry) return json(res, 404, { error: "document not found" });
377
+ const source = await fs.readFile(entry, "utf8");
378
+ const result = replaceTextAt(source, loc, text, {
379
+ index: typeof body.index === "number" ? body.index : void 0,
380
+ expected: typeof body.expected === "string" ? body.expected : void 0
381
+ });
382
+ if (!result.ok) return json(res, result.status, { error: result.error });
383
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
384
+ return json(res, 200, { ok: true });
385
+ }
386
+ if (method === "POST" && url.pathname === "/comment") {
387
+ const check = validateMutationRequest(req, { requireJsonBody: true });
388
+ if (!check.ok) return json(res, check.status, { error: check.error });
389
+ const body = await readBody(req);
390
+ const loc = readLoc(body);
391
+ const note = body.note;
392
+ if (!loc || typeof note !== "string" || note.trim() === "") return json(res, 400, { error: "invalid payload" });
393
+ const entry = entryFor(loc.docId);
394
+ if (!entry) return json(res, 404, { error: "document not found" });
395
+ const source = await fs.readFile(entry, "utf8");
396
+ const inserted = insertMarker(source, loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
397
+ if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
398
+ await fs.writeFile(entry, inserted.source, "utf8");
399
+ return json(res, 200, {
400
+ ok: true,
401
+ id: inserted.id
402
+ });
403
+ }
404
+ return next();
405
+ } catch (err) {
406
+ json(res, 500, { error: String(err.message ?? err) });
407
+ }
408
+ });
409
+ server.middlewares.use("/__comments", async (req, res, next) => {
410
+ const url = new URL(req.url ?? "/", "http://local");
411
+ const method = req.method ?? "GET";
412
+ const docId = url.searchParams.get("docId") ?? "";
413
+ const entry = entryFor(docId);
414
+ try {
415
+ if (method === "GET") {
416
+ if (!entry) return json(res, 200, { comments: [] });
417
+ return json(res, 200, { comments: parseMarkers(await fs.readFile(entry, "utf8")) });
418
+ }
419
+ if (method === "DELETE") {
420
+ const check = validateMutationRequest(req);
421
+ if (!check.ok) return json(res, check.status, { error: check.error });
422
+ const id = url.searchParams.get("id") ?? "";
423
+ if (!entry || !/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
424
+ const source = await fs.readFile(entry, "utf8");
425
+ const next$1 = removeMarker(source, id);
426
+ if (next$1 === null) return json(res, 404, { error: "comment not found" });
427
+ await fs.writeFile(entry, next$1, "utf8");
428
+ return json(res, 200, { ok: true });
429
+ }
430
+ return next();
431
+ } catch (err) {
432
+ json(res, 500, { error: String(err.message ?? err) });
433
+ }
434
+ });
435
+ }
436
+
437
+ //#endregion
438
+ //#region src/vite/routes/folders.ts
439
+ function registerFolderRoutes(server, ctx) {
440
+ server.middlewares.use("/__folders", async (req, res, next) => {
441
+ const url = new URL(req.url ?? "/", "http://local");
442
+ const method = req.method ?? "GET";
443
+ try {
444
+ if (method === "GET" && url.pathname === "/") return json(res, 200, await readManifest(ctx.manifestPath));
445
+ if (method === "POST" && url.pathname === "/") {
446
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
447
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
448
+ const body = await readBody(req);
449
+ const name = validateName(body.name);
450
+ if (!name) return json(res, 400, { error: "invalid name" });
451
+ const icon = validateIcon(body.icon);
452
+ if (!icon) return json(res, 400, { error: "invalid icon" });
453
+ const manifest = await readManifest(ctx.manifestPath);
454
+ const folder = {
455
+ id: newFolderId(),
456
+ name,
457
+ icon
458
+ };
459
+ manifest.folders.push(folder);
460
+ await writeManifest(ctx.manifestPath, manifest);
461
+ return json(res, 200, folder);
462
+ }
463
+ if (method === "PUT" && url.pathname === "/assign") {
464
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
465
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
466
+ const body = await readBody(req);
467
+ if (typeof body.docId !== "string" || !DOC_ID_RE.test(body.docId)) return json(res, 400, { error: "invalid docId" });
468
+ const docId = body.docId;
469
+ let folderId;
470
+ if (body.folderId === null) folderId = null;
471
+ else if (typeof body.folderId === "string" && FOLDER_ID_RE.test(body.folderId)) folderId = body.folderId;
472
+ else return json(res, 400, { error: "invalid folderId" });
473
+ const manifest = await readManifest(ctx.manifestPath);
474
+ if (folderId && !manifest.folders.some((f) => f.id === folderId)) return json(res, 404, { error: "folder not found" });
475
+ if (folderId === null) delete manifest.assignments[docId];
476
+ else manifest.assignments[docId] = folderId;
477
+ await writeManifest(ctx.manifestPath, manifest);
478
+ return json(res, 200, { ok: true });
479
+ }
480
+ if (method === "PUT" && url.pathname === "/reorder") {
481
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
482
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
483
+ const body = await readBody(req);
484
+ const manifest = await readManifest(ctx.manifestPath);
485
+ const ids = validateReorder(body.ids, manifest.folders);
486
+ if (!ids) return json(res, 400, { error: "invalid ids" });
487
+ const byId = new Map(manifest.folders.map((f) => [f.id, f]));
488
+ manifest.folders = ids.map((id) => byId.get(id));
489
+ await writeManifest(ctx.manifestPath, manifest);
490
+ return json(res, 200, { ok: true });
491
+ }
492
+ const idMatch = url.pathname.match(/^\/([^/]+)$/);
493
+ if (idMatch) {
494
+ const id = idMatch[1];
495
+ if (!FOLDER_ID_RE.test(id)) return json(res, 400, { error: "invalid id" });
496
+ if (method === "PATCH") {
497
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
498
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
499
+ const body = await readBody(req);
500
+ const manifest = await readManifest(ctx.manifestPath);
501
+ const folder = manifest.folders.find((f) => f.id === id);
502
+ if (!folder) return json(res, 404, { error: "folder not found" });
503
+ if (body.name !== void 0) {
504
+ const name = validateName(body.name);
505
+ if (!name) return json(res, 400, { error: "invalid name" });
506
+ folder.name = name;
507
+ }
508
+ if (body.icon !== void 0) {
509
+ const icon = validateIcon(body.icon);
510
+ if (!icon) return json(res, 400, { error: "invalid icon" });
511
+ folder.icon = icon;
512
+ }
513
+ await writeManifest(ctx.manifestPath, manifest);
514
+ return json(res, 200, folder);
515
+ }
516
+ if (method === "DELETE") {
517
+ const requestCheck = validateMutationRequest(req);
518
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
519
+ const manifest = await readManifest(ctx.manifestPath);
520
+ const before = manifest.folders.length;
521
+ manifest.folders = manifest.folders.filter((f) => f.id !== id);
522
+ if (manifest.folders.length === before) return json(res, 404, { error: "folder not found" });
523
+ for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
524
+ await writeManifest(ctx.manifestPath, manifest);
525
+ return json(res, 200, { ok: true });
526
+ }
527
+ }
528
+ next();
529
+ } catch (err) {
530
+ json(res, 500, { error: String(err.message ?? err) });
531
+ }
532
+ });
533
+ }
534
+
535
+ //#endregion
536
+ //#region src/vite/api-plugin.ts
537
+ function apiPlugin(opts) {
538
+ return {
539
+ name: "open-doc:api",
540
+ apply: "serve",
541
+ configureServer(server) {
542
+ const ctx = makeContext(opts);
543
+ registerAssetRoutes(server, ctx);
544
+ registerFolderRoutes(server, ctx);
545
+ registerDocRoutes(server, ctx);
546
+ registerEditRoutes(server, ctx);
547
+ }
548
+ };
549
+ }
550
+
551
+ //#endregion
552
+ //#region src/vite/design-plugin.ts
553
+ function parseSource$1(source) {
554
+ try {
555
+ return parse(source, {
556
+ sourceType: "module",
557
+ plugins: ["typescript", "jsx"],
558
+ errorRecovery: true
559
+ });
560
+ } catch {
561
+ return null;
562
+ }
563
+ }
564
+ function programBody(ast) {
565
+ return ast.program?.body ?? [];
566
+ }
567
+ function designObjectOf(node) {
568
+ let varDecl = null;
569
+ if (node.type === "VariableDeclaration") varDecl = node;
570
+ else if (node.type === "ExportNamedDeclaration") {
571
+ const decl = node.declaration;
572
+ if (decl?.type === "VariableDeclaration") varDecl = decl;
573
+ }
574
+ if (!varDecl) return null;
575
+ const declarations = varDecl.declarations ?? [];
576
+ for (const d of declarations) {
577
+ const id = d.id;
578
+ if (id?.type !== "Identifier" || id.name !== "design") continue;
579
+ const init = d.init;
580
+ if (!init) return "unsupported";
581
+ let inner = init;
582
+ if (inner.type === "TSSatisfiesExpression" || inner.type === "TSAsExpression") {
583
+ const expr = inner.expression;
584
+ if (expr) inner = expr;
585
+ }
586
+ if (inner.type !== "ObjectExpression") return "unsupported";
587
+ return {
588
+ decl: node,
589
+ object: inner
590
+ };
591
+ }
592
+ return null;
593
+ }
594
+ function findDesign(ast) {
595
+ for (const node of programBody(ast)) {
596
+ const hit = designObjectOf(node);
597
+ if (hit === null) continue;
598
+ if (hit === "unsupported") return null;
599
+ return {
600
+ loc: {
601
+ declStart: hit.decl.start,
602
+ declEnd: hit.decl.end,
603
+ objectStart: hit.object.start,
604
+ objectEnd: hit.object.end
605
+ },
606
+ object: hit.object
607
+ };
608
+ }
609
+ return null;
610
+ }
611
+ function literalToValue(node) {
612
+ switch (node.type) {
613
+ case "StringLiteral": return node.value;
614
+ case "NumericLiteral": return node.value;
615
+ case "BooleanLiteral": return node.value;
616
+ case "NullLiteral": return null;
617
+ case "UnaryExpression": {
618
+ const op = node.operator;
619
+ const arg = node.argument;
620
+ const v = literalToValue(arg);
621
+ if (op === "-" && typeof v === "number") return -v;
622
+ if (op === "+" && typeof v === "number") return v;
623
+ throw new Error(`unsupported unary operator ${op}`);
624
+ }
625
+ case "TemplateLiteral": {
626
+ const quasis = node.quasis;
627
+ const expressions = node.expressions;
628
+ if (expressions.length > 0) throw new Error("template literal has expressions");
629
+ const value = quasis[0].value;
630
+ return value.cooked ?? value.raw;
631
+ }
632
+ case "ObjectExpression": {
633
+ const properties = node.properties;
634
+ const out = {};
635
+ for (const prop of properties) {
636
+ if (prop.type !== "ObjectProperty") throw new Error("object has spread or method");
637
+ const p = prop;
638
+ if (p.computed) throw new Error("object has computed key");
639
+ let key;
640
+ if (p.key.type === "Identifier" && typeof p.key.name === "string") key = p.key.name;
641
+ else if (p.key.type === "StringLiteral" && typeof p.key.value === "string") key = p.key.value;
642
+ else throw new Error("unsupported object key");
643
+ out[key] = literalToValue(p.value);
644
+ }
645
+ return out;
646
+ }
647
+ default: throw new Error(`unsupported node type ${node.type}`);
648
+ }
649
+ }
650
+ function isPlainObject(v) {
651
+ return typeof v === "object" && v !== null && !Array.isArray(v);
652
+ }
653
+ function mergeDesign(base, patch) {
654
+ const out = JSON.parse(JSON.stringify(base));
655
+ const apply = (target, src) => {
656
+ for (const [k, v] of Object.entries(src)) if (isPlainObject(v) && isPlainObject(target[k])) apply(target[k], v);
657
+ else target[k] = v;
658
+ };
659
+ if (isPlainObject(patch)) apply(out, patch);
660
+ return out;
661
+ }
662
+ function indent(level) {
663
+ return " ".repeat(level);
664
+ }
665
+ function jsString(s) {
666
+ return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
667
+ }
668
+ function isValidIdentifier(name) {
669
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
670
+ }
671
+ function serializeValue(value, level) {
672
+ if (value === null) return "null";
673
+ if (typeof value === "string") return jsString(value);
674
+ if (typeof value === "number") {
675
+ if (!Number.isFinite(value)) throw new Error("non-finite number");
676
+ return String(value);
677
+ }
678
+ if (typeof value === "boolean") return value ? "true" : "false";
679
+ if (isPlainObject(value)) {
680
+ const entries = Object.entries(value);
681
+ if (entries.length === 0) return "{}";
682
+ const childIndent = indent(level + 1);
683
+ const lines = entries.map(([k, v]) => {
684
+ const key = isValidIdentifier(k) ? k : jsString(k);
685
+ return `${childIndent}${key}: ${serializeValue(v, level + 1)},`;
686
+ });
687
+ return `{\n${lines.join("\n")}\n${indent(level)}}`;
688
+ }
689
+ throw new Error(`unsupported value type ${typeof value}`);
690
+ }
691
+ function serializeDesign(design) {
692
+ return serializeValue(design, 0);
693
+ }
694
+ function parseDocDesign(source) {
695
+ const ast = parseSource$1(source);
696
+ if (!ast) return {
697
+ ok: false,
698
+ exists: true,
699
+ error: "could not parse document source"
700
+ };
701
+ const found = findDesign(ast);
702
+ if (!found) {
703
+ const hasBinding = programBody(ast).some((node) => designObjectOf(node) !== null);
704
+ if (hasBinding) return {
705
+ ok: false,
706
+ exists: true,
707
+ error: "design has an unsupported initializer"
708
+ };
709
+ return {
710
+ ok: false,
711
+ exists: false
712
+ };
713
+ }
714
+ let value;
715
+ try {
716
+ value = literalToValue(found.object);
717
+ } catch (err) {
718
+ return {
719
+ ok: false,
720
+ exists: true,
721
+ error: err.message
722
+ };
723
+ }
724
+ return {
725
+ ok: true,
726
+ design: mergeDesign(defaultDesign, value),
727
+ loc: found.loc
728
+ };
729
+ }
730
+ function findImports(ast) {
731
+ const out = [];
732
+ for (const node of programBody(ast)) {
733
+ if (node.type !== "ImportDeclaration") continue;
734
+ const src = node.source?.value;
735
+ if (typeof src !== "string") continue;
736
+ out.push({
737
+ node,
738
+ source: src,
739
+ specifiers: node.specifiers ?? []
740
+ });
741
+ }
742
+ return out;
743
+ }
744
+ function ensureDesignSystemImport(source, ast) {
745
+ const imports = findImports(ast);
746
+ const coreImport = imports.find((imp) => imp.source === "@open-document/core");
747
+ if (coreImport) {
748
+ const hasDesignSystem = coreImport.specifiers.some((spec) => {
749
+ if (spec.type !== "ImportSpecifier") return false;
750
+ const imported = spec.imported;
751
+ return imported?.name === "DesignSystem";
752
+ });
753
+ if (hasDesignSystem) return source;
754
+ const node = coreImport.node;
755
+ const importText = source.slice(node.start, node.end);
756
+ const braceClose = importText.lastIndexOf("}");
757
+ if (braceClose === -1) return source;
758
+ const absoluteBrace = node.start + braceClose;
759
+ const insertText = coreImport.specifiers.length > 0 ? ", type DesignSystem" : "type DesignSystem";
760
+ return source.slice(0, absoluteBrace) + insertText + source.slice(absoluteBrace);
761
+ }
762
+ const stmt = `import type { DesignSystem } from '@open-document/core';\n`;
763
+ if (imports.length > 0) {
764
+ const insertAt = imports[imports.length - 1].node.end;
765
+ const trail = source[insertAt] === "\n" ? "" : "\n";
766
+ return `${source.slice(0, insertAt)}\n${stmt.slice(0, -1)}${trail}${source.slice(insertAt)}`;
767
+ }
768
+ return `${stmt}\n${source}`;
769
+ }
770
+ function findInsertionPoint(source, ast) {
771
+ const imports = findImports(ast);
772
+ if (imports.length === 0) return 0;
773
+ let off = imports[imports.length - 1].node.end;
774
+ while (off < source.length && source[off] !== "\n") off++;
775
+ if (off < source.length) off++;
776
+ return off;
777
+ }
778
+ function applyDesignWrite(source, next) {
779
+ let body;
780
+ try {
781
+ body = serializeDesign(next);
782
+ } catch (err) {
783
+ return {
784
+ ok: false,
785
+ status: 422,
786
+ error: `serialize failed: ${err.message}`
787
+ };
788
+ }
789
+ const ast = parseSource$1(source);
790
+ if (!ast) return {
791
+ ok: false,
792
+ status: 422,
793
+ error: "could not parse document source"
794
+ };
795
+ const found = findDesign(ast);
796
+ if (found) {
797
+ const out = source.slice(0, found.loc.objectStart) + body + source.slice(found.loc.objectEnd);
798
+ return {
799
+ ok: true,
800
+ source: out,
801
+ created: false
802
+ };
803
+ }
804
+ const withImport = ensureDesignSystemImport(source, ast);
805
+ const ast2 = parseSource$1(withImport);
806
+ if (!ast2) return {
807
+ ok: false,
808
+ status: 422,
809
+ error: "failed to re-parse after adding import"
810
+ };
811
+ const insertAt = findInsertionPoint(withImport, ast2);
812
+ const block = `\nexport const design: DesignSystem = ${body};\n`;
813
+ return {
814
+ ok: true,
815
+ source: withImport.slice(0, insertAt) + block + withImport.slice(insertAt),
816
+ created: true
817
+ };
818
+ }
819
+ function designPlugin(opts) {
820
+ const userCwd = opts.userCwd;
821
+ const docsDir = opts.docsDir ?? "docs";
822
+ return {
823
+ name: "open-doc:design",
824
+ apply: "serve",
825
+ configureServer(server) {
826
+ server.middlewares.use("/__design", async (req, res, next) => {
827
+ const url = new URL(req.url ?? "/", "http://local");
828
+ const method = req.method ?? "GET";
829
+ const docId = url.searchParams.get("docId") ?? "";
830
+ const file = resolveDocPath(userCwd, docsDir, docId);
831
+ if (!file) return json(res, 400, { error: "invalid docId" });
832
+ try {
833
+ if (method === "GET" && url.pathname === "/") {
834
+ let source;
835
+ try {
836
+ source = await fs.readFile(file, "utf8");
837
+ } catch {
838
+ return json(res, 404, { error: "document not found" });
839
+ }
840
+ const parsed = parseDocDesign(source);
841
+ if (parsed.ok) return json(res, 200, {
842
+ design: parsed.design,
843
+ exists: true,
844
+ warning: null
845
+ });
846
+ if (parsed.exists === false) return json(res, 200, {
847
+ design: defaultDesign,
848
+ exists: false,
849
+ warning: null
850
+ });
851
+ return json(res, 200, {
852
+ design: defaultDesign,
853
+ exists: true,
854
+ warning: parsed.error
855
+ });
856
+ }
857
+ if (method === "PUT" && url.pathname === "/") {
858
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
859
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
860
+ const body = await readBody(req);
861
+ const patch = body.patch;
862
+ if (!patch || typeof patch !== "object") return json(res, 400, { error: "missing patch object" });
863
+ let source;
864
+ try {
865
+ source = await fs.readFile(file, "utf8");
866
+ } catch {
867
+ return json(res, 404, { error: "document not found" });
868
+ }
869
+ const parsed = parseDocDesign(source);
870
+ if (!parsed.ok && parsed.exists) return json(res, 422, { error: parsed.error });
871
+ const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
872
+ const written = applyDesignWrite(source, merged);
873
+ if (!written.ok) return json(res, written.status, { error: written.error });
874
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
875
+ return json(res, 200, {
876
+ ok: true,
877
+ design: merged,
878
+ created: written.created
879
+ });
880
+ }
881
+ if (method === "POST" && url.pathname === "/reset") {
882
+ const requestCheck = validateMutationRequest(req);
883
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
884
+ let source;
885
+ try {
886
+ source = await fs.readFile(file, "utf8");
887
+ } catch {
888
+ return json(res, 404, { error: "document not found" });
889
+ }
890
+ const written = applyDesignWrite(source, defaultDesign);
891
+ if (!written.ok) return json(res, written.status, { error: written.error });
892
+ if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
893
+ return json(res, 200, {
894
+ ok: true,
895
+ design: defaultDesign,
896
+ created: written.created
897
+ });
898
+ }
899
+ return next();
900
+ } catch (err) {
901
+ json(res, 500, { error: String(err.message ?? err) });
902
+ }
903
+ });
904
+ }
905
+ };
906
+ }
907
+
908
+ //#endregion
909
+ //#region src/vite/loc-tags-plugin.ts
910
+ const FORWARDING_COMPONENTS = new Set(["ImagePlaceholder"]);
911
+ function taggableName(opening) {
912
+ const name = opening.name;
913
+ if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
914
+ if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
915
+ return null;
916
+ }
917
+ function alreadyTagged(opening) {
918
+ const attributes = opening.attributes ?? [];
919
+ return attributes.some((attr) => {
920
+ if (attr.type !== "JSXAttribute") return false;
921
+ const name = attr.name;
922
+ return name?.name === "data-od-loc";
923
+ });
924
+ }
925
+ function injectLocTags(code) {
926
+ const ast = parseSource(code);
927
+ if (!ast) return null;
928
+ const insertions = [];
929
+ walkJsx(ast, (node) => {
930
+ const opening = node.openingElement;
931
+ if (!opening || !node.loc) return;
932
+ if (!taggableName(opening) || alreadyTagged(opening)) return;
933
+ const nameNode = opening.name;
934
+ insertions.push({
935
+ offset: nameNode.end,
936
+ text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
937
+ });
938
+ });
939
+ if (insertions.length === 0) return null;
940
+ insertions.sort((a, b) => b.offset - a.offset);
941
+ let next = code;
942
+ for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
943
+ return next;
944
+ }
945
+ function isDocSourceFile(id, docsRootPosix) {
946
+ const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
947
+ if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
948
+ if (!filePath.endsWith(".tsx")) return false;
949
+ if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
950
+ return filePath.slice(docsRootPosix.length + 1).includes("/");
951
+ }
952
+ function locTagsPlugin(opts) {
953
+ const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
954
+ return {
955
+ name: "open-doc:loc-tags",
956
+ apply: "serve",
957
+ enforce: "pre",
958
+ transform(code, id) {
959
+ if (!isDocSourceFile(id, docsRoot)) return null;
960
+ const next = injectLocTags(code);
961
+ return next === null ? null : {
962
+ code: next,
963
+ map: null
964
+ };
965
+ }
966
+ };
967
+ }
968
+
969
+ //#endregion
970
+ //#region src/vite/mcp-plugin.ts
971
+ /**
972
+ * Mounts `@open-document/mcp` on the dev server so an agent and the browser act on
973
+ * one workspace — a tool call lands on disk and the page hot-reloads.
974
+ *
975
+ * The package is imported dynamically and is *not* a dependency of core: the
976
+ * MCP SDK is sizeable and only matters to people wiring up agents, so it stays
977
+ * opt-in. A missing install is reported, never fatal.
978
+ */
979
+ function mcpPlugin(opts) {
980
+ const endpoint = opts.endpoint ?? "/mcp";
981
+ return {
982
+ name: "open-doc:mcp",
983
+ apply: "serve",
984
+ async configureServer(server) {
985
+ let middleware;
986
+ try {
987
+ const specifier = "@open-document/mcp";
988
+ const mod = await import(specifier);
989
+ middleware = mod.createOpenDocMcpMiddleware({
990
+ userCwd: opts.userCwd,
991
+ docsDir: opts.docsDir,
992
+ assetsDir: opts.assetsDir,
993
+ version: opts.coreVersion
994
+ });
995
+ } catch {
996
+ server.config.logger.warn(chalk.yellow(" MCP endpoint disabled — run `pnpm add -D @open-document/mcp` to enable it.\n"));
997
+ return;
998
+ }
999
+ server.middlewares.use(endpoint, middleware);
1000
+ server.httpServer?.once("listening", () => {
1001
+ const address = server.httpServer?.address();
1002
+ const port = typeof address === "object" && address ? address.port : "";
1003
+ server.config.logger.info(` ${chalk.green("➜")} ${chalk.bold("MCP")}: ${chalk.cyan(`http://localhost:${port}${endpoint}`)}`);
1004
+ });
1005
+ }
1006
+ };
1007
+ }
1008
+
1009
+ //#endregion
1010
+ //#region src/vite/config.ts
1011
+ function findPackageRoot(fromFile) {
1012
+ let dir = path.dirname(fromFile);
1013
+ while (dir !== path.dirname(dir)) {
1014
+ if (existsSync(path.join(dir, "package.json"))) return dir;
1015
+ dir = path.dirname(dir);
1016
+ }
1017
+ throw new Error(`Could not find package.json walking up from ${fromFile}`);
1018
+ }
1019
+ const PKG_ROOT = findPackageRoot(fileURLToPath(import.meta.url));
1020
+ const APP_ROOT = path.join(PKG_ROOT, "src", "app");
1021
+ function readCoreVersion() {
1022
+ try {
1023
+ const raw = readFileSync(path.join(PKG_ROOT, "package.json"), "utf8");
1024
+ return JSON.parse(raw).version ?? "0.0.0";
1025
+ } catch {
1026
+ return "0.0.0";
1027
+ }
1028
+ }
1029
+ const CORE_VERSION = readCoreVersion();
1030
+ async function createViteConfig(opts) {
1031
+ const userCwd = path.resolve(opts.userCwd);
1032
+ const config = opts.config ?? await loadUserConfig(userCwd);
1033
+ const docsDir = config.docsDir ?? "docs";
1034
+ const assetsDir = config.assetsDir ?? "assets";
1035
+ const docsAbs = path.resolve(userCwd, docsDir);
1036
+ const themesAbs = path.resolve(userCwd, config.themesDir ?? "themes");
1037
+ const assetsAbs = path.resolve(userCwd, assetsDir);
1038
+ return {
1039
+ base: config.base ?? "/",
1040
+ root: APP_ROOT,
1041
+ configFile: false,
1042
+ envDir: userCwd,
1043
+ plugins: [
1044
+ locTagsPlugin({
1045
+ userCwd,
1046
+ docsDir
1047
+ }),
1048
+ react(),
1049
+ tailwindcss(),
1050
+ openDocPlugin({
1051
+ userCwd,
1052
+ config,
1053
+ coreVersion: CORE_VERSION
1054
+ }),
1055
+ themesPlugin({
1056
+ userCwd,
1057
+ config
1058
+ }),
1059
+ designPlugin({
1060
+ userCwd,
1061
+ docsDir
1062
+ }),
1063
+ apiPlugin({
1064
+ userCwd,
1065
+ docsDir,
1066
+ assetsDir,
1067
+ coreVersion: CORE_VERSION
1068
+ }),
1069
+ ...opts.mcp ? [mcpPlugin({
1070
+ userCwd,
1071
+ docsDir,
1072
+ assetsDir,
1073
+ coreVersion: CORE_VERSION
1074
+ })] : []
1075
+ ],
1076
+ resolve: { alias: {
1077
+ "@": APP_ROOT,
1078
+ "@assets": assetsAbs
1079
+ } },
1080
+ optimizeDeps: {
1081
+ entries: [path.join(APP_ROOT, "main.tsx")],
1082
+ include: [
1083
+ "react",
1084
+ "react-dom",
1085
+ "react-dom/client",
1086
+ "react-router-dom",
1087
+ "next-themes",
1088
+ "lucide-react",
1089
+ "clsx",
1090
+ "tailwind-merge"
1091
+ ],
1092
+ esbuildOptions: { plugins: [{
1093
+ name: "open-doc:virtual-externals",
1094
+ setup(build) {
1095
+ build.onResolve({ filter: /^virtual:open-doc\// }, (args) => ({
1096
+ path: args.path,
1097
+ external: true
1098
+ }));
1099
+ }
1100
+ }] }
1101
+ },
1102
+ server: {
1103
+ port: config.port ?? 5273,
1104
+ ...config.allowedHosts !== void 0 ? { allowedHosts: config.allowedHosts } : {},
1105
+ fs: { allow: [
1106
+ APP_ROOT,
1107
+ userCwd,
1108
+ docsAbs,
1109
+ themesAbs,
1110
+ assetsAbs
1111
+ ] }
1112
+ },
1113
+ build: {
1114
+ outDir: path.resolve(userCwd, "dist"),
1115
+ emptyOutDir: true
1116
+ }
1117
+ };
1118
+ }
1119
+
1120
+ //#endregion
1121
+ export { createViteConfig };