@matra/site-generation 0.1.0-site.5 → 0.2.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 ADDED
@@ -0,0 +1,116 @@
1
+ # @matra/site-generation
2
+
3
+ `@matra/site-generation`はMarkdownコンテンツとMatraのページ・レイアウトから
4
+ 静的サイトを生成します。`matra.site.yaml`、`matra.site.json`、
5
+ `matra.site.matra`で設定するファイル方式のAPIと、JavaScriptからページを
6
+ 直接登録するAPIを提供します。
7
+
8
+ ## 要件
9
+
10
+ Node.js 22以降を推奨します。projectにinstallします。
11
+
12
+ ```sh
13
+ npm install @matra/site-generation
14
+ ```
15
+
16
+ ## ファイル方式での生成
17
+
18
+ project rootにsite設定を作成します。
19
+
20
+ ```yaml
21
+ version: 1
22
+ site:
23
+ pages: pages
24
+ layouts: layouts
25
+ defaultLayout: default
26
+ output: dist
27
+ ```
28
+
29
+ `pages/`以下にMarkdownページを配置します。通常の`.md`はcontentとして
30
+ 公開されます。実行するMatraページとlayoutは`.matra.md`を使い、
31
+ FrontMatterの`matra.entry`でentry pointを指定します。次のようにbuildします。
32
+
33
+ ```js
34
+ import { buildSite } from "@matra/site-generation"
35
+
36
+ const outputs = await buildSite(process.cwd())
37
+ console.log(`Generated ${outputs.length} files`)
38
+ ```
39
+
40
+ `buildSite()`はsite設定を読み込み、ページ・layout・文書を収集してサイトを
41
+ 生成し、生成fileのpathを返します。`matra.site.yaml`、`matra.site.json`、
42
+ `matra.site.matra`は同じversioned schemaを使用します。
43
+
44
+ `buildSitePreview(directory)`は同じビルドを実行し、ローカル配信用に`files`、
45
+ `outputDirectory`、`routes`(ルートから出力相対パスへのmap)、`basePath`、`notFound`を返します。
46
+
47
+ ## JavaScriptからの直接登録
48
+
49
+ ページdataがすでにJavaScriptにあり、中間fileを作らずMatraに直接渡す場合は
50
+ `generateSite()`を使います。
51
+
52
+ ```js
53
+ import { generateSite } from "@matra/site-generation"
54
+
55
+ const products = [
56
+ { slug: "first", title: "First product", description: "Product details" },
57
+ { slug: "second", title: "Second product", description: "More details" },
58
+ ]
59
+
60
+ const outputs = await generateSite({
61
+ root: process.cwd(),
62
+ defaultLayout: "default",
63
+ layouts: {
64
+ default: { source: "html { head {}; body { ...page.content } }" },
65
+ },
66
+ templates: { product: { source: "main { h1 { page.data.title }; p { page.data.description } }" } },
67
+ pages: products.map(product => ({
68
+ kind: "matra",
69
+ route: `/products/${product.slug}/`,
70
+ template: "product",
71
+ data: product,
72
+ })),
73
+ })
74
+ console.log(`Generated ${outputs.length} files`)
75
+ ```
76
+
77
+ 各ページは`kind`(`"matra"`または`"markdown"`)、`route`、`source`文字列を
78
+ 指定します。Matraページでは`source`の代わりに名前付き`template`を指定できます。
79
+ テンプレートは一度だけコンパイルし、その`document`と記事側の`document`・`route`を区別して診断します。
80
+ `data`、`layout`、`document`は任意で、ページdata、使用layout
81
+ (`layout: false`で無効化可能)、diagnosticと相対link解決に使う論理文書pathを
82
+ 指定します。`layouts`と`components`は名前から`{ source, document? }`へのmapです。
83
+
84
+ 両APIはlayout、asset、base path、再利用可能なMatra部品に対応します。
85
+ Matra部品は`fn Name(props, children) { ... }`で定義し、単一の文書nodeを返します。
86
+ 設定schema、入力規則、部品の動作、出力保証の詳細は
87
+ [サイト生成の契約](../../spec/site-generation.ja.md)を参照してください。
88
+
89
+ ## Markdownとブログの出力
90
+
91
+ 既定のMarkdown変換はそのままです。site-generation `0.2.x`で、サイトに`npm install @matra/markdown-unified@^0.1.0`し、
92
+ `markdown: "unified"`(ファイル設定では`site.markdown`)を指定すると、
93
+ YAML frontmatter・GFM・数式(MathML)・見出しID・目次・抜粋を利用できます。
94
+ 目次は`page.data.toc`、抜粋は`page.data.excerpt`から参照できます。
95
+ 独自構文が必要な場合だけ[公式プリセット](../markdown-unified/README.md)にプラグインを渡してください。
96
+
97
+ `generateSite()`の`markdown`には`async ({ body, document, metadata }) => ...`も指定できます。
98
+ 戻り値は文書ノード列、または`{ content: ノード列, data: 派生フィールド }`です。
99
+ リンク・画像に本文先頭を1とする`position.start.line`を付けると、Matraが変換後のURLを検証し、
100
+ frontmatterを含めた元記事の行番号を報告します。HTML文字列をそのまま挿入することはありません。
101
+
102
+ `publicDir: "public"`は、従来の`assets`とは別に`public/favicon.ico`を`/favicon.ico`のように
103
+ 元のパスで公開します。`notFound: "/404/"`は、指定ページの通常のルートを残しながら
104
+ 同じHTMLを`/404.html`にも出力します。どちらも既存の衝突・symlink検証、ステージング、
105
+ manifestによる不要ファイルの削除の対象です。
106
+
107
+ ## 出力の安全性
108
+
109
+ 入力を検証し、公開前にページを生成します。生成fileはstageを経てまとめて公開され、
110
+ 生成・検証に失敗した場合は既存出力を維持します。manifestで生成fileを追跡し、
111
+ 次回の成功buildで不要になった生成fileを削除しますが、追跡されていないfileは
112
+ 削除しません。入力symlinkとproject root外のpathは拒否されます。
113
+
114
+ ## ライセンス
115
+
116
+ MIT
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @matra/site-generation
2
+
3
+ `@matra/site-generation` generates static websites from Markdown content and
4
+ Matra pages and layouts. It provides a file-based API for projects configured
5
+ with `matra.site.yaml`, `matra.site.json`, or `matra.site.matra`, as well as a
6
+ JavaScript API for registering pages directly.
7
+
8
+ ## Requirements
9
+
10
+ Node.js 22 or later is recommended. Install the package in a project:
11
+
12
+ ```sh
13
+ npm install @matra/site-generation
14
+ ```
15
+
16
+ ## File-based generation
17
+
18
+ Create a site configuration in the project root:
19
+
20
+ ```yaml
21
+ version: 1
22
+ site:
23
+ pages: pages
24
+ layouts: layouts
25
+ defaultLayout: default
26
+ output: dist
27
+ ```
28
+
29
+ Add Markdown pages under `pages/`. Ordinary `.md` files are published as
30
+ content. Executable Matra pages and layouts use the `.matra.md` extension and
31
+ declare their entry point with `matra.entry` front matter. Then build the site:
32
+
33
+ ```js
34
+ import { buildSite } from "@matra/site-generation"
35
+
36
+ const outputs = await buildSite(process.cwd())
37
+ console.log(`Generated ${outputs.length} files`)
38
+ ```
39
+
40
+ `buildSite()` reads the site configuration, collects pages, layouts, and
41
+ documents, renders the site, and returns the generated file paths. The
42
+ `matra.site.yaml`, `matra.site.json`, and `matra.site.matra` formats use the
43
+ same versioned schema.
44
+
45
+ `buildSitePreview(directory)` performs the same build and additionally returns its `files`,
46
+ `outputDirectory`, `routes` (route to relative output path), `basePath`, and `notFound` for local serving.
47
+
48
+ ## Direct JavaScript API
49
+
50
+ Use `generateSite()` when page data is already available in JavaScript and
51
+ should be passed directly to Matra without writing intermediate files:
52
+
53
+ ```js
54
+ import { generateSite } from "@matra/site-generation"
55
+
56
+ const products = [
57
+ { slug: "first", title: "First product", description: "Product details" },
58
+ { slug: "second", title: "Second product", description: "More details" },
59
+ ]
60
+
61
+ const outputs = await generateSite({
62
+ root: process.cwd(),
63
+ defaultLayout: "default",
64
+ layouts: {
65
+ default: { source: "html { head {}; body { ...page.content } }" },
66
+ },
67
+ templates: { product: { source: "main { h1 { page.data.title }; p { page.data.description } }" } },
68
+ pages: products.map(product => ({
69
+ kind: "matra",
70
+ route: `/products/${product.slug}/`,
71
+ template: "product",
72
+ data: product,
73
+ })),
74
+ })
75
+ console.log(`Generated ${outputs.length} files`)
76
+ ```
77
+
78
+ Each page specifies `kind` (`"matra"` or `"markdown"`), a `route`, and a
79
+ `source` string (or a named `template` instead of `source` for a Matra page).
80
+ Templates compile once; `templates.product.document` identifies the template, while the
81
+ page's `document` and `route` identify the article in runtime errors. Optional `data`, `layout`, and `document` fields provide page
82
+ data, select a layout (or disable it with `layout: false`), and set the
83
+ logical document path used for diagnostics and relative links. `layouts` and
84
+ `components` map names to `{ source, document? }` objects.
85
+
86
+ Both APIs support layouts, assets, a base path, and reusable Matra components.
87
+ Matra components are defined as `fn Name(props, children) { ... }` and return
88
+ one document node. See the [site-generation contract](../../spec/site-generation.md)
89
+ for the complete configuration schema, input rules, component behavior, and
90
+ output guarantees.
91
+
92
+ ## Markdown and blog outputs
93
+
94
+ The default Markdown behavior is unchanged. For frontmatter, GFM, math, heading IDs, TOC and
95
+ excerpts, use site-generation `0.2.x` and install the [optional unified preset](../markdown-unified/README.md) (`@matra/markdown-unified@^0.1.0`) in the site
96
+ and set `markdown: "unified"` (under `site` in file configuration).
97
+ `generateSite({ markdown: async ({ body, document, metadata }) => ..., ... })` also accepts a
98
+ custom hook returning a node sequence or `{ content: nodes, data: derivedFields }`.
99
+ Supply `position.start.line` on link/image nodes relative to the body (first line is 1).
100
+ Matra resolves and validates URLs after conversion and adds the frontmatter line offset.
101
+ Raw HTML strings are never injected into the page.
102
+
103
+ Set `publicDir: "public"` to copy files such as `public/favicon.ico` to `/favicon.ico`,
104
+ alongside the existing `assets` mount. Set `notFound: "/404/"` to also publish that page's
105
+ HTML at `/404.html` without breaking its regular route. Both outputs use the ordinary
106
+ collision checks, symlink rejection, staging and stale-file manifest.
107
+
108
+ ## Output safety
109
+
110
+ The generator validates inputs and renders pages before publishing. Generated
111
+ files are staged and published together; generation or validation failures
112
+ preserve the previous output. A manifest tracks generated files so obsolete
113
+ generated files can be removed on a later successful build without deleting
114
+ untracked files. Input symlinks and paths outside the project root are
115
+ rejected.
116
+
117
+ ## License
118
+
119
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matra/site-generation",
3
- "version": "0.1.0-site.5",
3
+ "version": "0.2.0",
4
4
  "description": "Declarative static site generation for Matra",
