@dooc-dev/dooc 0.0.3 → 0.0.5

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 (106) hide show
  1. package/dist/cli.js +98 -56
  2. package/dist/compiler/asset-references.d.ts +4 -0
  3. package/dist/compiler/asset-references.js +117 -0
  4. package/dist/compiler/bundle-urls.d.ts +1 -1
  5. package/dist/compiler/bundle-urls.js +15 -5
  6. package/dist/compiler/check.js +8 -5
  7. package/dist/compiler/code-languages.js +7 -2
  8. package/dist/compiler/compile.d.ts +5 -0
  9. package/dist/compiler/compile.js +105 -10
  10. package/dist/compiler/config.js +2 -1
  11. package/dist/compiler/export.d.ts +4 -0
  12. package/dist/compiler/export.js +140 -0
  13. package/dist/compiler/figures.js +4 -0
  14. package/dist/compiler/files.d.ts +1 -0
  15. package/dist/compiler/files.js +96 -38
  16. package/dist/compiler/fonts.js +4 -1
  17. package/dist/compiler/icons.d.ts +1 -1
  18. package/dist/compiler/icons.js +11 -2
  19. package/dist/compiler/ignored-files.d.ts +3 -0
  20. package/dist/compiler/ignored-files.js +68 -0
  21. package/dist/compiler/locales.js +13 -8
  22. package/dist/compiler/manifest.d.ts +2 -0
  23. package/dist/compiler/manifest.js +9 -2
  24. package/dist/compiler/ops.d.ts +6 -0
  25. package/dist/compiler/ops.js +98 -7
  26. package/dist/compiler/subformats.d.ts +24 -0
  27. package/dist/compiler/subformats.js +299 -0
  28. package/dist/compiler/textfile.js +3 -0
  29. package/dist/compiler/theme-variants.js +5 -2
  30. package/dist/core/content-metadata.d.ts +15 -6
  31. package/dist/core/content-metadata.js +278 -17
  32. package/dist/core/content-types.d.ts +3 -1
  33. package/dist/core/figure-frame.js +19 -1
  34. package/dist/core/files.d.ts +2 -1
  35. package/dist/core/files.js +6 -8
  36. package/dist/core/flow-base-css.generated.js +1 -1
  37. package/dist/core/html.js +3 -3
  38. package/dist/core/icons.d.ts +3 -0
  39. package/dist/core/icons.js +3 -0
  40. package/dist/core/json-tools.d.ts +1 -0
  41. package/dist/core/json-tools.js +12 -0
  42. package/dist/core/routing.d.ts +5 -2
  43. package/dist/core/routing.js +17 -5
  44. package/dist/core/subformat-record.d.ts +3 -0
  45. package/dist/core/subformat-record.js +131 -0
  46. package/dist/core/subformats.d.ts +43 -0
  47. package/dist/core/subformats.js +81 -0
  48. package/dist/core/toc-ui.js +25 -23
  49. package/dist/edit.global.js +322 -95
  50. package/dist/mcp.js +50 -9
  51. package/dist/plugins/index.d.ts +1 -0
  52. package/dist/plugins/local-storage.js +3 -0
  53. package/dist/plugins/oauth.d.ts +1 -1
  54. package/dist/plugins/oauth.js +8 -2
  55. package/dist/plugins/runtime.d.ts +6 -0
  56. package/dist/plugins/runtime.js +166 -34
  57. package/dist/plugins/transport.d.ts +22 -0
  58. package/dist/plugins/transport.js +1 -0
  59. package/dist/plugins/types.d.ts +3 -1
  60. package/dist/plugins.global.js +128 -0
  61. package/dist/subformats.global.js +127 -0
  62. package/dist/ui.global.js +91 -38
  63. package/dist/viewer/build-plugins.d.ts +7 -0
  64. package/dist/viewer/build-plugins.js +70 -0
  65. package/dist/viewer/build.d.ts +9 -0
  66. package/dist/viewer/build.js +32 -5
  67. package/dist/viewer/editor-tools.d.ts +7 -7
  68. package/dist/viewer/editor-tools.js +36 -5
  69. package/dist/viewer/font-picker.js +5 -1
  70. package/dist/viewer/git-diff.d.ts +3 -0
  71. package/dist/viewer/git-diff.js +47 -0
  72. package/dist/viewer/hmr.js +4 -1
  73. package/dist/viewer/i18n.js +7 -5
  74. package/dist/viewer/language-picker.d.ts +2 -2
  75. package/dist/viewer/language-picker.js +26 -9
  76. package/dist/viewer/lazy-graph.d.ts +2 -0
  77. package/dist/viewer/lazy-graph.js +30 -0
  78. package/dist/viewer/locales/eng.json +74 -10
  79. package/dist/viewer/locales/jpn.json +75 -11
  80. package/dist/viewer/locales/zho.json +75 -11
  81. package/dist/viewer/nav-focus.js +8 -1
  82. package/dist/viewer/nav-update.d.ts +2 -0
  83. package/dist/viewer/nav-update.js +117 -0
  84. package/dist/viewer/plugin-style.d.ts +1 -0
  85. package/dist/viewer/plugin-style.js +82 -0
  86. package/dist/viewer/plugins.js +46 -3
  87. package/dist/viewer/resize.d.ts +0 -2
  88. package/dist/viewer/resize.js +2 -98
  89. package/dist/viewer/resource-library.d.ts +10 -8
  90. package/dist/viewer/resource-library.js +179 -30
  91. package/dist/viewer/search.d.ts +4 -2
  92. package/dist/viewer/search.js +252 -53
  93. package/dist/viewer/serve.d.ts +10 -5
  94. package/dist/viewer/serve.js +882 -287
  95. package/dist/viewer/site-icon.js +13 -6
  96. package/dist/viewer/site-title.d.ts +13 -0
  97. package/dist/viewer/site-title.js +50 -0
  98. package/dist/viewer/textfile.d.ts +3 -0
  99. package/dist/viewer/textfile.js +19 -2
  100. package/dist/viewer/theme-picker.d.ts +2 -0
  101. package/dist/viewer/theme-picker.js +24 -8
  102. package/dist/viewer/workspace.d.ts +2 -0
  103. package/dist/viewer/workspace.js +46 -1
  104. package/package.json +24 -9
  105. package/dist/compiler/bundle.d.ts +0 -2
  106. package/dist/compiler/bundle.js +0 -100
