@p10i/flowmatter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Andrei Piontkovskii
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # flowmatter
2
+
3
+ `flowmatter` turns a folder or glob of Markdown files into one interactive
4
+ [flowjob](https://github.com/piontkovsk11andre1/flowjob) map and a mirrored tree
5
+ of linked, standalone HTML pages.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 20 or newer
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @p10i/flowmatter
15
+ ```
16
+
17
+ ## Markdown schema
18
+
19
+ Each Markdown file is a flowjob submodule. Its frontmatter defines its stable
20
+ identity, parent module, and outgoing relations:
21
+
22
+ ```markdown
23
+ ---
24
+ id: place-order
25
+ title: Place order
26
+ module:
27
+ id: orders
28
+ name: Orders
29
+ type: application
30
+ relations:
31
+ - id: charge-card
32
+ to: capture-payment
33
+ type: capturePayment()
34
+ relationType: call
35
+ ---
36
+
37
+ # Place order
38
+
39
+ Validate the order and request payment.
40
+ ```
41
+
42
+ `relations[].to` references another document's `id`. `relations[].type` is the
43
+ flow label. `relations[].id` and `relations[].relationType` are optional; an
44
+ omitted relation ID is generated as `<document-id>:<one-based-index>`.
45
+
46
+ The following values are inferred when omitted:
47
+
48
+ | Field | Default |
49
+ | --- | --- |
50
+ | `id` | Relative Markdown path without `.md` |
51
+ | `title` | First level-one heading, then filename |
52
+ | `module` | Parent directory, or `root` for top-level files |
53
+ | `module.id` | Slug of `module.name` |
54
+ | `module.name` | `module.id` or parent directory name |
55
+
56
+ A string module is shorthand for a named module with a slug-generated ID:
57
+
58
+ ```yaml
59
+ module: Orders
60
+ ```
61
+
62
+ ## CLI
63
+
64
+ Build every Markdown file under a directory:
65
+
66
+ ```sh
67
+ flowmatter docs --output site
68
+ ```
69
+
70
+ Build a glob relative to the current directory:
71
+
72
+ ```sh
73
+ flowmatter "docs/**/*.md" --output site --title "Order processing"
74
+ ```
75
+
76
+ The default output directory is `flowmatter-dist`. It contains `flow.html`
77
+ and one `.html` page per source file with the same relative path. Existing
78
+ generated files are not overwritten unless `--force` is passed.
79
+
80
+ ```text
81
+ Usage: flowmatter <folder-or-glob> [options]
82
+
83
+ Options:
84
+ -o, --output <directory> Output directory (default: flowmatter-dist)
85
+ --flow <filename> Flow HTML filename (default: flow.html)
86
+ --title <title> Override the flow title
87
+ -f, --force Overwrite generated files
88
+ -h, --help Show help
89
+ -v, --version Show the package version
90
+ ```
91
+
92
+ Malformed frontmatter, duplicate IDs, conflicting module definitions, missing
93
+ relation targets, invalid generated flow data, and output collisions fail the
94
+ build with a nonzero exit code.
95
+
96
+ ## Library
97
+
98
+ ```js
99
+ import { buildSite } from "@p10i/flowmatter";
100
+
101
+ const result = await buildSite({
102
+ input: "docs/**/*.md",
103
+ outputDir: "site",
104
+ title: "Order processing",
105
+ });
106
+
107
+ console.log(result.flowPath, result.pages);
108
+ ```
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { buildSite, FlowmatterError } from "../src/index.mjs";
4
+
5
+ const HELP = `Usage: flowmatter <folder-or-glob> [options]
6
+
7
+ Generate a flowjob map and standalone HTML pages from Markdown files.
8
+
9
+ Options:
10
+ -o, --output <directory> Output directory (default: flowmatter-dist)
11
+ --flow <filename> Flow HTML filename (default: flow.html)
12
+ --title <title> Override the flow title
13
+ -f, --force Overwrite generated files
14
+ -h, --help Show this help
15
+ -v, --version Show the package version`;
16
+
17
+ function fail(message, exitCode = 2) {
18
+ console.error(message);
19
+ process.exitCode = exitCode;
20
+ }
21
+
22
+ function takeValue(args, index, option) {
23
+ const value = args[index + 1];
24
+ if (!value || value.startsWith("-")) {
25
+ throw new Error(`${option} requires a value`);
26
+ }
27
+ return value;
28
+ }
29
+
30
+ function parseArgs(args) {
31
+ const options = { force: false };
32
+ const inputs = [];
33
+
34
+ for (let index = 0; index < args.length; index += 1) {
35
+ const argument = args[index];
36
+ if (argument === "-f" || argument === "--force") {
37
+ options.force = true;
38
+ } else if (argument === "-o" || argument === "--output") {
39
+ options.outputDir = takeValue(args, index, argument);
40
+ index += 1;
41
+ } else if (argument === "--flow") {
42
+ options.flowFile = takeValue(args, index, argument);
43
+ index += 1;
44
+ } else if (argument === "--title") {
45
+ options.title = takeValue(args, index, argument);
46
+ index += 1;
47
+ } else if (argument.startsWith("-")) {
48
+ throw new Error(`Unknown option: ${argument}`);
49
+ } else {
50
+ inputs.push(argument);
51
+ }
52
+ }
53
+
54
+ if (inputs.length !== 1) {
55
+ throw new Error("Exactly one folder or glob is required");
56
+ }
57
+ return { input: inputs[0], ...options };
58
+ }
59
+
60
+ const args = process.argv.slice(2);
61
+ if (args.includes("-h") || args.includes("--help")) {
62
+ console.log(HELP);
63
+ } else if (args.includes("-v") || args.includes("--version")) {
64
+ console.log("0.1.0");
65
+ } else {
66
+ try {
67
+ const result = await buildSite(parseArgs(args));
68
+ console.log(
69
+ `Generated ${result.pageCount} page${result.pageCount === 1 ? "" : "s"} and ${result.flowPath}`,
70
+ );
71
+ } catch (error) {
72
+ if (error instanceof FlowmatterError) {
73
+ fail(error.message, 1);
74
+ } else if (error instanceof Error) {
75
+ fail(error.message);
76
+ } else {
77
+ throw error;
78
+ }
79
+ }
80
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@p10i/flowmatter",
3
+ "version": "0.1.0",
4
+ "description": "Generate flowjob maps and linked HTML pages from Markdown frontmatter.",
5
+ "type": "module",
6
+ "exports": "./src/index.mjs",
7
+ "bin": {
8
+ "flowmatter": "bin/flowmatter.mjs"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "test:coverage": "node --test --experimental-test-coverage",
22
+ "prepublishOnly": "npm test"
23
+ },
24
+ "keywords": [
25
+ "flowjob",
26
+ "frontmatter",
27
+ "flowmatter",
28
+ "markdown",
29
+ "diagram"
30
+ ],
31
+ "author": "Andrei Piontkovskii",
32
+ "license": "ISC",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/piontkovsk11andre1/flowmatter.git"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "dependencies": {
41
+ "@p10i/flowjob": "0.1.2",
42
+ "glob": "13.0.6",
43
+ "glob-parent": "6.0.2",
44
+ "gray-matter": "4.0.3",
45
+ "marked": "18.0.7"
46
+ }
47
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,377 @@
1
+ import { access, mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { buildFlow, validateFlow } from "@p10i/flowjob";
4
+ import { glob } from "glob";
5
+ import globParent from "glob-parent";
6
+ import matter from "gray-matter";
7
+ import { marked } from "marked";
8
+
9
+ const PAGE_STYLE = `
10
+ :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; line-height: 1.6; }
11
+ body { margin: 0; background: #f4f1ea; color: #27241f; }
12
+ main { width: min(52rem, calc(100% - 2rem)); margin: 0 auto; padding: 3rem 0 5rem; }
13
+ header { border-bottom: 1px solid #c9c1b3; margin-bottom: 2rem; padding-bottom: 1.25rem; }
14
+ h1, h2, h3 { font-family: Georgia, "Times New Roman", serif; line-height: 1.15; }
15
+ h1 { font-size: clamp(2.2rem, 7vw, 4.5rem); letter-spacing: -.04em; margin: .25rem 0; }
16
+ a { color: #9a3f22; text-underline-offset: .18em; }
17
+ .eyebrow { color: #70685d; font-size: .78rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
18
+ .relations { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); margin: 2.5rem 0; }
19
+ .relation-card { background: #fffaf0; border: 1px solid #d8cebd; border-radius: .35rem; padding: 1rem 1.2rem; }
20
+ .relation-card h2 { font-size: 1rem; margin: 0 0 .65rem; }
21
+ .relation-card ul { margin: 0; padding-left: 1.2rem; }
22
+ article img { height: auto; max-width: 100%; }
23
+ article pre { overflow-x: auto; padding: 1rem; background: #25231f; color: #f9f3e8; }
24
+ article code { font-family: "SFMono-Regular", Consolas, monospace; }
25
+ @media (prefers-color-scheme: dark) {
26
+ body { background: #1d1b18; color: #eee7db; }
27
+ header { border-color: #4b453c; }
28
+ a { color: #ef9b7c; }
29
+ .eyebrow { color: #aaa195; }
30
+ .relation-card { background: #292620; border-color: #514a40; }
31
+ }
32
+ `;
33
+
34
+ export class FlowmatterError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "FlowmatterError";
38
+ }
39
+ }
40
+
41
+ function isObject(value) {
42
+ return value !== null && typeof value === "object" && !Array.isArray(value);
43
+ }
44
+
45
+ function isNonEmptyString(value) {
46
+ return typeof value === "string" && value.trim().length > 0;
47
+ }
48
+
49
+ function toPosix(value) {
50
+ return value.split(path.sep).join("/");
51
+ }
52
+
53
+ function slugify(value) {
54
+ return value
55
+ .toLowerCase()
56
+ .trim()
57
+ .replace(/[^a-z0-9]+/g, "-")
58
+ .replace(/^-|-$/g, "") || "root";
59
+ }
60
+
61
+ function titleFromContent(content, fallback) {
62
+ const heading = content.match(/^#\s+(.+?)\s*$/m)?.[1];
63
+ return heading || fallback.replace(/[-_]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
64
+ }
65
+
66
+ function describeModule(value, relativePath) {
67
+ const directory = path.posix.dirname(relativePath);
68
+ const fallbackId = directory === "." ? "root" : directory;
69
+ const fallbackName = directory === "." ? "Root" : titleFromContent("", path.posix.basename(directory));
70
+
71
+ if (value === undefined) {
72
+ return { id: fallbackId, name: fallbackName };
73
+ }
74
+ if (isNonEmptyString(value)) {
75
+ return { id: slugify(value), name: value.trim() };
76
+ }
77
+ if (!isObject(value)) {
78
+ throw new FlowmatterError(`${relativePath}: "module" must be a string or object`);
79
+ }
80
+
81
+ const id = value.id ?? (isNonEmptyString(value.name) ? slugify(value.name) : fallbackId);
82
+ const name = value.name ?? (isNonEmptyString(value.id) ? value.id : fallbackName);
83
+ if (!isNonEmptyString(id) || !isNonEmptyString(name)) {
84
+ throw new FlowmatterError(`${relativePath}: module "id" and "name" must be non-empty strings`);
85
+ }
86
+ if (value.type !== undefined && !isNonEmptyString(value.type)) {
87
+ throw new FlowmatterError(`${relativePath}: module "type" must be a non-empty string`);
88
+ }
89
+ return { id: id.trim(), name: name.trim(), ...(value.type ? { type: value.type.trim() } : {}) };
90
+ }
91
+
92
+ function parseRelations(value, relativePath) {
93
+ if (value === undefined) return [];
94
+ if (!Array.isArray(value)) {
95
+ throw new FlowmatterError(`${relativePath}: "relations" must be an array`);
96
+ }
97
+
98
+ return value.map((relation, index) => {
99
+ const location = `${relativePath}: relations[${index}]`;
100
+ if (!isObject(relation)) throw new FlowmatterError(`${location} must be an object`);
101
+ if (!isNonEmptyString(relation.to)) throw new FlowmatterError(`${location}.to must be a non-empty string`);
102
+ if (!isNonEmptyString(relation.type)) throw new FlowmatterError(`${location}.type must be a non-empty string`);
103
+ if (relation.id !== undefined && !isNonEmptyString(relation.id)) {
104
+ throw new FlowmatterError(`${location}.id must be a non-empty string`);
105
+ }
106
+ if (relation.relationType !== undefined && !isNonEmptyString(relation.relationType)) {
107
+ throw new FlowmatterError(`${location}.relationType must be a non-empty string`);
108
+ }
109
+ return {
110
+ ...(relation.id ? { id: relation.id.trim() } : {}),
111
+ to: relation.to.trim(),
112
+ type: relation.type.trim(),
113
+ ...(relation.relationType ? { relationType: relation.relationType.trim() } : {}),
114
+ };
115
+ });
116
+ }
117
+
118
+ async function pathExists(filePath) {
119
+ try {
120
+ await access(filePath);
121
+ return true;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ async function resolveInput(input, cwd) {
128
+ const resolved = path.resolve(cwd, input);
129
+ try {
130
+ const details = await stat(resolved);
131
+ if (details.isDirectory()) {
132
+ return {
133
+ baseDir: resolved,
134
+ files: await glob("**/*.md", { absolute: true, cwd: resolved, nodir: true }),
135
+ };
136
+ }
137
+ if (details.isFile()) return { baseDir: path.dirname(resolved), files: [resolved] };
138
+ } catch (error) {
139
+ if (error.code !== "ENOENT") throw error;
140
+ }
141
+
142
+ const baseDir = path.resolve(cwd, globParent(input));
143
+ const files = await glob(input, { absolute: true, cwd, nodir: true });
144
+ return { baseDir, files };
145
+ }
146
+
147
+ async function readDocuments(input, cwd) {
148
+ const { baseDir, files } = await resolveInput(input, cwd);
149
+ const markdownFiles = [...new Set(files.map((file) => path.resolve(file)))]
150
+ .filter((file) => /\.md$/i.test(file))
151
+ .sort((left, right) => left.localeCompare(right));
152
+
153
+ if (markdownFiles.length === 0) {
154
+ throw new FlowmatterError(`No Markdown files matched "${input}"`);
155
+ }
156
+
157
+ const documents = await Promise.all(markdownFiles.map(async (sourcePath) => {
158
+ const relativePath = toPosix(path.relative(baseDir, sourcePath));
159
+ if (relativePath === ".." || relativePath.startsWith("../")) {
160
+ throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`);
161
+ }
162
+
163
+ let parsed;
164
+ try {
165
+ parsed = matter(await readFile(sourcePath, "utf8"));
166
+ } catch (error) {
167
+ throw new FlowmatterError(`${relativePath}: invalid frontmatter (${error.message})`);
168
+ }
169
+
170
+ if (!isObject(parsed.data)) {
171
+ throw new FlowmatterError(`${relativePath}: frontmatter must be an object`);
172
+ }
173
+
174
+ const fallbackId = relativePath.replace(/\.md$/i, "");
175
+ const id = parsed.data.id ?? fallbackId;
176
+ const title = parsed.data.title ?? titleFromContent(parsed.content, path.posix.basename(fallbackId));
177
+ if (!isNonEmptyString(id)) throw new FlowmatterError(`${relativePath}: "id" must be a non-empty string`);
178
+ if (!isNonEmptyString(title)) throw new FlowmatterError(`${relativePath}: "title" must be a non-empty string`);
179
+
180
+ return {
181
+ id: id.trim(),
182
+ title: title.trim(),
183
+ module: describeModule(parsed.data.module, relativePath),
184
+ relations: parseRelations(parsed.data.relations, relativePath),
185
+ content: parsed.content,
186
+ sourcePath,
187
+ relativePath,
188
+ outputRelativePath: relativePath.replace(/\.md$/i, ".html"),
189
+ };
190
+ }));
191
+ return { baseDir, documents };
192
+ }
193
+
194
+ function compile(documents, title) {
195
+ const byId = new Map();
196
+ const modules = new Map();
197
+ const flowIds = new Map();
198
+
199
+ for (const document of documents) {
200
+ if (byId.has(document.id)) {
201
+ throw new FlowmatterError(
202
+ `${document.relativePath}: duplicate document id "${document.id}" (also used by ${byId.get(document.id).relativePath})`,
203
+ );
204
+ }
205
+ byId.set(document.id, document);
206
+
207
+ const existing = modules.get(document.module.id);
208
+ if (existing && (
209
+ existing.name !== document.module.name
210
+ || (existing.type && document.module.type && existing.type !== document.module.type)
211
+ )) {
212
+ throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`);
213
+ }
214
+ if (!existing) modules.set(document.module.id, { ...document.module, submodules: [] });
215
+ if (existing && !existing.type && document.module.type) existing.type = document.module.type;
216
+ modules.get(document.module.id).submodules.push({ id: document.id, name: document.title });
217
+ }
218
+
219
+ const flows = [];
220
+ for (const document of documents) {
221
+ document.relations.forEach((relation, index) => {
222
+ const target = byId.get(relation.to);
223
+ if (!target) {
224
+ throw new FlowmatterError(`${document.relativePath}: relation target "${relation.to}" does not exist`);
225
+ }
226
+ const id = relation.id ?? `${document.id}:${index + 1}`;
227
+ if (flowIds.has(id)) {
228
+ throw new FlowmatterError(`${document.relativePath}: duplicate relation id "${id}" (also used by ${flowIds.get(id)})`);
229
+ }
230
+ flowIds.set(id, document.relativePath);
231
+ flows.push({
232
+ id,
233
+ type: relation.type,
234
+ ...(relation.relationType ? { relationType: relation.relationType } : {}),
235
+ from: { module: document.module.id, submodule: document.id },
236
+ to: { module: target.module.id, submodule: target.id },
237
+ });
238
+ });
239
+ }
240
+
241
+ const flow = {
242
+ schemaVersion: 1,
243
+ title,
244
+ modules: [...modules.values()],
245
+ flows,
246
+ };
247
+ const validation = validateFlow(flow);
248
+ if (!validation.valid) {
249
+ const diagnostics = validation.errors.map((error) => error.message ?? String(error)).join("; ");
250
+ throw new FlowmatterError(`Generated flow is invalid: ${diagnostics}`);
251
+ }
252
+ return { byId, flow };
253
+ }
254
+
255
+ function escapeHtml(value) {
256
+ return String(value)
257
+ .replaceAll("&", "&amp;")
258
+ .replaceAll("<", "&lt;")
259
+ .replaceAll(">", "&gt;")
260
+ .replaceAll('"', "&quot;")
261
+ .replaceAll("'", "&#39;");
262
+ }
263
+
264
+ function relativeHref(fromPath, toPath) {
265
+ return toPosix(path.relative(path.dirname(fromPath), toPath)) || path.basename(toPath);
266
+ }
267
+
268
+ function renderRelationList(title, relations, currentOutputPath) {
269
+ if (relations.length === 0) return "";
270
+ const items = relations.map(({ document, type }) => {
271
+ const href = relativeHref(currentOutputPath, document.outputPath);
272
+ return `<li><a href="${escapeHtml(href)}">${escapeHtml(document.title)}</a> <small>${escapeHtml(type)}</small></li>`;
273
+ }).join("\n");
274
+ return `<section class="relation-card"><h2>${escapeHtml(title)}</h2><ul>${items}</ul></section>`;
275
+ }
276
+
277
+ function renderPage(document, documents, byId, flowPath) {
278
+ const outgoing = document.relations.map((relation) => ({ document: byId.get(relation.to), type: relation.type }));
279
+ const incoming = documents.flatMap((candidate) => candidate.relations
280
+ .filter((relation) => relation.to === document.id)
281
+ .map((relation) => ({ document: candidate, type: relation.type })));
282
+
283
+ const sourceToOutput = new Map(documents.map((candidate) => [candidate.sourcePath, candidate.outputPath]));
284
+ const body = marked.parse(document.content, {
285
+ walkTokens(token) {
286
+ if (token.type !== "link" || !isNonEmptyString(token.href)) return;
287
+ const match = token.href.match(/^([^?#]+\.md)([?#].*)?$/i);
288
+ if (!match || path.isAbsolute(match[1])) return;
289
+ const targetOutput = sourceToOutput.get(path.resolve(path.dirname(document.sourcePath), match[1]));
290
+ if (targetOutput) token.href = `${relativeHref(document.outputPath, targetOutput)}${match[2] ?? ""}`;
291
+ },
292
+ });
293
+ const relations = [
294
+ renderRelationList("Leads to", outgoing, document.outputPath),
295
+ renderRelationList("Reached from", incoming, document.outputPath),
296
+ ].filter(Boolean).join("\n");
297
+
298
+ return `<!DOCTYPE html>
299
+ <html lang="en">
300
+ <head>
301
+ <meta charset="utf-8">
302
+ <meta name="viewport" content="width=device-width, initial-scale=1">
303
+ <title>${escapeHtml(document.title)}</title>
304
+ <style>${PAGE_STYLE}</style>
305
+ </head>
306
+ <body>
307
+ <main>
308
+ <header>
309
+ <div class="eyebrow">${escapeHtml(document.module.name)} · <a href="${escapeHtml(relativeHref(document.outputPath, flowPath))}">Open flow</a></div>
310
+ <h1>${escapeHtml(document.title)}</h1>
311
+ </header>
312
+ ${relations ? `<aside class="relations" aria-label="Relations">${relations}</aside>` : ""}
313
+ <article>${body}</article>
314
+ </main>
315
+ </body>
316
+ </html>
317
+ `;
318
+ }
319
+
320
+ export async function buildSite({
321
+ input,
322
+ outputDir = "flowmatter-dist",
323
+ flowFile = "flow.html",
324
+ title,
325
+ force = false,
326
+ cwd = process.cwd(),
327
+ } = {}) {
328
+ if (!isNonEmptyString(input)) throw new FlowmatterError("A folder or glob input is required");
329
+ if (!isNonEmptyString(outputDir)) throw new FlowmatterError("The output directory must be a non-empty string");
330
+ if (!isNonEmptyString(flowFile) || path.basename(flowFile) !== flowFile || !/\.html?$/i.test(flowFile)) {
331
+ throw new FlowmatterError("The flow filename must be an HTML filename without a directory");
332
+ }
333
+ if (title !== undefined && !isNonEmptyString(title)) {
334
+ throw new FlowmatterError("The title must be a non-empty string");
335
+ }
336
+
337
+ const { baseDir, documents } = await readDocuments(input, path.resolve(cwd));
338
+ const outputRoot = path.resolve(cwd, outputDir);
339
+ const flowPath = path.join(outputRoot, flowFile);
340
+ for (const document of documents) {
341
+ document.outputPath = path.join(outputRoot, document.outputRelativePath);
342
+ if (path.resolve(document.outputPath) === path.resolve(flowPath)) {
343
+ throw new FlowmatterError(`${document.relativePath}: rendered page conflicts with ${flowFile}`);
344
+ }
345
+ }
346
+
347
+ const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
348
+ const { byId, flow } = compile(documents, siteTitle);
349
+ const outputs = [
350
+ { path: flowPath, content: buildFlow(flow, { title: siteTitle }) },
351
+ ...documents.map((document) => ({
352
+ path: document.outputPath,
353
+ content: renderPage(document, documents, byId, flowPath),
354
+ })),
355
+ ];
356
+
357
+ if (!force) {
358
+ for (const output of outputs) {
359
+ if (await pathExists(output.path)) {
360
+ throw new FlowmatterError(`${output.path} already exists; use --force to overwrite generated files`);
361
+ }
362
+ }
363
+ }
364
+
365
+ for (const output of outputs) {
366
+ await mkdir(path.dirname(output.path), { recursive: true });
367
+ await writeFile(output.path, output.content, "utf8");
368
+ }
369
+
370
+ return {
371
+ flow,
372
+ flowPath,
373
+ outputDir: outputRoot,
374
+ pageCount: documents.length,
375
+ pages: documents.map((document) => document.outputPath),
376
+ };
377
+ }