grimoire3d 0.0.0-dev.ef50bb6 → 0.0.0-dev.f7e9e26

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 (117) hide show
  1. package/README.md +28 -124
  2. package/cli/cli.js +348 -0
  3. package/cli/content.js +382 -0
  4. package/cli/cover-options.d.ts +15 -0
  5. package/cli/cover-options.js +105 -0
  6. package/cli/markdown.js +139 -0
  7. package/cli/markup.d.ts +3 -0
  8. package/cli/markup.js +60 -0
  9. package/cli/routes.d.ts +6 -0
  10. package/cli/routes.js +19 -0
  11. package/cli/static-pages.js +467 -0
  12. package/cli/video-url.d.ts +5 -0
  13. package/cli/video-url.js +51 -0
  14. package/dist/BookViewer-CwCn-LTn.js +332 -0
  15. package/dist/components/BookModel.d.ts +20 -0
  16. package/dist/components/BookViewer.d.ts +17 -0
  17. package/dist/components/index.d.ts +2 -0
  18. package/dist/components/index.js +5 -0
  19. package/dist/grimoire3d.css +1 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.js +4 -0
  22. package/dist/main.d.ts +1 -0
  23. package/dist/site/assets/BookReader-BxKrexRZ.js +2 -0
  24. package/dist/site/assets/BookScene-DN1_Kxe3.js +4045 -0
  25. package/dist/site/assets/MermaidDiagram-Dma3Cwvn.js +312 -0
  26. package/dist/site/assets/PageMarkdown-C-gI_dXg.js +37 -0
  27. package/dist/site/assets/abnfDiagram-S7VZAUFO-BIA2ezcb.js +1 -0
  28. package/dist/site/assets/alcove-cyX4Tv3E.avif +0 -0
  29. package/dist/site/assets/architectureDiagram-YGSQEFNW-DMB5UtEZ.js +36 -0
  30. package/dist/site/assets/blockDiagram-APKKGZFW-CeBSUSaW.js +140 -0
  31. package/dist/site/assets/bpmnIcons-APHXDYXF-ByGoYv9M.js +1 -0
  32. package/dist/site/assets/c4Diagram-KJ2TOQU5-BmBo2PHu.js +38 -0
  33. package/dist/site/assets/catalog-07-UR91A.avif +0 -0
  34. package/dist/site/assets/chunk-2Q5K7J3B-BDgDFVbx.js +1 -0
  35. package/dist/site/assets/chunk-5VM5RSS4-CCNs5Q1j.js +15 -0
  36. package/dist/site/assets/chunk-HFQBQIA3-B8uXoLoT.js +1 -0
  37. package/dist/site/assets/chunk-JWPE2WC7-BiKy7CcD.js +1 -0
  38. package/dist/site/assets/chunk-KQLB2F66-D_kpUTKA.js +2 -0
  39. package/dist/site/assets/chunk-KS47KZWR-C_s_qnHf.js +1 -0
  40. package/dist/site/assets/chunk-OY52VR5R-D8f7gl4W.js +88 -0
  41. package/dist/site/assets/chunk-TU62E6Q5-Bm44Znlj.js +1 -0
  42. package/dist/site/assets/chunk-XXDRQBXY-ChLLr56_.js +1 -0
  43. package/dist/site/assets/classDiagram-v2-L25IHNXF-DwKi-r2i.js +217 -0
  44. package/dist/site/assets/cose-bilkent-JH36ORCC-8N6YUm1i.js +1 -0
  45. package/dist/site/assets/cover-blue-Bh8Xp4T5.avif +0 -0
  46. package/dist/site/assets/cover-blue-mobile-YcuYIg0I.avif +0 -0
  47. package/dist/site/assets/cover-green-By13JjUx.avif +0 -0
  48. package/dist/site/assets/cover-green-mobile-BNTgNt7v.avif +0 -0
  49. package/dist/site/assets/cover-red-mobile-DHOCz3wI.avif +0 -0
  50. package/dist/site/assets/cover-red-qvZEk3PI.avif +0 -0
  51. package/dist/site/assets/cynefin-EF2NZ3EQ-Df5ATUPb.js +141 -0
  52. package/dist/site/assets/cynefinDiagram-L36ESFBY-DmAbfxAU.js +62 -0
  53. package/dist/site/assets/cytoscape.esm-BHa1VTXv.js +321 -0
  54. package/dist/site/assets/d3-scale-4DPf7zan.js +1 -0
  55. package/dist/site/assets/dagre-SPEB5RXH-B_2grAE7.js +4 -0
  56. package/dist/site/assets/diagram-3B7GL73J-C9FXwDlf.js +200 -0
  57. package/dist/site/assets/diagram-DNEMPZML-DflAT3gr.js +24 -0
  58. package/dist/site/assets/diagram-L3MUGCDN-B04gjrM_.js +41 -0
  59. package/dist/site/assets/diagram-LA4NIPWU-cfWJg8HX.js +24 -0
  60. package/dist/site/assets/diagram-MHCOC4E2-jRbOs2Df.js +3 -0
  61. package/dist/site/assets/diagram-XPFHEONP-yR45xV59.js +30 -0
  62. package/dist/site/assets/ebnfDiagram-UZSYDL2S-DlmNJUx4.js +1 -0
  63. package/dist/site/assets/elk-XV6XMXQE-cHLdRN7u.js +27 -0
  64. package/dist/site/assets/erDiagram-EYBAPDEH-7HsRsmBI.js +99 -0
  65. package/dist/site/assets/es-DoLiZPBX.js +2 -0
  66. package/dist/site/assets/favicon-C9YRygge.png +0 -0
  67. package/dist/site/assets/flowDiagram-MALGAFMO-DoJjw4RA.js +213 -0
  68. package/dist/site/assets/ganttDiagram-23REXITY-D2uZtX_8.js +292 -0
  69. package/dist/site/assets/gitGraphDiagram-STJD7YCW-CjftfLRK.js +106 -0
  70. package/dist/site/assets/graph-D8UmR1vK.js +1 -0
  71. package/dist/site/assets/index-CqcyU6rA.js +1 -0
  72. package/dist/site/assets/index-DWW-KDWe.css +1 -0
  73. package/dist/site/assets/infoDiagram-KBXO4MBG-HN-1tqq1.js +2 -0
  74. package/dist/site/assets/ishikawaDiagram-M35NCXHK-DcnRwsO0.js +70 -0
  75. package/dist/site/assets/journeyDiagram-OPLOXDXO-CMZGp8mG.js +139 -0
  76. package/dist/site/assets/kanban-definition-BZKZHSQY-C9vGS-EW.js +89 -0
  77. package/dist/site/assets/katex-DLSO0Xi6.js +257 -0
  78. package/dist/site/assets/mindmap-definition-I2QAS2VK-R2SGME7R.js +98 -0
  79. package/dist/site/assets/mobile-cabinet-BUr9vtlo.avif +0 -0
  80. package/dist/site/assets/mobile-cabinet-sm-pauJUfRH.avif +0 -0
  81. package/dist/site/assets/mobile-paper-DF0CuLes.avif +0 -0
  82. package/dist/site/assets/mobile-paper-sm-77eJHX6h.avif +0 -0
  83. package/dist/site/assets/open-nWGD2hyb.glb +0 -0
  84. package/dist/site/assets/pegDiagram-FD4XPPHP-eDMY4Hpd.js +1 -0
  85. package/dist/site/assets/pieDiagram-J4AKIIQI-DoHNiqwi.js +39 -0
  86. package/dist/site/assets/quadrantDiagram-XTYBLID2-Bz5idec8.js +7 -0
  87. package/dist/site/assets/railroadDiagram-MRQ6NCDL-DHJisW8P.js +1 -0
  88. package/dist/site/assets/requirementDiagram-Y7LWUY3S-5aETRIZz.js +84 -0
  89. package/dist/site/assets/resting-amber-BSjsErIg.avif +0 -0
  90. package/dist/site/assets/resting-black-DDQ4XMJI.avif +0 -0
  91. package/dist/site/assets/resting-blue-DDOT8IQ8.avif +0 -0
  92. package/dist/site/assets/resting-green-DkRrV8eX.avif +0 -0
  93. package/dist/site/assets/resting-ivory-CEqoG5yI.avif +0 -0
  94. package/dist/site/assets/resting-plum-B-8tkSmP.avif +0 -0
  95. package/dist/site/assets/resting-red-D0hLpMpz.avif +0 -0
  96. package/dist/site/assets/resting-slate-CH8Z_Rky.avif +0 -0
  97. package/dist/site/assets/resting-teal-CGt6jFmT.avif +0 -0
  98. package/dist/site/assets/resting-walnut-t3WgHgUO.avif +0 -0
  99. package/dist/site/assets/sankeyDiagram-WGJFYUXA-C7O4v9rg.js +40 -0
  100. package/dist/site/assets/search-stage-B8cH1AE_.avif +0 -0
  101. package/dist/site/assets/search-stage-mobile-BZ58ew4F.avif +0 -0
  102. package/dist/site/assets/sequenceDiagram-5NDRBG5M-D4sVU6s6.js +169 -0
  103. package/dist/site/assets/sizeCapture-INFHLROL-Bi2DkFS3.js +1 -0
  104. package/dist/site/assets/stateDiagram-v2-FJ4FJNEA-WqXK7YOd.js +291 -0
  105. package/dist/site/assets/swimlanes-UMQ2AFYF-Czo9WyoV.js +1 -0
  106. package/dist/site/assets/swimlanesDiagram-OMPLPG4O-BH5aEx0X.js +8 -0
  107. package/dist/site/assets/three-core-Dkab0Vtn.js +40 -0
  108. package/dist/site/assets/timeline-definition-SEUHKTQE-KGKDZW_q.js +120 -0
  109. package/dist/site/assets/usecaseDiagram-AFA6YXN4-S0_9S22K.js +370 -0
  110. package/dist/site/assets/vennDiagram-NNMJR3RB-DJOjLlbA.js +34 -0
  111. package/dist/site/assets/wardleyDiagram-S7YFUSEH-BnzYzY-n.js +78 -0
  112. package/dist/site/assets/xychartDiagram-GGNKY7IX-CKOVznoa.js +7 -0
  113. package/dist/site/index.html +14 -0
  114. package/dist/types/index.d.ts +163 -0
  115. package/package.json +27 -11
  116. package/dist/grimoire3d.js +0 -54501
  117. package/dist/grimoire3d.umd.cjs +0 -4212
