@dooc-dev/dooc 0.0.4 → 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 (95) hide show
  1. package/dist/cli.js +41 -3
  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.js +80 -41
  15. package/dist/compiler/fonts.js +4 -1
  16. package/dist/compiler/icons.d.ts +1 -1
  17. package/dist/compiler/icons.js +11 -2
  18. package/dist/compiler/ignored-files.d.ts +3 -0
  19. package/dist/compiler/ignored-files.js +68 -0
  20. package/dist/compiler/locales.js +13 -8
  21. package/dist/compiler/ops.d.ts +6 -0
  22. package/dist/compiler/ops.js +98 -7
  23. package/dist/compiler/subformats.d.ts +24 -0
  24. package/dist/compiler/subformats.js +299 -0
  25. package/dist/compiler/textfile.js +3 -0
  26. package/dist/compiler/theme-variants.js +5 -2
  27. package/dist/core/content-metadata.d.ts +15 -6
  28. package/dist/core/content-metadata.js +278 -17
  29. package/dist/core/content-types.d.ts +3 -1
  30. package/dist/core/figure-frame.js +19 -1
  31. package/dist/core/files.d.ts +2 -1
  32. package/dist/core/files.js +6 -8
  33. package/dist/core/flow-base-css.generated.js +1 -1
  34. package/dist/core/html.js +3 -3
  35. package/dist/core/icons.d.ts +3 -0
  36. package/dist/core/icons.js +3 -0
  37. package/dist/core/json-tools.d.ts +1 -0
  38. package/dist/core/json-tools.js +12 -0
  39. package/dist/core/routing.d.ts +5 -2
  40. package/dist/core/routing.js +17 -5
  41. package/dist/core/subformat-record.d.ts +3 -0
  42. package/dist/core/subformat-record.js +131 -0
  43. package/dist/core/subformats.d.ts +43 -0
  44. package/dist/core/subformats.js +81 -0
  45. package/dist/core/toc-ui.js +25 -23
  46. package/dist/edit.global.js +322 -95
  47. package/dist/mcp.js +50 -9
  48. package/dist/plugins/index.d.ts +1 -0
  49. package/dist/plugins/transport.d.ts +22 -0
  50. package/dist/plugins/transport.js +1 -0
  51. package/dist/plugins.global.js +128 -0
  52. package/dist/subformats.global.js +127 -0
  53. package/dist/ui.global.js +91 -38
  54. package/dist/viewer/build-plugins.d.ts +7 -0
  55. package/dist/viewer/build-plugins.js +70 -0
  56. package/dist/viewer/build.d.ts +9 -0
  57. package/dist/viewer/build.js +32 -5
  58. package/dist/viewer/editor-tools.d.ts +7 -7
  59. package/dist/viewer/editor-tools.js +36 -5
  60. package/dist/viewer/font-picker.js +5 -1
  61. package/dist/viewer/git-diff.d.ts +3 -0
  62. package/dist/viewer/git-diff.js +47 -0
  63. package/dist/viewer/hmr.js +4 -1
  64. package/dist/viewer/i18n.js +7 -5
  65. package/dist/viewer/language-picker.d.ts +2 -2
  66. package/dist/viewer/language-picker.js +26 -9
  67. package/dist/viewer/lazy-graph.d.ts +2 -0
  68. package/dist/viewer/lazy-graph.js +30 -0
  69. package/dist/viewer/locales/eng.json +72 -10
  70. package/dist/viewer/locales/jpn.json +73 -11
  71. package/dist/viewer/locales/zho.json +73 -11
  72. package/dist/viewer/nav-focus.js +8 -1
  73. package/dist/viewer/nav-update.d.ts +2 -0
  74. package/dist/viewer/nav-update.js +117 -0
  75. package/dist/viewer/plugin-style.d.ts +1 -0
  76. package/dist/viewer/plugin-style.js +82 -0
  77. package/dist/viewer/resize.d.ts +0 -2
  78. package/dist/viewer/resize.js +2 -98
  79. package/dist/viewer/resource-library.d.ts +10 -8
  80. package/dist/viewer/resource-library.js +179 -30
  81. package/dist/viewer/search.d.ts +4 -2
  82. package/dist/viewer/search.js +252 -53
  83. package/dist/viewer/serve.d.ts +10 -5
  84. package/dist/viewer/serve.js +789 -278
  85. package/dist/viewer/site-icon.js +13 -6
  86. package/dist/viewer/site-title.js +15 -2
  87. package/dist/viewer/textfile.d.ts +3 -0
  88. package/dist/viewer/textfile.js +19 -2
  89. package/dist/viewer/theme-picker.d.ts +2 -0
  90. package/dist/viewer/theme-picker.js +24 -8
  91. package/dist/viewer/workspace.d.ts +2 -0
  92. package/dist/viewer/workspace.js +46 -1
  93. package/package.json +24 -9
  94. package/dist/compiler/bundle.d.ts +0 -2
  95. package/dist/compiler/bundle.js +0 -100
