@matra/site-generation 0.3.0 → 0.4.1-preview.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/README.ja.md CHANGED
@@ -87,8 +87,9 @@ console.log(`Generated ${outputs.length} files`)
87
87
 
88
88
  両APIはlayout、asset、base path、再利用可能なMatra部品に対応します。
89
89
  Matra部品は`fn Name(props, children) { ... }`で定義し、単一の文書nodeを返します。
90
- 子要素なしの呼び出しは`Name(props, [])`と書きます。第2引数の省略には、公開済みの
91
- Core `0.3.1`より新しいruntimeが必要です。
90
+ 子要素なしの呼び出しは`Name(props)`または`Name(props, [])`と書きます。
91
+ markup属性では`<meta name="description" content=page.data.description />`のように
92
+ ページdataのmemberを直接参照できます。
92
93
  設定schema、入力規則、部品の動作、出力保証の詳細は
93
94
  [サイト生成の契約](../../spec/site-generation.ja.md)を参照してください。
94
95
 
@@ -98,7 +99,7 @@ HTML出力では子要素の配列を再帰的に平坦化するため、条件
98
99
 
99
100
  ## Markdownとブログの出力
100
101
 
101
- 既定のMarkdown変換はそのままです。site-generation `0.3.x`で、サイトに`npm install @matra/markdown-unified@^0.1.2`し、
102
+ 既定のMarkdown変換はそのままです。site-generation `0.4.x`で、サイトに`npm install @matra/markdown-unified@^0.1.3`し、
102
103
  `markdown: "unified"`(ファイル設定では`site.markdown`)を指定すると、
103
104
  YAML frontmatter・GFM・数式(MathML)・見出しID・目次・抜粋を利用できます。
104
105
  目次は`page.data.toc`、抜粋は`page.data.excerpt`から参照できます。
package/README.md CHANGED
@@ -90,8 +90,7 @@ link validation, page data and content, routes, and output management are unaffe
90
90
 
91
91
  Both APIs support layouts, assets, a base path, and reusable Matra components.
92
92
  Matra components are defined as `fn Name(props, children) { ... }` and return
93
- one document node. Use `Name(props, [])` when there are no children; omitting the
94
- second argument requires a newer Core runtime than the published `0.3.1`. See the
93
+ one document node. Use `Name(props)` or `Name(props, [])` when there are no children. See the
95
94
  [site-generation contract](../../spec/site-generation.md)
96
95
  for the complete configuration schema, input rules, component behavior, and
97
96
  output guarantees.
@@ -103,7 +102,7 @@ The document value retains its array structure, but child arrays previously rend
103
102
  ## Markdown and blog outputs
104
103
 
105
104
  The default Markdown behavior is unchanged. For frontmatter, GFM, math, heading IDs, TOC and
106
- excerpts, use site-generation `0.3.x` and install the [optional unified preset](../markdown-unified/README.md) (`@matra/markdown-unified@^0.1.2`) in the site
105
+ excerpts, use site-generation `0.4.x` and install the [optional unified preset](../markdown-unified/README.md) (`@matra/markdown-unified@^0.1.3`) in the site
107
106
  and set `markdown: "unified"` (under `site` in file configuration).
108
107
  `generateSite({ markdown: async ({ body, document, metadata }) => ..., ... })` also accepts a
109
108
  custom hook returning a node sequence or `{ content: nodes, data: derivedFields }`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matra/site-generation",
3
- "version": "0.3.0",
3
+ "version": "0.4.1-preview.0",
4
4
  "description": "Declarative static site generation for Matra",
5
5
  "type": "module",
6
6
  "exports": {
@@ -10,8 +10,8 @@
10
10
  "src"
11
11
  ],
12
12
  "dependencies": {
13
- "@matra/core": "^0.3.1",
14
- "@matra/html": "^0.4.0",
13
+ "@matra/core": "^0.4.1",
14
+ "@matra/html": "^0.4.1",
15
15
  "js-yaml": "^5.2.2",
16
16
  "markdown-it": "^14.3.0"
17
17
  },
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "license": "MIT",
28
28
  "scripts": {
29
- "build": "node --check src/index.mjs && node --check src/site.mjs && node --check src/markdown.mjs",
29
+ "build": "node --check src/index.mjs && node --check src/site.mjs && node --check src/site-worker.mjs && node --check src/markdown.mjs",
30
30
  "check": "pnpm run build",
31
31
  "test": "pnpm run build && node --test"
32
32
  }