package/README.md CHANGED
@@ -1,151 +1,55 @@
1
- # grimoire3d
1
+ # Grimoire3D
2
2
 
3
- [![npm version](https://badge.fury.io/js/grimoire3d.svg)](https://badge.fury.io/js/grimoire3d)
4
- [![CI](https://github.com/kkm-horikawa/grimoire3d/actions/workflows/ci.yml/badge.svg)](https://github.com/kkm-horikawa/grimoire3d/actions/workflows/ci.yml)
5
- [![codecov](https://codecov.io/gh/kkm-horikawa/grimoire3d/branch/develop/graph/badge.svg)](https://codecov.io/gh/kkm-horikawa/grimoire3d)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+ Turn Markdown into 3D books you can open and flip through in a browser.
7
4
 
8
- A 3D magical book documentation generator. Transform your docs into an interactive grimoire with realistic page-flip animations.
5
+ ![A Markdown chapter is added under docs, then opened and paged through from the Grimoire3D bookshelf](docs/book-experience/quick-start.gif)
9
6
 
10
- ## What is this?
7
+ [Read the documentation](https://kkm-horikawa.github.io/grimoire3d/)
11
8
 
12
- Grimoire3D transforms your Markdown documentation into an interactive 3D book. Perfect for:
9
+ ## Install
13
10
 
14
- - Project documentation
15
- - Design specifications
16
- - Technical notes
17
- - Portfolios
18
- - Tutorials
11
+ Use Node.js 22 or later. The current npm release predates the CLI. From a checkout of this source, build the installable archive.
19
12
 
20
- ## Features
21
-
22
- - Realistic 3D page-flip animation
23
- - Markdown rendering
24
- - HTML support
25
- - Mermaid diagram support (planned)
26
- - Multiple themes
27
- - Static site generation
28
- - Zero-config setup
29
-
30
- ## Installation
31
-
32
- ```bash
33
- npm install grimoire3d
34
- # or
35
- pnpm add grimoire3d
36
- # or
37
- yarn add grimoire3d
13
+ ```sh
14
+ npm ci
15
+ npm run build
16
+ npm pack
38
17
  ```
39
18
 
40
- ## Quick Start
19
+ In the project where you want your books, install that archive. Run `npm init -y` first if it has no `package.json`.
41
20
 
42
- ### 1. Create your docs directory
43
-
44
- ```
45
- my-project/
46
- ├── grimoire.yml # Configuration (optional)
47
- └── docs/
48
- ├── index.md # Cover page
49
- ├── 01-overview.md
50
- ├── 02-features.md
51
- └── assets/
52
- └── diagram.png
21
+ ```sh
22
+ npm install -D /path/to/grimoire3d-0.0.0.tgz
53
23
  ```
54
24
 
55
- ### 2. Write your content
56
-
57
- ```markdown
58
- <!-- docs/index.md -->
59
- # My Project
25
+ ## Write and preview
60
26
 
61
- Welcome to the documentation.
27
+ Create `docs/field-notes/index.md`.
62
28
 
63
- ## Overview
29
+ ```markdown
30
+ # Field Notes
64
31
 
65
- This is an amazing project...
32
+ This is my first 3D book.
66
33
  ```
67
34
 
68
- ### 3. Start the dev server
35
+ Add Markdown files in the same folder for more chapters. Add folders directly under `docs/` for more books.
69
36
 
70
- ```bash
37
+ ```sh
71
38
  npx grimoire3d serve
72
39
  ```
73
40
 
74
- ### 4. Build for production
75
-
76
- ```bash
77
- npx grimoire3d build
78
- ```
41
+ Open the URL printed in the terminal. The preview updates when you save.
79
42
 
80
- ## Configuration
43
+ ![Workflow from Markdown files to a local bookshelf and a static site in dist](docs/book-experience/workflow.avif)
81
44
 
82
- Create a `grimoire.yml` file in your project root:
45
+ ## Build and publish
83
46
 
84
- ```yaml
85
- title: "My Project Documentation"
86
- theme: "vintage-red" # or "modern-dark", "paper-white"
87
- pages:
88
- - index.md
89
- - 01-overview.md
90
- - 02-features.md
91
- # Omit 'pages' to auto-detect all .md files
92
- ```
93
-
94
- ## Using as a React Component
95
-
96
- ```tsx
97
- import { BookViewer } from "grimoire3d/components";
98
-
99
- const pages = [
100
- {
101
- id: "cover",
102
- title: "Cover",
103
- front: <CoverPage />,
104
- back: <AboutPage />,
105
- tabColor: "#E57373",
106
- tabLabel: "Cover",
107
- },
108
- // ... more pages
109
- ];
110
-
111
- function App() {
112
- return <BookViewer pages={pages} />;
113
- }
47
+ ```sh
48
+ npx grimoire3d build
114
49
  ```
115
50
 
116
- ## Themes
117
-
118
- | Theme | Description |
119
- |-------|-------------|
120
- | `vintage-red` | Classic red leather book cover |
121
- | `modern-dark` | Sleek dark mode |
122
- | `paper-white` | Clean minimal design |
123
- | `forest-green` | Nature-inspired |
124
-
125
- ## Roadmap
126
-
127
- - [ ] v0.1.0 - MVP with basic page-flip and Markdown support
128
- - [ ] v0.2.0 - Mermaid diagrams and code highlighting
129
- - [ ] v0.3.0 - CLI for static site generation
130
- - [ ] v0.4.0 - Theme customization and plugins
131
-
132
- ## Documentation
133
-
134
- - [Architecture & Design Decisions](docs/ARCHITECTURE.md)
135
- - [Glossary of Terms](docs/GLOSSARY.md)
136
- - [Contributing Guide](CONTRIBUTING.md)
137
-
138
- ## Requirements
139
-
140
- - Node.js 22+
141
- - React 19+
142
-
143
- ## License
144
-
145
- MIT License. See [LICENSE](LICENSE) for details.
51
+ Deploy the contents of `dist/` to any static host, including Cloudflare Pages and GitHub Pages. Use `--out-dir site` to choose a different output directory.
146
52
 
147
- ## Inspiration
53
+ For chapter links, formatting, media, Mermaid, cover styles, locale, and SEO, see the [Grimoire3D documentation](https://kkm-horikawa.github.io/grimoire3d/).
148
54
 
149
- - Ancient grimoires and magical tomes
150
- - Vintage technical manuals
151
- - React component libraries
55
+ [Contributing](CONTRIBUTING.md) · [MIT License](LICENSE)
package/cli/cli.js ADDED
@@ -0,0 +1,348 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createReadStream, watch } from "node:fs";
4
+ import {
5
+ copyFile,
6
+ cp,
7
+ lstat,
8
+ mkdir,
9
+ mkdtemp,
10
+ readdir,
11
+ readFile,
12
+ rename,
13
+ rm,
14
+ stat,
15
+ writeFile,
16
+ } from "node:fs/promises";
17
+ import { createServer } from "node:http";
18
+ import {
19
+ basename,
20
+ dirname,
21
+ isAbsolute,
22
+ join,
23
+ relative,
24
+ resolve,
25
+ sep,
26
+ } from "node:path";
27
+ import { fileURLToPath } from "node:url";
28
+ import { parseArgs } from "node:util";
29
+ import { contentType, lookup } from "mime-types";
30
+ import { readLibrary, readSettings } from "./content.js";
31
+ import { previewHead, writeStaticPages } from "./static-pages.js";
32
+
33
+ const template = fileURLToPath(new URL("../dist/site/", import.meta.url));
34
+ const marker = ".grimoire3d-output.json";
35
+
36
+ function json(value) {
37
+ return JSON.stringify(value);
38
+ }
39
+
40
+ async function listFiles(root, directory = "") {
41
+ const entries = await readdir(join(root, directory), { withFileTypes: true });
42
+ const results = [];
43
+ for (const entry of entries) {
44
+ const path = join(directory, entry.name);
45
+ if (entry.isDirectory()) results.push(...(await listFiles(root, path)));
46
+ else results.push(path.split(sep).join("/"));
47
+ }
48
+ return results.sort();
49
+ }
50
+
51
+ async function existingOutput(output, locale) {
52
+ const info = await lstat(output).catch((error) => {
53
+ if (error.code !== "ENOENT") throw error;
54
+ return undefined;
55
+ });
56
+ if (!info) return false;
57
+ const files = info.isDirectory() ? await listFiles(output) : ["unknown"];
58
+ if (!files.length) return true;
59
+ const previous = await readFile(join(output, marker), "utf8")
60
+ .then(JSON.parse, () => undefined)
61
+ .catch(() => undefined);
62
+ if (
63
+ Array.isArray(previous) &&
64
+ files
65
+ .filter((name) => name !== marker)
66
+ .every((file) => previous.includes(file))
67
+ )
68
+ return true;
69
+ throw new Error(
70
+ locale === "ja"
71
+ ? `${output} には既存のファイルがあります。--out-dir で空の出力先を指定してください。`
72
+ : `${output} contains existing files. Use --out-dir to select an empty directory.`
73
+ );
74
+ }
75
+
76
+ function serializedLibrary(library) {
77
+ return new Map([
78
+ ["library.json", json(library.manifest)],
79
+ ...library.books.map((book) => [`books/${book.id}.json`, json(book)]),
80
+ ]);
81
+ }
82
+
83
+ async function writeStaticSite(cwd, outDir, library) {
84
+ const output = resolve(cwd, outDir);
85
+ const { locale } = library.manifest;
86
+ const exists = await existingOutput(output, locale);
87
+ const parent = dirname(output);
88
+ await mkdir(parent, { recursive: true });
89
+ const temporary = await mkdtemp(join(parent, ".grimoire3d-"));
90
+ const staging = join(temporary, "site");
91
+ const backup = join(temporary, "previous");
92
+ let preserveBackup = false;
93
+ try {
94
+ await cp(template, staging, { recursive: true });
95
+ for (const [name, content] of serializedLibrary(library)) {
96
+ const path = join(staging, name);
97
+ await mkdir(dirname(path), { recursive: true });
98
+ await writeFile(path, content);
99
+ }
100
+ for (const [name, source] of library.assets) {
101
+ const path = join(staging, "content", name);
102
+ await mkdir(dirname(path), { recursive: true });
103
+ await copyFile(source, path);
104
+ }
105
+ await writeStaticPages(template, staging, library);
106
+ await writeFile(join(staging, marker), json(await listFiles(staging)));
107
+ if (exists) await rename(output, backup);
108
+ try {
109
+ await rename(staging, output);
110
+ } catch (error) {
111
+ if (exists) {
112
+ preserveBackup = true;
113
+ await rename(backup, output);
114
+ preserveBackup = false;
115
+ }
116
+ throw error;
117
+ }
118
+ } finally {
119
+ if (!preserveBackup) await rm(temporary, { recursive: true, force: true });
120
+ }
121
+ return output;
122
+ }
123
+
124
+ function showIssues(library) {
125
+ if (!library.issues.length) return;
126
+ const label =
127
+ library.manifest.locale === "ja"
128
+ ? "参照先が見つかりません"
129
+ : "Unresolved reference";
130
+ for (const issue of library.issues) console.error(`${label}: ${issue}`);
131
+ }
132
+
133
+ function snapshot(library) {
134
+ return {
135
+ files: serializedLibrary(library),
136
+ manifest: library.manifest,
137
+ assets: library.assets,
138
+ error: null,
139
+ };
140
+ }
141
+
142
+ function serve(cwd, port, initial) {
143
+ let current = snapshot(initial);
144
+ let timer;
145
+ let changes = 0;
146
+ const clients = new Set();
147
+ const notify = () => {
148
+ for (const client of clients) client.write("event: update\ndata: {}\n\n");
149
+ };
150
+ async function refresh() {
151
+ const revision = ++changes;
152
+ try {
153
+ const library = await readLibrary(cwd, await readSettings(cwd));
154
+ if (revision !== changes) return;
155
+ current = snapshot(library);
156
+ showIssues(library);
157
+ } catch (error) {
158
+ if (revision !== changes) return;
159
+ current = { ...current, error: error.message };
160
+ console.error(error.message);
161
+ }
162
+ notify();
163
+ }
164
+ function schedule() {
165
+ clearTimeout(timer);
166
+ timer = setTimeout(() => void refresh(), 140);
167
+ }
168
+ const watchers = [
169
+ watch(join(cwd, "docs"), { recursive: true }, schedule),
170
+ watch(cwd, (_event, name) => {
171
+ if (name === "grimoire.yml") schedule();
172
+ }),
173
+ ];
174
+
175
+ const server = createServer(async (request, response) => {
176
+ try {
177
+ const url = new URL(request.url, "http://localhost");
178
+ const name = decodeURIComponent(url.pathname.slice(1)) || "index.html";
179
+ if (name === "__grimoire_events") {
180
+ response.writeHead(200, {
181
+ "Content-Type": "text/event-stream",
182
+ "Cache-Control": "no-cache",
183
+ });
184
+ response.write(": connected\n\n");
185
+ clients.add(response);
186
+ response.on("close", () => clients.delete(response));
187
+ return;
188
+ }
189
+ if (current.error && name === "library.json") {
190
+ response
191
+ .writeHead(422, { "Content-Type": "application/json" })
192
+ .end(json({ error: current.error }));
193
+ return;
194
+ }
195
+ const content = current.files.get(name);
196
+ if (content !== undefined) {
197
+ response
198
+ .writeHead(200, {
199
+ "Content-Type": "application/json",
200
+ "Cache-Control": "no-store",
201
+ })
202
+ .end(content);
203
+ return;
204
+ }
205
+ const requested = resolve(template, name);
206
+ if (
207
+ name.startsWith("content/") &&
208
+ !current.assets.has(name.slice("content/".length))
209
+ ) {
210
+ response.writeHead(404).end();
211
+ return;
212
+ }
213
+ const asset = current.assets.get(name.slice("content/".length));
214
+ const diff = relative(template, requested);
215
+ if (diff === ".." || diff.startsWith(`..${sep}`) || isAbsolute(diff)) {
216
+ response.writeHead(404).end();
217
+ return;
218
+ }
219
+ const path = name.startsWith("content/") ? asset : requested;
220
+ const file = await stat(path);
221
+ if (!file.isFile()) {
222
+ response.writeHead(404).end();
223
+ return;
224
+ }
225
+ const mediaType = contentType(lookup(path) || "application/octet-stream");
226
+ if (name === "index.html") {
227
+ const html = await readFile(path, "utf8");
228
+ response.writeHead(200, {
229
+ "Content-Type": mediaType,
230
+ "Cache-Control": "no-store",
231
+ });
232
+ response.end(
233
+ html
234
+ .replace(
235
+ '<html lang="en">',
236
+ `<html lang="${current.manifest.locale}">`
237
+ )
238
+ .replace("</head>", () => `${previewHead(current.manifest)}</head>`)
239
+ );
240
+ return;
241
+ }
242
+ const headers = {
243
+ "Content-Type": mediaType,
244
+ "Cache-Control": "no-cache",
245
+ "Content-Length": file.size,
246
+ };
247
+ let status = 200;
248
+ let slice;
249
+ if (typeof mediaType === "string" && mediaType.startsWith("video/")) {
250
+ headers["Accept-Ranges"] = "bytes";
251
+ const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
252
+ if (range) {
253
+ const [, from, to] = range;
254
+ const start = from
255
+ ? Number(from)
256
+ : Math.max(0, file.size - Number(to));
257
+ const end =
258
+ from && to ? Math.min(Number(to), file.size - 1) : file.size - 1;
259
+ if (!Number.isSafeInteger(start) || start > end) {
260
+ response
261
+ .writeHead(416, {
262
+ "Accept-Ranges": "bytes",
263
+ "Content-Range": `bytes */${file.size}`,
264
+ })
265
+ .end();
266
+ return;
267
+ }
268
+ status = 206;
269
+ slice = { start, end };
270
+ headers["Content-Length"] = end - start + 1;
271
+ headers["Content-Range"] = `bytes ${start}-${end}/${file.size}`;
272
+ }
273
+ }
274
+ response.writeHead(status, headers);
275
+ if (request.method === "HEAD") response.end();
276
+ else
277
+ createReadStream(path, slice)
278
+ .on("error", () => response.destroy())
279
+ .pipe(response);
280
+ } catch (error) {
281
+ if (response.headersSent) response.destroy();
282
+ else response.writeHead(error.code === "ENOENT" ? 404 : 400).end();
283
+ }
284
+ });
285
+ const stopWatchers = () => {
286
+ clearTimeout(timer);
287
+ for (const watcher of watchers) watcher.close();
288
+ };
289
+ server.on("error", (error) => {
290
+ stopWatchers();
291
+ console.error(error.message);
292
+ process.exitCode = 1;
293
+ });
294
+ server.listen(port, "127.0.0.1", () => {
295
+ const label = initial.manifest.locale === "ja" ? "プレビュー" : "Preview";
296
+ console.log(`${label}: http://127.0.0.1:${server.address().port}/`);
297
+ });
298
+ }
299
+
300
+ async function main() {
301
+ const {
302
+ positionals: [command],
303
+ values,
304
+ } = parseArgs({
305
+ allowPositionals: true,
306
+ options: {
307
+ help: { type: "boolean", short: "h" },
308
+ port: { type: "string" },
309
+ "out-dir": { type: "string" },
310
+ },
311
+ });
312
+ if (!command || values.help) {
313
+ console.log(
314
+ "grimoire3d serve [--port 3000]\ngrimoire3d build [--out-dir dist]"
315
+ );
316
+ return;
317
+ }
318
+ if (!["serve", "build"].includes(command))
319
+ throw new Error(`Unknown command: ${command}. See --help.`);
320
+ const cwd = process.cwd();
321
+ const settings = await readSettings(cwd);
322
+ const library = await readLibrary(cwd, settings);
323
+ showIssues(library);
324
+ if (command === "build") {
325
+ const output = await writeStaticSite(
326
+ cwd,
327
+ values["out-dir"] ?? settings.outDir ?? "dist",
328
+ library
329
+ );
330
+ const label = settings.locale === "ja" ? "書き出し先" : "Built to";
331
+ console.log(`${label}: ${basename(output)}/ (${output})`);
332
+ return;
333
+ }
334
+ const port = Number(values.port ?? 3000);
335
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
336
+ throw new Error(
337
+ settings.locale === "ja"
338
+ ? "--port は 0 から 65535 の整数にしてください。"
339
+ : "--port must be an integer from 0 to 65535."
340
+ );
341
+ }
342
+ serve(cwd, port, library);
343
+ }
344
+
345
+ main().catch((error) => {
346
+ console.error(error.message);
347
+ process.exitCode = 1;
348
+ });