@open-document/core 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-BWZJ1gvL.js → build-C3pMGxJN.js} +2 -6
- package/dist/check-Dtwb1wvU.js +42 -0
- package/dist/cli/bin.d.ts +1 -1
- package/dist/cli/bin.js +124 -13
- package/dist/{config-EBFfKtWH.d.ts → config-CSC5lHsR.d.ts} +3 -2
- package/dist/config-Dg1AMP0r.js +2461 -0
- package/dist/context-FoX0afRf.js +26 -0
- package/dist/{dev-CZtw1oqs.js → dev-Cdd7NZRQ.js} +2 -6
- package/dist/diagram-xlVDekYk.js +763 -0
- package/dist/export-ClJ4T1uU.js +36 -0
- package/dist/import-D7Psi8WK.js +25 -0
- package/dist/index.d.ts +238 -117
- package/dist/index.js +516 -57
- package/dist/ops/index.d.ts +98 -8
- package/dist/ops/index.js +3 -202
- package/dist/ops-Ci5Xw6QG.js +1270 -0
- package/dist/{preview-DUfQl7Ij.js → preview-BhbCiAKC.js} +2 -6
- package/dist/sdk-CWMsH9Ms.d.ts +123 -0
- package/dist/vite/index.d.ts +9 -4
- package/dist/vite/index.js +2 -5
- package/env.d.ts +33 -1
- package/package.json +17 -6
- package/skills/create-doc/SKILL.md +6 -2
- package/skills/current-doc/SKILL.md +120 -0
- package/skills/doc-authoring/SKILL.md +79 -0
- package/skills/doc-authoring/references/long-form.md +131 -0
- package/src/app/components/data-table.tsx +196 -0
- package/src/app/components/diagram.tsx +76 -0
- package/src/app/components/flow-page.tsx +20 -3
- package/src/app/components/footnote.tsx +196 -0
- package/src/app/components/inspector/inspector.tsx +16 -0
- package/src/app/components/numbering.tsx +208 -0
- package/src/app/lib/agent-bridge.ts +128 -0
- package/src/app/lib/diagnostics.ts +282 -0
- package/src/app/lib/export-html.ts +35 -11
- package/src/app/lib/export-pdf.ts +54 -19
- package/src/app/lib/flow-measure.ts +100 -31
- package/src/app/lib/flow.test.ts +46 -0
- package/src/app/lib/flow.ts +28 -3
- package/src/app/lib/footnotes.test.tsx +102 -0
- package/src/app/lib/footnotes.ts +94 -0
- package/src/app/lib/labels.ts +175 -0
- package/src/app/lib/page-context.tsx +6 -1
- package/src/app/lib/scan.ts +26 -0
- package/src/app/lib/sdk.ts +3 -0
- package/src/app/lib/use-doc-pages.ts +50 -15
- package/src/app/routes/doc.tsx +25 -5
- package/dist/config-DBp4mOOf.js +0 -1121
- package/dist/design-BJLvOcCO.js +0 -53
- package/dist/edit-ops-DSdUroVO.js +0 -1225
- package/dist/sync-6GTPAt2t.js +0 -86
- package/dist/sync-C6CsPmyK.js +0 -3
|
@@ -1,1225 +0,0 @@
|
|
|
1
|
-
import fs from "node:fs/promises";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
4
|
-
import fg from "fast-glob";
|
|
5
|
-
import { loadConfigFromFile, normalizePath } from "vite";
|
|
6
|
-
import { parse } from "@babel/parser";
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
-
|
|
9
|
-
//#region src/vite/open-doc-plugin.ts
|
|
10
|
-
const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
11
|
-
const CONFIG_FILE = "open-doc.config.ts";
|
|
12
|
-
const DOCS_VMOD = "virtual:open-doc/docs";
|
|
13
|
-
const CONFIG_VMOD = "virtual:open-doc/config";
|
|
14
|
-
const FOLDERS_VMOD = "virtual:open-doc/folders";
|
|
15
|
-
async function readFoldersManifest(file) {
|
|
16
|
-
try {
|
|
17
|
-
const parsed = JSON.parse(await fs.readFile(file, "utf8"));
|
|
18
|
-
return {
|
|
19
|
-
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
|
20
|
-
assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
|
|
21
|
-
};
|
|
22
|
-
} catch (err) {
|
|
23
|
-
if (err.code === "ENOENT") return {
|
|
24
|
-
folders: [],
|
|
25
|
-
assignments: {}
|
|
26
|
-
};
|
|
27
|
-
throw err;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
function resolved$1(id) {
|
|
31
|
-
return `\0${id}`;
|
|
32
|
-
}
|
|
33
|
-
async function findDocs(userCwd, docsDir) {
|
|
34
|
-
const abs = path.resolve(userCwd, docsDir);
|
|
35
|
-
if (!existsSync(abs)) return [];
|
|
36
|
-
const hits = await fg("*/index.{tsx,jsx,ts,js}", {
|
|
37
|
-
cwd: abs,
|
|
38
|
-
absolute: true,
|
|
39
|
-
onlyFiles: true
|
|
40
|
-
});
|
|
41
|
-
return hits.sort();
|
|
42
|
-
}
|
|
43
|
-
function toId(absFile, docsRoot) {
|
|
44
|
-
return path.relative(docsRoot, absFile).split(path.sep)[0];
|
|
45
|
-
}
|
|
46
|
-
const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
|
|
47
|
-
const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
|
|
48
|
-
/**
|
|
49
|
-
* Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
|
|
50
|
-
* every discovery pass, and the two fields it needs (sort order, theme back-link)
|
|
51
|
-
* are contractually string literals.
|
|
52
|
-
*/
|
|
53
|
-
function extractMeta(src) {
|
|
54
|
-
const empty = {
|
|
55
|
-
theme: null,
|
|
56
|
-
createdAt: null
|
|
57
|
-
};
|
|
58
|
-
const metaStart = src.search(/export\s+const\s+meta\b/);
|
|
59
|
-
if (metaStart === -1) return empty;
|
|
60
|
-
const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
|
|
61
|
-
if (openBrace === -1) return empty;
|
|
62
|
-
let depth = 0;
|
|
63
|
-
let closeBrace = -1;
|
|
64
|
-
for (let i = openBrace; i < src.length; i++) {
|
|
65
|
-
const ch = src[i];
|
|
66
|
-
if (ch === "{") depth++;
|
|
67
|
-
else if (ch === "}") {
|
|
68
|
-
depth--;
|
|
69
|
-
if (depth === 0) {
|
|
70
|
-
closeBrace = i;
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
if (closeBrace === -1) return empty;
|
|
76
|
-
const body = src.slice(openBrace + 1, closeBrace);
|
|
77
|
-
return {
|
|
78
|
-
theme: body.match(META_THEME_RE)?.[1] ?? null,
|
|
79
|
-
createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
function parseCreatedAtMs(iso) {
|
|
83
|
-
if (!iso) return null;
|
|
84
|
-
const ms = Date.parse(iso);
|
|
85
|
-
return Number.isFinite(ms) ? ms : null;
|
|
86
|
-
}
|
|
87
|
-
async function readMeta(abs) {
|
|
88
|
-
try {
|
|
89
|
-
return extractMeta(await fs.readFile(abs, "utf8"));
|
|
90
|
-
} catch {
|
|
91
|
-
return {
|
|
92
|
-
theme: null,
|
|
93
|
-
createdAt: null
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
const warnedInvalidDocIds = new Set();
|
|
98
|
-
async function generateDocsModule(files, docsRoot, isDev) {
|
|
99
|
-
const scanned = await Promise.all(files.map(async (abs) => {
|
|
100
|
-
const meta = await readMeta(abs);
|
|
101
|
-
return {
|
|
102
|
-
id: toId(abs, docsRoot),
|
|
103
|
-
importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
|
|
104
|
-
theme: meta.theme,
|
|
105
|
-
createdAt: parseCreatedAtMs(meta.createdAt)
|
|
106
|
-
};
|
|
107
|
-
}));
|
|
108
|
-
const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
|
|
109
|
-
const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
|
|
110
|
-
const ids = JSON.stringify(entries.map((e) => e.id).sort());
|
|
111
|
-
const createdAtMap = {};
|
|
112
|
-
const themesMap = {};
|
|
113
|
-
for (const e of entries) {
|
|
114
|
-
if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
|
|
115
|
-
if (e.theme) themesMap[e.id] = e.theme;
|
|
116
|
-
}
|
|
117
|
-
const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
|
|
118
|
-
const devRuntime = isDev ? `
|
|
119
|
-
const docImportTokens = ${importTokens};
|
|
120
|
-
if (import.meta.hot) {
|
|
121
|
-
import.meta.hot.on('open-doc:doc-changed', (data) => {
|
|
122
|
-
const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
|
|
123
|
-
const token = Date.now();
|
|
124
|
-
for (const id of ids) {
|
|
125
|
-
if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
|
|
126
|
-
}
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
` : "";
|
|
130
|
-
const cases = entries.map((e) => {
|
|
131
|
-
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)})`;
|
|
132
|
-
return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
|
|
133
|
-
}).join("\n");
|
|
134
|
-
const code = `// virtual:open-doc/docs — generated
|
|
135
|
-
export const docIds = ${ids};
|
|
136
|
-
export const docCreatedAt = ${JSON.stringify(createdAtMap)};
|
|
137
|
-
export const docThemes = ${JSON.stringify(themesMap)};
|
|
138
|
-
${devRuntime}
|
|
139
|
-
|
|
140
|
-
export async function loadDoc(id) {
|
|
141
|
-
switch (id) {
|
|
142
|
-
${cases}
|
|
143
|
-
default: throw new Error('Document not found: ' + id);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
`;
|
|
147
|
-
return {
|
|
148
|
-
code,
|
|
149
|
-
ignored
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
function openDocPlugin(opts) {
|
|
153
|
-
const { userCwd, config, coreVersion } = opts;
|
|
154
|
-
const docsDir = config.docsDir ?? "docs";
|
|
155
|
-
const docsRoot = path.resolve(userCwd, docsDir);
|
|
156
|
-
const foldersManifestPath = path.join(docsRoot, ".folders.json");
|
|
157
|
-
let isDev = false;
|
|
158
|
-
const docIdForEntry = (p) => {
|
|
159
|
-
const rel = path.relative(docsRoot, p);
|
|
160
|
-
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
|
|
161
|
-
const parts = rel.split(path.sep);
|
|
162
|
-
if (parts.length !== 2) return null;
|
|
163
|
-
if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
|
|
164
|
-
return parts[0];
|
|
165
|
-
};
|
|
166
|
-
let docChangeTimer = null;
|
|
167
|
-
const pendingDocChanges = new Set();
|
|
168
|
-
const queueDocChanged = (server, id) => {
|
|
169
|
-
pendingDocChanges.add(id);
|
|
170
|
-
if (docChangeTimer) clearTimeout(docChangeTimer);
|
|
171
|
-
docChangeTimer = setTimeout(() => {
|
|
172
|
-
docChangeTimer = null;
|
|
173
|
-
const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
|
|
174
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
175
|
-
const docIds = Array.from(pendingDocChanges);
|
|
176
|
-
pendingDocChanges.clear();
|
|
177
|
-
server.ws.send({
|
|
178
|
-
type: "custom",
|
|
179
|
-
event: "open-doc:doc-changed",
|
|
180
|
-
data: { docIds }
|
|
181
|
-
});
|
|
182
|
-
}, 100);
|
|
183
|
-
};
|
|
184
|
-
return {
|
|
185
|
-
name: "open-doc",
|
|
186
|
-
config(_c, env) {
|
|
187
|
-
isDev = env.command === "serve";
|
|
188
|
-
return { server: { fs: { allow: [userCwd] } } };
|
|
189
|
-
},
|
|
190
|
-
resolveId(id) {
|
|
191
|
-
if (id === DOCS_VMOD) return resolved$1(DOCS_VMOD);
|
|
192
|
-
if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
|
|
193
|
-
if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
|
|
194
|
-
return null;
|
|
195
|
-
},
|
|
196
|
-
async load(id) {
|
|
197
|
-
if (id === resolved$1(DOCS_VMOD)) {
|
|
198
|
-
const files = await findDocs(userCwd, docsDir);
|
|
199
|
-
const { code, ignored } = await generateDocsModule(files, docsRoot, isDev);
|
|
200
|
-
for (const docId of ignored) {
|
|
201
|
-
if (warnedInvalidDocIds.has(docId)) continue;
|
|
202
|
-
warnedInvalidDocIds.add(docId);
|
|
203
|
-
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.`);
|
|
204
|
-
}
|
|
205
|
-
return code;
|
|
206
|
-
}
|
|
207
|
-
if (id === resolved$1(CONFIG_VMOD)) {
|
|
208
|
-
const userBuild = config.build ?? {};
|
|
209
|
-
const build$1 = isDev ? {
|
|
210
|
-
showDocBrowser: true,
|
|
211
|
-
allowHtmlExport: true
|
|
212
|
-
} : {
|
|
213
|
-
showDocBrowser: userBuild.showDocBrowser ?? true,
|
|
214
|
-
allowHtmlExport: userBuild.allowHtmlExport ?? true
|
|
215
|
-
};
|
|
216
|
-
return `export default ${JSON.stringify({
|
|
217
|
-
...config,
|
|
218
|
-
build: build$1,
|
|
219
|
-
version: coreVersion
|
|
220
|
-
})};\n`;
|
|
221
|
-
}
|
|
222
|
-
if (id === resolved$1(FOLDERS_VMOD)) {
|
|
223
|
-
const manifest = await readFoldersManifest(foldersManifestPath);
|
|
224
|
-
return `export default ${JSON.stringify(manifest)};\n`;
|
|
225
|
-
}
|
|
226
|
-
return null;
|
|
227
|
-
},
|
|
228
|
-
handleHotUpdate(ctx) {
|
|
229
|
-
const docId = docIdForEntry(ctx.file);
|
|
230
|
-
if (!docId) return;
|
|
231
|
-
queueDocChanged(ctx.server, docId);
|
|
232
|
-
return [];
|
|
233
|
-
},
|
|
234
|
-
configureServer(server) {
|
|
235
|
-
const isDocEntry = (p) => docIdForEntry(p) !== null;
|
|
236
|
-
let reloadTimer = null;
|
|
237
|
-
const reload = () => {
|
|
238
|
-
if (reloadTimer) clearTimeout(reloadTimer);
|
|
239
|
-
reloadTimer = setTimeout(() => {
|
|
240
|
-
reloadTimer = null;
|
|
241
|
-
const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
|
|
242
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
243
|
-
server.ws.send({ type: "full-reload" });
|
|
244
|
-
}, 150);
|
|
245
|
-
};
|
|
246
|
-
server.watcher.add(docsRoot);
|
|
247
|
-
server.watcher.on("add", (p) => {
|
|
248
|
-
if (isDocEntry(p)) reload();
|
|
249
|
-
});
|
|
250
|
-
server.watcher.on("unlink", (p) => {
|
|
251
|
-
if (isDocEntry(p)) reload();
|
|
252
|
-
});
|
|
253
|
-
server.watcher.on("unlinkDir", (p) => {
|
|
254
|
-
if (path.dirname(p) === docsRoot) reload();
|
|
255
|
-
});
|
|
256
|
-
let foldersTimer = null;
|
|
257
|
-
const foldersChanged = () => {
|
|
258
|
-
if (foldersTimer) clearTimeout(foldersTimer);
|
|
259
|
-
foldersTimer = setTimeout(() => {
|
|
260
|
-
foldersTimer = null;
|
|
261
|
-
const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
|
|
262
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
263
|
-
server.ws.send({
|
|
264
|
-
type: "custom",
|
|
265
|
-
event: "open-doc:files-changed",
|
|
266
|
-
data: {}
|
|
267
|
-
});
|
|
268
|
-
}, 100);
|
|
269
|
-
};
|
|
270
|
-
server.watcher.add(foldersManifestPath);
|
|
271
|
-
for (const event of [
|
|
272
|
-
"add",
|
|
273
|
-
"change",
|
|
274
|
-
"unlink"
|
|
275
|
-
]) server.watcher.on(event, (p) => {
|
|
276
|
-
if (p === foldersManifestPath) foldersChanged();
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
async function loadUserConfig(userCwd) {
|
|
282
|
-
const file = path.join(userCwd, CONFIG_FILE);
|
|
283
|
-
if (!existsSync(file)) return {};
|
|
284
|
-
const loaded = await loadConfigFromFile({
|
|
285
|
-
command: "serve",
|
|
286
|
-
mode: "development"
|
|
287
|
-
}, file, userCwd, "silent");
|
|
288
|
-
return loaded?.config ?? {};
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
//#endregion
|
|
292
|
-
//#region src/vite/routes/context.ts
|
|
293
|
-
function makeContext(opts) {
|
|
294
|
-
const userCwd = opts.userCwd;
|
|
295
|
-
const docsDir = opts.docsDir ?? "docs";
|
|
296
|
-
const assetsDir = opts.assetsDir ?? "assets";
|
|
297
|
-
const docsRoot = path.resolve(userCwd, docsDir);
|
|
298
|
-
return {
|
|
299
|
-
userCwd,
|
|
300
|
-
docsDir,
|
|
301
|
-
docsRoot,
|
|
302
|
-
globalAssetsRoot: path.resolve(userCwd, assetsDir),
|
|
303
|
-
manifestPath: path.join(docsRoot, ".folders.json"),
|
|
304
|
-
coreVersion: opts.coreVersion
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
async function readBody(req) {
|
|
308
|
-
return await new Promise((resolve, reject) => {
|
|
309
|
-
const chunks = [];
|
|
310
|
-
req.on("data", (c) => chunks.push(c));
|
|
311
|
-
req.on("end", () => {
|
|
312
|
-
const raw = Buffer.concat(chunks).toString("utf8");
|
|
313
|
-
if (!raw) return resolve({});
|
|
314
|
-
try {
|
|
315
|
-
resolve(JSON.parse(raw));
|
|
316
|
-
} catch (e) {
|
|
317
|
-
reject(e);
|
|
318
|
-
}
|
|
319
|
-
});
|
|
320
|
-
req.on("error", reject);
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
function json(res, status, body) {
|
|
324
|
-
res.statusCode = status;
|
|
325
|
-
res.setHeader("content-type", "application/json");
|
|
326
|
-
res.end(JSON.stringify(body));
|
|
327
|
-
}
|
|
328
|
-
const ENTRY_NAMES$1 = [
|
|
329
|
-
"index.tsx",
|
|
330
|
-
"index.jsx",
|
|
331
|
-
"index.ts",
|
|
332
|
-
"index.js"
|
|
333
|
-
];
|
|
334
|
-
/** Absolute path of a document's entry file, or null when the id is unusable. */
|
|
335
|
-
function resolveDocPath(userCwd, docsDir, docId) {
|
|
336
|
-
if (!DOC_ID_RE.test(docId)) return null;
|
|
337
|
-
const docsRoot = path.resolve(userCwd, docsDir);
|
|
338
|
-
const full = path.resolve(docsRoot, docId, ENTRY_NAMES$1[0]);
|
|
339
|
-
if (!full.startsWith(docsRoot + path.sep)) return null;
|
|
340
|
-
return full;
|
|
341
|
-
}
|
|
342
|
-
/** The entry file that actually exists on disk for a document, or null. */
|
|
343
|
-
function resolveDocEntry(docsRoot, docId) {
|
|
344
|
-
if (!DOC_ID_RE.test(docId)) return null;
|
|
345
|
-
const docDir$1 = path.resolve(docsRoot, docId);
|
|
346
|
-
if (!docDir$1.startsWith(docsRoot + path.sep)) return null;
|
|
347
|
-
for (const name of ENTRY_NAMES$1) {
|
|
348
|
-
const candidate = path.join(docDir$1, name);
|
|
349
|
-
if (existsSync(candidate)) return candidate;
|
|
350
|
-
}
|
|
351
|
-
return null;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
//#endregion
|
|
355
|
-
//#region src/editing/doc-ops.ts
|
|
356
|
-
function parseSource$1(source) {
|
|
357
|
-
try {
|
|
358
|
-
return parse(source, {
|
|
359
|
-
sourceType: "module",
|
|
360
|
-
plugins: ["typescript", "jsx"],
|
|
361
|
-
errorRecovery: true
|
|
362
|
-
});
|
|
363
|
-
} catch {
|
|
364
|
-
return null;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
function programBody(ast) {
|
|
368
|
-
return ast.program?.body ?? [];
|
|
369
|
-
}
|
|
370
|
-
function metaObjectOf(node) {
|
|
371
|
-
if (node.type !== "ExportNamedDeclaration") return null;
|
|
372
|
-
const decl = node.declaration;
|
|
373
|
-
if (decl?.type !== "VariableDeclaration") return null;
|
|
374
|
-
const declarations = decl.declarations ?? [];
|
|
375
|
-
for (const d of declarations) {
|
|
376
|
-
const id = d.id;
|
|
377
|
-
if (id?.type !== "Identifier" || id.name !== "meta") continue;
|
|
378
|
-
let init = d.init;
|
|
379
|
-
if (!init) return null;
|
|
380
|
-
if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
|
|
381
|
-
const expr = init.expression;
|
|
382
|
-
if (expr) init = expr;
|
|
383
|
-
}
|
|
384
|
-
return init.type === "ObjectExpression" ? init : null;
|
|
385
|
-
}
|
|
386
|
-
return null;
|
|
387
|
-
}
|
|
388
|
-
function findMetaObject(ast) {
|
|
389
|
-
for (const node of programBody(ast)) {
|
|
390
|
-
const object = metaObjectOf(node);
|
|
391
|
-
if (object) return object;
|
|
392
|
-
}
|
|
393
|
-
return null;
|
|
394
|
-
}
|
|
395
|
-
function jsString(value) {
|
|
396
|
-
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
|
|
397
|
-
}
|
|
398
|
-
function validateDocTitle(v) {
|
|
399
|
-
if (typeof v !== "string") return null;
|
|
400
|
-
const trimmed = v.trim();
|
|
401
|
-
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
402
|
-
return trimmed;
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Rewrites `meta.title` in place, adding the property when the meta object
|
|
406
|
-
* exists without one. Returns null when there is no meta object to edit —
|
|
407
|
-
* the caller reports that rather than inventing an export.
|
|
408
|
-
*/
|
|
409
|
-
function setMetaTitle(source, title) {
|
|
410
|
-
const ast = parseSource$1(source);
|
|
411
|
-
if (!ast) return null;
|
|
412
|
-
const object = findMetaObject(ast);
|
|
413
|
-
if (!object) return null;
|
|
414
|
-
const properties = object.properties ?? [];
|
|
415
|
-
for (const prop of properties) {
|
|
416
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
417
|
-
const p = prop;
|
|
418
|
-
if (p.computed) continue;
|
|
419
|
-
const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
|
|
420
|
-
if (key !== "title") continue;
|
|
421
|
-
return source.slice(0, p.value.start) + jsString(title) + source.slice(p.value.end);
|
|
422
|
-
}
|
|
423
|
-
const open = object.start + 1;
|
|
424
|
-
const rest = source.slice(open, object.end - 1);
|
|
425
|
-
const isEmpty = rest.trim() === "";
|
|
426
|
-
const inserted = isEmpty ? `\n title: ${jsString(title)},\n` : `\n title: ${jsString(title)},`;
|
|
427
|
-
return source.slice(0, open) + inserted + source.slice(open);
|
|
428
|
-
}
|
|
429
|
-
function readMetaTitle(source) {
|
|
430
|
-
const ast = parseSource$1(source);
|
|
431
|
-
if (!ast) return null;
|
|
432
|
-
const object = findMetaObject(ast);
|
|
433
|
-
if (!object) return null;
|
|
434
|
-
const properties = object.properties ?? [];
|
|
435
|
-
for (const prop of properties) {
|
|
436
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
437
|
-
const p = prop;
|
|
438
|
-
if (p.computed) continue;
|
|
439
|
-
const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
|
|
440
|
-
if (key !== "title") continue;
|
|
441
|
-
if (p.value.type !== "StringLiteral") return null;
|
|
442
|
-
return typeof p.value.value === "string" ? p.value.value : null;
|
|
443
|
-
}
|
|
444
|
-
return null;
|
|
445
|
-
}
|
|
446
|
-
/** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
|
|
447
|
-
function nextCopyId(baseId, taken) {
|
|
448
|
-
const stem = baseId.replace(/-copy(-\d+)?$/, "");
|
|
449
|
-
let candidate = `${stem}-copy`;
|
|
450
|
-
let n = 2;
|
|
451
|
-
while (taken.has(candidate)) {
|
|
452
|
-
candidate = `${stem}-copy-${n}`;
|
|
453
|
-
n++;
|
|
454
|
-
}
|
|
455
|
-
return candidate;
|
|
456
|
-
}
|
|
457
|
-
function copyTitle(title) {
|
|
458
|
-
return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
//#endregion
|
|
462
|
-
//#region src/files/folders.ts
|
|
463
|
-
const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
|
|
464
|
-
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
|
465
|
-
function emptyManifest() {
|
|
466
|
-
return {
|
|
467
|
-
folders: [],
|
|
468
|
-
assignments: {}
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
async function readManifest(file) {
|
|
472
|
-
try {
|
|
473
|
-
const raw = await fs.readFile(file, "utf8");
|
|
474
|
-
const parsed = JSON.parse(raw);
|
|
475
|
-
return {
|
|
476
|
-
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
|
477
|
-
assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
|
|
478
|
-
};
|
|
479
|
-
} catch (err) {
|
|
480
|
-
if (err.code === "ENOENT") return emptyManifest();
|
|
481
|
-
throw err;
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
async function writeManifest(file, manifest) {
|
|
485
|
-
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
486
|
-
await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
487
|
-
}
|
|
488
|
-
function newFolderId() {
|
|
489
|
-
return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
490
|
-
}
|
|
491
|
-
function validateName(v) {
|
|
492
|
-
if (typeof v !== "string") return null;
|
|
493
|
-
const trimmed = v.trim();
|
|
494
|
-
if (trimmed.length < 1 || trimmed.length > 40) return null;
|
|
495
|
-
return trimmed;
|
|
496
|
-
}
|
|
497
|
-
function validateReorder(v, current) {
|
|
498
|
-
if (!Array.isArray(v) || v.length !== current.length) return null;
|
|
499
|
-
const known = new Set(current.map((f) => f.id));
|
|
500
|
-
const seen = new Set();
|
|
501
|
-
const out = [];
|
|
502
|
-
for (const id of v) {
|
|
503
|
-
if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
|
|
504
|
-
if (!known.has(id) || seen.has(id)) return null;
|
|
505
|
-
seen.add(id);
|
|
506
|
-
out.push(id);
|
|
507
|
-
}
|
|
508
|
-
return out;
|
|
509
|
-
}
|
|
510
|
-
function validateIcon(v) {
|
|
511
|
-
if (!v || typeof v !== "object") return null;
|
|
512
|
-
const icon = v;
|
|
513
|
-
if (icon.type === "emoji") {
|
|
514
|
-
if (typeof icon.value !== "string") return null;
|
|
515
|
-
if (icon.value.length < 1 || icon.value.length > 8) return null;
|
|
516
|
-
return {
|
|
517
|
-
type: "emoji",
|
|
518
|
-
value: icon.value
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
if (icon.type === "color") {
|
|
522
|
-
if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
|
|
523
|
-
return {
|
|
524
|
-
type: "color",
|
|
525
|
-
value: icon.value
|
|
526
|
-
};
|
|
527
|
-
}
|
|
528
|
-
return null;
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
//#endregion
|
|
532
|
-
//#region src/ops/documents.ts
|
|
533
|
-
/**
|
|
534
|
-
* Operations shared by the dev API and the MCP server. Everything here takes an
|
|
535
|
-
* `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
|
|
536
|
-
* and a browser calling `/__docs` end up in exactly the same code.
|
|
537
|
-
*/
|
|
538
|
-
var OpsError = class extends Error {
|
|
539
|
-
constructor(status, message) {
|
|
540
|
-
super(message);
|
|
541
|
-
this.status = status;
|
|
542
|
-
this.name = "OpsError";
|
|
543
|
-
}
|
|
544
|
-
};
|
|
545
|
-
const ENTRY_NAMES = [
|
|
546
|
-
"index.tsx",
|
|
547
|
-
"index.jsx",
|
|
548
|
-
"index.ts",
|
|
549
|
-
"index.js"
|
|
550
|
-
];
|
|
551
|
-
function docDir(ctx, docId) {
|
|
552
|
-
if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
553
|
-
const dir = path.resolve(ctx.docsRoot, docId);
|
|
554
|
-
if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
555
|
-
return dir;
|
|
556
|
-
}
|
|
557
|
-
function resolveEntry(ctx, docId) {
|
|
558
|
-
const dir = docDir(ctx, docId);
|
|
559
|
-
for (const name of ENTRY_NAMES) {
|
|
560
|
-
const file = path.join(dir, name);
|
|
561
|
-
if (existsSync(file)) return file;
|
|
562
|
-
}
|
|
563
|
-
return null;
|
|
564
|
-
}
|
|
565
|
-
async function listDocIds(ctx) {
|
|
566
|
-
try {
|
|
567
|
-
const entries = await fs.readdir(ctx.docsRoot, { withFileTypes: true });
|
|
568
|
-
return entries.filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
569
|
-
} catch {
|
|
570
|
-
return [];
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
/** Reads what the doc declares without executing it — a regex over `export const meta`. */
|
|
574
|
-
function readMetaField(source, field) {
|
|
575
|
-
const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
|
|
576
|
-
const inMeta = source.slice(source.indexOf("export const meta"));
|
|
577
|
-
const match = inMeta.match(re);
|
|
578
|
-
return match?.[2];
|
|
579
|
-
}
|
|
580
|
-
async function listDocuments(ctx) {
|
|
581
|
-
const ids = await listDocIds(ctx);
|
|
582
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
583
|
-
const out = [];
|
|
584
|
-
for (const id of ids) {
|
|
585
|
-
const entry = resolveEntry(ctx, id);
|
|
586
|
-
const source = entry ? await fs.readFile(entry, "utf8") : "";
|
|
587
|
-
out.push({
|
|
588
|
-
id,
|
|
589
|
-
title: source ? readMetaTitle(source) : null,
|
|
590
|
-
subtitle: source ? readMetaField(source, "subtitle") : void 0,
|
|
591
|
-
theme: source ? readMetaField(source, "theme") : void 0,
|
|
592
|
-
createdAt: source ? readMetaField(source, "createdAt") : void 0,
|
|
593
|
-
folder: manifest.assignments[id],
|
|
594
|
-
entry: entry ? path.relative(ctx.userCwd, entry) : null
|
|
595
|
-
});
|
|
596
|
-
}
|
|
597
|
-
return out;
|
|
598
|
-
}
|
|
599
|
-
async function readDocument(ctx, docId) {
|
|
600
|
-
const entry = resolveEntry(ctx, docId);
|
|
601
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
602
|
-
return {
|
|
603
|
-
id: docId,
|
|
604
|
-
entry: path.relative(ctx.userCwd, entry),
|
|
605
|
-
source: await fs.readFile(entry, "utf8")
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
async function createDocument(ctx, docId, source) {
|
|
609
|
-
const dir = docDir(ctx, docId);
|
|
610
|
-
if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
|
|
611
|
-
await fs.mkdir(dir, { recursive: true });
|
|
612
|
-
const entry = path.join(dir, "index.tsx");
|
|
613
|
-
await fs.writeFile(entry, source, "utf8");
|
|
614
|
-
return {
|
|
615
|
-
id: docId,
|
|
616
|
-
entry: path.relative(ctx.userCwd, entry)
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
/**
|
|
620
|
-
* Whole-file overwrite. `expected` is the source the caller believes is on
|
|
621
|
-
* disk; passing it turns a blind overwrite into a conflict check, which is what
|
|
622
|
-
* keeps two agents (or an agent and a person) from clobbering each other.
|
|
623
|
-
*/
|
|
624
|
-
async function writeDocument(ctx, docId, source, expected) {
|
|
625
|
-
const entry = resolveEntry(ctx, docId);
|
|
626
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
627
|
-
if (expected !== void 0) {
|
|
628
|
-
const current = await fs.readFile(entry, "utf8");
|
|
629
|
-
if (current !== expected) throw new OpsError(409, "document changed on disk since it was read");
|
|
630
|
-
}
|
|
631
|
-
await fs.writeFile(entry, source, "utf8");
|
|
632
|
-
return {
|
|
633
|
-
id: docId,
|
|
634
|
-
entry: path.relative(ctx.userCwd, entry)
|
|
635
|
-
};
|
|
636
|
-
}
|
|
637
|
-
async function renameDocument(ctx, docId, rawTitle) {
|
|
638
|
-
const title = validateDocTitle(rawTitle);
|
|
639
|
-
if (!title) throw new OpsError(400, "invalid title");
|
|
640
|
-
const entry = resolveEntry(ctx, docId);
|
|
641
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
642
|
-
const source = await fs.readFile(entry, "utf8");
|
|
643
|
-
const next = setMetaTitle(source, title);
|
|
644
|
-
if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
|
|
645
|
-
if (next !== source) await fs.writeFile(entry, next, "utf8");
|
|
646
|
-
return {
|
|
647
|
-
id: docId,
|
|
648
|
-
title
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
async function duplicateDocument(ctx, docId, newId) {
|
|
652
|
-
const dir = docDir(ctx, docId);
|
|
653
|
-
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
654
|
-
const taken = new Set(await listDocIds(ctx));
|
|
655
|
-
let targetId;
|
|
656
|
-
if (newId) {
|
|
657
|
-
if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
|
|
658
|
-
if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
|
|
659
|
-
targetId = newId;
|
|
660
|
-
} else targetId = nextCopyId(docId, taken);
|
|
661
|
-
await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
|
|
662
|
-
const entry = resolveEntry(ctx, targetId);
|
|
663
|
-
if (entry) {
|
|
664
|
-
const source = await fs.readFile(entry, "utf8");
|
|
665
|
-
const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
|
|
666
|
-
if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
|
|
667
|
-
}
|
|
668
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
669
|
-
const folderId = manifest.assignments[docId];
|
|
670
|
-
if (folderId) {
|
|
671
|
-
manifest.assignments[targetId] = folderId;
|
|
672
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
673
|
-
}
|
|
674
|
-
return { id: targetId };
|
|
675
|
-
}
|
|
676
|
-
async function deleteDocument(ctx, docId) {
|
|
677
|
-
const dir = docDir(ctx, docId);
|
|
678
|
-
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
679
|
-
await fs.rm(dir, {
|
|
680
|
-
recursive: true,
|
|
681
|
-
force: true
|
|
682
|
-
});
|
|
683
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
684
|
-
if (manifest.assignments[docId]) {
|
|
685
|
-
delete manifest.assignments[docId];
|
|
686
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
//#endregion
|
|
691
|
-
//#region src/files/assets.ts
|
|
692
|
-
const GLOBAL_SCOPE = "@global";
|
|
693
|
-
const ASSET_MAX_BYTES = 25 * 1024 * 1024;
|
|
694
|
-
const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
|
|
695
|
-
const MIME_BY_EXT = {
|
|
696
|
-
png: "image/png",
|
|
697
|
-
jpg: "image/jpeg",
|
|
698
|
-
jpeg: "image/jpeg",
|
|
699
|
-
gif: "image/gif",
|
|
700
|
-
svg: "image/svg+xml",
|
|
701
|
-
webp: "image/webp",
|
|
702
|
-
avif: "image/avif",
|
|
703
|
-
ico: "image/x-icon",
|
|
704
|
-
pdf: "application/pdf",
|
|
705
|
-
woff: "font/woff",
|
|
706
|
-
woff2: "font/woff2",
|
|
707
|
-
ttf: "font/ttf",
|
|
708
|
-
otf: "font/otf",
|
|
709
|
-
csv: "text/csv; charset=utf-8",
|
|
710
|
-
json: "application/json",
|
|
711
|
-
txt: "text/plain; charset=utf-8",
|
|
712
|
-
md: "text/markdown; charset=utf-8"
|
|
713
|
-
};
|
|
714
|
-
function mimeForFilename(name) {
|
|
715
|
-
const dot = name.lastIndexOf(".");
|
|
716
|
-
if (dot < 0) return "application/octet-stream";
|
|
717
|
-
return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
|
|
718
|
-
}
|
|
719
|
-
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
720
|
-
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
721
|
-
}
|
|
722
|
-
function validateAssetName(v) {
|
|
723
|
-
if (typeof v !== "string") return null;
|
|
724
|
-
const trimmed = v.trim();
|
|
725
|
-
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
726
|
-
if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
|
|
727
|
-
if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
|
|
728
|
-
if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
|
|
729
|
-
const dot = trimmed.lastIndexOf(".");
|
|
730
|
-
if (dot <= 0 || dot === trimmed.length - 1) return null;
|
|
731
|
-
return trimmed;
|
|
732
|
-
}
|
|
733
|
-
function resolveAssetsDir(docsRoot, docId) {
|
|
734
|
-
if (!DOC_ID_RE.test(docId)) return null;
|
|
735
|
-
const docDir$1 = path.resolve(docsRoot, docId);
|
|
736
|
-
if (!docDir$1.startsWith(docsRoot + path.sep)) return null;
|
|
737
|
-
const assetsDir = path.resolve(docDir$1, "assets");
|
|
738
|
-
if (assetsDir !== path.join(docDir$1, "assets")) return null;
|
|
739
|
-
return assetsDir;
|
|
740
|
-
}
|
|
741
|
-
function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
|
|
742
|
-
if (scope === GLOBAL_SCOPE) return globalAssetsRoot;
|
|
743
|
-
return resolveAssetsDir(docsRoot, scope);
|
|
744
|
-
}
|
|
745
|
-
function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
|
|
746
|
-
if (!validateAssetName(filename)) return null;
|
|
747
|
-
const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
|
|
748
|
-
if (!dir) return null;
|
|
749
|
-
const file = path.resolve(dir, filename);
|
|
750
|
-
if (!file.startsWith(dir + path.sep)) return null;
|
|
751
|
-
return file;
|
|
752
|
-
}
|
|
753
|
-
/** How a document imports an asset — the string we look for when counting usages. */
|
|
754
|
-
function assetImportPath(scope, filename) {
|
|
755
|
-
return scope === GLOBAL_SCOPE ? `@assets/${filename}` : `./assets/${filename}`;
|
|
756
|
-
}
|
|
757
|
-
function escapeRegExp(value) {
|
|
758
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
759
|
-
}
|
|
760
|
-
/**
|
|
761
|
-
* Counts references to an asset in a document's source. Matches the quoted path
|
|
762
|
-
* in both import statements and `new URL('./assets/x.png', import.meta.url)`,
|
|
763
|
-
* which is every form the authoring skill sanctions.
|
|
764
|
-
*/
|
|
765
|
-
function countAssetUsages(source, importPath) {
|
|
766
|
-
const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
|
|
767
|
-
return source.match(quoted)?.length ?? 0;
|
|
768
|
-
}
|
|
769
|
-
function findReferencedAssets(source, importPaths) {
|
|
770
|
-
return importPaths.filter((p) => countAssetUsages(source, p) > 0);
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
//#endregion
|
|
774
|
-
//#region src/vite/themes-plugin.ts
|
|
775
|
-
const THEMES_VMOD = "virtual:open-doc/themes";
|
|
776
|
-
function resolved(id) {
|
|
777
|
-
return `\0${id}`;
|
|
778
|
-
}
|
|
779
|
-
const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
|
|
780
|
-
function parseFrontmatter(raw, themeId) {
|
|
781
|
-
const match = raw.match(FM_RE);
|
|
782
|
-
const fmText = match ? match[1] : "";
|
|
783
|
-
const body = match ? match[2] : raw;
|
|
784
|
-
const data = {};
|
|
785
|
-
for (const line of fmText.split(/\r?\n/)) {
|
|
786
|
-
const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
787
|
-
if (!m) continue;
|
|
788
|
-
let value = m[2].trim();
|
|
789
|
-
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
790
|
-
data[m[1]] = value;
|
|
791
|
-
}
|
|
792
|
-
return {
|
|
793
|
-
fm: {
|
|
794
|
-
name: data.name || themeId,
|
|
795
|
-
description: data.description || "",
|
|
796
|
-
pageSize: data.pageSize || "",
|
|
797
|
-
mode: data.mode || ""
|
|
798
|
-
},
|
|
799
|
-
body: body.trim()
|
|
800
|
-
};
|
|
801
|
-
}
|
|
802
|
-
async function findThemes(userCwd, themesDir) {
|
|
803
|
-
const abs = path.resolve(userCwd, themesDir);
|
|
804
|
-
if (!existsSync(abs)) return [];
|
|
805
|
-
const hits = await fg("*.md", {
|
|
806
|
-
cwd: abs,
|
|
807
|
-
absolute: true,
|
|
808
|
-
onlyFiles: true
|
|
809
|
-
});
|
|
810
|
-
return hits.sort();
|
|
811
|
-
}
|
|
812
|
-
async function readTheme(mdAbs, themesRoot) {
|
|
813
|
-
const id = path.basename(mdAbs, ".md");
|
|
814
|
-
const raw = await fs.readFile(mdAbs, "utf8");
|
|
815
|
-
const { fm, body } = parseFrontmatter(raw, id);
|
|
816
|
-
let demoAbs = null;
|
|
817
|
-
for (const cand of [
|
|
818
|
-
`${id}.demo.tsx`,
|
|
819
|
-
`${id}.demo.jsx`,
|
|
820
|
-
`${id}.demo.ts`,
|
|
821
|
-
`${id}.demo.js`
|
|
822
|
-
]) {
|
|
823
|
-
const p = path.join(themesRoot, cand);
|
|
824
|
-
if (existsSync(p)) {
|
|
825
|
-
demoAbs = p;
|
|
826
|
-
break;
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
return {
|
|
830
|
-
id,
|
|
831
|
-
frontmatter: fm,
|
|
832
|
-
body,
|
|
833
|
-
demoAbs
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
function generateThemesModule(themes, isDev) {
|
|
837
|
-
const meta = themes.map((t) => ({
|
|
838
|
-
id: t.id,
|
|
839
|
-
name: t.frontmatter.name,
|
|
840
|
-
description: t.frontmatter.description,
|
|
841
|
-
pageSize: t.frontmatter.pageSize,
|
|
842
|
-
mode: t.frontmatter.mode,
|
|
843
|
-
body: t.body,
|
|
844
|
-
hasDemo: t.demoAbs !== null
|
|
845
|
-
}));
|
|
846
|
-
const cases = themes.flatMap((t) => {
|
|
847
|
-
const abs = t.demoAbs;
|
|
848
|
-
if (!abs) return [];
|
|
849
|
-
const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
|
|
850
|
-
const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
|
|
851
|
-
return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
|
|
852
|
-
}).join("\n");
|
|
853
|
-
return `// virtual:open-doc/themes — generated
|
|
854
|
-
export const themes = ${JSON.stringify(meta)};
|
|
855
|
-
|
|
856
|
-
export async function loadThemeDemo(id) {
|
|
857
|
-
switch (id) {
|
|
858
|
-
${cases}
|
|
859
|
-
default: throw new Error('Theme demo not found: ' + id);
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
`;
|
|
863
|
-
}
|
|
864
|
-
function themesPlugin(opts) {
|
|
865
|
-
const { userCwd, config } = opts;
|
|
866
|
-
const themesDir = config.themesDir ?? "themes";
|
|
867
|
-
const themesRoot = path.resolve(userCwd, themesDir);
|
|
868
|
-
let isDev = false;
|
|
869
|
-
return {
|
|
870
|
-
name: "open-doc:themes",
|
|
871
|
-
config(_c, env) {
|
|
872
|
-
isDev = env.command === "serve";
|
|
873
|
-
},
|
|
874
|
-
resolveId(id) {
|
|
875
|
-
if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
|
|
876
|
-
return null;
|
|
877
|
-
},
|
|
878
|
-
async load(id) {
|
|
879
|
-
if (id !== resolved(THEMES_VMOD)) return null;
|
|
880
|
-
const files = await findThemes(userCwd, themesDir);
|
|
881
|
-
const themes = await Promise.all(files.map((f) => readTheme(f, themesRoot)));
|
|
882
|
-
return generateThemesModule(themes, isDev);
|
|
883
|
-
},
|
|
884
|
-
configureServer(server) {
|
|
885
|
-
const isThemeFile = (p) => {
|
|
886
|
-
const rel = path.relative(themesRoot, p);
|
|
887
|
-
if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
|
|
888
|
-
if (rel.includes(path.sep)) return false;
|
|
889
|
-
return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
|
|
890
|
-
};
|
|
891
|
-
let reloadTimer = null;
|
|
892
|
-
const reload = () => {
|
|
893
|
-
if (reloadTimer) clearTimeout(reloadTimer);
|
|
894
|
-
reloadTimer = setTimeout(() => {
|
|
895
|
-
reloadTimer = null;
|
|
896
|
-
const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
|
|
897
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
898
|
-
server.ws.send({ type: "full-reload" });
|
|
899
|
-
}, 150);
|
|
900
|
-
};
|
|
901
|
-
server.watcher.add(themesRoot);
|
|
902
|
-
for (const event of [
|
|
903
|
-
"add",
|
|
904
|
-
"unlink",
|
|
905
|
-
"change"
|
|
906
|
-
]) server.watcher.on(event, (p) => {
|
|
907
|
-
if (isThemeFile(p)) reload();
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
};
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
//#endregion
|
|
914
|
-
//#region src/editing/babel-walk.ts
|
|
915
|
-
function parseSource(code) {
|
|
916
|
-
try {
|
|
917
|
-
return parse(code, {
|
|
918
|
-
sourceType: "module",
|
|
919
|
-
plugins: ["typescript", "jsx"],
|
|
920
|
-
errorRecovery: true
|
|
921
|
-
});
|
|
922
|
-
} catch {
|
|
923
|
-
return null;
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
function isNode(value) {
|
|
927
|
-
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
928
|
-
}
|
|
929
|
-
/** Depth-first walk over every node; the visitor decides what it cares about. */
|
|
930
|
-
function walkAst(node, visit) {
|
|
931
|
-
if (Array.isArray(node)) {
|
|
932
|
-
for (const child of node) walkAst(child, visit);
|
|
933
|
-
return;
|
|
934
|
-
}
|
|
935
|
-
if (!isNode(node)) return;
|
|
936
|
-
visit(node);
|
|
937
|
-
for (const key of Object.keys(node)) {
|
|
938
|
-
if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
|
|
939
|
-
walkAst(node[key], visit);
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
function walkJsx(ast, visit) {
|
|
943
|
-
walkAst(ast, (node) => {
|
|
944
|
-
if (node.type === "JSXElement") visit(node);
|
|
945
|
-
});
|
|
946
|
-
}
|
|
947
|
-
/**
|
|
948
|
-
* The JSX element whose opening tag starts at this source position.
|
|
949
|
-
*
|
|
950
|
-
* The match is exact on both line and column. Anything looser can resolve to a
|
|
951
|
-
* different element on the same line, and this location decides where an edit
|
|
952
|
-
* gets written — a near miss silently rewrites the wrong text.
|
|
953
|
-
*/
|
|
954
|
-
function findJsxAt(ast, line, column) {
|
|
955
|
-
let found = null;
|
|
956
|
-
walkJsx(ast, (node) => {
|
|
957
|
-
if (found) return;
|
|
958
|
-
const start = node.loc?.start;
|
|
959
|
-
if (start && start.line === line && start.column === column) found = node;
|
|
960
|
-
});
|
|
961
|
-
return found;
|
|
962
|
-
}
|
|
963
|
-
/**
|
|
964
|
-
* Every JSX element that starts on a line, nearest column first.
|
|
965
|
-
*
|
|
966
|
-
* Columns cannot be trusted for locations derived from React's `_debugSource`:
|
|
967
|
-
* injecting the loc attribute shifts the columns of anything later on the same
|
|
968
|
-
* line, so the offset differs per element. The line survives that, so callers
|
|
969
|
-
* scan the line and pick by content instead.
|
|
970
|
-
*/
|
|
971
|
-
function findJsxOnLine(ast, line, column) {
|
|
972
|
-
const hits = [];
|
|
973
|
-
walkJsx(ast, (node) => {
|
|
974
|
-
const start = node.loc?.start;
|
|
975
|
-
if (!start || start.line !== line) return;
|
|
976
|
-
hits.push({
|
|
977
|
-
node,
|
|
978
|
-
distance: Math.abs(start.column - column)
|
|
979
|
-
});
|
|
980
|
-
});
|
|
981
|
-
return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
//#endregion
|
|
985
|
-
//#region src/editing/comments.ts
|
|
986
|
-
const MARKER_RE = /\{\/\*\s*@doc-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
|
|
987
|
-
function b64urlEncode(value) {
|
|
988
|
-
return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
989
|
-
}
|
|
990
|
-
function b64urlDecode(value) {
|
|
991
|
-
const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
|
|
992
|
-
return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
|
|
993
|
-
}
|
|
994
|
-
function parseMarkers(source) {
|
|
995
|
-
const comments = [];
|
|
996
|
-
source.split("\n").forEach((line, index) => {
|
|
997
|
-
const match = MARKER_RE.exec(line);
|
|
998
|
-
if (!match) return;
|
|
999
|
-
const [, id, ts, payload] = match;
|
|
1000
|
-
try {
|
|
1001
|
-
const decoded = JSON.parse(b64urlDecode(payload));
|
|
1002
|
-
comments.push({
|
|
1003
|
-
id,
|
|
1004
|
-
line: index + 1,
|
|
1005
|
-
ts,
|
|
1006
|
-
note: decoded.note,
|
|
1007
|
-
hint: decoded.hint
|
|
1008
|
-
});
|
|
1009
|
-
} catch {}
|
|
1010
|
-
});
|
|
1011
|
-
return comments;
|
|
1012
|
-
}
|
|
1013
|
-
function newCommentId() {
|
|
1014
|
-
return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
1015
|
-
}
|
|
1016
|
-
function markerFor(id, ts, note, hint) {
|
|
1017
|
-
const payload = b64urlEncode(JSON.stringify(hint ? {
|
|
1018
|
-
note,
|
|
1019
|
-
hint
|
|
1020
|
-
} : { note }));
|
|
1021
|
-
return `{/* @doc-comment id="${id}" ts="${ts}" text="${payload}" */}`;
|
|
1022
|
-
}
|
|
1023
|
-
function markerPattern(id) {
|
|
1024
|
-
return `\\{\\/\\*\\s*@doc-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text="[A-Za-z0-9_\\-]+={0,2}"\\s*\\*\\/\\}`;
|
|
1025
|
-
}
|
|
1026
|
-
/**
|
|
1027
|
-
* Removes a marker and the whitespace the insertion added — whichever side it
|
|
1028
|
-
* landed on — so deleting a comment restores the file byte for byte.
|
|
1029
|
-
*/
|
|
1030
|
-
function removeMarker(source, id) {
|
|
1031
|
-
const pattern = markerPattern(id);
|
|
1032
|
-
for (const re of [
|
|
1033
|
-
new RegExp(`[ \\t]*${pattern}\\n`),
|
|
1034
|
-
new RegExp(`\\n[ \\t]*${pattern}`),
|
|
1035
|
-
new RegExp(pattern)
|
|
1036
|
-
]) if (re.test(source)) return source.replace(re, "");
|
|
1037
|
-
return null;
|
|
1038
|
-
}
|
|
1039
|
-
function indentOfLine(source, offset) {
|
|
1040
|
-
const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
|
|
1041
|
-
const match = /^[ \t]*/.exec(source.slice(lineStart, offset));
|
|
1042
|
-
return match?.[0] ?? "";
|
|
1043
|
-
}
|
|
1044
|
-
/**
|
|
1045
|
-
* Splices the marker in as the **first child** of the target element. A
|
|
1046
|
-
* JSX-comment token outside a JSX child position parses as an empty object
|
|
1047
|
-
* literal and breaks the surrounding expression, so this never puts one before
|
|
1048
|
-
* an element.
|
|
1049
|
-
*/
|
|
1050
|
-
function insertMarker(source, target, note, hint) {
|
|
1051
|
-
const ast = parseSource(source);
|
|
1052
|
-
if (!ast) return null;
|
|
1053
|
-
const element = findJsxAt(ast, target.line, target.column);
|
|
1054
|
-
if (!element) return null;
|
|
1055
|
-
const opening = element.openingElement;
|
|
1056
|
-
if (!opening) return null;
|
|
1057
|
-
if (opening.selfClosing === true) return null;
|
|
1058
|
-
const offset = opening.end;
|
|
1059
|
-
const id = newCommentId();
|
|
1060
|
-
const marker = markerFor(id, new Date().toISOString(), note, hint);
|
|
1061
|
-
const indent = indentOfLine(source, element.start ?? offset);
|
|
1062
|
-
const next = `${source.slice(0, offset)}\n${indent} ${marker}${source.slice(offset)}`;
|
|
1063
|
-
return {
|
|
1064
|
-
source: next,
|
|
1065
|
-
id
|
|
1066
|
-
};
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
//#endregion
|
|
1070
|
-
//#region src/editing/edit-ops.ts
|
|
1071
|
-
/** JSX text is written literally; only these characters have to be escaped. */
|
|
1072
|
-
function escapeJsxText(text) {
|
|
1073
|
-
return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
|
|
1074
|
-
}
|
|
1075
|
-
function normalizeText(value) {
|
|
1076
|
-
return value.replace(/\s+/g, " ").trim();
|
|
1077
|
-
}
|
|
1078
|
-
function jsxChildren(element) {
|
|
1079
|
-
return element.children ?? [];
|
|
1080
|
-
}
|
|
1081
|
-
function labelOf(node) {
|
|
1082
|
-
if (node.type === "JSXExpressionContainer") return "{…}";
|
|
1083
|
-
if (node.type === "JSXElement") {
|
|
1084
|
-
const name = node.openingElement?.name;
|
|
1085
|
-
return `<${name?.name ?? "element"}>`;
|
|
1086
|
-
}
|
|
1087
|
-
return "…";
|
|
1088
|
-
}
|
|
1089
|
-
/** Text children with content, in document order. */
|
|
1090
|
-
function textNodes(element) {
|
|
1091
|
-
return jsxChildren(element).filter((child) => child.type === "JSXText" && child.value.trim() !== "");
|
|
1092
|
-
}
|
|
1093
|
-
function partsOf(element) {
|
|
1094
|
-
const parts = [];
|
|
1095
|
-
let index = 0;
|
|
1096
|
-
for (const child of jsxChildren(element)) {
|
|
1097
|
-
if (child.type === "JSXText") {
|
|
1098
|
-
const value = child.value;
|
|
1099
|
-
if (value.trim() === "") continue;
|
|
1100
|
-
parts.push({
|
|
1101
|
-
kind: "text",
|
|
1102
|
-
index: index++,
|
|
1103
|
-
value: value.trim()
|
|
1104
|
-
});
|
|
1105
|
-
continue;
|
|
1106
|
-
}
|
|
1107
|
-
parts.push({
|
|
1108
|
-
kind: "markup",
|
|
1109
|
-
label: labelOf(child)
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
|
-
return parts;
|
|
1113
|
-
}
|
|
1114
|
-
function describe(element) {
|
|
1115
|
-
const parts = partsOf(element);
|
|
1116
|
-
const texts = parts.filter((part) => part.kind === "text");
|
|
1117
|
-
if (texts.length === 0) {
|
|
1118
|
-
const generated = parts.some((part) => part.kind === "markup" && part.label === "{…}");
|
|
1119
|
-
return {
|
|
1120
|
-
editable: false,
|
|
1121
|
-
text: "",
|
|
1122
|
-
parts,
|
|
1123
|
-
reason: generated ? "text is produced by code — edit whatever feeds it" : "element has no text of its own"
|
|
1124
|
-
};
|
|
1125
|
-
}
|
|
1126
|
-
return {
|
|
1127
|
-
editable: true,
|
|
1128
|
-
text: texts.map((part) => part.value).join(" "),
|
|
1129
|
-
parts
|
|
1130
|
-
};
|
|
1131
|
-
}
|
|
1132
|
-
/**
|
|
1133
|
-
* Picks the element an inspector click meant.
|
|
1134
|
-
*
|
|
1135
|
-
* Coordinates alone are not enough: fallback candidates come from React's
|
|
1136
|
-
* `_debugSource`, whose columns drift once the loc-tag transform has widened
|
|
1137
|
-
* the line. The rendered text the user is looking at is the tiebreaker — an
|
|
1138
|
-
* element only wins if its source text is part of what is on screen.
|
|
1139
|
-
*/
|
|
1140
|
-
function resolveTextTarget(source, candidates, expected) {
|
|
1141
|
-
const ast = parseSource(source);
|
|
1142
|
-
if (!ast) return null;
|
|
1143
|
-
const shown = expected ? normalizeText(expected) : null;
|
|
1144
|
-
const matches = (info) => {
|
|
1145
|
-
if (!shown) return true;
|
|
1146
|
-
const runs = info.parts.filter((part) => part.kind === "text");
|
|
1147
|
-
if (runs.length === 0) return false;
|
|
1148
|
-
return runs.every((part) => part.kind === "text" && shown.includes(normalizeText(part.value)));
|
|
1149
|
-
};
|
|
1150
|
-
for (const candidate of candidates) {
|
|
1151
|
-
const exact = findJsxAt(ast, candidate.line, candidate.column);
|
|
1152
|
-
if (exact) {
|
|
1153
|
-
const info = describe(exact);
|
|
1154
|
-
if (info.editable && matches(info)) return {
|
|
1155
|
-
...info,
|
|
1156
|
-
...candidate
|
|
1157
|
-
};
|
|
1158
|
-
}
|
|
1159
|
-
if (!shown) continue;
|
|
1160
|
-
for (const node of findJsxOnLine(ast, candidate.line, candidate.column)) {
|
|
1161
|
-
const info = describe(node);
|
|
1162
|
-
const start = node.loc?.start;
|
|
1163
|
-
if (!info.editable || !matches(info) || !start) continue;
|
|
1164
|
-
return {
|
|
1165
|
-
...info,
|
|
1166
|
-
line: start.line,
|
|
1167
|
-
column: start.column
|
|
1168
|
-
};
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
const first = candidates[0];
|
|
1172
|
-
if (!first) return null;
|
|
1173
|
-
const clicked = findJsxAt(ast, first.line, first.column);
|
|
1174
|
-
return clicked ? {
|
|
1175
|
-
...describe(clicked),
|
|
1176
|
-
...first
|
|
1177
|
-
} : null;
|
|
1178
|
-
}
|
|
1179
|
-
/**
|
|
1180
|
-
* Replaces one text run of an element, leaving its markup and every other run
|
|
1181
|
-
* untouched. `expected` is the text the caller believes is there; a mismatch
|
|
1182
|
-
* means the source moved under us and the write is refused.
|
|
1183
|
-
*/
|
|
1184
|
-
function replaceTextAt(source, target, text, opts = {}) {
|
|
1185
|
-
const ast = parseSource(source);
|
|
1186
|
-
if (!ast) return {
|
|
1187
|
-
ok: false,
|
|
1188
|
-
status: 422,
|
|
1189
|
-
error: "could not parse document source"
|
|
1190
|
-
};
|
|
1191
|
-
const element = findJsxAt(ast, target.line, target.column);
|
|
1192
|
-
if (!element) return {
|
|
1193
|
-
ok: false,
|
|
1194
|
-
status: 404,
|
|
1195
|
-
error: "no element at that source location"
|
|
1196
|
-
};
|
|
1197
|
-
const nodes = textNodes(element);
|
|
1198
|
-
if (nodes.length === 0) return {
|
|
1199
|
-
ok: false,
|
|
1200
|
-
status: 422,
|
|
1201
|
-
error: "element has no text to replace"
|
|
1202
|
-
};
|
|
1203
|
-
const child = nodes[opts.index ?? 0];
|
|
1204
|
-
if (!child) return {
|
|
1205
|
-
ok: false,
|
|
1206
|
-
status: 404,
|
|
1207
|
-
error: "no such text run in this element"
|
|
1208
|
-
};
|
|
1209
|
-
const raw = child.value;
|
|
1210
|
-
if (opts.expected !== void 0 && normalizeText(raw) !== normalizeText(opts.expected)) return {
|
|
1211
|
-
ok: false,
|
|
1212
|
-
status: 409,
|
|
1213
|
-
error: "source changed since this was opened — reselect it"
|
|
1214
|
-
};
|
|
1215
|
-
const leading = raw.match(/^\s*/)?.[0] ?? "";
|
|
1216
|
-
const trailing = raw.match(/\s*$/)?.[0] ?? "";
|
|
1217
|
-
const next = source.slice(0, child.start) + leading + escapeJsxText(text) + trailing + source.slice(child.end);
|
|
1218
|
-
return {
|
|
1219
|
-
ok: true,
|
|
1220
|
-
source: next
|
|
1221
|
-
};
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
//#endregion
|
|
1225
|
-
export { ASSET_MAX_BYTES, DOC_ID_RE, FOLDER_ID_RE, GLOBAL_SCOPE, OpsError, assetCreatedAt, assetImportPath, countAssetUsages, createDocument, deleteDocument, docDir, duplicateDocument, findReferencedAssets, insertMarker, json, listDocIds, listDocuments, loadUserConfig, makeContext, mimeForFilename, newFolderId, openDocPlugin, parseFrontmatter, parseMarkers, parseSource, readBody, readDocument, readManifest, removeMarker, renameDocument, replaceTextAt, resolveDocEntry, resolveDocPath, resolveEntry, resolveScopedAssetFile, resolveScopedAssetsDir, resolveTextTarget, themesPlugin, validateAssetName, validateIcon, validateName, validateReorder, walkJsx, writeDocument, writeManifest };
|