@@ -0,0 +1,24 @@
1
+ import { parentPort, workerData } from "node:worker_threads"
2
+ import { buildSiteInProcess } from "./site.mjs"
3
+
4
+ try {
5
+ const result = await buildSiteInProcess(
6
+ workerData.root,
7
+ workerData.observe
8
+ ? (path, directory) => {
9
+ const status = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT))
10
+ parentPort.postMessage({ type: "input", path, directory, status: status.buffer })
11
+ Atomics.wait(status, 0, 0)
12
+ if (Atomics.load(status, 0) !== 1) throw new Error("Site input monitoring failed")
13
+ }
14
+ : undefined,
15
+ )
16
+ parentPort.postMessage({ type: "result", result })
17
+ } catch (error) {
18
+ parentPort.postMessage({
19
+ type: "error",
20
+ message: error?.message ?? String(error),
21
+ code: error?.code,
22
+ document: error?.document,
23
+ })
24
+ }
package/src/site.mjs CHANGED
@@ -15,6 +15,7 @@ import { createRequire } from "node:module"
15
15
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"
16
16
  import { pathToFileURL } from "node:url"
17
17
  import { types } from "node:util"
18
+ import { Worker } from "node:worker_threads"
18
19
  import { evaluateStatic, isMatraAST, parse, staticValueToAST } from "@matra/core"