@@ -2,13 +2,13 @@
2
2
  // add / remove figures). Shared by the viewer's edit API, the CLI (doc / figure) and MCP.
3
3
  // Failures are returned as { error, status } (status is HTTP-like) with no partial updates.
4
4
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
5
- import { dirname, join } from "node:path";
6
- import { flattenTree, insertDoc, isDocId, moveDoc, removeDoc, renameDoc, } from "../core/content-metadata.js";
7
- import { defaultFilePath, docIconFile, isDocumentFileName, parseFileLayout, } from "../core/files.js";
5
+ import { dirname, join, posix } from "node:path";
6
+ import { flattenTree, insertDoc, isDocId, moveDoc, removeDoc, renameDoc, subformatPageId, } from "../core/content-metadata.js";
7
+ import { defaultFilePath, docIconFile, fileDocumentId, isDocumentFileName, parseFileLayout, } from "../core/files.js";
8
8
  import { parseDocLink } from "../core/routing.js";
9
9
  import { collectDocLinks, compileSite } from "./compile.js";
10
10
  import { figureName, figureUploadName } from "./figures.js";
11
- import { projectFiles, rewriteFileLinks } from "./files.js";
11
+ import { filesSnapshot, projectFiles, rewriteFileLinks, updateFiles } from "./files.js";
12
12
  import { translationFile, translationFiles, translationLanguages } from "./locales.js";
13
13
  import { docFile, readManifest, writeManifest } from "./manifest.js";
14
14
  import { assembleDoc } from "./serialize.js";
@@ -27,7 +27,10 @@ export const createDocOps = (root) => {
27
27
  ? { error: manifest.errors.join(" / "), status: 409 }
28
28
  : manifest;
29
29
  };
30
- const existingDoc = (id) => typeof id === "string" && isDocId(id) && existsSync(docPath(id))
30
+ const existingDoc = (id) => typeof id === "string" &&
31
+ isDocId(id) &&
32
+ !flattenTree(readManifest(root).tree).some((node) => node.id === id && node.subformat) &&
33
+ existsSync(docPath(id))
31
34
  ? { id }
32
35
  : { error: `doc "${String(id)}" not found`, status: 404 };
33
36
  // Include extracted callout sources and unregistered Markdown files in reference checks.
