@forwardimpact/libdoc 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Dick Olsson
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # libdoc
2
+
3
+ Documentation build and serve tools for the Forward Impact documentation site.
4
+ Generates static sites from Markdown files with Mustache templating support.
5
+
6
+ ## Usage
7
+
8
+ ```javascript
9
+ import {
10
+ DocsBuilder,
11
+ DocsServer,
12
+ parseFrontMatter,
13
+ } from "@forwardimpact/libdoc";
14
+
15
+ const builder = new DocsBuilder({ srcDir: "docs", outDir: "public" });
16
+ await builder.build();
17
+
18
+ const server = new DocsServer({ port: 3000 });
19
+ await server.start();
20
+ ```
21
+
22
+ ## CLI
23
+
24
+ ```sh
25
+ # Build documentation site
26
+ npx fit-doc build --src=docs --out=dist
27
+
28
+ # Serve documentation locally
29
+ npx fit-doc serve --port=3000
30
+
31
+ # Serve with watch mode for development
32
+ npx fit-doc serve --watch
33
+ ```
34
+
35
+ ## API
36
+
37
+ | Export | Description |
38
+ | ------------------ | -------------------------------------------- |
39
+ | `DocsBuilder` | Build static documentation sites |
40
+ | `DocsServer` | Serve documentation locally with live reload |
41
+ | `parseFrontMatter` | Parse YAML front matter from markdown files |
package/bin/fit-doc.js ADDED
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { Hono } from "hono";
6
+ import { serve } from "@hono/node-server";
7
+ import { marked } from "marked";
8
+ import mustache from "mustache";
9
+ import prettier from "prettier";
10
+
11
+ import { DocsBuilder, DocsServer } from "../index.js";
12
+ import { parseFrontMatter } from "../frontmatter.js";
13
+
14
+ const USAGE = `
15
+ Usage: fit-doc <command> [options]
16
+
17
+ Commands:
18
+ build Build documentation site from markdown files
19
+ serve Build and serve documentation with optional watch mode
20
+
21
+ Options:
22
+ -h, --help Show this help message
23
+
24
+ Build options:
25
+ --src=<dir> Source directory (default: docs)
26
+ --out=<dir> Output directory (default: dist)
27
+
28
+ Serve options:
29
+ --src=<dir> Source directory (default: docs)
30
+ --out=<dir> Output directory (default: dist)
31
+ -p, --port Port to serve on (default: 3000)
32
+ -w, --watch Watch for changes and rebuild
33
+ `;
34
+
35
+ /**
36
+ * @param {string} message
37
+ */
38
+ function error(message) {
39
+ console.error(`Error: ${message}`);
40
+ process.exit(1);
41
+ }
42
+
43
+ /**
44
+ * @param {import("../builder.js").DocsBuilder} builder
45
+ * @param {string} docsDir
46
+ * @param {string} distDir
47
+ */
48
+ async function runBuild(builder, docsDir, distDir) {
49
+ if (!fs.existsSync(docsDir)) {
50
+ error(`Source directory not found: ${docsDir}`);
51
+ }
52
+
53
+ await builder.build(docsDir, distDir);
54
+ }
55
+
56
+ /**
57
+ * @param {import("../builder.js").DocsBuilder} builder
58
+ * @param {import("../server.js").DocsServer} server
59
+ * @param {string} docsDir
60
+ * @param {string} distDir
61
+ * @param {{ port: number, watch: boolean }} options
62
+ */
63
+ async function runServe(builder, server, docsDir, distDir, options) {
64
+ if (!fs.existsSync(docsDir)) {
65
+ error(`Source directory not found: ${docsDir}`);
66
+ }
67
+
68
+ await builder.build(docsDir, distDir);
69
+
70
+ if (options.watch) {
71
+ server.watch(docsDir, distDir);
72
+ }
73
+
74
+ server.serve(distDir, { port: options.port, hostname: "0.0.0.0" });
75
+ console.log("Press Ctrl+C to stop");
76
+ }
77
+
78
+ async function main() {
79
+ const args = process.argv.slice(2);
80
+
81
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help") {
82
+ console.log(USAGE.trim());
83
+ process.exit(args.length === 0 ? 1 : 0);
84
+ }
85
+
86
+ const command = args[0];
87
+ const commandArgs = args.slice(1);
88
+
89
+ if (!["build", "serve"].includes(command)) {
90
+ error(`Unknown command: ${command}\n\n${USAGE.trim()}`);
91
+ }
92
+
93
+ const { values } = parseArgs({
94
+ args: commandArgs,
95
+ options: {
96
+ src: { type: "string", default: "docs" },
97
+ out: { type: "string", default: "dist" },
98
+ port: { type: "string", short: "p", default: "3000" },
99
+ watch: { type: "boolean", short: "w", default: false },
100
+ help: { type: "boolean", short: "h", default: false },
101
+ },
102
+ allowPositionals: false,
103
+ });
104
+
105
+ if (values.help) {
106
+ console.log(USAGE.trim());
107
+ process.exit(0);
108
+ }
109
+
110
+ const workingDir = process.env.INIT_CWD || process.cwd();
111
+ const docsDir = path.join(workingDir, values.src);
112
+ const distDir = path.join(workingDir, values.out);
113
+
114
+ const builder = new DocsBuilder(
115
+ fs,
116
+ path,
117
+ marked,
118
+ parseFrontMatter,
119
+ mustache.render,
120
+ prettier,
121
+ );
122
+
123
+ try {
124
+ if (command === "build") {
125
+ await runBuild(builder, docsDir, distDir);
126
+ } else {
127
+ const server = new DocsServer(fs, Hono, serve, builder);
128
+ await runServe(builder, server, docsDir, distDir, {
129
+ port: parseInt(values.port, 10),
130
+ watch: values.watch,
131
+ });
132
+ }
133
+ } catch (err) {
134
+ error(err.message);
135
+ }
136
+ }
137
+
138
+ main();
package/builder.js ADDED
@@ -0,0 +1,267 @@
1
+ import { gfmHeadingId } from "marked-gfm-heading-id";
2
+ import { markedHighlight } from "marked-highlight";
3
+
4
+ /**
5
+ * Documentation builder for converting Markdown files to HTML
6
+ */
7
+ export class DocsBuilder {
8
+ #fs;
9
+ #path;
10
+ #marked;
11
+ #matter;
12
+ #mustacheRender;
13
+ #prettier;
14
+
15
+ /**
16
+ * Creates a new DocsBuilder instance
17
+ * @param {object} fs - File system module
18
+ * @param {object} path - Path module
19
+ * @param {Function} markedParser - Marked parser function
20
+ * @param {Function} matterParser - Front matter parser function
21
+ * @param {Function} mustacheRender - Mustache render function
22
+ * @param {object} prettier - Prettier module for HTML formatting
23
+ */
24
+ constructor(fs, path, markedParser, matterParser, mustacheRender, prettier) {
25
+ if (!fs) throw new Error("fs is required");
26
+ if (!path) throw new Error("path is required");
27
+ if (!markedParser) throw new Error("markedParser is required");
28
+ if (!matterParser) throw new Error("matterParser is required");
29
+ if (!mustacheRender) throw new Error("mustacheRender is required");
30
+ if (!prettier) throw new Error("prettier is required");
31
+
32
+ this.#fs = fs;
33
+ this.#path = path;
34
+ this.#marked = markedParser;
35
+ this.#matter = matterParser;
36
+ this.#mustacheRender = mustacheRender;
37
+ this.#prettier = prettier;
38
+
39
+ // Configure marked with extensions
40
+ this.#marked.use(
41
+ gfmHeadingId({
42
+ prefix: "", // No prefix for heading IDs
43
+ }),
44
+ );
45
+
46
+ this.#marked.use(
47
+ markedHighlight({
48
+ langPrefix: "language-", // Adds 'language-' prefix to code block classes
49
+ highlight(code, _lang) {
50
+ // Return the code as-is with proper language class
51
+ // Prism.js will handle highlighting on the client side
52
+ return code;
53
+ },
54
+ }),
55
+ );
56
+ }
57
+
58
+ /**
59
+ * Generate table of contents from h2 headings
60
+ * @param {string} html - HTML content to extract headings from
61
+ * @returns {string} HTML list of ToC links
62
+ */
63
+ #generateToc(html) {
64
+ const headings = Array.from(
65
+ html.matchAll(/<h2 id="([^"]+)">([^<]+)<\/h2>/g),
66
+ (m) => `<li><a href="#${m[1]}">${m[2]}</a></li>`,
67
+ );
68
+ return headings.length ? `<ul>${headings.join("\n")}</ul>` : "";
69
+ }
70
+
71
+ /**
72
+ * Copy directory recursively
73
+ * @param {string} src - Source directory
74
+ * @param {string} dest - Destination directory
75
+ * @returns {boolean} True if directory was copied
76
+ */
77
+ #copyDir(src, dest) {
78
+ if (!this.#fs.existsSync(src)) return false;
79
+
80
+ this.#fs.mkdirSync(dest, { recursive: true });
81
+ const entries = this.#fs.readdirSync(src, { withFileTypes: true });
82
+
83
+ for (const entry of entries) {
84
+ const srcPath = this.#path.join(src, entry.name);
85
+ const destPath = this.#path.join(dest, entry.name);
86
+ entry.isDirectory()
87
+ ? this.#copyDir(srcPath, destPath)
88
+ : this.#fs.copyFileSync(srcPath, destPath);
89
+ }
90
+ return true;
91
+ }
92
+
93
+ /**
94
+ * Copy static assets to distribution directory
95
+ * @param {string} docsDir - Source docs directory
96
+ * @param {string} distDir - Destination distribution directory
97
+ */
98
+ #copyStaticAssets(docsDir, distDir) {
99
+ // Copy assets directory (CSS, JS, images)
100
+ if (
101
+ this.#copyDir(
102
+ this.#path.join(docsDir, "assets"),
103
+ this.#path.join(distDir, "assets"),
104
+ )
105
+ ) {
106
+ console.log(" ✓ assets/");
107
+ }
108
+
109
+ // Copy public files (favicon, etc.)
110
+ const publicDir = this.#path.join(docsDir, "public");
111
+ if (!this.#fs.existsSync(publicDir)) return;
112
+
113
+ this.#fs
114
+ .readdirSync(publicDir, { withFileTypes: true })
115
+ .filter((entry) => entry.isFile())
116
+ .forEach((entry) => {
117
+ this.#fs.copyFileSync(
118
+ this.#path.join(publicDir, entry.name),
119
+ this.#path.join(distDir, entry.name),
120
+ );
121
+ console.log(` ✓ ${entry.name}`);
122
+ });
123
+ }
124
+
125
+ /**
126
+ * Recursively find all Markdown files in a directory
127
+ * @param {string} dir - Directory to search
128
+ * @param {string} baseDir - Base directory for relative paths
129
+ * @returns {string[]} Array of relative paths to Markdown files
130
+ */
131
+ #findMarkdownFiles(dir, baseDir = dir) {
132
+ const results = [];
133
+ const entries = this.#fs.readdirSync(dir);
134
+
135
+ for (const entryName of entries) {
136
+ if (["assets", "public"].includes(entryName)) continue;
137
+ const fullPath = this.#path.join(dir, entryName);
138
+
139
+ // Use statSync to check if it's a directory or file
140
+ try {
141
+ const stat = this.#fs.statSync(fullPath);
142
+ if (stat.isDirectory && stat.isDirectory()) {
143
+ results.push(...this.#findMarkdownFiles(fullPath, baseDir));
144
+ } else if (entryName.endsWith(".md")) {
145
+ // Get path relative to base directory
146
+ const relativePath = fullPath.slice(baseDir.length + 1);
147
+ results.push(relativePath);
148
+ }
149
+ } catch {
150
+ // Skip files that can't be stat'd (e.g., template files)
151
+ if (entryName.endsWith(".md")) {
152
+ const relativePath = fullPath.slice(baseDir.length + 1);
153
+ results.push(relativePath);
154
+ }
155
+ }
156
+ }
157
+ return results;
158
+ }
159
+
160
+ /**
161
+ * Build documentation from Markdown files
162
+ * @param {string} docsDir - Source documentation directory
163
+ * @param {string} distDir - Destination distribution directory
164
+ * @returns {Promise<void>}
165
+ */
166
+ async build(docsDir, distDir) {
167
+ console.log("Building documentation...");
168
+
169
+ // Clean and create dist directory
170
+ if (this.#fs.existsSync(distDir)) {
171
+ this.#fs.rmSync(distDir, { recursive: true });
172
+ }
173
+ this.#fs.mkdirSync(distDir, { recursive: true });
174
+
175
+ // Read and validate template
176
+ const templatePath = this.#path.join(docsDir, "index.template.html");
177
+ if (!this.#fs.existsSync(templatePath)) {
178
+ throw new Error("index.template.html not found in docs directory");
179
+ }
180
+ const template = this.#fs.readFileSync(templatePath, "utf-8");
181
+
182
+ // Process each Markdown file (recursive)
183
+ const mdFiles = this.#findMarkdownFiles(docsDir);
184
+
185
+ if (mdFiles.length === 0) {
186
+ console.warn("Warning: No Markdown files found in docs/");
187
+ }
188
+
189
+ for (const mdFile of mdFiles) {
190
+ const { data: frontMatter, content: markdown } = this.#matter(
191
+ this.#fs.readFileSync(this.#path.join(docsDir, mdFile), "utf-8"),
192
+ );
193
+
194
+ if (!frontMatter.title) {
195
+ console.error(`Error: Missing 'title' in front matter of ${mdFile}`);
196
+ continue;
197
+ }
198
+
199
+ // Convert Markdown to HTML
200
+ const html = this.#marked(markdown);
201
+ const toc = frontMatter.toc !== false ? this.#generateToc(html) : "";
202
+
203
+ // Render template with context
204
+ const outputHtml = this.#mustacheRender(template, {
205
+ title: frontMatter.title,
206
+ description: frontMatter.description || "",
207
+ content: html,
208
+ toc,
209
+ hasToc: !!toc,
210
+ });
211
+
212
+ // Format HTML with prettier
213
+ const formattedHtml = await this.#prettier.format(outputHtml, {
214
+ parser: "html",
215
+ printWidth: 80,
216
+ tabWidth: 2,
217
+ useTabs: false,
218
+ });
219
+
220
+ // Post-process: Unescape HTML entities in Mermaid code blocks
221
+ // Prettier escapes entities, but Mermaid.js needs raw syntax
222
+ let finalHtml = formattedHtml;
223
+ const mermaidBlocks = formattedHtml.match(
224
+ /<code class="language-mermaid">[\s\S]*?<\/code>/g,
225
+ );
226
+ if (mermaidBlocks) {
227
+ finalHtml = formattedHtml.replace(
228
+ /<code class="language-mermaid">([\s\S]*?)<\/code>/g,
229
+ (_match, code) => {
230
+ const unescapedCode = code
231
+ .replace(/&amp;/g, "&")
232
+ .replace(/&lt;/g, "<")
233
+ .replace(/&gt;/g, ">")
234
+ .replace(/&quot;/g, '"')
235
+ .replace(/&#39;/g, "'");
236
+ return `<code class="language-mermaid">${unescapedCode}</code>`;
237
+ },
238
+ );
239
+ }
240
+
241
+ // Determine output path:
242
+ // index.md → index.html
243
+ // dir/index.md → dir/index.html
244
+ // example.md → example/index.html
245
+ // dir/example.md → dir/example/index.html
246
+ const baseName = mdFile.replace(".md", "");
247
+ const isIndex = baseName === "index" || baseName.endsWith("/index");
248
+ const outputPath = isIndex
249
+ ? baseName
250
+ : this.#path.join(baseName, "index");
251
+ const outputDir = this.#path.dirname(
252
+ this.#path.join(distDir, outputPath),
253
+ );
254
+
255
+ this.#fs.mkdirSync(outputDir, { recursive: true });
256
+ this.#fs.writeFileSync(
257
+ this.#path.join(distDir, outputPath + ".html"),
258
+ finalHtml,
259
+ "utf-8",
260
+ );
261
+ console.log(` ✓ ${outputPath}.html`);
262
+ }
263
+
264
+ this.#copyStaticAssets(docsDir, distDir);
265
+ console.log("Documentation build complete!");
266
+ }
267
+ }
package/frontmatter.js ADDED
@@ -0,0 +1,29 @@
1
+ import yaml from "js-yaml";
2
+
3
+ /**
4
+ * Parse simple front matter from markdown content
5
+ * @param {string} content - Markdown content with optional front matter
6
+ * @returns {{data: object, content: string}} Parsed front matter and remaining content
7
+ */
8
+ export function parseFrontMatter(content) {
9
+ const data = {};
10
+
11
+ // Check if content starts with ---
12
+ if (!content.trimStart().startsWith("---")) {
13
+ return { data, content };
14
+ }
15
+
16
+ // Find the closing ---
17
+ const match = content.match(/^\s*---\n([\s\S]*?)\n---\n([\s\S]*)$/);
18
+ if (!match) {
19
+ return { data, content };
20
+ }
21
+
22
+ const [, frontMatter, remainingContent] = match;
23
+ const parsedData = yaml.load(frontMatter);
24
+
25
+ return {
26
+ data: parsedData || {},
27
+ content: remainingContent,
28
+ };
29
+ }
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { DocsBuilder } from "./builder.js";
2
+ export { DocsServer } from "./server.js";
3
+ export { parseFrontMatter } from "./frontmatter.js";
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@forwardimpact/libdoc",
3
+ "version": "0.1.0",
4
+ "description": "Documentation build and serve tools for static site generation from Markdown",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/forwardimpact/pathway",
9
+ "directory": "libs/libdoc"
10
+ },
11
+ "type": "module",
12
+ "main": "index.js",
13
+ "bin": {
14
+ "fit-doc": "./bin/fit-doc.js"
15
+ },
16
+ "files": [
17
+ "bin/",
18
+ "*.js"
19
+ ],
20
+ "exports": {
21
+ ".": "./index.js",
22
+ "./builder": "./builder.js",
23
+ "./server": "./server.js",
24
+ "./frontmatter": "./frontmatter.js"
25
+ },
26
+ "scripts": {
27
+ "test": "node --test test/*.test.js"
28
+ },
29
+ "dependencies": {
30
+ "@hono/node-server": "^1.19.9",
31
+ "hono": "^4.11.4",
32
+ "js-yaml": "^4.1.1",
33
+ "marked": "^14.1.4",
34
+ "marked-gfm-heading-id": "^4.1.3",
35
+ "marked-highlight": "^2.2.3",
36
+ "mustache": "^4.2.0",
37
+ "prettier": "^3.8.0"
38
+ },
39
+ "engines": {
40
+ "node": ">=18.0.0"
41
+ }
42
+ }
package/server.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Documentation server for serving built documentation and watching for changes
3
+ */
4
+ export class DocsServer {
5
+ #fs;
6
+ #Hono;
7
+ #serve;
8
+ #builder;
9
+ #watcher;
10
+
11
+ /**
12
+ * Creates a new DocsServer instance
13
+ * @param {object} fs - File system module
14
+ * @param {Function} HonoConstructor - Hono constructor (optional, required for serve())
15
+ * @param {Function} serveFn - Hono serve function from @hono/node-server (optional, required for serve())
16
+ * @param {import("./builder.js").DocsBuilder} builder - DocsBuilder instance
17
+ */
18
+ constructor(fs, HonoConstructor, serveFn, builder) {
19
+ if (!fs) throw new Error("fs is required");
20
+ if (!builder) throw new Error("builder is required");
21
+
22
+ this.#fs = fs;
23
+ this.#Hono = HonoConstructor;
24
+ this.#serve = serveFn;
25
+ this.#builder = builder;
26
+ this.#watcher = null;
27
+ }
28
+
29
+ /**
30
+ * Start watching for changes and rebuild
31
+ * @param {string} docsDir - Documentation directory to watch
32
+ * @param {string} distDir - Distribution directory for output
33
+ * @returns {void}
34
+ */
35
+ watch(docsDir, distDir) {
36
+ console.log("Watching for changes in docs/...");
37
+
38
+ this.#watcher = this.#fs.watch(
39
+ docsDir,
40
+ { recursive: true },
41
+ (eventType, filename) => {
42
+ if (
43
+ filename &&
44
+ (filename.endsWith(".md") ||
45
+ filename.endsWith(".mustache") ||
46
+ filename.startsWith("assets/"))
47
+ ) {
48
+ console.log(`\nRebuilding due to change in ${filename}...`);
49
+ this.#builder.build(docsDir, distDir).catch((error) => {
50
+ console.error("Build error:", error);
51
+ });
52
+ }
53
+ },
54
+ );
55
+
56
+ // Keep process alive
57
+ process.on("SIGINT", () => {
58
+ this.stopWatch();
59
+ process.exit(0);
60
+ });
61
+ }
62
+
63
+ /**
64
+ * Stop watching for changes
65
+ * @returns {void}
66
+ */
67
+ stopWatch() {
68
+ if (this.#watcher) {
69
+ this.#watcher.close();
70
+ this.#watcher = null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Serve static files from distribution directory
76
+ * @param {string} distDir - Distribution directory to serve
77
+ * @param {object} options - Server options
78
+ * @param {number} options.port - Port to listen on
79
+ * @param {string} options.hostname - Hostname to bind to
80
+ * @returns {object} Server instance
81
+ */
82
+ serve(distDir, options = {}) {
83
+ if (!this.#Hono) {
84
+ throw new Error(
85
+ "HonoConstructor is required for serve() - pass it to constructor",
86
+ );
87
+ }
88
+ if (!this.#serve) {
89
+ throw new Error(
90
+ "serveFn is required for serve() - pass it to constructor",
91
+ );
92
+ }
93
+
94
+ const { port = 3000, hostname = "0.0.0.0" } = options;
95
+
96
+ const app = new this.#Hono();
97
+
98
+ // Serve static files
99
+ app.get("*", async (c) => {
100
+ let filePath = c.req.path;
101
+
102
+ // Default to index.html for root
103
+ if (filePath === "/") {
104
+ filePath = "/index.html";
105
+ }
106
+
107
+ // Remove leading slash and resolve path
108
+ let fullPath = distDir + filePath;
109
+
110
+ // Check if path is a directory and append index.html
111
+ if (this.#fs.existsSync(fullPath)) {
112
+ const stats = this.#fs.statSync(fullPath);
113
+ if (stats.isDirectory()) {
114
+ // Ensure we don't double up slashes
115
+ fullPath = fullPath.replace(/\/$/, "") + "/index.html";
116
+ filePath = filePath.replace(/\/$/, "") + "/index.html";
117
+ }
118
+ }
119
+
120
+ // Check if file exists
121
+ if (!this.#fs.existsSync(fullPath)) {
122
+ return c.text("Not Found", 404);
123
+ }
124
+
125
+ // Read and serve file
126
+ const content = this.#fs.readFileSync(fullPath);
127
+
128
+ // Set content type based on extension
129
+ const ext = filePath.split(".").pop();
130
+ const contentTypes = {
131
+ html: "text/html",
132
+ css: "text/css",
133
+ js: "application/javascript",
134
+ json: "application/json",
135
+ png: "image/png",
136
+ jpg: "image/jpeg",
137
+ jpeg: "image/jpeg",
138
+ gif: "image/gif",
139
+ svg: "image/svg+xml",
140
+ ico: "image/x-icon",
141
+ };
142
+
143
+ const contentType = contentTypes[ext] || "text/plain";
144
+ return c.body(content, 200, {
145
+ "Content-Type": contentType,
146
+ });
147
+ });
148
+
149
+ console.log(`Serving documentation at http://${hostname}:${port}`);
150
+
151
+ return this.#serve({ fetch: app.fetch, port, hostname });
152
+ }
153
+ }