grimoire3d 0.0.0-dev.754921a → 0.0.0-dev.8e373ff

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 (150) hide show
  1. package/README.md +28 -122
  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-GXuBR_bC.js +339 -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 +1 -0
  19. package/dist/grimoire3d.css +3 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.js +1 -0
  22. package/dist/main.d.ts +1 -0
  23. package/dist/site/assets/BookReader-D9DTDoVN.js +2 -0
  24. package/dist/site/assets/BookScene-CRRCRbS-.js +4294 -0
  25. package/dist/site/assets/MermaidDiagram-Bxdgtrdz.js +44 -0
  26. package/dist/site/assets/PageMarkdown-DivaoRyY.js +37 -0
  27. package/dist/site/assets/abnfDiagram-S7VZAUFO-3C_OdetW.js +1 -0
  28. package/dist/site/assets/alcove-cyX4Tv3E.avif +0 -0
  29. package/dist/site/assets/architecture-WOLXFQ4H-ClT8xcGX.js +1 -0
  30. package/dist/site/assets/architectureDiagram-YGSQEFNW-CK_KGYM7.js +36 -0
  31. package/dist/site/assets/blockDiagram-APKKGZFW-Dv8HHTZM.js +140 -0
  32. package/dist/site/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  33. package/dist/site/assets/c4Diagram-KJ2TOQU5-bUOK8koN.js +38 -0
  34. package/dist/site/assets/catalog-07-UR91A.avif +0 -0
  35. package/dist/site/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  36. package/dist/site/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  37. package/dist/site/assets/chunk-6MUBBAK2-Dhr6vz4d.js +2 -0
  38. package/dist/site/assets/chunk-AXFCVDMN-CJuQOkJp.js +62 -0
  39. package/dist/site/assets/chunk-BG4553SI-D_ouALrp.js +129 -0
  40. package/dist/site/assets/chunk-DQASFODM-CSXm1WR2.js +10 -0
  41. package/dist/site/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  42. package/dist/site/assets/chunk-HFQBQIA3-2tYBolF0.js +1 -0
  43. package/dist/site/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  44. package/dist/site/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  45. package/dist/site/assets/chunk-KQLB2F66-0rMPIpbk.js +2 -0
  46. package/dist/site/assets/chunk-KS47KZWR-sbTBdTDZ.js +1 -0
  47. package/dist/site/assets/chunk-LEVMRMFU-CrCXzzZ8.js +1 -0
  48. package/dist/site/assets/chunk-M57EVK23-BtiKZKSt.js +1 -0
  49. package/dist/site/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  50. package/dist/site/assets/chunk-OY52VR5R-DKbCtBD_.js +88 -0
  51. package/dist/site/assets/chunk-QB3YPZ4I-C32_U2xo.js +213 -0
  52. package/dist/site/assets/chunk-R3KSYZAL-C2G1pznM.js +1 -0
  53. package/dist/site/assets/chunk-STOXU5M4-BJio7l1X.js +72 -0
  54. package/dist/site/assets/chunk-TU62E6Q5-x1V58wrI.js +1 -0
  55. package/dist/site/assets/chunk-X4PVCEUW-BO2caIzH.js +1 -0
  56. package/dist/site/assets/chunk-XXDRQBXY-XZOBW_TA.js +1 -0
  57. package/dist/site/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  58. package/dist/site/assets/classDiagram-v2-L25IHNXF-CDRx2JxZ.js +217 -0
  59. package/dist/site/assets/cose-bilkent-JH36ORCC-Xb6l_5xI.js +1 -0
  60. package/dist/site/assets/cover-blue-Bh8Xp4T5.avif +0 -0
  61. package/dist/site/assets/cover-blue-mobile-YcuYIg0I.avif +0 -0
  62. package/dist/site/assets/cover-green-By13JjUx.avif +0 -0
  63. package/dist/site/assets/cover-green-mobile-BNTgNt7v.avif +0 -0
  64. package/dist/site/assets/cover-red-mobile-DHOCz3wI.avif +0 -0
  65. package/dist/site/assets/cover-red-qvZEk3PI.avif +0 -0
  66. package/dist/site/assets/cynefin-EF2NZ3EQ-SKDisiP3.js +1 -0
  67. package/dist/site/assets/cynefinDiagram-L36ESFBY-pVbgTfJD.js +62 -0
  68. package/dist/site/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  69. package/dist/site/assets/d3-scale-CElPUUud.js +1 -0
  70. package/dist/site/assets/d3-selection-kHFbchcH.js +1 -0
  71. package/dist/site/assets/dagre-SPEB5RXH-BGUZz8BM.js +4 -0
  72. package/dist/site/assets/diagram-3B7GL73J-T_tHWTmo.js +200 -0
  73. package/dist/site/assets/diagram-DNEMPZML-CtVDDp-U.js +24 -0
  74. package/dist/site/assets/diagram-L3MUGCDN-ATfcFnxu.js +41 -0
  75. package/dist/site/assets/diagram-LA4NIPWU-DuKn6GVN.js +24 -0
  76. package/dist/site/assets/diagram-MHCOC4E2-CoYXddFV.js +3 -0
  77. package/dist/site/assets/diagram-XPFHEONP-PWcONvv5.js +30 -0
  78. package/dist/site/assets/dist-Df-HpYgo.js +1 -0
  79. package/dist/site/assets/ebnfDiagram-UZSYDL2S-QwcSWQtq.js +1 -0
  80. package/dist/site/assets/elk-XV6XMXQE-gGhuAlgw.js +27 -0
  81. package/dist/site/assets/erDiagram-EYBAPDEH-BcKIzgVW.js +99 -0
  82. package/dist/site/assets/es-YYQGP5MR.js +2 -0
  83. package/dist/site/assets/eventmodeling-K75KTNOO-BgXoz0Cb.js +1 -0
  84. package/dist/site/assets/favicon-C9YRygge.png +0 -0
  85. package/dist/site/assets/flowDiagram-MALGAFMO-DiXTmYsl.js +1 -0
  86. package/dist/site/assets/ganttDiagram-23REXITY-BsOpEgyJ.js +292 -0
  87. package/dist/site/assets/gitGraph-VSP46ZUC-BvZwuD9a.js +1 -0
  88. package/dist/site/assets/gitGraphDiagram-STJD7YCW-CgTfP6lP.js +106 -0
  89. package/dist/site/assets/graphlib-DS17s2tU.js +1 -0
  90. package/dist/site/assets/index-B0X5YS5c.js +2 -0
  91. package/dist/site/assets/index-aLXzUwjX.css +1 -0
  92. package/dist/site/assets/info-OHQRW6UA-Cbk2iY0G.js +1 -0
  93. package/dist/site/assets/infoDiagram-KBXO4MBG-CGpwGLzV.js +2 -0
  94. package/dist/site/assets/ishikawaDiagram-M35NCXHK-BrcKiitX.js +70 -0
  95. package/dist/site/assets/journeyDiagram-OPLOXDXO-RjmDNudH.js +139 -0
  96. package/dist/site/assets/jsxRuntime-WpZ1bTm4.js +1 -0
  97. package/dist/site/assets/kanban-definition-BZKZHSQY-Cqly2HjG.js +89 -0
  98. package/dist/site/assets/katex-MEuSR36T.js +257 -0
  99. package/dist/site/assets/mermaid-parser.core-RESTiE7S.js +7 -0
  100. package/dist/site/assets/mindmap-definition-I2QAS2VK-CR7dRk0O.js +98 -0
  101. package/dist/site/assets/mobile-cabinet-BUr9vtlo.avif +0 -0
  102. package/dist/site/assets/mobile-cabinet-sm-pauJUfRH.avif +0 -0
  103. package/dist/site/assets/mobile-paper-DF0CuLes.avif +0 -0
  104. package/dist/site/assets/mobile-paper-sm-77eJHX6h.avif +0 -0
  105. package/dist/site/assets/open-nWGD2hyb.glb +0 -0
  106. package/dist/site/assets/packet-JDAUHWVQ-sDl3Fvvj.js +1 -0
  107. package/dist/site/assets/pegDiagram-FD4XPPHP-_nOcBmES.js +1 -0
  108. package/dist/site/assets/pie-XZMESJXO-Dz-SNuSp.js +1 -0
  109. package/dist/site/assets/pieDiagram-J4AKIIQI-BWjfLhr7.js +39 -0
  110. package/dist/site/assets/quadrantDiagram-XTYBLID2-CDzlnVP8.js +7 -0
  111. package/dist/site/assets/radar-ABXABTNO-DZkkeg4H.js +1 -0
  112. package/dist/site/assets/railroad-I3PHUGI6-QVjACEaP.js +1 -0
  113. package/dist/site/assets/railroad-abnf-LNEFI6M7-CoHufu6k.js +1 -0
  114. package/dist/site/assets/railroad-ebnf-DWYD2UWJ-B0-_gPPJ.js +1 -0
  115. package/dist/site/assets/railroad-peg-JR7BVNR7-Bf3oGGtp.js +1 -0
  116. package/dist/site/assets/railroadDiagram-MRQ6NCDL-BwmYLRhX.js +1 -0
  117. package/dist/site/assets/requirementDiagram-Y7LWUY3S-D2k0b4h5.js +84 -0
  118. package/dist/site/assets/resting-amber-BSjsErIg.avif +0 -0
  119. package/dist/site/assets/resting-black-DDQ4XMJI.avif +0 -0
  120. package/dist/site/assets/resting-blue-DDOT8IQ8.avif +0 -0
  121. package/dist/site/assets/resting-green-DkRrV8eX.avif +0 -0
  122. package/dist/site/assets/resting-ivory-CEqoG5yI.avif +0 -0
  123. package/dist/site/assets/resting-plum-B-8tkSmP.avif +0 -0
  124. package/dist/site/assets/resting-red-D0hLpMpz.avif +0 -0
  125. package/dist/site/assets/resting-slate-CH8Z_Rky.avif +0 -0
  126. package/dist/site/assets/resting-teal-CGt6jFmT.avif +0 -0
  127. package/dist/site/assets/resting-walnut-t3WgHgUO.avif +0 -0
  128. package/dist/site/assets/rough.esm-Dy-Kn_BL.js +1 -0
  129. package/dist/site/assets/sankeyDiagram-WGJFYUXA-7erN02Ay.js +40 -0
  130. package/dist/site/assets/search-stage-B8cH1AE_.avif +0 -0
  131. package/dist/site/assets/search-stage-mobile-BZ58ew4F.avif +0 -0
  132. package/dist/site/assets/sequenceDiagram-5NDRBG5M-Ddn68zfA.js +169 -0
  133. package/dist/site/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  134. package/dist/site/assets/stateDiagram-v2-FJ4FJNEA-QN3M8fzm.js +291 -0
  135. package/dist/site/assets/swimlanes-UMQ2AFYF-Eiju8-d1.js +1 -0
  136. package/dist/site/assets/swimlanesDiagram-OMPLPG4O-CKlrgwLP.js +8 -0
  137. package/dist/site/assets/three-core-B1q6MRTI.js +5 -0
  138. package/dist/site/assets/timeline-definition-SEUHKTQE-ry_z_OQ9.js +120 -0
  139. package/dist/site/assets/treeView-D4JQ5SDB-BYWgIBIS.js +1 -0
  140. package/dist/site/assets/treemap-SAJKECNS-BAqqKL7u.js +1 -0
  141. package/dist/site/assets/usecaseDiagram-AFA6YXN4-B6f_iQYg.js +328 -0
  142. package/dist/site/assets/vennDiagram-NNMJR3RB-DkNaQfXm.js +34 -0
  143. package/dist/site/assets/wardley-7MLQ67FV-C8hbgiNF.js +1 -0
  144. package/dist/site/assets/wardleyDiagram-S7YFUSEH-ghtx6WE3.js +78 -0
  145. package/dist/site/assets/xychartDiagram-GGNKY7IX-LXCdkASt.js +7 -0
  146. package/dist/site/index.html +15 -0
  147. package/dist/types/index.d.ts +163 -0
  148. package/package.json +50 -28
  149. package/dist/grimoire3d.js +0 -504
  150. package/dist/grimoire3d.umd.cjs +0 -27