@@ -18,9 +18,11 @@ import { createFileCache, createSigCache, dirSig, fileSig } from "./file-cache.j
18
18
  import { projectFiles } from "./files.js";
19
19
  import { toBlocks } from "./from-mdast.js";
20
20
  import { loadIcons, squareSvg } from "./icons.js";
21
+ import { assertNotIgnored, ignoredFiles } from "./ignored-files.js";
21
22
  import { contentLanguageCode, isContentLanguage } from "./language-codes.js";
22
23
  import { siteContentLanguages, translationFile } from "./locales.js";
23
24
  import { parseManifestText } from "./manifest.js";
25
+ import { loadSubformat, parseSubformatRecord, validateSubformatRecord } from "./subformats.js";
24
26
  import { parseTermSource } from "./terms.js";
25
27
  import { readTextfile, selectTextfileRange } from "./textfile.js";
26
28
  import { TextfileUnavailable } from "./textfile-remote.js";
@@ -50,6 +52,7 @@ const parseFile = (raw, previews, file) => {
50
52
  const figureFiles = refs.figures;
51
53
  return {
52
54
  raw,
55
+ referencedFiles: [...refs.textfiles, ...refs.figures, ...refs.terms],
53
56
  parsed,
54
57
  blocks,
55
58
  toc,
@@ -239,7 +242,8 @@ export const createCompiler = (root, options = {}) => {
239
242
  !siteContentLanguages(root, manifest).includes(options.locale))
240
243
  throw new Error(`Language ${options.locale} is not declared in dooc.yaml languages`);
241
244
  const themes = siteThemes(root, manifest);
242
- const visualFiles = projectFiles(root)
245
+ const paths = projectFiles(root);
246
+ const visualFiles = paths
243
247
  .map((file) => file.path)
244
248
  .filter((file) => /\.(svg|html|png|webp|gif|mp4|webm|jpe?g)$/.test(file));
245
249
  const { figures, errors: figErrors } = figuresCache.get(dirSig(figuresDir) +
@@ -251,9 +255,12 @@ export const createCompiler = (root, options = {}) => {
251
255
  const previews = parsePreviewSettings(options.previews ?? defaultPreviewSettings());
252
256
  let title;
253
257
  let icon;
258
+ let iconVariants;
254
259
  let iconFile;
255
260
  const files = [];
256
- if (!existsSync(contentDir) && !manifest.files) {
261
+ if (!existsSync(contentDir) &&
262
+ !manifest.files &&
263
+ !flattenTree(manifest.tree).some((node) => node.subformat)) {
257
264
  siteErrors.push(`${contentDir}: content/ is missing`);
258
265
  }
259
266
  else {
@@ -263,13 +270,23 @@ export const createCompiler = (root, options = {}) => {
263
270
  docCache = createFileCache();
264
271
  previewKey = nextPreviewKey;
265
272
  }
266
- title = manifestTitle;
273
+ title =
274
+ manifest.titles?.[options.locale ?? contentLanguageCode(defaultLang)] ??
275
+ manifestTitle;
267
276
  iconFile = manifestIcon;
268
277
  if (iconFile) {
269
278
  try {
270
279
  icon = squareSvg(readTextfile(root, iconFile));
271
280
  if (!icon)
272
281
  throw new Error("expected an SVG with a viewBox or width and height");
282
+ const variants = Object.entries(manifest.themeIcons ?? themeVariants(root, iconFile, themes));
283
+ if (variants.length)
284
+ iconVariants = Object.fromEntries(variants.map(([theme, file]) => {
285
+ const svg = squareSvg(readTextfile(root, file));
286
+ if (!svg)
287
+ throw new Error(`${file}: expected an SVG with a viewBox or width and height`);
288
+ return [theme, svg];
289
+ }));
273
290
  }
274
291
  catch (error) {
275
292
  siteErrors.push(`${MANIFEST_FILE}: icon ${iconFile}: ${error instanceof Error ? error.message : error}`);
@@ -278,9 +295,13 @@ export const createCompiler = (root, options = {}) => {
278
295
  siteErrors.push(...manifestErrors);
279
296
  // Directly under content/: flat <id>.md files only (no folders).
280
297
  const onDisk = new Set();
281
- for (const entry of existsSync(contentDir)
298
+ const contentEntries = existsSync(contentDir)
282
299
  ? readdirSync(contentDir, { withFileTypes: true })
283
- : []) {
300
+ : [];
301
+ const ignoredContent = ignoredFiles(root, contentEntries.map((entry) => `content/${entry.name}`));
302
+ for (const entry of contentEntries) {
303
+ if (ignoredContent.has(`content/${entry.name}`))
304
+ continue;
284
305
  if (entry.name.startsWith(".")) {
285
306
  continue;
286
307
  }
@@ -294,7 +315,9 @@ export const createCompiler = (root, options = {}) => {
294
315
  onDisk.add(id);
295
316
  }
296
317
  // Manifest pre-order is the display order.
297
- for (const { id, parent } of flattenTree(tree)) {
318
+ for (const { id, parent, subformat } of flattenTree(tree)) {
319
+ if (subformat)
320
+ continue;
298
321
  const rel = docFile(id, manifest.files);
299
322
  if (rel.startsWith("content/")) {
300
323
  const diskId = docIdOfFile(rel.slice("content/".length));
@@ -304,6 +327,7 @@ export const createCompiler = (root, options = {}) => {
304
327
  let path;
305
328
  try {
306
329
  path = textfilePath(root, rel);
330
+ assertNotIgnored(root, rel);
307
331
  }
308
332
  catch (error) {
309
333
  siteErrors.push(`${rel}: ${error}`);
@@ -320,6 +344,7 @@ export const createCompiler = (root, options = {}) => {
320
344
  try {
321
345
  const translated = textfilePath(root, file);
322
346
  if (existsSync(translated)) {
347
+ assertNotIgnored(root, file);
323
348
  parsed = docCache.get(translated, (raw) => parseFile(raw, previews, rel));
324
349
  language = options.locale;
325
350
  }
@@ -339,7 +364,12 @@ export const createCompiler = (root, options = {}) => {
339
364
  if (!file.startsWith("figures/"))
340
365
  siteErrors.push(...figErrors.filter((error) => error.startsWith(`${file}:`)));
341
366
  // Icons are small, so read them every time (no cache).
342
- const { icons, errors: iconErrors } = loadIcons(root, new Set(files.map((f) => f.doc.id)), iconFile, manifest.files);
367
+ const { icons, errors: iconErrors } = loadIcons(root, new Set([
368
+ ...files.map((f) => f.doc.id),
369
+ ...flattenTree(manifest.tree)
370
+ .filter((node) => node.subformat)
371
+ .map((node) => node.id),
372
+ ]), iconFile, manifest.files, Object.values(manifest.themeIcons ?? {}));
343
373
  siteErrors.push(...iconErrors);
344
374
  for (const { doc } of files) {
345
375
  const icon = icons.get(doc.id);
@@ -348,9 +378,6 @@ export const createCompiler = (root, options = {}) => {
348
378
  }
349
379
  }
350
380
  const docs = files.map((f) => f.doc);
351
- if (docs.length === 0) {
352
- siteErrors.push(`${contentDir}: no docs`);
353
- }
354
381
  const ctx = {
355
382
  docs,
356
383
  figures: new Map(figures.map((f) => [f.name, f])),
@@ -363,18 +390,85 @@ export const createCompiler = (root, options = {}) => {
363
390
  errors.push(...errs.map((e) => `${doc.file}: ${e}`));
364
391
  sources.set(doc.file, {
365
392
  terms: parsed.parsed.terms,
393
+ referencedFiles: parsed.referencedFiles,
366
394
  raw: parsed.raw,
367
395
  frontmatter: parsed.parsed.frontmatter,
368
396
  lines: parsed.lines,
369
397
  errors: errs,
370
398
  });
371
399
  }
400
+ for (const node of flattenTree(manifest.tree).filter((node) => node.subformat)) {
401
+ const config = manifest.subformats?.find((format) => format.ext === node.subformat);
402
+ if (!config)
403
+ continue;
404
+ const file = `subformat:${config.ext}`;
405
+ const title = node.title ?? config.ext;
406
+ const pageErrors = [];
407
+ const collection = {
408
+ ...config,
409
+ fields: [],
410
+ records: [],
411
+ };
412
+ try {
413
+ assertNotIgnored(root, config.schema);
414
+ if (!paths.some((file) => file.path === config.schema))
415
+ throw new Error("Subformat schema is not available in the workspace");
416
+ const loaded = loadSubformat(root, config);
417
+ collection.fields = loaded.fields;
418
+ collection.template = loaded.template;
419
+ collection.defaultFolder = manifest.defaultSubformatFolder;
420
+ for (const record of paths.filter((file) => file.extension === config.ext && file.path !== config.schema)) {
421
+ try {
422
+ const content = readTextfile(root, record.path);
423
+ const data = parseSubformatRecord(content, config.format);
424
+ validateSubformatRecord(loaded, data);
425
+ collection.records.push({ file: record.path, content, data });
426
+ }
427
+ catch (error) {
428
+ pageErrors.push(`${record.path}: ${error instanceof Error ? error.message : error}`);
429
+ }
430
+ }
431
+ }
432
+ catch (error) {
433
+ pageErrors.push(`${config.schema}: ${error instanceof Error ? error.message : error}`);
434
+ }
435
+ docs.push({
436
+ id: node.id,
437
+ parent: node.parent,
438
+ title,
439
+ file,
440
+ lang: defaultLang,
441
+ subformat: collection,
442
+ icon: icons.get(node.id),
443
+ body: "",
444
+ blocks: [],
445
+ toc: [],
446
+ refs: { figures: [], terms: [] },
447
+ });
448
+ sources.set(file, {
449
+ terms: [],
450
+ referencedFiles: [],
451
+ raw: "",
452
+ frontmatter: { title },
453
+ lines: [],
454
+ errors: pageErrors,
455
+ });
456
+ errors.push(...pageErrors);
457
+ }
458
+ const order = flattenTree(manifest.tree).map((node) => node.id);
459
+ docs.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
460
+ if (!docs.length) {
461
+ siteErrors.push(`${contentDir}: no docs`);
462
+ errors.push(`${contentDir}: no docs`);
463
+ }
372
464
  return {
373
465
  previews,
466
+ subformats: manifest.subformats,
374
467
  ...(manifest.languages ? { contentLanguages: manifest.languages } : {}),
375
468
  ...(manifest.themes ? { themes: manifest.themes } : {}),
376
469
  ...(title === undefined ? {} : { title }),
377
470
  ...(icon === undefined ? {} : { icon }),
471
+ ...(iconVariants === undefined ? {} : { iconVariants }),
378
472
  docs,
379
473
  terms: [...termMap(files.flatMap(({ parsed }) => parsed.parsed.terms)).values()],
380
474
  figures,
@@ -399,6 +493,7 @@ export const compileDraft = (ctx, file, raw) => {
399
493
  doc: toDoc(known?.id ?? "", known?.parent, file, parsed, ctx.defaultLang ?? DEFAULT_LANG),
400
494
  source: {
401
495
  terms: parsed.parsed.terms,
496
+ referencedFiles: parsed.referencedFiles,
402
497
  raw,
403
498
  frontmatter: parsed.parsed.frontmatter,
404
499
  lines: parsed.lines,
@@ -6,6 +6,7 @@ import { existsSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { pathToFileURL } from "node:url";
8
8
  import { isLangTag } from "../core/language.js";
9
+ import { ignoredFiles } from "./ignored-files.js";
9
10
  export const CONFIG_FILE = "docs.config.mjs";
10
11
  const FUNCTION_KEYS = ["isTermBoundary", "compareTerms", "lint"];
11
12
  const checkAdapter = (value, i) => {
@@ -30,7 +31,7 @@ const checkAdapter = (value, i) => {
30
31
  /** Reads docs.config.mjs; defaults when absent. Throws with a readable message when invalid. */
31
32
  export const loadDocsConfig = async (root) => {
32
33
  const file = join(root, CONFIG_FILE);
33
- if (!existsSync(file)) {
34
+ if (!existsSync(file) || ignoredFiles(root, [CONFIG_FILE]).has(CONFIG_FILE)) {
34
35
  return {
35
36
  languages: [],
36
37
  };
@@ -0,0 +1,4 @@
1
+ import { type ZipEntry } from "./zip.js";
2
+ /** Collect source dependencies without executing configuration, plugins or remote requests. */
3
+ export declare const exportEntries: (root: string) => ZipEntry[];
4
+ export declare const exportBundle: (root: string) => Buffer;
@@ -0,0 +1,140 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { posix } from "node:path";
3
+ import { visit } from "unist-util-visit";
4
+ import { flattenTree, MANIFEST_FILE } from "../core/content-metadata.js";
5
+ import { docFile, docIconFile, fileExtension, localFile } from "../core/files.js";
6
+ import { contentLinks, parseMdast } from "../core/markdown.js";
7
+ import { isRemoteTextfile, parseFileReference } from "../core/textfile.js";
8
+ import { assetReferences } from "./asset-references.js";
9
+ import { CODE_LANGUAGES_DIR } from "./code-languages.js";
10
+ import { CONFIG_FILE } from "./config.js";
11
+ import { collectRefs } from "./dialect.js";
12
+ import { projectFiles } from "./files.js";
13
+ import { PROJECT_FONTS_DIR } from "./fonts.js";
14
+ import { assertNotIgnored, ignoredFiles } from "./ignored-files.js";
15
+ import { siteContentLanguages, translationFile } from "./locales.js";
16
+ import { readManifest } from "./manifest.js";
17
+ import { readTextfile, textfilePath } from "./textfile.js";
18
+ import { themeVariants } from "./theme-variants.js";
19
+ import { zip } from "./zip.js";
20
+ /** Collect source dependencies without executing configuration, plugins or remote requests. */
21
+ export const exportEntries = (root) => {
22
+ const manifest = readManifest(root);
23
+ if (manifest.errors.length)
24
+ throw new Error(manifest.errors.join("\n"));
25
+ const entries = new Map();
26
+ const add = (file) => {
27
+ file = file.replace(/^(\.\/)+/, "");
28
+ if (entries.has(file))
29
+ return;
30
+ const settingsFile = [PROJECT_FONTS_DIR, CODE_LANGUAGES_DIR, ".dooc/editor-tools"].some((dir) => file.startsWith(`${dir}/`) && localFile(file.slice(dir.length + 1)));
31
+ // References are already URL-decoded; # and ? are literal filename characters here.
32
+ if (!localFile(file.replace(/[?#]/g, "_")) && !settingsFile)
33
+ throw new Error(`Invalid export dependency: ${file}`);
34
+ const path = textfilePath(root, file);
35
+ assertNotIgnored(root, file);
36
+ if (!statSync(path).isFile())
37
+ throw new Error(`Expected a regular source file: ${file}`);
38
+ entries.set(file, { name: file, data: readFileSync(path) });
39
+ for (const variant of Object.values(themeVariants(root, file)))
40
+ add(variant);
41
+ };
42
+ const optional = (file) => {
43
+ if (existsSync(textfilePath(root, file)) && !ignoredFiles(root, [file]).has(file))
44
+ add(file);
45
+ };
46
+ add(MANIFEST_FILE);
47
+ optional(CONFIG_FILE);
48
+ for (const { id, subformat } of flattenTree(manifest.tree)) {
49
+ const file = subformat ? undefined : docFile(id, manifest.files);
50
+ if (file)
51
+ add(file);
52
+ if (manifest.files?.icons?.[id])
53
+ add(docIconFile(id, manifest.files));
54
+ else
55
+ optional(docIconFile(id, manifest.files));
56
+ if (!file)
57
+ continue;
58
+ for (const language of siteContentLanguages(root, manifest))
59
+ optional(translationFile(file, language));
60
+ }
61
+ for (const file of new Set([manifest.icon, ...Object.values(manifest.themeIcons ?? {})]))
62
+ if (file)
63
+ add(file);
64
+ const files = projectFiles(root);
65
+ for (const format of manifest.subformats ?? []) {
66
+ add(format.schema);
67
+ for (const file of files)
68
+ if (file.extension === format.ext)
69
+ add(file.path);
70
+ }
71
+ for (const dir of [PROJECT_FONTS_DIR, CODE_LANGUAGES_DIR, ".dooc/editor-tools"]) {
72
+ const path = textfilePath(root, dir);
73
+ if (!existsSync(path))
74
+ continue;
75
+ for (const file of readdirSync(path, { recursive: true, withFileTypes: true }))
76
+ if (file.isFile())
77
+ optional(posix.join(dir, posix.relative(path, file.parentPath), file.name));
78
+ }
79
+ const relative = (source, file) => {
80
+ if (!source || source.startsWith("#") || /^(?:[a-z][\w+.-]*:|\/\/)/i.test(source))
81
+ return;
82
+ if (source.startsWith("/"))
83
+ throw new Error(`Export dependencies must be relative: ${source}`);
84
+ const path = decodeURIComponent(source.split(/[?#]/)[0] ?? "");
85
+ if (!path)
86
+ return;
87
+ const dependency = posix.normalize(posix.join(posix.dirname(file), path));
88
+ add(dependency);
89
+ return dependency;
90
+ };
91
+ const schemas = new Set(manifest.subformats?.map((format) => format.schema));
92
+ for (const file of schemas) {
93
+ const refs = (value) => {
94
+ if (!value || typeof value !== "object")
95
+ return;
96
+ for (const [key, child] of Object.entries(value)) {
97
+ if (key === "$ref" && typeof child === "string") {
98
+ const dependency = relative(child, file);
99
+ if (dependency)
100
+ schemas.add(dependency);
101
+ }
102
+ else
103
+ refs(child);
104
+ }
105
+ };
106
+ refs(JSON.parse(entries.get(file)?.data.toString("utf8") ?? ""));
107
+ }
108
+ // Map iteration visits dependencies appended while walking the graph, once per path.
109
+ for (const entry of entries.values()) {
110
+ const ext = fileExtension(entry.name);
111
+ if (["md", "callouth"].includes(ext)) {
112
+ const tree = parseMdast(entry.data.toString("utf8"));
113
+ const refs = collectRefs(tree);
114
+ for (const file of refs.figures)
115
+ if (!isRemoteTextfile(file))
116
+ add(file);
117
+ for (const file of [...refs.terms, ...refs.textfiles])
118
+ if (!isRemoteTextfile(file)) {
119
+ readTextfile(root, file);
120
+ add(file);
121
+ }
122
+ const reference = (url) => {
123
+ if (/^(?:[a-z][\w+.-]*:|[/#])/i.test(url))
124
+ return;
125
+ add(parseFileReference(url).file.replace(/^(\.\/)+/, ""));
126
+ };
127
+ visit(tree, "image", (node) => reference(node.url));
128
+ for (const link of contentLinks(tree))
129
+ reference(link.url);
130
+ }
131
+ else if (["html", "htm", "svg", "css"].includes(ext))
132
+ assetReferences(entry.data.toString("utf8"), ext, (url, embedded) => {
133
+ if (embedded)
134
+ relative(url, entry.name);
135
+ return url;
136
+ });
137
+ }
138
+ return [...entries.values()];
139
+ };
140
+ export const exportBundle = (root) => zip(exportEntries(root));
@@ -23,6 +23,7 @@ import { createHash } from "node:crypto";
23
23
  import { readdirSync, readFileSync } from "node:fs";
24
24
  import { dirname } from "node:path";
25
25
  import { extractMxfile, isDrawioSvg, normalizeDrawioSvg } from "./drawio.js";
26
+ import { ignoredFiles } from "./ignored-files.js";
26
27
  import { textfilePath } from "./textfile.js";
27
28
  const EXT_RE = /\.(drawio\.svg|svg|html|png|webp|gif|mp4|webm|jpe?g)$/;
28
29
  const FILE_RE = /^[a-z0-9][a-z0-9_-]*\.(drawio\.svg|svg|html|png|webp|gif|mp4|webm|jpe?g)$/;
@@ -136,8 +137,11 @@ export const loadFigures = (figuresDir, extraFiles = []) => {
136
137
  // A missing figures/ is valid.
137
138
  }
138
139
  files = [...new Set([...files.map((file) => `figures/${file}`), ...extraFiles])];
140
+ const ignored = ignoredFiles(dirname(figuresDir), files);
139
141
  const keyframeOwner = new Map();
140
142
  for (const file of files) {
143
+ if (ignored.has(file))
144
+ continue;
141
145
  if (file.startsWith("figures/") &&
142
146
  !file.slice(8).includes("/") &&
143
147
  !FILE_RE.test(file.slice(8))) {
@@ -5,6 +5,7 @@ export interface ProjectFile {
5
5
  size: number;
6
6
  extension: string;
7
7
  }
8
+ export declare const completeFilePaths: (root: string, prefix: unknown) => string[];
8
9
  export declare const projectFiles: (root: string) => ProjectFile[];
9
10
  export declare const filesSnapshot: (root: string) => {
10
11
  files: ProjectFile[];
@@ -1,16 +1,17 @@
1
- import { spawnSync } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
4
3
  import { dirname, join, posix } from "node:path";
5
4
  import { visit } from "unist-util-visit";
6
5
  import { Document, isSeq, parseDocument } from "yaml";
7
- import { flattenTree, MANIFEST_FILE } from "../core/content-metadata.js";
6
+ import { flattenTree, MANIFEST_FILE, serializeManifest } from "../core/content-metadata.js";
8
7
  import { defaultFilePath, docFile, docIconFile, fileExtension, isDocumentFileName, localFile, MAX_FILE_UPLOAD_BYTES, parseFileLayout, } from "../core/files.js";
9
8
  import { codeBlockAt, parseMdast } from "../core/markdown.js";
10
9
  import { docPath } from "../core/routing.js";
11
10
  import { termFileUrl } from "../core/term-reference.js";
12
11
  import { isRemoteTextfile, parseFileReference } from "../core/textfile.js";
12
+ import { assetReferences } from "./asset-references.js";
13
13
  import { fileSig } from "./file-cache.js";
14
+ import { ignoredFiles } from "./ignored-files.js";
14
15
  import { translationFile, translationFiles, translationLanguages } from "./locales.js";
15
16
  import { readManifest } from "./manifest.js";
16
17
  import { textfilePath, writeTextfile } from "./textfile.js";
@@ -18,6 +19,43 @@ import { themeNames, themeVariants } from "./theme-variants.js";
18
19
  // Project settings and translations have their own layout, outside file restructuring.
19
20
  const reserved = new Set([MANIFEST_FILE, "docs.config.mjs", "node_modules", "dist", "locales"]);
20
21
  export const managedFile = (file) => localFile(file) && !reserved.has(file.split("/")[0] ?? "");
22
+ const names = new Intl.Collator("en", { numeric: true });
23
+ const compareFilePaths = (a, b) => {
24
+ const left = a.split("/");
25
+ const right = b.split("/");
26
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
27
+ const first = left[i];
28
+ const second = right[i];
29
+ if (first === second)
30
+ continue;
31
+ return (Number(i < right.length - 1) - Number(i < left.length - 1) ||
32
+ names.compare(first, second) ||
33
+ (first < second ? -1 : 1));
34
+ }
35
+ return left.length - right.length;
36
+ };
37
+ export const completeFilePaths = (root, prefix) => {
38
+ if (typeof prefix !== "string" || prefix.length > 4096)
39
+ throw new Error("Invalid file prefix");
40
+ const slash = prefix.lastIndexOf("/");
41
+ const directory = prefix.slice(0, slash + 1);
42
+ if (prefix && !managedFile(prefix.replace(/\/$/, "")))
43
+ throw new Error("Expected a relative project path");
44
+ const path = directory ? textfilePath(root, directory) : root;
45
+ if (!existsSync(path))
46
+ return [];
47
+ const entries = readdirSync(path, { withFileTypes: true })
48
+ .filter((entry) => !entry.isSymbolicLink() &&
49
+ (entry.isFile() || entry.isDirectory()) &&
50
+ managedFile(directory + entry.name) &&
51
+ (directory + entry.name).toLowerCase().startsWith(prefix.toLowerCase()))
52
+ .map((entry) => directory + entry.name + (entry.isDirectory() ? "/" : ""));
53
+ const ignored = ignoredFiles(root, entries);
54
+ return entries
55
+ .filter((file) => !ignored.has(file))
56
+ .sort(compareFilePaths)
57
+ .slice(0, 200);
58
+ };
21
59
  export const projectFiles = (root) => {
22
60
  const result = [];
23
61
  const walk = (directory) => {
@@ -36,30 +74,17 @@ export const projectFiles = (root) => {
36
74
  }
37
75
  };
38
76
  walk("");
39
- return result.sort((a, b) => a.path.localeCompare(b.path));
77
+ const ignored = ignoredFiles(root, result.map((file) => file.path));
78
+ return result
79
+ .filter((file) => !ignored.has(file.path))
80
+ .sort((a, b) => compareFilePaths(a.path, b.path));
40
81
  };
41
82
  export const filesSnapshot = (root) => {
42
83
  const manifest = readManifest(root);
43
84
  if (manifest.errors.length)
44
85
  throw new Error(manifest.errors.join("\n"));
45
- let files = projectFiles(root);
46
- if (files.length) {
47
- const ignored = spawnSync("git", ["-C", root, "check-ignore", "--stdin", "-z"], {
48
- input: `${files.map((file) => file.path).join("\0")}\0`,
49
- encoding: "utf8",
50
- timeout: 2_000,
51
- maxBuffer: 5_000_000,
52
- windowsHide: true,
53
- });
54
- if (ignored.status === 0) {
55
- const paths = new Set(ignored.stdout.split("\0"));
56
- files = files.filter((file) => !paths.has(file.path));
57
- }
58
- }
86
+ const files = projectFiles(root);
59
87
  const layout = manifest.files ?? parseFileLayout({});
60
- const rank = new Map(layout.order.map((path, index) => [path, index]));
61
- files.sort((a, b) => (rank.get(a.path) ?? Infinity) - (rank.get(b.path) ?? Infinity) ||
62
- a.path.localeCompare(b.path));
63
88
  const hash = createHash("sha256");
64
89
  hash.update(existsSync(join(root, MANIFEST_FILE)) ? readFileSync(join(root, MANIFEST_FILE)) : "");
65
90
  for (const file of files)
@@ -73,7 +98,9 @@ export const filesSnapshot = (root) => {
73
98
  files,
74
99
  layout,
75
100
  revision: hash.digest("hex"),
76
- documents: Object.fromEntries(docs.map(({ id }) => [docFile(id, layout), docPath(docs, id)])),
101
+ documents: Object.fromEntries(docs
102
+ .filter((node) => !node.subformat)
103
+ .map(({ id }) => [docFile(id, layout), docPath(docs, id)])),
77
104
  };
78
105
  };
79
106
  export const uploadFile = (root, input) => {
@@ -217,7 +244,6 @@ export const updateFiles = (root, input) => {
217
244
  const layout = snapshot.layout;
218
245
  const paths = snapshot.files.map((file) => file.path);
219
246
  const moves = new Map();
220
- let order = [...paths];
221
247
  if (input.action === "layout") {
222
248
  if (typeof input.enabled !== "boolean")
223
249
  throw new Error("Invalid layout setting");
@@ -244,7 +270,7 @@ export const updateFiles = (root, input) => {
244
270
  throw new Error("File not found");
245
271
  if (!localFile(input.name) || input.name.includes("/"))
246
272
  throw new Error("Invalid file name");
247
- if (flattenTree(manifest.tree).some(({ id }) => docFile(id, layout) === input.file) &&
273
+ if (flattenTree(manifest.tree).some(({ id, subformat }) => !subformat && docFile(id, layout) === input.file) &&
248
274
  !isDocumentFileName(input.name))
249
275
  throw new Error("Enter a file name ending in .md");
250
276
  const target = posix.join(posix.dirname(input.file), input.name);
@@ -272,20 +298,16 @@ export const updateFiles = (root, input) => {
272
298
  const target = directory
273
299
  ? `${directory}/${posix.basename(item)}`
274
300
  : posix.basename(item);
301
+ if (manifest.defaultSubformatFolder === item ||
302
+ manifest.defaultSubformatFolder?.startsWith(`${item}/`))
303
+ manifest.defaultSubformatFolder =
304
+ target + manifest.defaultSubformatFolder.slice(item.length);
275
305
  for (const file of picked.filter((path) => path === item || path.startsWith(`${item}/`))) {
276
306
  const next = target + file.slice(item.length);
277
307
  if (next !== file)
278
308
  moves.set(file, next);
279
309
  }
280
310
  }
281
- order = paths.filter((path) => !picked.includes(path));
282
- const before = input.before;
283
- const index = before === undefined
284
- ? order.length
285
- : order.findIndex((path) => path === before || path.startsWith(`${before}/`));
286
- if (index < 0)
287
- throw new Error("Invalid drop position");
288
- order.splice(index, 0, ...picked);
289
311
  }
290
312
  else
291
313
  throw new Error("Unknown file action");
@@ -310,7 +332,9 @@ export const updateFiles = (root, input) => {
310
332
  if (existsSync(path))
311
333
  throw new Error(`File already exists: ${target}`);
312
334
  }
313
- for (const { id } of flattenTree(manifest.tree)) {
335
+ for (const { id, subformat } of flattenTree(manifest.tree)) {
336
+ if (subformat)
337
+ continue;
314
338
  const file = docFile(id, layout);
315
339
  if (moves.has(file))
316
340
  layout.documents[id] = moves.get(file);
@@ -320,20 +344,52 @@ export const updateFiles = (root, input) => {
320
344
  layout.icons[id] = moves.get(icon);
321
345
  }
322
346
  }
323
- layout.order = order.map((file) => moves.get(file) ?? file);
324
347
  const rawManifest = existsSync(join(root, MANIFEST_FILE))
325
348
  ? readFileSync(join(root, MANIFEST_FILE), "utf8")
326
349
  : null;
327
350
  const parsed = parseDocument(rawManifest ?? "docs: []\n");
328
351
  const yaml = isSeq(parsed.contents) ? new Document({ docs: parsed.toJS() }) : parsed;
329
- yaml.set("files", layout);
352
+ manifest.files = layout;
330
353
  if (manifest.icon && moves.has(manifest.icon))
331
- yaml.set("icon", moves.get(manifest.icon));
354
+ manifest.icon = moves.get(manifest.icon);
355
+ if (manifest.themeIcons)
356
+ for (const [theme, file] of Object.entries(manifest.themeIcons))
357
+ manifest.themeIcons[theme] = moves.get(file) ?? file;
358
+ for (const subformat of manifest.subformats ?? [])
359
+ subformat.schema = moves.get(subformat.schema) ?? subformat.schema;
360
+ if (manifest.format !== "nested") {
361
+ yaml.set("files", layout);
362
+ if (manifest.icon)
363
+ yaml.set("icon", manifest.icon);
364
+ if (manifest.subformats)
365
+ yaml.set("subformats", manifest.subformats);
366
+ if (manifest.defaultSubformatFolder)
367
+ yaml.set("default_subformat_folder", manifest.defaultSubformatFolder);
368
+ }
332
369
  const writes = [];
333
370
  const links = new Map(moves);
334
- for (const file of [...paths, ...translated].filter((file) => /\.(md|callouth)$/.test(file))) {
371
+ for (const file of [...paths, ...translated].filter((file) => /\.(md|callouth|html|htm|svg|css)$/.test(file))) {
335
372
  const base = readFileSync(textfilePath(root, file));
336
- const next = rewriteFileLinks(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(base), moves);
373
+ const raw = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(base);
374
+ const next = /\.(md|callouth)$/.test(file)
375
+ ? rewriteFileLinks(raw, moves)
376
+ : moves.size
377
+ ? assetReferences(raw, fileExtension(file), (url) => {
378
+ if (!url || /^(?:[a-z][\w+.-]*:|[/#])/i.test(url))
379
+ return url;
380
+ const path = decodeURIComponent(url.split(/[?#]/)[0] ?? "");
381
+ if (!path)
382
+ return url;
383
+ const source = posix.normalize(posix.join(posix.dirname(file), path));
384
+ const target = moves.get(source) ?? source;
385
+ const owner = moves.get(file) ?? file;
386
+ if (target === source && posix.dirname(owner) === posix.dirname(file))
387
+ return url;
388
+ const relative = posix.relative(posix.dirname(owner), target);
389
+ return (relative.split("/").map(encodeURIComponent).join("/") +
390
+ url.slice(url.search(/[?#]|$/)));
391
+ })
392
+ : raw;
337
393
  const data = Buffer.from(next);
338
394
  if (base.equals(data))
339
395
  continue;
@@ -349,7 +405,9 @@ export const updateFiles = (root, input) => {
349
405
  writes.push({
350
406
  file: MANIFEST_FILE,
351
407
  base: rawManifest === null ? null : Buffer.from(rawManifest),
352
- data: Buffer.from(yaml.toString()),
408
+ data: Buffer.from(manifest.format === "nested"
409
+ ? serializeManifest(manifest.tree, manifest)
410
+ : yaml.toString()),
353
411
  });
354
412
  const originalModes = new Map([...moves.keys()].map((file) => [file, statSync(textfilePath(root, file)).mode]));
355
413
  const originals = new Map([...moves.keys()].map((file) => [