5
5
  "type": "module",
6
6
  "exports": {
@@ -10,11 +10,20 @@
10
10
  "src"
11
11
  ],
12
12
  "dependencies": {
13
- "@matra/core": "^0.3.1-site.4",
14
- "@matra/html": "^0.3.1-site.0",
13
+ "@matra/core": "^0.3.1",
14
+ "@matra/html": "^0.3.1",
15
15
  "js-yaml": "^5.2.2",
16
16
  "markdown-it": "^14.3.0"
17
17
  },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/matralang/matra.git",
21
+ "directory": "packages/site-generation"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org"
26
+ },
18
27
  "license": "MIT",
19
28
  "scripts": {
20
29
  "build": "node --check src/index.mjs && node --check src/site.mjs && node --check src/markdown.mjs",
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  buildSite,
3
+ buildSitePreview,
3
4
  generateSite,
4
5
  getSiteProgramDocuments,
5
6
  renderLiterateDocument,
package/src/markdown.mjs CHANGED
@@ -1,6 +1,23 @@
1
1
  import MarkdownIt from "markdown-it"
2
2
 
3
3
  const markdown = new MarkdownIt({ html: false, linkify: false, typographer: false })
4
+ // inline token には map がなく、複数行のコード等は token 化後に改行が失われる。
5
+ markdown.inline.State = class extends markdown.inline.State {
6
+ lineOffset = 0
7
+ nextBreak = this.src.indexOf("\n")
8
+
9
+ push(type, tag, nesting) {
10
+ const token = super.push(type, tag, nesting)
11
+ if (type === "link_open" || type === "image") {
12
+ while (this.nextBreak !== -1 && this.nextBreak < this.pos) {
13
+ this.lineOffset++
14
+ this.nextBreak = this.src.indexOf("\n", this.nextBreak + 1)
15
+ }
16
+ token.meta = { lineOffset: this.lineOffset }
17
+ }
18
+ return token
19
+ }
20
+ }
4
21
  const BLOCK_TAGS = {
5
22
  blockquote_open: "blockquote",
6
23
  bullet_list_open: "ul",
@@ -22,11 +39,17 @@ const INLINE_TAGS = {
22
39
  strong_open: "strong",
23
40
  }
24
41
 
25
- export function markdownToNodes(source, { resolveLink = value => value } = {}) {
42
+ export function isSafeMarkdownUrl(url) {
43
+ return markdown.validateLink(url.replace(/[\t\r\n]/g, ""))
44
+ }
45
+
46
+ export function markdownToNodes(source) {
26
47
  const tokens = markdown.parse(source, {})
27
48
  const root = { tag: "$root", props: {}, children: [] }
28
49
  const stack = [root]
50
+ let line = 1
29
51
  for (const token of tokens) {
52
+ if (token.map) line = token.map[0] + 1
30
53
  if (token.type.endsWith("_open")) {
31
54
  if (token.hidden) continue
32
55
  const tag = BLOCK_TAGS[token.type]
@@ -41,7 +64,7 @@ export function markdownToNodes(source, { resolveLink = value => value } = {}) {
41
64
  if (token.hidden) continue
42
65
  if (BLOCK_TAGS[token.type.replace("_close", "_open")]) stack.pop()
43
66
  } else if (token.type === "inline") {
44
- stack.at(-1).children.push(...inlineNodes(token.children ?? [], resolveLink))
67
+ stack.at(-1).children.push(...inlineNodes(token.children ?? [], line))
45
68
  } else if (token.type === "fence" || token.type === "code_block") {
46
69
  const codeProps = {}
47
70
  const language = token.info.trim().split(/\s+/, 1)[0]
@@ -60,7 +83,7 @@ export function markdownToNodes(source, { resolveLink = value => value } = {}) {
60
83
  return root.children
61
84
  }
62
85
 
63
- function inlineNodes(tokens, resolveLink) {
86
+ function inlineNodes(tokens, line) {
64
87
  const root = { tag: "$root", props: {}, children: [] }
65
88
  const stack = [root]
66
89
  for (const token of tokens) {
@@ -68,18 +91,22 @@ function inlineNodes(tokens, resolveLink) {
68
91
  const tag = INLINE_TAGS[token.type]
69
92
  if (!tag) continue
70
93
  const props = Object.fromEntries(token.attrs ?? [])
71
- if (tag === "a" && props.href) props.href = resolveLink(props.href, "link")
72
94
  const node = { tag, props, children: [] }
95
+ if (tag === "a") node.position = { start: { line: line + token.meta.lineOffset } }
73
96
  stack.at(-1).children.push(node)
74
97
  stack.push(node)
75
98
  } else if (token.type.endsWith("_close")) {
76
99
  if (INLINE_TAGS[token.type.replace("_close", "_open")]) stack.pop()
77
100
  } else if (token.type === "image") {
78
101
  const props = Object.fromEntries(token.attrs ?? [])
79
- if (props.src) props.src = resolveLink(props.src, "image")
80
102
  props.alt = token.content
81
103
  if (token.attrGet("title")) props.title = token.attrGet("title")
82
- stack.at(-1).children.push({ tag: "img", props, children: [] })
104
+ stack.at(-1).children.push({
105
+ tag: "img",
106
+ props,
107
+ children: [],
108
+ position: { start: { line: line + token.meta.lineOffset } },
109
+ })
83
110
  } else if (token.type === "code_inline") {
84
111
  stack.at(-1).children.push({ tag: "code", props: {}, children: [token.content] })
85
112
  } else if (token.type === "hardbreak") {
package/src/site.mjs CHANGED
@@ -11,9 +11,11 @@ import {
11
11
  rmdir,
12
12
  writeFile,
13
13
  } from "node:fs/promises"
14
+ import { createRequire } from "node:module"
14
15
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"
16
+ import { pathToFileURL } from "node:url"
15
17
  import { types } from "node:util"
16
- import { evaluateStatic, parse, staticValueToAST } from "@matra/core"
18
+ import { evaluateStatic, isMatraAST, parse, staticValueToAST } from "@matra/core"
17
19
  import {
18
20
  buildLiterate,
19
21
  buildMatraComponent,
@@ -22,7 +24,7 @@ import {
22
24
  } from "@matra/core/experimental/literate"
23
25
  import { toHTML } from "@matra/html"
24
26
  import { load as loadYaml } from "js-yaml"
25
- import { markdownToNodes } from "./markdown.mjs"
27
+ import { isSafeMarkdownUrl, markdownToNodes } from "./markdown.mjs"
26
28
 
27
29
  const CONFIG_NAMES = ["matra.site.yaml", "matra.site.json", "matra.site.matra"]
28
30
  const SITE_KEYS = new Set(["route", "layout", "data"])
@@ -42,11 +44,15 @@ export async function renderLiterateDocument(markdown, options = {}) {
42
44
  }
43
45
 
44
46
  export async function buildSite(directory) {
45
- const site = await loadSite(resolve(directory))
47
+ return (await buildSitePreview(directory)).files
48
+ }
49
+
50
+ export async function buildSitePreview(directory, onInputs) {
51
+ const site = await loadSite(resolve(directory), onInputs)
46
52
  const { root, settings } = site
47
53
  const components = []
48
54
  if (settings.componentsDirectory) {
49
- for (const path of await walkFiles(settings.componentsDirectory)) {
55
+ for (const path of await walkFiles(settings.componentsDirectory, settings.observeDirectory)) {
50
56
  if (!path.endsWith(".matra")) continue
51
57
  components.push({
52
58
  source: await readFile(path, "utf8"),
@@ -54,14 +60,29 @@ export async function buildSite(directory) {
54
60
  })
55
61
  }
56
62
  }
57
- return generateLoadedSite({ ...site, components })
63
+ const result = await generateLoadedSite({ ...site, components })
64
+ return {
65
+ ...result,
66
+ outputDirectory: settings.outputDirectory,
67
+ basePath: settings.basePath,
68
+ notFound: settings.notFound,
69
+ }
58
70
  }
59
71
 
60
- async function generateLoadedSite({ root, settings, documents, layouts, pages, components }) {
72
+ async function generateLoadedSite({
73
+ root,
74
+ settings,
75
+ documents,
76
+ layouts,
77
+ pages,
78
+ components,
79
+ templates = new Map(),
80
+ }) {
61
81
  settings.components = []
62
82
  const names = new Set()
63
83
  for (const source of components) {
64
84
  const component = await buildMatraComponent(source.source, { document: source.document })
85
+ warnDiscardedNodes(component.entry)
65
86
  if (source.name !== undefined && source.name !== component.name) {
66
87
  throw new Error(`${source.document}: component name must match '${source.name}'`)
67
88
  }
@@ -72,56 +93,187 @@ async function generateLoadedSite({ root, settings, documents, layouts, pages, c
72
93
  names.add(key)
73
94
  settings.components.push(component)
74
95
  }
75
- const assets = settings.assetsDirectory ? await collectAssets(settings.assetsDirectory) : []
96
+ const assets = [
97
+ ...(settings.assetsDirectory
98
+ ? await collectAssets(settings.assetsDirectory, "assets", settings.observeDirectory)
99
+ : []),
100
+ ...(settings.publicDirectory
101
+ ? await collectAssets(settings.publicDirectory, "", settings.observeDirectory)
102
+ : []),
103
+ ]
76
104
  const outputPlan = planOutput(pages, assets, settings)
77
105
  settings.routes = new Map(pages.map(page => [page.path, page.route]))
78
106
  settings.routesByRoute = new Set(pages.map(page => page.route))
79
- settings.assetFiles = new Set(assets.map(asset => resolve(asset.source)))
80
- settings.assetOutputs = new Set(assets.map(asset => `/${asset.output.split(sep).join("/")}`))
107
+ settings.assetFiles = new Map(
108
+ assets.map(asset => [asset.source, `/${asset.output.split(sep).join("/")}`]),
109
+ )
110
+ settings.assetOutputs = new Set(settings.assetFiles.values())
81
111
  await validateOutput(root, settings.outputDirectory, { files: [] })
82
- settings.documents = documents.map(document => ({
83
- id: document.id,
84
- path: document.id,
85
- metadata: document.metadataIsData ? document.metadata : metadataValues(document.metadata),
86
- content: markdownToNodes(
87
- document.body,
88
- settings.routes.has(document.path)
89
- ? {
90
- resolveLink: (href, kind) => resolveMarkdownLink(href, kind, document, settings),
91
- }
92
- : {},
93
- ),
94
- }))
95
- for (const layout of layouts.values()) {
96
- layout.bundle = await buildTemplate(layout, root)
112
+ const transform =
113
+ settings.markdown === "unified" ? await loadUnifiedPreset(root) : settings.markdown
114
+ const pagesByPath = new Map(pages.map(page => [page.path, page]))
115
+ settings.documents = []
116
+ for (const document of documents) {
117
+ const page = pagesByPath.get(document.path)
118
+ const metadata =
119
+ page && (transform || document.metadataIsData) ? page.data : metadataValues(document.metadata)
120
+ const { content, data } = await convertMarkdown(document, page, settings, transform, metadata)
121
+ if (page) {
122
+ page.content = content
123
+ page.data = { ...data, ...page.data }
124
+ }
125
+ settings.documents.push({
126
+ id: document.id,
127
+ path: document.id,
128
+ route: page?.route ?? null,
129
+ metadata: { ...data, ...metadata },
130
+ content,
131
+ })
132
+ }
133
+ for (const template of [...layouts.values(), ...templates.values()]) {
134
+ template.bundle = await buildTemplate(template, root)
97
135
  }
98
136
  for (const page of pages) {
99
137
  if (page.kind === "program") {
100
- page.bundle = await buildTemplate(page, root)
138
+ page.bundle = page.template
139
+ ? templates.get(page.template).bundle
140
+ : await buildTemplate(page, root)
101
141
  }
102
142
  }
103
143
 
104
144
  const rendered = []
105
145
  for (const page of pages) {
106
- const content = await renderPage(page, settings)
107
- const document = page.layout
108
- ? await renderLayout(layouts.get(page.layout), content, page, settings)
109
- : content
110
- assertCompleteDocument(document, page.path)
111
- rendered.push({
112
- path: outputPlan.routes.get(page.route),
113
- content: `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`,
114
- })
146
+ try {
147
+ const content = await renderPage(page, settings)
148
+ const document = page.layout
149
+ ? await renderLayout(layouts.get(page.layout), content, page, settings)
150
+ : content
151
+ assertCompleteDocument(document, page.path)
152
+ const html = `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`
153
+ rendered.push({ path: outputPlan.routes.get(page.route), content: html })
154
+ if (page.route === settings.notFound && outputPlan.routes.get(page.route) !== "404.html") {
155
+ rendered.push({ path: "404.html", content: html })
156
+ }
157
+ } catch (error) {
158
+ error.message = `${page.document} (route ${page.route}): ${error.message}`
159
+ throw error
160
+ }
115
161
  }
116
162
  for (const asset of assets) rendered.push({ path: asset.output, content: asset.content })
117
163
  await publish(root, settings.outputDirectory, rendered)
118
- return rendered.map(file => join(settings.outputDirectory, file.path))
164
+ return {
165
+ files: rendered.map(file => join(settings.outputDirectory, file.path)),
166
+ routes: outputPlan.routes,
167
+ }
168
+ }
169
+
170
+ async function buildTemplate(template, root) {
171
+ const bundle =
172
+ template.sourceKind === "matra"
173
+ ? await buildMatraProgram(template.source, { document: template.document })
174
+ : await buildLiterate(template.source, { document: template.document, moduleRoot: root })
175
+ warnDiscardedNodes(bundle.entry)
176
+ return bundle
177
+ }
178
+
179
+ function warnDiscardedNodes(entry) {
180
+ if (!entry.source.includes("if")) return
181
+ let syntax
182
+ try {
183
+ syntax = parse(entry.source)
184
+ } catch (error) {
185
+ if (!(error instanceof SyntaxError)) throw error
186
+ console.warn(`${entry.document}: template warning check unavailable: ${error.message}`)
187
+ return
188
+ }
189
+ function visit(value) {
190
+ if (!value || typeof value !== "object") return
191
+ if (value.kind === "if") {
192
+ for (const branch of [value.thenBody, value.elseBody]) {
193
+ for (const statement of branch.slice(0, -1)) {
194
+ if (statement.kind === "expression" && statement.expression.kind === "node") {
195
+ console.warn(
196
+ `${entry.document}: if branch discards <${statement.expression.tag}>. Use ...if with an array to emit multiple nodes.`,
197
+ )
198
+ }
199
+ }
200
+ }
201
+ }
202
+ Object.values(value).forEach(visit)
203
+ }
204
+ visit(syntax)
119
205
  }
120
206
 
121
- function buildTemplate(template, root) {
122
- return template.sourceKind === "matra"
123
- ? buildMatraProgram(template.source, { document: template.document })
124
- : buildLiterate(template.source, { document: template.document, moduleRoot: root })
207
+ async function loadUnifiedPreset(root) {
208
+ let path
209
+ try {
210
+ path = createRequire(join(root, "package.json")).resolve("@matra/markdown-unified")
211
+ } catch (error) {
212
+ if (error.code !== "MODULE_NOT_FOUND") throw error
213
+ throw new Error(
214
+ "markdown: unified requires @matra/markdown-unified installed in the site project",
215
+ { cause: error },
216
+ )
217
+ }
218
+ const { createUnifiedMarkdown } = await import(pathToFileURL(path).href)
219
+ return createUnifiedMarkdown()
220
+ }
221
+
222
+ async function convertMarkdown(document, page, settings, transform, metadata) {
223
+ const path = relative(settings.root, document.path).split(sep).join("/")
224
+ const firstLine = document.bodyLine
225
+ const location = line => `${path}:${firstLine + line - 1}${page ? ` (route ${page.route})` : ""}`
226
+ let result
227
+ if (transform) {
228
+ try {
229
+ result = await transform({
230
+ body: document.body,
231
+ document: path,
232
+ metadata: structuredClone(metadata),
233
+ })
234
+ } catch (error) {
235
+ throw new Error(`${location(error?.line ?? 1)}: ${error?.message ?? String(error)}`, {
236
+ cause: error,
237
+ })
238
+ }
239
+ assertPlainData(result, `${location(1)}: Markdown transform result`)
240
+ result = structuredClone(result)
241
+ } else {
242
+ result = markdownToNodes(document.body)
243
+ }
244
+ const { content, data = {} } = Array.isArray(result) ? { content: result } : (result ?? {})
245
+ if (!Array.isArray(content) || !isRecord(data)) {
246
+ throw new TypeError(
247
+ `${location(1)}: expected Markdown nodes or { content: nodes, data?: object }`,
248
+ )
249
+ }
250
+ function resolveNode(node, parentLine) {
251
+ if (node === null || ["string", "number", "boolean"].includes(typeof node)) return node
252
+ if (!isMatraAST(node))
253
+ throw new TypeError(`${location(parentLine)}: invalid Markdown document node`)
254
+ const line = node.position?.start?.line ?? parentLine
255
+ if (!Number.isSafeInteger(line) || line < 1)
256
+ throw new TypeError(`${location(parentLine)}: invalid Markdown node line`)
257
+ const props = { ...node.props }
258
+ for (const name of ["href", "src"]) {
259
+ if (!Object.hasOwn(props, name)) continue
260
+ const href = props[name]
261
+ if (typeof href !== "string" || !isSafeMarkdownUrl(href)) {
262
+ throw new TypeError(`${location(line)}: invalid Markdown ${name}: ${href}`)
263
+ }
264
+ if (page || transform) {
265
+ props[name] = resolveMarkdownLink(
266
+ href,
267
+ name === "src" ? "image" : "link",
268
+ document,
269
+ settings,
270
+ location(line),
271
+ )
272
+ }
273
+ }
274
+ return { tag: node.tag, props, children: node.children.map(child => resolveNode(child, line)) }
275
+ }
276
+ return { content: content.map(node => resolveNode(node, 1)), data }
125
277
  }
126
278
 
127
279
  export async function generateSite(options) {
@@ -132,6 +284,7 @@ export async function generateSite(options) {
132
284
  for (const directory of [
133
285
  ...settings.documentDirectories,
134
286
  ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
287
+ ...(settings.publicDirectory ? [settings.publicDirectory] : []),
135
288
  ]) {
136
289
  assertInputOutputSeparation(directory, settings.outputDirectory)
137
290
  await assertDirectory(root, directory)
@@ -140,6 +293,7 @@ export async function generateSite(options) {
140
293
  const logicalPaths = new Set([
141
294
  ...site.pages.map(page => page.path.toLowerCase()),
142
295
  ...[...site.layouts.values()].map(layout => layout.path.toLowerCase()),
296
+ ...[...site.templates.values()].map(template => template.path.toLowerCase()),
143
297
  ...site.components.map(component => component.path.toLowerCase()),
144
298
  ])
145
299
  for (const document of documents) {
@@ -152,22 +306,35 @@ export async function generateSite(options) {
152
306
  const id = page.document
153
307
  if (ids.has(id.toLowerCase())) throw new Error(`Duplicate document ID ignoring case: ${id}`)
154
308
  ids.add(id.toLowerCase())
309
+ const parsed = settings.markdown
310
+ ? parseFrontMatter(page.body, id, page.route)
311
+ : { body: page.body, bodyLine: 1, metadata: {} }
312
+ page.data = { ...parsed.metadata, ...page.data }
155
313
  documents.push({
156
314
  id,
157
315
  path: page.path,
158
- body: page.body,
316
+ body: parsed.body,
317
+ bodyLine: parsed.bodyLine,
159
318
  metadata: page.data,
160
319
  metadataIsData: true,
161
320
  })
162
321
  }
163
322
  documents.sort((left, right) => left.id.localeCompare(right.id, "en"))
164
- return generateLoadedSite({ ...site, documents })
323
+ return (await generateLoadedSite({ ...site, documents })).files
165
324
  }
166
325
 
167
326
  function normalizeDirectSite(input) {
168
- if (!isRecord(input)) throw new TypeError("generateSite options must be an object")
169
- assertPlainData(input, "generateSite options")
170
- const options = structuredClone(input)
327
+ if (types.isProxy(input) || !isRecord(input))
328
+ throw new TypeError("generateSite options must be an object")
329
+ const descriptors = Object.getOwnPropertyDescriptors(input)
330
+ const transform =
331
+ descriptors.markdown?.enumerable && typeof descriptors.markdown.value === "function"
332
+ ? descriptors.markdown.value
333
+ : undefined
334
+ if (transform) delete descriptors.markdown
335
+ const data = Object.defineProperties({}, descriptors)
336
+ assertPlainData(data, "generateSite options")
337
+ const options = structuredClone(data)
171
338
  rejectUnknownKeys(
172
339
  options,
173
340
  new Set([
@@ -175,11 +342,15 @@ function normalizeDirectSite(input) {
175
342
  "output",
176
343
  "format",
177
344
  "assets",
345
+ "publicDir",
346
+ "notFound",
347
+ "markdown",
178
348
  "basePath",
179
349
  "data",
180
350
  "defaultLayout",
181
351
  "pages",
182
352
  "layouts",
353
+ "templates",
183
354
  "components",
184
355
  "documents",
185
356
  ]),
@@ -190,11 +361,23 @@ function normalizeDirectSite(input) {
190
361
  }
191
362
  const root = resolve(options.root ?? process.cwd())
192
363
  const siteOptions = Object.fromEntries(
193
- ["output", "format", "assets", "basePath", "data", "defaultLayout", "documents"]
364
+ [
365
+ "output",
366
+ "format",
367
+ "assets",
368
+ "publicDir",
369
+ "notFound",
370
+ "markdown",
371
+ "basePath",
372
+ "data",
373
+ "defaultLayout",
374
+ "documents",
375
+ ]
194
376
  .filter(key => Object.hasOwn(options, key))
195
377
  .map(key => [key, options[key]]),
196
378
  )
197
379
  const settings = normalizeSettings({ version: 1, site: siteOptions }, root)
380
+ if (transform) settings.markdown = transform
198
381
  if (settings.outputDirectory === root) throw new Error("site.output must not be the project root")
199
382
  const documentDirectories =
200
383
  typeof options.documents === "string" ? [options.documents] : (options.documents ?? [])
@@ -202,7 +385,8 @@ function normalizeDirectSite(input) {
202
385
  const documents = new Set()
203
386
  const sourceEntry = (entry, fallback, label) => {
204
387
  if (!isRecord(entry)) throw new TypeError(`${label} must be an object`)
205
- if (typeof entry.source !== "string") throw new TypeError(`${label}.source must be a string`)
388
+ if (!Object.hasOwn(entry, "template") && typeof entry.source !== "string")
389
+ throw new TypeError(`${label}.source must be a string`)
206
390
  const document = entry.document === undefined ? fallback : entry.document
207
391
  if (
208
392
  typeof document !== "string" ||
@@ -240,6 +424,7 @@ function normalizeDirectSite(input) {
240
424
  )
241
425
  }
242
426
  const layouts = namedSources(options.layouts, "layouts")
427
+ const templates = namedSources(options.templates, "templates")
243
428
  selectedLayout(undefined, settings.defaultLayout, layouts, "defaultLayout")
244
429
  const components = [...namedSources(options.components, "components").values()]
245
430
  if (!Array.isArray(options.pages)) throw new TypeError("pages must be an array")
@@ -248,12 +433,26 @@ function normalizeDirectSite(input) {
248
433
  if (!isRecord(entry)) throw new TypeError(`${label} must be an object`)
249
434
  rejectUnknownKeys(
250
435
  entry,
251
- new Set(["kind", "route", "source", "layout", "data", "document"]),
436
+ new Set(["kind", "route", "source", "template", "layout", "data", "document"]),
252
437
  label,
253
438
  )
254
439
  if (!["matra", "markdown"].includes(entry.kind))
255
440
  throw new TypeError(`${label}.kind must be 'matra' or 'markdown'`)
256
441
  if (typeof entry.route !== "string") throw new TypeError(`${label}.route must be a string`)
442
+ if (Object.hasOwn(entry, "template")) {
443
+ if (entry.kind !== "matra" || Object.hasOwn(entry, "source")) {
444
+ throw new TypeError(`${label}: template replaces source on a matra page only`)
445
+ }
446
+ if (!templates.has(entry.template))
447
+ throw new TypeError(`${label}: unknown template '${entry.template}'`)
448
+ }
449
+ const route = normalizeRoute(entry.route, settings.format, label)
450
+ const stem = route === "/" ? "index" : route.slice(1).replace(/\/$/, "")
451
+ const source = sourceEntry(
452
+ entry,
453
+ `pages/${stem}.${entry.kind === "matra" ? "matra" : "md"}`,
454
+ label,
455
+ )
257
456
  const controls = siteControls(
258
457
  {
259
458
  site: {
@@ -261,27 +460,21 @@ function normalizeDirectSite(input) {
261
460
  ...(Object.hasOwn(entry, "data") ? { data: entry.data } : {}),
262
461
  },
263
462
  },
264
- label,
265
- )
266
- const route = normalizeRoute(entry.route, settings.format, label)
267
- const stem = route === "/" ? "index" : route.slice(1).replace(/\/$/, "")
268
- const source = sourceEntry(
269
- entry,
270
- `pages/${stem}.${entry.kind === "matra" ? "matra" : "md"}`,
271
- label,
463
+ `${source.document} (route ${route})`,
272
464
  )
273
465
  return {
274
466
  ...source,
275
467
  kind: entry.kind === "matra" ? "program" : "markdown",
276
468
  id: source.document,
277
469
  body: entry.source,
470
+ template: entry.template,
278
471
  route,
279
472
  data: controls.data ?? {},
280
473
  layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, source.document),
281
474
  }
282
475
  })
283
476
  sortAndValidateRoutes(pages)
284
- return { root, settings, layouts, pages, components }
477
+ return { root, settings, layouts, templates, pages, components }
285
478
  }
286
479
 
287
480
  function assertInputOutputSeparation(input, output) {
@@ -302,24 +495,30 @@ export async function getSiteProgramDocuments(directory) {
302
495
  ].sort((left, right) => left.localeCompare(right, "en"))
303
496
  }
304
497
 
305
- async function loadSite(root) {
498
+ async function loadSite(root, onInputs) {
499
+ for (const name of CONFIG_NAMES) onInputs?.(join(root, name))
306
500
  const config = await readConfig(root)
307
501
  const settings = normalizeSettings(config, root)
308
- for (const input of [
502
+ const inputs = [
309
503
  settings.pagesDirectory,
310
504
  ...settings.documentDirectories,
311
505
  settings.layoutsDirectory,
312
506
  ...(settings.componentsDirectory ? [settings.componentsDirectory] : []),
313
507
  ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
314
- ]) {
508
+ ...(settings.publicDirectory ? [settings.publicDirectory] : []),
509
+ ]
510
+ for (const input of inputs) {
315
511
  assertInputOutputSeparation(input, settings.outputDirectory)
512
+ onInputs?.(input)
316
513
  }
514
+ if (onInputs) settings.observeDirectory = path => onInputs(path, true)
317
515
  await Promise.all([
318
516
  assertDirectory(root, settings.pagesDirectory),
319
517
  ...settings.documentDirectories.map(path => assertDirectory(root, path)),
320
518
  assertDirectory(root, settings.layoutsDirectory, { optional: true }),
321
519
  ...(settings.componentsDirectory ? [assertDirectory(root, settings.componentsDirectory)] : []),
322
520
  ...(settings.assetsDirectory ? [assertDirectory(root, settings.assetsDirectory)] : []),
521
+ ...(settings.publicDirectory ? [assertDirectory(root, settings.publicDirectory)] : []),
323
522
  ])
324
523
  const documents = await collectDocuments(root, settings)
325
524
  const layouts = await collectLayouts(root, settings)
@@ -375,6 +574,9 @@ function normalizeSettings(config, root) {
375
574
  "output",
376
575
  "format",
377
576
  "assets",
577
+ "publicDir",
578
+ "notFound",
579
+ "markdown",
378
580
  "basePath",
379
581
  "data",
380
582
  ]),
@@ -412,6 +614,25 @@ function normalizeSettings(config, root) {
412
614
  const outputDirectory = resolveDirectory(site.output, "output", "dist")
413
615
  const assetsDirectory =
414
616
  site.assets === undefined ? undefined : resolveDirectory(site.assets, "assets", site.assets)
617
+ const publicDirectory =
618
+ site.publicDir === undefined
619
+ ? undefined
620
+ : resolveDirectory(site.publicDir, "publicDir", site.publicDir)
621
+ if (
622
+ assetsDirectory &&
623
+ publicDirectory &&
624
+ (assetsDirectory === publicDirectory ||
625
+ assetsDirectory.startsWith(`${publicDirectory}${sep}`) ||
626
+ publicDirectory.startsWith(`${assetsDirectory}${sep}`))
627
+ ) {
628
+ throw new TypeError("site.publicDir and site.assets must not overlap")
629
+ }
630
+ if (site.markdown !== undefined && site.markdown !== "unified") {
631
+ throw new TypeError("site.markdown must be 'unified'")
632
+ }
633
+ if (site.notFound !== undefined && typeof site.notFound !== "string") {
634
+ throw new TypeError("site.notFound must be a page route")
635
+ }
415
636
  if (site.format !== undefined && !["directory", "flat"].includes(site.format)) {
416
637
  throw new TypeError("site.format must be 'directory' or 'flat'")
417
638
  }
@@ -436,6 +657,12 @@ function normalizeSettings(config, root) {
436
657
  componentsDirectory,
437
658
  outputDirectory,
438
659
  assetsDirectory,
660
+ publicDirectory,
661
+ notFound:
662
+ site.notFound === undefined
663
+ ? undefined
664
+ : normalizeRoute(site.notFound, format, "site.notFound"),
665
+ markdown: site.markdown,
439
666
  defaultLayout: site.defaultLayout === undefined ? false : site.defaultLayout,
440
667
  format,
441
668
  basePath,
@@ -463,9 +690,10 @@ async function assertDirectory(root, path, { optional = false } = {}) {
463
690
  return true
464
691
  }
465
692
 
466
- async function walkFiles(directory) {
693
+ async function walkFiles(directory, observeDirectory) {
467
694
  const results = []
468
695
  async function visit(current) {
696
+ observeDirectory?.(current)
469
697
  const entries = await readdir(current, { withFileTypes: true })
470
698
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"))
471
699
  for (const entry of entries) {
@@ -484,7 +712,7 @@ async function collectDocuments(root, settings) {
484
712
  const ids = new Map()
485
713
  for (const directory of settings.documentDirectories) {
486
714
  await assertDirectory(root, directory)
487
- for (const path of await walkFiles(directory)) {
715
+ for (const path of await walkFiles(directory, settings.observeDirectory)) {
488
716
  if (!path.endsWith(".md") || path.endsWith(".matra.md")) continue
489
717
  const id = relative(directory, path).split(sep).join("/")
490
718
  const key = id.toLocaleLowerCase("en-US")
@@ -500,6 +728,7 @@ async function collectDocuments(root, settings) {
500
728
  path,
501
729
  source,
502
730
  body: parsed.body,
731
+ bodyLine: parsed.bodyLine,
503
732
  metadata: parsed.metadata,
504
733
  })
505
734
  }
@@ -511,7 +740,7 @@ async function collectDocuments(root, settings) {
511
740
  async function collectLayouts(root, settings) {
512
741
  const layouts = new Map()
513
742
  if (!(await assertDirectory(root, settings.layoutsDirectory, { optional: true }))) return layouts
514
- for (const path of await walkFiles(settings.layoutsDirectory)) {
743
+ for (const path of await walkFiles(settings.layoutsDirectory, settings.observeDirectory)) {
515
744
  if (!path.endsWith(".matra.md")) continue
516
745
  const name = relative(settings.layoutsDirectory, path)
517
746
  .split(sep)
@@ -536,7 +765,7 @@ async function collectLayouts(root, settings) {
536
765
 
537
766
  async function collectPages(root, settings, documents, layouts) {
538
767
  const pages = []
539
- for (const path of await walkFiles(settings.pagesDirectory)) {
768
+ for (const path of await walkFiles(settings.pagesDirectory, settings.observeDirectory)) {
540
769
  if (path.endsWith(".matra.md")) {
541
770
  const source = await readFile(path, "utf8")
542
771
  const frontMatter = parseFrontMatter(source, path)
@@ -560,9 +789,8 @@ async function collectPages(root, settings, documents, layouts) {
560
789
  if (!path.endsWith(".md")) continue
561
790
  const document = documents.find(entry => entry.path === path)
562
791
  if (!document) throw new Error(`Page document was not collected: ${path}`)
563
- const parsed = parseFrontMatter(document.source, path)
564
- const controls = siteControls(parsed.metadata, path)
565
- const metadata = metadataValues(parsed.metadata)
792
+ const controls = siteControls(document.metadata, path)
793
+ const metadata = metadataValues(document.metadata)
566
794
  if (controls.data && Object.keys(metadata).length) {
567
795
  throw new Error(`${path}: use either site.data or ordinary front matter values, not both`)
568
796
  }
@@ -572,8 +800,7 @@ async function collectPages(root, settings, documents, layouts) {
572
800
  id,
573
801
  path,
574
802
  source: document.source,
575
- body: parsed.body,
576
- document,
803
+ document: relative(root, path).split(sep).join("/"),
577
804
  data: controls.data ?? metadata,
578
805
  route: normalizeRoute(controls.route ?? routeFromId(id), settings.format, path),
579
806
  layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, path),
@@ -593,24 +820,29 @@ function sortAndValidateRoutes(pages) {
593
820
  }
594
821
  }
595
822
 
596
- function parseFrontMatter(source, path) {
823
+ function parseFrontMatter(source, path, route) {
597
824
  const opening = /^(?:\uFEFF)?---[ \t]*\r?\n/.exec(source)
598
- if (!opening) return { present: false, metadata: {}, body: source }
825
+ if (!opening) return { present: false, metadata: {}, body: source, bodyLine: 1 }
599
826
  const rest = source.slice(opening[0].length)
600
827
  const closing = /(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/.exec(rest)
601
- if (!closing) throw new SyntaxError(`${path}: unclosed YAML front matter`)
828
+ const at = line => `${path}:${line}${route ? ` (route ${route})` : ""}`
829
+ if (!closing) throw new SyntaxError(`${at(1)}: unclosed YAML front matter`)
602
830
  const yaml = rest.slice(0, closing.index)
603
831
  let metadata
604
832
  try {
605
833
  metadata = loadYaml(yaml)
606
834
  } catch (error) {
607
- throw new SyntaxError(`${path}: invalid YAML front matter: ${error.message}`, { cause: error })
835
+ throw new SyntaxError(
836
+ `${at((error.mark?.line ?? 0) + 2)}: invalid YAML front matter: ${error.message}`,
837
+ { cause: error },
838
+ )
608
839
  }
609
- assertPlainData(metadata, `${path} front matter`)
610
840
  if (metadata === undefined) metadata = {}
611
- if (!isRecord(metadata)) throw new TypeError(`${path}: front matter must be an object`)
841
+ assertPlainData(metadata, `${at(2)} front matter`)
842
+ if (!isRecord(metadata)) throw new TypeError(`${at(2)}: front matter must be an object`)
612
843
  const end = closing.index + closing[0].length
613
- return { present: true, metadata, body: rest.slice(end) }
844
+ const bodyLine = 2 + (rest.slice(0, end).match(/\n/g)?.length ?? 0)
845
+ return { present: true, metadata, body: rest.slice(end), bodyLine }
614
846
  }
615
847
 
616
848
  function siteControls(metadata, path) {
@@ -693,13 +925,7 @@ function normalizeBasePath(value) {
693
925
 
694
926
  async function renderPage(page, settings) {
695
927
  if (page.kind === "markdown") {
696
- return {
697
- tag: "$root",
698
- props: {},
699
- children: markdownToNodes(page.body, {
700
- resolveLink: (href, kind) => resolveMarkdownLink(href, kind, page, settings),
701
- }),
702
- }
928
+ return { tag: "$root", props: {}, children: page.content }
703
929
  }
704
930
  const value = await runLiterate(page.bundle, {
705
931
  globals: globalsFor(page, settings, []),
@@ -737,40 +963,43 @@ function globalsFor(page, settings, content) {
737
963
  }
738
964
  }
739
965
 
740
- function resolveMarkdownLink(href, kind, page, settings) {
966
+ function resolveMarkdownLink(href, kind, document, settings, location) {
741
967
  if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/.test(href) || href.startsWith("#")) return href
742
968
  const suffixStart = href.search(/[?#]/)
743
969
  const pathname = suffixStart === -1 ? href : href.slice(0, suffixStart)
744
970
  const suffix = suffixStart === -1 ? "" : href.slice(suffixStart)
745
971
  if (!pathname) return href
746
- if (pathname.startsWith("/")) {
747
- const route = normalizeRoute(pathname, settings.format, page.path)
748
- if (settings.routesByRoute.has(route)) return `${route}${suffix}`
749
- if (settings.assetOutputs.has(pathname)) return `${pathname}${suffix}`
750
- throw new Error(`${page.path}: local reference does not resolve: ${href}`)
751
- }
752
972
  let decodedPath
753
973
  try {
754
974
  decodedPath = decodeURIComponent(pathname)
755
975
  } catch (error) {
756
- throw new Error(`${page.path}: invalid encoded local reference: ${href}`, { cause: error })
976
+ throw new Error(`${location}: invalid encoded local reference: ${href}`, { cause: error })
757
977
  }
758
- const target = resolve(dirname(page.path), decodedPath)
759
- const assetRoot = settings.assetsDirectory
760
- if (assetRoot && (target === assetRoot || target.startsWith(`${assetRoot}${sep}`))) {
761
- if (!settings.assetFiles.has(target)) {
762
- throw new Error(`${page.path}: local asset does not exist: ${href}`)
978
+ if (pathname.startsWith("/")) {
979
+ if (settings.assetOutputs.has(decodedPath)) return `${pathname}${suffix}`
980
+ if (kind === "link") {
981
+ if (settings.notFound && pathname === "/404.html") return href
982
+ const route = normalizeRoute(decodedPath, settings.format, location)
983
+ if (settings.routesByRoute.has(route)) return `${route}${suffix}`
984
+ }
985
+ throw new Error(`${location}: local reference does not resolve: ${href}`)
986
+ }
987
+ const target = resolve(dirname(document.path), decodedPath)
988
+ const asset = settings.assetFiles.get(target)
989
+ if (asset !== undefined) return `${asset.split("/").map(encodeURIComponent).join("/")}${suffix}`
990
+ for (const directory of [settings.assetsDirectory, settings.publicDirectory]) {
991
+ if (directory && (target === directory || target.startsWith(`${directory}${sep}`))) {
992
+ throw new Error(`${location}: local asset does not exist: ${href}`)
763
993
  }
764
- const assetPath = relative(assetRoot, target).split(sep).join("/")
765
- return `/assets/${assetPath}${suffix}`
766
994
  }
767
- if (settings.routes.has(target) || extname(target) === ".md" || pathname.endsWith(".matra.md")) {
995
+ if (kind === "image")
996
+ throw new Error(`${location}: local image is not in site.assets or site.publicDir: ${href}`)
997
+ if (settings.routes.has(target) || extname(target) === ".md") {
768
998
  const route = settings.routes.get(target)
769
- if (!route) throw new Error(`${page.path}: local Markdown link does not resolve: ${href}`)
999
+ if (!route) throw new Error(`${location}: local Markdown link does not resolve: ${href}`)
770
1000
  return `${route}${suffix}`
771
1001
  }
772
- if (kind === "image") throw new Error(`${page.path}: local image is not in site.assets: ${href}`)
773
- throw new Error(`${page.path}: local reference does not resolve: ${href}`)
1002
+ throw new Error(`${location}: local reference does not resolve: ${href}`)
774
1003
  }
775
1004
 
776
1005
  function assertCompleteDocument(ast, source) {
@@ -786,16 +1015,16 @@ function assertCompleteDocument(ast, source) {
786
1015
  }
787
1016
  }
788
1017
 
789
- async function collectAssets(directory) {
1018
+ async function collectAssets(directory, prefix, observeDirectory) {
790
1019
  const assets = []
791
- for (const source of await walkFiles(directory)) {
1020
+ for (const source of await walkFiles(directory, observeDirectory)) {
792
1021
  const name = relative(directory, source).split(sep).join("/")
793
- if (name.split("/").some(part => !isSafeSegment(part))) {
1022
+ if (name.includes("\\") || name.split("/").some(part => !isSafeSegment(part))) {
794
1023
  throw new Error(`Invalid asset path: ${name}`)
795
1024
  }
796
1025
  assets.push({
797
1026
  source,
798
- output: join("assets", ...name.split("/")),
1027
+ output: join(prefix, ...name.split("/")),
799
1028
  content: await readFile(source),
800
1029
  })
801
1030
  }
@@ -816,6 +1045,11 @@ function planOutput(pages, assets, settings) {
816
1045
  routes.set(route, path)
817
1046
  outputs.push(path)
818
1047
  }
1048
+ if (settings.notFound !== undefined) {
1049
+ if (!routes.has(settings.notFound))
1050
+ throw new Error(`site.notFound: unknown page route '${settings.notFound}'`)
1051
+ if (routes.get(settings.notFound) !== "404.html") outputs.push("404.html")
1052
+ }
819
1053
  outputs.push(...assets.map(asset => asset.output))
820
1054
  const seen = new Map()
821
1055
  for (const output of outputs) {