19
20
  import {
20
21
  buildLiterate,
@@ -48,8 +49,18 @@ export async function buildSite(directory) {
48
49
  }
49
50
 
50
51
  export async function buildSitePreview(directory, onInputs) {
51
- const site = await loadSite(resolve(directory), onInputs)
52
- const { root, settings } = site
52
+ const root = resolve(directory)
53
+ for (const name of CONFIG_NAMES) onInputs?.(join(root, name))
54
+ const config = await readConfig(root)
55
+ const settings = normalizeSettings(config, root)
56
+ if (settings.hooks) return buildSiteInWorker(root, onInputs)
57
+ return buildSiteInProcess(root, onInputs, config, settings)
58
+ }
59
+
60
+ export async function buildSiteInProcess(root, onInputs, config, settings) {
61
+ config ??= await readConfig(root)
62
+ settings ??= normalizeSettings(config, root)
63
+ const site = await loadSite(root, onInputs, config, settings)
53
64
  const components = []
54
65
  if (settings.componentsDirectory) {
55
66
  for (const path of await walkFiles(settings.componentsDirectory, settings.observeDirectory)) {
@@ -60,7 +71,70 @@ export async function buildSitePreview(directory, onInputs) {
60
71
  })
61
72
  }
62
73
  }
63
- const result = await generateLoadedSite({ ...site, components })
74
+ let templates = new Map()
75
+ if (settings.hooks) {
76
+ const hooks = await loadHooks(root, settings, onInputs)
77
+ if (hooks.markdown) {
78
+ if (settings.markdown) {
79
+ throw new Error("site.markdown cannot be combined with the markdown hook")
80
+ }
81
+ settings.markdown = hooks.markdown
82
+ settings.markdownLabel = `markdown hook (${settings.hooks.module})`
83
+ }
84
+ if (hooks.pages) {
85
+ let registrations
86
+ try {
87
+ registrations = await hooks.pages({ root })
88
+ } catch (error) {
89
+ throw new Error(
90
+ `pages hook (${settings.hooks.module}): ${error?.message ?? String(error)}`,
91
+ {
92
+ cause: error,
93
+ },
94
+ )
95
+ }
96
+ let direct
97
+ try {
98
+ assertPlainData(registrations, "pages hook result")
99
+ const returned = Array.isArray(registrations) ? { pages: registrations } : registrations
100
+ if (!isRecord(returned)) throw new TypeError("pages hook must return an array or object")
101
+ rejectUnknownKeys(returned, new Set(["pages", "templates"]), "pages hook result")
102
+ direct = normalizeDirectSite(
103
+ {
104
+ root,
105
+ output: relative(root, settings.outputDirectory),
106
+ format: settings.format,
107
+ defaultLayout: settings.defaultLayout,
108
+ pages: returned.pages,
109
+ ...(returned.templates === undefined ? {} : { templates: returned.templates }),
110
+ },
111
+ site.layouts,
112
+ )
113
+ sortAndValidateRoutes([...site.pages, ...direct.pages])
114
+ const existing = [...site.documents, ...site.pages, ...site.layouts.values(), ...components]
115
+ const existingPaths = new Set(
116
+ existing.map(source => (source.path ?? resolve(root, source.document)).toLowerCase()),
117
+ )
118
+ for (const template of direct.templates.values()) {
119
+ if (existingPaths.has(template.path.toLowerCase())) {
120
+ throw new Error(`Template conflicts with a site input: ${template.document}`)
121
+ }
122
+ }
123
+ await addDirectDocuments(direct.pages, site.documents, settings, [
124
+ ...site.pages,
125
+ ...site.layouts.values(),
126
+ ...components,
127
+ ...direct.templates.values(),
128
+ ])
129
+ } catch (error) {
130
+ throw new Error(`pages hook (${settings.hooks.module}): ${error.message}`, { cause: error })
131
+ }
132
+ site.pages.push(...direct.pages)
133
+ sortAndValidateRoutes(site.pages)
134
+ templates = direct.templates
135
+ }
136
+ }
137
+ const result = await generateLoadedSite({ ...site, components, templates })
64
138
  return {
65
139
  ...result,
66
140
  outputDirectory: settings.outputDirectory,
@@ -69,6 +143,85 @@ export async function buildSitePreview(directory, onInputs) {
69
143
  }
70
144
  }
71
145
 
146
+ function buildSiteInWorker(root, onInputs) {
147
+ return new Promise((resolveBuild, rejectBuild) => {
148
+ const worker = new Worker(new URL("./site-worker.mjs", import.meta.url), {
149
+ workerData: { root, observe: Boolean(onInputs) },
150
+ })
151
+ let settled = false
152
+ worker.on("message", message => {
153
+ if (message.type === "input") {
154
+ const status = new Int32Array(message.status)
155
+ try {
156
+ onInputs?.(message.path, message.directory)
157
+ Atomics.store(status, 0, 1)
158
+ } catch (error) {
159
+ Atomics.store(status, 0, 2)
160
+ settled = true
161
+ void worker.terminate()
162
+ rejectBuild(error)
163
+ } finally {
164
+ Atomics.notify(status, 0)
165
+ }
166
+ } else if (message.type === "result") {
167
+ settled = true
168
+ worker.terminate().then(() => resolveBuild(message.result), rejectBuild)
169
+ } else if (message.type === "error") {
170
+ settled = true
171
+ const error = new Error(message.message)
172
+ if (message.code) error.code = message.code
173
+ if (message.document) error.document = message.document
174
+ worker.terminate().then(() => rejectBuild(error), rejectBuild)
175
+ }
176
+ })
177
+ worker.on("error", error => {
178
+ settled = true
179
+ rejectBuild(error)
180
+ })
181
+ worker.on("exit", code => {
182
+ if (!settled) rejectBuild(new Error(`Site build worker exited unexpectedly (code ${code})`))
183
+ })
184
+ })
185
+ }
186
+
187
+ async function loadHooks(root, settings, onInputs) {
188
+ const { module, watch } = settings.hooks
189
+ for (const path of [module, ...watch]) {
190
+ const absolute = resolve(root, path)
191
+ onInputs?.(absolute)
192
+ assertInputOutputSeparation(absolute, settings.outputDirectory)
193
+ await assertSafeHookPath(root, absolute)
194
+ const info = await lstat(absolute)
195
+ if (info.isDirectory()) {
196
+ if (path === module) throw new Error(`Hook module must be a regular file: ${path}`)
197
+ await walkFiles(absolute, settings.observeDirectory)
198
+ } else if (!info.isFile()) {
199
+ throw new Error(`Hook input must be a regular file or directory: ${path}`)
200
+ }
201
+ }
202
+ let hooks
203
+ try {
204
+ hooks = await import(pathToFileURL(resolve(root, module)).href)
205
+ } catch (error) {
206
+ throw new Error(`hook module ${module}: ${error?.message ?? String(error)}`, { cause: error })
207
+ }
208
+ for (const name of ["pages", "markdown"]) {
209
+ if (hooks[name] !== undefined && typeof hooks[name] !== "function") {
210
+ throw new TypeError(`hook module ${module}: ${name} must be a function`)
211
+ }
212
+ }
213
+ return hooks
214
+ }
215
+
216
+ async function assertSafeHookPath(root, path) {
217
+ let current = root
218
+ for (const part of relative(root, path).split(sep).filter(Boolean)) {
219
+ current = join(current, part)
220
+ const info = await lstat(current)
221
+ if (info.isSymbolicLink()) throw new Error(`Hook input must not contain a symlink: ${current}`)
222
+ }
223
+ }
224
+
72
225
  async function generateLoadedSite({
73
226
  root,
74
227
  settings,
@@ -224,7 +377,8 @@ async function loadUnifiedPreset(root) {
224
377
  async function convertMarkdown(document, page, settings, transform, metadata) {
225
378
  const path = relative(settings.root, document.path).split(sep).join("/")
226
379
  const firstLine = document.bodyLine
227
- const location = line => `${path}:${firstLine + line - 1}${page ? ` (route ${page.route})` : ""}`
380
+ const location = line =>
381
+ `${path}:${firstLine + line - 1}${page ? ` (route ${page.route})` : ""}${settings.markdownLabel ? `: ${settings.markdownLabel}` : ""}`
228
382
  let result
229
383
  if (transform) {
230
384
  try {
@@ -292,19 +446,45 @@ export async function generateSite(options) {
292
446
  await assertDirectory(root, directory)
293
447
  }
294
448
  const documents = await collectDocuments(root, settings)
295
- const logicalPaths = new Set([
296
- ...site.pages.map(page => page.path.toLowerCase()),
297
- ...[...site.layouts.values()].map(layout => layout.path.toLowerCase()),
298
- ...[...site.templates.values()].map(template => template.path.toLowerCase()),
299
- ...site.components.map(component => component.path.toLowerCase()),
300
- ])
449
+ await addDirectDocuments(
450
+ site.pages,
451
+ documents,
452
+ settings,
453
+ [...site.layouts.values(), ...site.templates.values(), ...site.components],
454
+ true,
455
+ )
456
+ return (await generateLoadedSite({ ...site, documents })).files
457
+ }
458
+
459
+ async function addDirectDocuments(
460
+ pages,
461
+ documents,
462
+ settings,
463
+ existingSources,
464
+ checkAllSources = false,
465
+ ) {
466
+ const existingPaths = new Set(
467
+ [...documents, ...existingSources]
468
+ .filter(source => source.path || source.document)
469
+ .map(source => (source.path ?? resolve(settings.root, source.document)).toLowerCase()),
470
+ )
471
+ for (const page of pages) {
472
+ if (existingPaths.has(page.path.toLowerCase())) {
473
+ throw new Error(`Collected document conflicts with a logical document: ${page.document}`)
474
+ }
475
+ }
476
+ const logicalPaths = new Set(
477
+ [...pages, ...(checkAllSources ? existingSources : [])].map(source =>
478
+ source.path.toLowerCase(),
479
+ ),
480
+ )
301
481
  for (const document of documents) {
302
482
  if (logicalPaths.has(document.path.toLowerCase())) {
303
483
  throw new Error(`Collected document conflicts with a logical document: ${document.path}`)
304
484
  }
305
485
  }
306
486
  const ids = new Set(documents.map(document => document.id.toLowerCase()))
307
- for (const page of site.pages.filter(page => page.kind === "markdown")) {
487
+ for (const page of pages.filter(page => page.kind === "markdown")) {
308
488
  const id = page.document
309
489
  if (ids.has(id.toLowerCase())) throw new Error(`Duplicate document ID ignoring case: ${id}`)
310
490
  ids.add(id.toLowerCase())
@@ -322,10 +502,9 @@ export async function generateSite(options) {
322
502
  })
323
503
  }
324
504
  documents.sort((left, right) => left.id.localeCompare(right.id, "en"))
325
- return (await generateLoadedSite({ ...site, documents })).files
326
505
  }
327
506
 
328
- function normalizeDirectSite(input) {
507
+ function normalizeDirectSite(input, inheritedLayouts) {
329
508
  if (types.isProxy(input) || !isRecord(input))
330
509
  throw new TypeError("generateSite options must be an object")
331
510
  const descriptors = Object.getOwnPropertyDescriptors(input)
@@ -433,7 +612,7 @@ function normalizeDirectSite(input) {
433
612
  }),
434
613
  )
435
614
  }
436
- const layouts = namedSources(options.layouts, "layouts")
615
+ const layouts = inheritedLayouts ?? namedSources(options.layouts, "layouts")
437
616
  const templates = namedSources(options.templates, "templates")
438
617
  selectedLayout(undefined, settings.defaultLayout, layouts, "defaultLayout")
439
618
  const components = [...namedSources(options.components, "components").values()]
@@ -505,10 +684,10 @@ export async function getSiteProgramDocuments(directory) {
505
684
  ].sort((left, right) => left.localeCompare(right, "en"))
506
685
  }
507
686
 
508
- async function loadSite(root, onInputs) {
687
+ async function loadSite(root, onInputs, config, normalizedSettings) {
509
688
  for (const name of CONFIG_NAMES) onInputs?.(join(root, name))
510
- const config = await readConfig(root)
511
- const settings = normalizeSettings(config, root)
689
+ config ??= await readConfig(root)
690
+ const settings = normalizedSettings ?? normalizeSettings(config, root)
512
691
  const inputs = [
513
692
  settings.pagesDirectory,
514
693
  ...settings.documentDirectories,
@@ -522,8 +701,15 @@ async function loadSite(root, onInputs) {
522
701
  onInputs?.(input)
523
702
  }
524
703
  if (onInputs) settings.observeDirectory = path => onInputs(path, true)
704
+ const pagesExist = await assertDirectory(root, settings.pagesDirectory, {
705
+ optional: Boolean(settings.hooks),
706
+ })
707
+ if (!pagesExist) {
708
+ settings.documentDirectories = settings.documentDirectories.filter(
709
+ path => path !== settings.pagesDirectory,
710
+ )
711
+ }
525
712
  await Promise.all([
526
- assertDirectory(root, settings.pagesDirectory),
527
713
  ...settings.documentDirectories.map(path => assertDirectory(root, path)),
528
714
  assertDirectory(root, settings.layoutsDirectory, { optional: true }),
529
715
  ...(settings.componentsDirectory ? [assertDirectory(root, settings.componentsDirectory)] : []),
@@ -532,7 +718,7 @@ async function loadSite(root, onInputs) {
532
718
  ])
533
719
  const documents = await collectDocuments(root, settings)
534
720
  const layouts = await collectLayouts(root, settings)
535
- const pages = await collectPages(root, settings, documents, layouts)
721
+ const pages = pagesExist ? await collectPages(root, settings, documents, layouts) : []
536
722
  return { root, settings, documents, layouts, pages }
537
723
  }
538
724
 
@@ -589,6 +775,8 @@ function normalizeSettings(config, root) {
589
775
  "markdown",
590
776
  "basePath",
591
777
  "data",
778
+ "hooks",
779
+ "includeDocumentsInTemplates",
592
780
  ]),
593
781
  "site",
594
782
  )
@@ -622,6 +810,19 @@ function normalizeSettings(config, root) {
622
810
  ? undefined
623
811
  : resolveDirectory(site.components, "components", site.components)
624
812
  const outputDirectory = resolveDirectory(site.output, "output", "dist")
813
+ let hooks
814
+ if (site.hooks !== undefined) {
815
+ if (!isRecord(site.hooks)) throw new TypeError("site.hooks must be an object")
816
+ rejectUnknownKeys(site.hooks, new Set(["module", "watch"]), "site.hooks")
817
+ if (typeof site.hooks.module !== "string" || !site.hooks.module.endsWith(".mjs")) {
818
+ throw new TypeError("site.hooks.module must be a project-relative .mjs path")
819
+ }
820
+ resolveDirectory(site.hooks.module, "hooks.module")
821
+ const watch = site.hooks.watch ?? []
822
+ if (!Array.isArray(watch)) throw new TypeError("site.hooks.watch must be an array of paths")
823
+ for (const path of watch) resolveDirectory(path, "hooks.watch")
824
+ hooks = { module: site.hooks.module, watch }
825
+ }
625
826
  const assetsDirectory =
626
827
  site.assets === undefined ? undefined : resolveDirectory(site.assets, "assets", site.assets)
627
828
  const publicDirectory =
@@ -652,6 +853,12 @@ function normalizeSettings(config, root) {
652
853
  if (site.data !== undefined && !isRecord(site.data)) {
653
854
  throw new TypeError("site.data must be an object")
654
855
  }
856
+ if (
857
+ site.includeDocumentsInTemplates !== undefined &&
858
+ typeof site.includeDocumentsInTemplates !== "boolean"
859
+ ) {
860
+ throw new TypeError("site.includeDocumentsInTemplates must be a boolean")
861
+ }
655
862
  if (
656
863
  site.defaultLayout !== undefined &&
657
864
  site.defaultLayout !== false &&
@@ -673,10 +880,12 @@ function normalizeSettings(config, root) {
673
880
  ? undefined
674
881
  : normalizeRoute(site.notFound, format, "site.notFound"),
675
882
  markdown: site.markdown,
883
+ hooks,
676
884
  defaultLayout: site.defaultLayout === undefined ? false : site.defaultLayout,
677
885
  format,
678
886
  basePath,
679
887
  data: site.data ?? {},
888
+ includeDocumentsInTemplates: site.includeDocumentsInTemplates ?? true,
680
889
  }
681
890
  }
682
891