package/README.md CHANGED
@@ -1,149 +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
- [![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.
5
4
 
6
- 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)
7
6
 
8
- ## What is this?
7
+ [Read the documentation](https://kkm-horikawa.github.io/grimoire3d/)
9
8
 
10
- Grimoire3D transforms your Markdown documentation into an interactive 3D book. Perfect for:
9
+ ## Install
11
10
 
12
- - Project documentation
13
- - Design specifications
14
- - Technical notes
15
- - Portfolios
16
- - 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.
17
12
 
18
- ## Features
19
-
20
- - Realistic 3D page-flip animation
21
- - Markdown rendering
22
- - HTML support
23
- - Mermaid diagram support (planned)
24
- - Multiple themes
25
- - Static site generation
26
- - Zero-config setup
27
-
28
- ## Installation
29
-
30
- ```bash
31
- npm install grimoire3d
32
- # or
33
- pnpm add grimoire3d
34
- # or
35
- yarn add grimoire3d
13
+ ```sh
14
+ npm ci
15
+ npm run build
16
+ npm pack
36
17
  ```
37
18
 
38
- ## 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`.
39
20
 
40
- ### 1. Create your docs directory
41
-
42
- ```
43
- my-project/
44
- ├── grimoire.yml # Configuration (optional)
45
- └── docs/
46
- ├── index.md # Cover page
47
- ├── 01-overview.md
48
- ├── 02-features.md
49
- └── assets/
50
- └── diagram.png
21
+ ```sh
22
+ npm install -D /path/to/grimoire3d-0.0.0.tgz
51
23
  ```
52
24
 
53
- ### 2. Write your content
54
-
55
- ```markdown
56
- <!-- docs/index.md -->
57
- # My Project
25
+ ## Write and preview
58
26
 
59
- Welcome to the documentation.
27
+ Create `docs/field-notes/index.md`.
60
28
 
61
- ## Overview
29
+ ```markdown
30
+ # Field Notes
62
31
 
63
- This is an amazing project...
32
+ This is my first 3D book.
64
33
  ```
65
34
 
66
- ### 3. Start the dev server
35
+ Add Markdown files in the same folder for more chapters. Add folders directly under `docs/` for more books.
67
36
 
68
- ```bash
37
+ ```sh
69
38
  npx grimoire3d serve
70
39
  ```
71
40
 
72
- ### 4. Build for production
73
-
74
- ```bash
75
- npx grimoire3d build
76
- ```
41
+ Open the URL printed in the terminal. The preview updates when you save.
77
42
 
78
- ## Configuration
43
+ ![Workflow from Markdown files to a local bookshelf and a static site in dist](docs/book-experience/workflow.avif)
79
44
 
80
- Create a `grimoire.yml` file in your project root:
45
+ ## Build and publish
81
46
 
82
- ```yaml
83
- title: "My Project Documentation"
84
- theme: "vintage-red" # or "modern-dark", "paper-white"
85
- pages:
86
- - index.md
87
- - 01-overview.md
88
- - 02-features.md
89
- # Omit 'pages' to auto-detect all .md files
90
- ```
91
-
92
- ## Using as a React Component
93
-
94
- ```tsx
95
- import { BookViewer } from "grimoire3d/components";
96
-
97
- const pages = [
98
- {
99
- id: "cover",
100
- title: "Cover",
101
- front: <CoverPage />,
102
- back: <AboutPage />,
103
- tabColor: "#E57373",
104
- tabLabel: "Cover",
105
- },
106
- // ... more pages
107
- ];
108
-
109
- function App() {
110
- return <BookViewer pages={pages} />;
111
- }
47
+ ```sh
48
+ npx grimoire3d build
112
49
  ```
113
50
 
114
- ## Themes
115
-
116
- | Theme | Description |
117
- |-------|-------------|
118
- | `vintage-red` | Classic red leather book cover |
119
- | `modern-dark` | Sleek dark mode |
120
- | `paper-white` | Clean minimal design |
121
- | `forest-green` | Nature-inspired |
122
-
123
- ## Roadmap
124
-
125
- - [ ] v0.1.0 - MVP with basic page-flip and Markdown support
126
- - [ ] v0.2.0 - Mermaid diagrams and code highlighting
127
- - [ ] v0.3.0 - CLI for static site generation
128
- - [ ] v0.4.0 - Theme customization and plugins
129
-
130
- ## Documentation
131
-
132
- - [Architecture & Design Decisions](docs/ARCHITECTURE.md)
133
- - [Glossary of Terms](docs/GLOSSARY.md)
134
- - [Contributing Guide](CONTRIBUTING.md)
135
-
136
- ## Requirements
137
-
138
- - Node.js 22+
139
- - React 19+
140
-
141
- ## License
142
-
143
- 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.
144
52
 
145
- ## Inspiration
53
+ For chapter links, formatting, media, Mermaid, cover styles, locale, and SEO, see the [Grimoire3D documentation](https://kkm-horikawa.github.io/grimoire3d/).
146
54
 
147
- - Ancient grimoires and magical tomes
148
- - Vintage technical manuals
149
- - 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
+ });