@@ -56,11 +59,20 @@ export const createDocOps = (root) => {
56
59
  if (isOpError(loaded)) {
57
60
  return loaded;
58
61
  }
62
+ if (loaded.format === "nested") {
63
+ const file = loaded.files?.defaultLayout !== false
64
+ ? defaultFilePath(filename ?? `${id}.md`)
65
+ : `content/${filename ?? `${id}.md`}`;
66
+ id = fileDocumentId(file);
67
+ loaded.files ??= parseFileLayout({});
68
+ loaded.files.documents[id] = file;
69
+ }
59
70
  const tree = insertDoc(loaded.tree, id, parent);
60
71
  if (!tree) {
61
72
  return { error: `duplicate id "${id}" or missing parent "${parent}"`, status: 409 };
62
73
  }
63
- if (filename !== undefined || loaded.files?.defaultLayout !== false) {
74
+ if (loaded.format !== "nested" &&
75
+ (filename !== undefined || loaded.files?.defaultLayout !== false)) {
64
76
  loaded.files ??= parseFileLayout({});
65
77
  loaded.files.documents[id] = loaded.files.defaultLayout
66
78
  ? defaultFilePath(filename ?? `${id}.md`)
@@ -92,6 +104,37 @@ export const createDocOps = (root) => {
92
104
  id = `${stem}-${index}`;
93
105
  return add(id, title, parent, name);
94
106
  };
107
+ const addSubformat = (ext, title, parent) => {
108
+ const loaded = loadTree();
109
+ if (isOpError(loaded))
110
+ return loaded;
111
+ if (!loaded.subformats?.some((format) => format.ext === ext) || !title.trim())
112
+ return { error: "Choose an existing subformat and enter a title", status: 400 };
113
+ const id = subformatPageId(ext);
114
+ const tree = insertDoc(loaded.tree, id, parent, { subformat: ext, title: title.trim() });
115
+ if (!tree)
116
+ return { error: "Page already exists or parent is missing", status: 409 };
117
+ writeManifest(root, tree, loaded);
118
+ return { id };
119
+ };
120
+ const renameSubformat = (id, title) => {
121
+ const loaded = loadTree();
122
+ if (isOpError(loaded))
123
+ return loaded;
124
+ if (!title.trim())
125
+ return { error: "title is required", status: 400 };
126
+ const visit = (nodes) => nodes.some((node) => {
127
+ if (node.id === id && node.subformat) {
128
+ node.title = title.trim();
129
+ return true;
130
+ }
131
+ return visit(node.children);
132
+ });
133
+ if (!visit(loaded.tree))
134
+ return { error: "Subformat page not found", status: 404 };
135
+ writeManifest(root, loaded.tree, loaded);
136
+ return { id };
137
+ };
95
138
  /**
96
139
  * Reorders and reparents. Rewrites only dooc.yaml. Omitted index = after the last child
97
140
  * of parent.
@@ -125,6 +168,37 @@ export const createDocOps = (root) => {
125
168
  if (newId === "" || newId === oldId) {
126
169
  return { id: oldId, updatedRefs: 0 };
127
170
  }
171
+ const manifest = readManifest(root);
172
+ if (manifest.format === "nested") {
173
+ const name = newId.endsWith(".md") ? newId : `${newId}.md`;
174
+ if (!isDocumentFileName(name))
175
+ return { error: "Enter a Markdown file name", status: 400 };
176
+ try {
177
+ const file = docFile(oldId, manifest.files);
178
+ const next = posix.join(posix.dirname(file), name);
179
+ const moves = new Map([[file, next]]);
180
+ const updatedRefs = referenceFiles().filter((path) => {
181
+ const raw = readFileSync(textfilePath(root, path), "utf8");
182
+ return rewriteFileLinks(raw, moves) !== raw;
183
+ }).length;
184
+ updateFiles(root, {
185
+ action: "rename",
186
+ file,
187
+ name,
188
+ revision: filesSnapshot(root).revision,
189
+ });
190
+ return {
191
+ id: fileDocumentId(next),
192
+ updatedRefs,
193
+ };
194
+ }
195
+ catch (error) {
196
+ return {
197
+ error: error instanceof Error ? error.message : String(error),
198
+ status: 409,
199
+ };
200
+ }
201
+ }
128
202
  if (!isDocId(newId)) {
129
203
  return { error: "id must be a slug (lowercase alphanumerics, hyphens)", status: 400 };
130
204
  }
@@ -204,6 +278,22 @@ export const createDocOps = (root) => {
204
278
  * referencedBy. parent = the deleted doc's parent.
205
279
  */
206
280
  const remove = (id, force = false) => {
281
+ const manifest = loadTree();
282
+ if (isOpError(manifest))
283
+ return manifest;
284
+ const page = flattenTree(manifest.tree).find((node) => node.id === id && node.subformat);
285
+ if (page) {
286
+ const tree = removeDoc(manifest.tree, id);
287
+ if (!tree)
288
+ return { error: "doc has children (move / delete them first)", status: 409 };
289
+ const removedIcon = iconPath(id);
290
+ if (manifest.files?.icons)
291
+ delete manifest.files.icons[id];
292
+ writeManifest(root, tree, manifest);
293
+ if (existsSync(removedIcon))
294
+ unlinkSync(removedIcon);
295
+ return { parent: page.parent, danglingRefs: 0 };
296
+ }
207
297
  const target = existingDoc(id);
208
298
  if (isOpError(target)) {
209
299
  return target;
@@ -245,7 +335,6 @@ export const createDocOps = (root) => {
245
335
  delete loaded.files.documents[id];
246
336
  if (loaded.files.icons)
247
337
  delete loaded.files.icons[id];
248
- loaded.files.order = loaded.files.order.filter((file) => join(root, file) !== removedPath);
249
338
  }
250
339
  writeManifest(root, tree, loaded);
251
340
  unlinkSync(removedPath);
@@ -352,6 +441,8 @@ export const createDocOps = (root) => {
352
441
  figureFiles,
353
442
  add,
354
443
  addFile,
444
+ addSubformat,
445
+ renameSubformat,
355
446
  move,
356
447
  rename,
357
448
  remove,
@@ -0,0 +1,24 @@
1
+ import type { ValidateFunction } from "ajv";
2
+ import { type Subformat, type SubformatCollection, type SubformatField } from "../core/subformats.js";
3
+ export interface LoadedSubformat extends Subformat {
4
+ fields: SubformatField[];
5
+ template: string;
6
+ validate: ValidateFunction;
7
+ }
8
+ export declare const compileSubformatSchema: (content: string) => {
9
+ schema: import("ajv").SchemaObject;
10
+ validate: ValidateFunction<unknown>;
11
+ };
12
+ export declare const loadSubformat: (root: string, config: Subformat) => LoadedSubformat;
13
+ export declare const validateSubformatRecord: (format: LoadedSubformat, data: Record<string, unknown>) => void;
14
+ export declare const validateSubformatFile: (root: string, file: string, content: string) => void;
15
+ export declare const subformatResponse: (root: string, input: Record<string, unknown> | undefined) => {
16
+ status: number;
17
+ body: {
18
+ content?: string;
19
+ data?: Record<string, unknown>;
20
+ collection?: SubformatCollection;
21
+ error?: string;
22
+ };
23
+ };
24
+ export { parseSubformatRecord } from "../core/subformat-record.js";
@@ -0,0 +1,299 @@
1
+ import { existsSync } from "node:fs";
2
+ import { Ajv2020 } from "ajv/dist/2020.js";
3
+ import addFormats from "ajv-formats";
4
+ import { stringify as stringifyToml } from "smol-toml";
5
+ import { Document, isSeq, parseDocument, stringify as stringifyYaml } from "yaml";
6
+ import { MANIFEST_FILE } from "../core/content-metadata.js";
7
+ import { fileExtension } from "../core/files.js";
8
+ import { parseSubformatRecord, setSubformatValue } from "../core/subformat-record.js";
9
+ import { parseSubformats, SUBFORMAT_SCHEMA_TEMPLATE, SUBFORMAT_SCHEMA_VERSION, } from "../core/subformats.js";
10
+ import { filesSnapshot, managedFile } from "./files.js";
11
+ import { parseManifestText, readManifest } from "./manifest.js";
12
+ import { readTextfile, textfilePath, writeTextfile } from "./textfile.js";
13
+ export const compileSubformatSchema = (content) => {
14
+ const schema = JSON.parse(content);
15
+ if (!schema || typeof schema !== "object" || Array.isArray(schema) || schema.$async)
16
+ throw new Error("Use a synchronous JSON object schema");
17
+ if (schema.$schema !== undefined && schema.$schema !== SUBFORMAT_SCHEMA_VERSION)
18
+ throw new Error(`Use JSON Schema 2020-12: ${SUBFORMAT_SCHEMA_VERSION}`);
19
+ const ajv = new Ajv2020({ allErrors: true, strict: true, ownProperties: true });
20
+ addFormats.default(ajv);
21
+ const validate = ajv.compile(schema);
22
+ return { schema, validate };
23
+ };
24
+ const schemaCache = new Map();
25
+ export const loadSubformat = (root, config) => {
26
+ const content = readTextfile(root, config.schema);
27
+ let compiled = schemaCache.get(content);
28
+ if (!compiled) {
29
+ compiled = compileSubformatSchema(content);
30
+ // Bound retained validators when schemas are edited repeatedly.
31
+ if (schemaCache.size >= 32)
32
+ schemaCache.clear();
33
+ schemaCache.set(content, compiled);
34
+ }
35
+ const { schema, validate } = compiled;
36
+ const resolve = (value) => {
37
+ const seen = new Set();
38
+ while (typeof value.$ref === "string" && value.$ref.startsWith("#/")) {
39
+ if (seen.has(value.$ref))
40
+ break;
41
+ seen.add(value.$ref);
42
+ const target = value.$ref
43
+ .slice(2)
44
+ .split("/")
45
+ .reduce((node, key) => {
46
+ const property = key.replaceAll("~1", "/").replaceAll("~0", "~");
47
+ return node && Object.hasOwn(node, property) ? node[property] : undefined;
48
+ }, schema);
49
+ if (!target || typeof target !== "object")
50
+ break;
51
+ const { $ref: _ref, ...siblings } = value;
52
+ value = { ...target, ...siblings };
53
+ }
54
+ return value;
55
+ };
56
+ // shortcut: controls use top-level properties and local refs, extend extraction for composed schemas.
57
+ const fields = Object.entries(resolve(schema).properties ?? {}).flatMap(([name, definition]) => {
58
+ if (!definition || typeof definition !== "object")
59
+ return [];
60
+ const property = resolve(definition);
61
+ const values = property.enum;
62
+ return [
63
+ {
64
+ name,
65
+ title: typeof property.title === "string" ? property.title : name,
66
+ ...(["string", "number", "integer", "boolean"].includes(property.type)
67
+ ? { type: property.type }
68
+ : {}),
69
+ ...(Array.isArray(values) &&
70
+ values.every((value) => value === null ||
71
+ ["string", "number", "boolean"].includes(typeof value))
72
+ ? { enum: values }
73
+ : {}),
74
+ ...(["date", "date-time"].includes(property.format)
75
+ ? { format: property.format }
76
+ : {}),
77
+ ...(property.readOnly === true ? { readOnly: true } : {}),
78
+ },
79
+ ];
80
+ });
81
+ const object = resolve(schema);
82
+ const initial = object.default ??
83
+ object.examples?.[0] ??
84
+ Object.fromEntries(Object.entries(object.properties ?? {}).flatMap(([name, definition]) => {
85
+ if (!definition || typeof definition !== "object")
86
+ return [];
87
+ const property = resolve(definition);
88
+ if (!object.required?.includes(name) && property.default === undefined)
89
+ return [];
90
+ const value = property.default ??
91
+ property.const ??
92
+ property.enum?.[0] ??
93
+ (property.type === "boolean"
94
+ ? false
95
+ : ["number", "integer"].includes(property.type)
96
+ ? (property.minimum ?? 0)
97
+ : property.type === "object"
98
+ ? {}
99
+ : property.type === "array"
100
+ ? []
101
+ : property.format === "date"
102
+ ? new Date().toISOString().slice(0, 10)
103
+ : property.format === "date-time"
104
+ ? new Date().toISOString()
105
+ : "");
106
+ return [[name, value]];
107
+ }));
108
+ let template = "";
109
+ try {
110
+ template =
111
+ config.format === "json"
112
+ ? `${JSON.stringify(initial, null, 2)}\n`
113
+ : config.format === "yaml"
114
+ ? stringifyYaml(initial)
115
+ : stringifyToml(initial);
116
+ }
117
+ catch {
118
+ // A schema example may contain values the configured format cannot represent.
119
+ }
120
+ return { ...config, fields, template, validate };
121
+ };
122
+ export const validateSubformatRecord = (format, data) => {
123
+ if (!format.validate(data))
124
+ throw new Error((format.validate.errors ?? [])
125
+ .map((error) => `${error.instancePath || "/"} ${error.message}`)
126
+ .join("; "));
127
+ };
128
+ export const validateSubformatFile = (root, file, content) => {
129
+ const configs = readManifest(root).subformats;
130
+ if (configs?.some((format) => format.schema === file.replace(/^(\.\/)+/, "")))
131
+ compileSubformatSchema(content);
132
+ const config = configs?.find((format) => format.ext === fileExtension(file));
133
+ if (!config)
134
+ return;
135
+ if (!filesSnapshot(root).files.some((file) => file.path === config.schema))
136
+ throw new Error("Subformat schema is not available in the workspace");
137
+ try {
138
+ validateSubformatRecord(loadSubformat(root, config), parseSubformatRecord(content, config.format));
139
+ }
140
+ catch (error) {
141
+ throw new Error(`${file} (${config.format}): ${error instanceof Error ? error.message : String(error)}`);
142
+ }
143
+ };
144
+ export const subformatResponse = (root, input) => {
145
+ try {
146
+ if (input?.action === "validate") {
147
+ if (typeof input.content !== "string")
148
+ throw new Error("Schema content is required");
149
+ compileSubformatSchema(input.content);
150
+ return { status: 200, body: {} };
151
+ }
152
+ if (input?.action === "layouts") {
153
+ if (typeof input.key !== "string" ||
154
+ !["card_title", "group_by", "sort_by", "sort_order"].includes(input.key) ||
155
+ typeof input.value !== "string" ||
156
+ (input.base !== null && typeof input.base !== "string"))
157
+ throw new Error("A layout key, value and previous value are required");
158
+ const raw = readTextfile(root, MANIFEST_FILE);
159
+ const manifest = parseManifestText(raw);
160
+ if (manifest.errors.length)
161
+ throw new Error(manifest.errors.join("\n"));
162
+ const index = manifest.subformats?.findIndex((format) => format.ext === input.ext) ?? -1;
163
+ const config = manifest.subformats?.[index];
164
+ if (!config)
165
+ throw new Error("Unknown subformat");
166
+ const key = input.key;
167
+ if ((config.layouts?.[key] ?? null) !== input.base)
168
+ return {
169
+ status: 409,
170
+ body: { error: "Default changed externally. Reload and try again." },
171
+ };
172
+ parseSubformats([{ ...config, layouts: { ...config.layouts, [key]: input.value } }]);
173
+ if (key !== "sort_order" && input.value) {
174
+ const field = loadSubformat(root, config).fields.find((field) => field.name === input.value);
175
+ if (!field ||
176
+ (key === "group_by" && !field.enum?.length) ||
177
+ (key === "sort_by" && !field.enum && !field.format && !field.type))
178
+ throw new Error("Default must reference a compatible schema field");
179
+ }
180
+ const document = parseDocument(raw);
181
+ const section = manifest.format === "nested" ? "json_subformats" : "subformats";
182
+ document.setIn([section, index, "layouts", key], input.value);
183
+ if (!writeTextfile(root, MANIFEST_FILE, document.toString(), raw))
184
+ return { status: 409, body: { error: "Manifest changed externally. Try again." } };
185
+ return { status: 200, body: {} };
186
+ }
187
+ if (input?.action === "register") {
188
+ const raw = readTextfile(root, MANIFEST_FILE);
189
+ const manifest = parseManifestText(raw);
190
+ if (manifest.errors.length)
191
+ throw new Error(manifest.errors.join("\n"));
192
+ const schema = input.schema === undefined || input.schema === ""
193
+ ? `${input.ext}.schema.json`
194
+ : input.schema;
195
+ const configs = parseSubformats([
196
+ ...(manifest.subformats ?? []),
197
+ { ext: input.ext, format: input.format, schema },
198
+ ]);
199
+ const config = configs[configs.length - 1];
200
+ if (!managedFile(config.schema))
201
+ throw new Error("Schema must be a local project file");
202
+ if (input.content !== undefined && typeof input.content !== "string")
203
+ throw new Error("Schema content must be text");
204
+ const initial = input.content ?? SUBFORMAT_SCHEMA_TEMPLATE;
205
+ compileSubformatSchema(initial);
206
+ if (!existsSync(textfilePath(root, config.schema))) {
207
+ if (!writeTextfile(root, config.schema, initial, null))
208
+ return {
209
+ status: 409,
210
+ body: { error: "Schema changed externally. Try again." },
211
+ };
212
+ }
213
+ else if (input.content !== undefined &&
214
+ readTextfile(root, config.schema) !== initial) {
215
+ return {
216
+ status: 409,
217
+ body: { error: "Schema file already exists. Choose another path." },
218
+ };
219
+ }
220
+ if (!filesSnapshot(root).files.some((file) => file.path === config.schema))
221
+ throw new Error("Subformat schema is not available in the workspace");
222
+ const loaded = loadSubformat(root, config);
223
+ const parsed = parseDocument(raw);
224
+ const document = isSeq(parsed.contents) || parsed.contents == null
225
+ ? new Document({ docs: parsed.toJS() ?? [] })
226
+ : parsed;
227
+ if (document !== parsed)
228
+ document.commentBefore = parsed.commentBefore;
229
+ const key = manifest.format === "nested" ? "json_subformats" : "subformats";
230
+ if (document.has(key))
231
+ document.addIn([key], config);
232
+ else
233
+ document.set(key, [config]);
234
+ if (!writeTextfile(root, MANIFEST_FILE, document.toString(), raw))
235
+ return { status: 409, body: { error: "Manifest changed externally. Try again." } };
236
+ return {
237
+ status: 200,
238
+ body: {
239
+ collection: {
240
+ ...config,
241
+ fields: loaded.fields,
242
+ template: loaded.template,
243
+ defaultFolder: manifest.defaultSubformatFolder,
244
+ records: [],
245
+ change: "added",
246
+ },
247
+ },
248
+ };
249
+ }
250
+ if (input?.action === "create") {
251
+ if (typeof input.file !== "string" || typeof input.content !== "string")
252
+ throw new Error("A record file and content are required");
253
+ const config = readManifest(root).subformats?.find((format) => format.ext === fileExtension(input.file));
254
+ if (!config)
255
+ throw new Error("Choose a configured subformat extension");
256
+ validateSubformatFile(root, input.file, input.content);
257
+ const data = parseSubformatRecord(input.content, config.format);
258
+ if (!writeTextfile(root, input.file, input.content, null))
259
+ return { status: 409, body: { error: "File already exists" } };
260
+ return { status: 200, body: { content: input.content, data } };
261
+ }
262
+ if (typeof input?.file !== "string" ||
263
+ typeof input.base !== "string" ||
264
+ typeof input.field !== "string")
265
+ throw new Error("A record file, original content and enum field are required");
266
+ const files = filesSnapshot(root).files.map((file) => file.path);
267
+ if (!files.includes(input.file))
268
+ throw new Error("Record file is not available in the workspace");
269
+ const config = readManifest(root).subformats?.find((format) => format.ext === fileExtension(input.file));
270
+ if (!config || !files.includes(config.schema))
271
+ throw new Error("Subformat schema is not available in the workspace");
272
+ const format = loadSubformat(root, config);
273
+ const field = format.fields.find((field) => field.name === input.field);
274
+ if (field?.readOnly || !field?.enum?.some((value) => value === input.value))
275
+ throw new Error("Choose a writable enum value defined by the schema");
276
+ const current = readTextfile(root, input.file);
277
+ if (current !== input.base)
278
+ return {
279
+ status: 409,
280
+ body: { error: "File changed externally. Reload it before saving." },
281
+ };
282
+ const content = setSubformatValue(current, format.format, [input.field], input.value);
283
+ const roundTrip = parseSubformatRecord(content, format.format);
284
+ validateSubformatRecord(format, roundTrip);
285
+ if (!writeTextfile(root, input.file, content, current))
286
+ return {
287
+ status: 409,
288
+ body: { error: "File changed externally. Reload it before saving." },
289
+ };
290
+ return { status: 200, body: { content, data: roundTrip } };
291
+ }
292
+ catch (error) {
293
+ return {
294
+ status: 400,
295
+ body: { error: error instanceof Error ? error.message : String(error) },
296
+ };
297
+ }
298
+ };
299
+ export { parseSubformatRecord } from "../core/subformat-record.js";
@@ -3,6 +3,7 @@ import { linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync,
3
3
  import { open, stat } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { isRemoteTextfile, parseTextfileRange } from "../core/textfile.js";
6
+ import { assertNotIgnored } from "./ignored-files.js";
6
7
  import { readRemoteTextfile, readRemoteTextfileAsync } from "./textfile-remote.js";
7
8
  export { parseTextfileRange } from "../core/textfile.js";
8
9
  /** Select whole lines, preserving their original separators and excluding the final separator. */
@@ -56,6 +57,7 @@ export const readTextfile = (root, file, refresh = false, domains = []) => {
56
57
  }
57
58
  else {
58
59
  const path = textfilePath(root, file);
60
+ assertNotIgnored(root, file);
59
61
  if (!statSync(path).isFile())
60
62
  throw new Error("expected a regular UTF-8 text file");
61
63
  data = readFileSync(path);
@@ -73,6 +75,7 @@ export const readTextfileAsync = async (root, file, refresh = false, domains = [
73
75
  return decodeTextfile(await readRemoteTextfileAsync(file, domains, refresh));
74
76
  }
75
77
  const path = textfilePath(root, file);
78
+ assertNotIgnored(root, file);
76
79
  if (!(await stat(path)).isFile())
77
80
  throw new Error("expected a regular UTF-8 text file");
78
81
  const handle = await open(path, "r");
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
2
  import { localFile } from "../core/files.js";
3
3
  import { themeVariantFile } from "../core/theme-variants.js";
4
+ import { ignoredFiles } from "./ignored-files.js";
4
5
  import { readManifest } from "./manifest.js";
5
6
  import { textfilePath } from "./textfile.js";
6
7
  export const themeNames = (root) => {
@@ -16,7 +17,9 @@ export const siteThemes = (root, manifest = readManifest(root)) => manifest.them
16
17
  export const themeVariants = (root, file, themes = siteThemes(root)) => {
17
18
  if (!localFile(file) || file.startsWith("themes/"))
18
19
  return {};
19
- return Object.fromEntries(themes
20
+ const variants = themes
20
21
  .map((theme) => [theme, themeVariantFile(file, theme)])
21
- .filter(([, path]) => existsSync(textfilePath(root, path))));
22
+ .filter(([, path]) => existsSync(textfilePath(root, path)));
23
+ const ignored = ignoredFiles(root, variants.map(([, path]) => path));
24
+ return Object.fromEntries(variants.filter(([, path]) => !ignored.has(path)));
22
25
  };
@@ -1,10 +1,17 @@
1
1
  import { type FileLayout } from "./files.js";
2
+ import { type Subformat } from "./subformats.js";
2
3
  export declare const MANIFEST_FILE = "dooc.yaml";
3
4
  export interface DocNode {
4
5
  id: string;
6
+ file?: string;
7
+ subformat?: string;
8
+ title?: string;
5
9
  children: DocNode[];
6
10
  }
7
11
  export interface ParsedManifest {
12
+ format?: "nested";
13
+ titles?: Record<string, string>;
14
+ themeIcons?: Record<string, string>;
8
15
  tree: DocNode[];
9
16
  title?: string;
10
17
  icon?: string;
@@ -14,10 +21,13 @@ export interface ParsedManifest {
14
21
  languages?: string[];
15
22
  /** Color themes offered by the site, with authored variants for embedded files. */
16
23
  themes?: ("light" | "dark")[];
24
+ subformats?: Subformat[];
25
+ defaultSubformatFolder?: string;
17
26
  errors: string[];
18
27
  }
19
28
  export declare const DOC_ID_RE: RegExp;
20
29
  export declare const isDocId: (s: string) => boolean;
30
+ export declare const subformatPageId: (ext: string) => string;
21
31
  /** Doc file name directly under content/ (`<id>.md`) → id. undefined if the shape differs. */
22
32
  export declare const docIdOfFile: (name: string) => string | undefined;
23
33
  /**
@@ -26,16 +36,15 @@ export declare const docIdOfFile: (name: string) => string | undefined;
26
36
  * Validates id shape and duplicates.
27
37
  */
28
38
  export declare const parseManifest: (value: unknown) => ParsedManifest;
29
- /** Tree → dooc.yaml text (serialized in the hand-written shape, keeping git diffs clean). */
30
- export declare const serializeManifest: (tree: readonly DocNode[], { title, icon, defaultLang, files, languages, themes, }?: Omit<ParsedManifest, "tree" | "errors">) => string;
39
+ /** Serialize the authored format; legacy manifests remain readable during migration. */
40
+ export declare const serializeManifest: (tree: readonly DocNode[], { format, titles, themeIcons, title, icon, defaultLang, files, languages, themes, subformats, defaultSubformatFolder, }?: Omit<ParsedManifest, "tree" | "errors">) => string;
31
41
  /** Flatten the tree into display order (pre-order). parent omitted = top level. */
32
- export declare const flattenTree: (tree: readonly DocNode[]) => {
33
- id: string;
42
+ export declare const flattenTree: (tree: readonly DocNode[]) => (Omit<DocNode, "children"> & {
34
43
  parent?: string;
35
44
  depth: number;
36
- }[];
45
+ })[];
37
46
  /** Append a new doc to the end of parent's children. Duplicate id / missing parent → undefined. */
38
- export declare const insertDoc: (tree: readonly DocNode[], id: string, parent?: string) => DocNode[] | undefined;
47
+ export declare const insertDoc: (tree: readonly DocNode[], id: string, parent?: string, page?: Pick<DocNode, "subformat" | "title">) => DocNode[] | undefined;
39
48
  /**
40
49
  * Move a doc (with its children) to position index under parent. It can't be moved under
41
50
  * itself or its own descendants (that would create a cycle). An invalid move returns undefined