@matra/site-generation 0.1.0-site.3 → 0.1.0-site.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matra/site-generation",
3
- "version": "0.1.0-site.3",
3
+ "version": "0.1.0-site.5",
4
4
  "description": "Declarative static site generation for Matra",
5
5
  "type": "module",
6
6
  "exports": {
@@ -10,7 +10,7 @@
10
10
  "src"
11
11
  ],
12
12
  "dependencies": {
13
- "@matra/core": "^0.3.1-site.1",
13
+ "@matra/core": "^0.3.1-site.4",
14
14
  "@matra/html": "^0.3.1-site.0",
15
15
  "js-yaml": "^5.2.2",
16
16
  "markdown-it": "^14.3.0"
package/src/index.mjs CHANGED
@@ -1 +1,6 @@
1
- export { buildSite, getSiteProgramDocuments, renderLiterateDocument } from "./site.mjs"
1
+ export {
2
+ buildSite,
3
+ generateSite,
4
+ getSiteProgramDocuments,
5
+ renderLiterateDocument,
6
+ } from "./site.mjs"
package/src/site.mjs CHANGED
@@ -12,8 +12,14 @@ import {
12
12
  writeFile,
13
13
  } from "node:fs/promises"
14
14
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"
15
+ import { types } from "node:util"
15
16
  import { evaluateStatic, parse, staticValueToAST } from "@matra/core"
16
- import { buildLiterate, runLiterate } from "@matra/core/experimental/literate"
17
+ import {
18
+ buildLiterate,
19
+ buildMatraComponent,
20
+ buildMatraProgram,
21
+ runLiterate,
22
+ } from "@matra/core/experimental/literate"
17
23
  import { toHTML } from "@matra/html"
18
24
  import { load as loadYaml } from "js-yaml"
19
25
  import { markdownToNodes } from "./markdown.mjs"
@@ -30,12 +36,42 @@ export async function renderLiterateDocument(markdown, options = {}) {
30
36
  const value = await runLiterate(bundle, {
31
37
  globals: options.globals,
32
38
  moduleRoot: options.moduleRoot,
39
+ components: options.components,
33
40
  })
34
41
  return staticValueToAST(value)
35
42
  }
36
43
 
37
44
  export async function buildSite(directory) {
38
- const { root, settings, documents, layouts, pages } = await loadSite(resolve(directory))
45
+ const site = await loadSite(resolve(directory))
46
+ const { root, settings } = site
47
+ const components = []
48
+ if (settings.componentsDirectory) {
49
+ for (const path of await walkFiles(settings.componentsDirectory)) {
50
+ if (!path.endsWith(".matra")) continue
51
+ components.push({
52
+ source: await readFile(path, "utf8"),
53
+ document: relative(root, path).split(sep).join("/"),
54
+ })
55
+ }
56
+ }
57
+ return generateLoadedSite({ ...site, components })
58
+ }
59
+
60
+ async function generateLoadedSite({ root, settings, documents, layouts, pages, components }) {
61
+ settings.components = []
62
+ const names = new Set()
63
+ for (const source of components) {
64
+ const component = await buildMatraComponent(source.source, { document: source.document })
65
+ if (source.name !== undefined && source.name !== component.name) {
66
+ throw new Error(`${source.document}: component name must match '${source.name}'`)
67
+ }
68
+ const key = component.name.toLowerCase()
69
+ if (names.has(key)) {
70
+ throw new Error(`${source.document}: Duplicate component name: ${component.name}`)
71
+ }
72
+ names.add(key)
73
+ settings.components.push(component)
74
+ }
39
75
  const assets = settings.assetsDirectory ? await collectAssets(settings.assetsDirectory) : []
40
76
  const outputPlan = planOutput(pages, assets, settings)
41
77
  settings.routes = new Map(pages.map(page => [page.path, page.route]))
@@ -46,7 +82,7 @@ export async function buildSite(directory) {
46
82
  settings.documents = documents.map(document => ({
47
83
  id: document.id,
48
84
  path: document.id,
49
- metadata: metadataValues(document.metadata),
85
+ metadata: document.metadataIsData ? document.metadata : metadataValues(document.metadata),
50
86
  content: markdownToNodes(
51
87
  document.body,
52
88
  settings.routes.has(document.path)
@@ -57,17 +93,11 @@ export async function buildSite(directory) {
57
93
  ),
58
94
  }))
59
95
  for (const layout of layouts.values()) {
60
- layout.bundle = await buildLiterate(layout.source, {
61
- document: layout.document,
62
- moduleRoot: root,
63
- })
96
+ layout.bundle = await buildTemplate(layout, root)
64
97
  }
65
98
  for (const page of pages) {
66
99
  if (page.kind === "program") {
67
- page.bundle = await buildLiterate(page.source, {
68
- document: page.document,
69
- moduleRoot: root,
70
- })
100
+ page.bundle = await buildTemplate(page, root)
71
101
  }
72
102
  }
73
103
 
@@ -77,7 +107,7 @@ export async function buildSite(directory) {
77
107
  const document = page.layout
78
108
  ? await renderLayout(layouts.get(page.layout), content, page, settings)
79
109
  : content
80
- assertCompleteDocument(document, page.source)
110
+ assertCompleteDocument(document, page.path)
81
111
  rendered.push({
82
112
  path: outputPlan.routes.get(page.route),
83
113
  content: `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`,
@@ -88,6 +118,182 @@ export async function buildSite(directory) {
88
118
  return rendered.map(file => join(settings.outputDirectory, file.path))
89
119
  }
90
120
 
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 })
125
+ }
126
+
127
+ export async function generateSite(options) {
128
+ const site = normalizeDirectSite(options)
129
+ const { root, settings } = site
130
+ const info = await lstat(root)
131
+ if (!info.isDirectory()) throw new Error(`Expected a project directory: ${root}`)
132
+ for (const directory of [
133
+ ...settings.documentDirectories,
134
+ ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
135
+ ]) {
136
+ assertInputOutputSeparation(directory, settings.outputDirectory)
137
+ await assertDirectory(root, directory)
138
+ }
139
+ const documents = await collectDocuments(root, settings)
140
+ const logicalPaths = new Set([
141
+ ...site.pages.map(page => page.path.toLowerCase()),
142
+ ...[...site.layouts.values()].map(layout => layout.path.toLowerCase()),
143
+ ...site.components.map(component => component.path.toLowerCase()),
144
+ ])
145
+ for (const document of documents) {
146
+ if (logicalPaths.has(document.path.toLowerCase())) {
147
+ throw new Error(`Collected document conflicts with a logical document: ${document.path}`)
148
+ }
149
+ }
150
+ const ids = new Set(documents.map(document => document.id.toLowerCase()))
151
+ for (const page of site.pages.filter(page => page.kind === "markdown")) {
152
+ const id = page.document
153
+ if (ids.has(id.toLowerCase())) throw new Error(`Duplicate document ID ignoring case: ${id}`)
154
+ ids.add(id.toLowerCase())
155
+ documents.push({
156
+ id,
157
+ path: page.path,
158
+ body: page.body,
159
+ metadata: page.data,
160
+ metadataIsData: true,
161
+ })
162
+ }
163
+ documents.sort((left, right) => left.id.localeCompare(right.id, "en"))
164
+ return generateLoadedSite({ ...site, documents })
165
+ }
166
+
167
+ 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)
171
+ rejectUnknownKeys(
172
+ options,
173
+ new Set([
174
+ "root",
175
+ "output",
176
+ "format",
177
+ "assets",
178
+ "basePath",
179
+ "data",
180
+ "defaultLayout",
181
+ "pages",
182
+ "layouts",
183
+ "components",
184
+ "documents",
185
+ ]),
186
+ "generateSite",
187
+ )
188
+ if (options.root !== undefined && (typeof options.root !== "string" || !options.root)) {
189
+ throw new TypeError("root must be a non-empty path")
190
+ }
191
+ const root = resolve(options.root ?? process.cwd())
192
+ const siteOptions = Object.fromEntries(
193
+ ["output", "format", "assets", "basePath", "data", "defaultLayout", "documents"]
194
+ .filter(key => Object.hasOwn(options, key))
195
+ .map(key => [key, options[key]]),
196
+ )
197
+ const settings = normalizeSettings({ version: 1, site: siteOptions }, root)
198
+ if (settings.outputDirectory === root) throw new Error("site.output must not be the project root")
199
+ const documentDirectories =
200
+ typeof options.documents === "string" ? [options.documents] : (options.documents ?? [])
201
+ settings.documentDirectories = [...new Set(documentDirectories.map(path => resolve(root, path)))]
202
+ const documents = new Set()
203
+ const sourceEntry = (entry, fallback, label) => {
204
+ 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`)
206
+ const document = entry.document === undefined ? fallback : entry.document
207
+ if (
208
+ typeof document !== "string" ||
209
+ !document ||
210
+ isAbsolute(document) ||
211
+ document.includes("\\") ||
212
+ document.includes("%") ||
213
+ document.split("/").some(part => !isSafeSegment(part))
214
+ ) {
215
+ throw new TypeError(`${label}.document must be a safe project-relative logical path`)
216
+ }
217
+ const key = document.toLowerCase()
218
+ if (documents.has(key))
219
+ throw new Error(`Duplicate logical document path ignoring case: ${document}`)
220
+ documents.add(key)
221
+ const path = resolve(root, document)
222
+ assertInputOutputSeparation(path, settings.outputDirectory)
223
+ return { source: entry.source, document, path, sourceKind: "matra" }
224
+ }
225
+ const namedSources = (entries, label) => {
226
+ if (entries === undefined) return new Map()
227
+ if (!isRecord(entries)) throw new TypeError(`${label} must be an object`)
228
+ const names = new Set()
229
+ return new Map(
230
+ Object.entries(entries).map(([name, entry]) => {
231
+ if (!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(name)) {
232
+ throw new TypeError(`Invalid ${label} name: ${name}`)
233
+ }
234
+ if (names.has(name.toLowerCase())) throw new Error(`Duplicate ${label} name: ${name}`)
235
+ names.add(name.toLowerCase())
236
+ if (!isRecord(entry)) throw new TypeError(`${label}.${name} must be an object`)
237
+ rejectUnknownKeys(entry, new Set(["source", "document"]), `${label}.${name}`)
238
+ return [name, { ...sourceEntry(entry, `${label}/${name}.matra`, `${label}.${name}`), name }]
239
+ }),
240
+ )
241
+ }
242
+ const layouts = namedSources(options.layouts, "layouts")
243
+ selectedLayout(undefined, settings.defaultLayout, layouts, "defaultLayout")
244
+ const components = [...namedSources(options.components, "components").values()]
245
+ if (!Array.isArray(options.pages)) throw new TypeError("pages must be an array")
246
+ const pages = options.pages.map((entry, index) => {
247
+ const label = `pages[${index}]`
248
+ if (!isRecord(entry)) throw new TypeError(`${label} must be an object`)
249
+ rejectUnknownKeys(
250
+ entry,
251
+ new Set(["kind", "route", "source", "layout", "data", "document"]),
252
+ label,
253
+ )
254
+ if (!["matra", "markdown"].includes(entry.kind))
255
+ throw new TypeError(`${label}.kind must be 'matra' or 'markdown'`)
256
+ if (typeof entry.route !== "string") throw new TypeError(`${label}.route must be a string`)
257
+ const controls = siteControls(
258
+ {
259
+ site: {
260
+ ...(Object.hasOwn(entry, "layout") ? { layout: entry.layout } : {}),
261
+ ...(Object.hasOwn(entry, "data") ? { data: entry.data } : {}),
262
+ },
263
+ },
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,
272
+ )
273
+ return {
274
+ ...source,
275
+ kind: entry.kind === "matra" ? "program" : "markdown",
276
+ id: source.document,
277
+ body: entry.source,
278
+ route,
279
+ data: controls.data ?? {},
280
+ layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, source.document),
281
+ }
282
+ })
283
+ sortAndValidateRoutes(pages)
284
+ return { root, settings, layouts, pages, components }
285
+ }
286
+
287
+ function assertInputOutputSeparation(input, output) {
288
+ if (
289
+ input === output ||
290
+ input.startsWith(`${output}${sep}`) ||
291
+ output.startsWith(`${input}${sep}`)
292
+ ) {
293
+ throw new Error("site.output must not overlap a site input directory or logical document")
294
+ }
295
+ }
296
+
91
297
  export async function getSiteProgramDocuments(directory) {
92
298
  const { layouts, pages } = await loadSite(resolve(directory))
93
299
  return [
@@ -103,20 +309,16 @@ async function loadSite(root) {
103
309
  settings.pagesDirectory,
104
310
  ...settings.documentDirectories,
105
311
  settings.layoutsDirectory,
312
+ ...(settings.componentsDirectory ? [settings.componentsDirectory] : []),
106
313
  ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
107
314
  ]) {
108
- if (
109
- input === settings.outputDirectory ||
110
- input.startsWith(`${settings.outputDirectory}${sep}`) ||
111
- settings.outputDirectory.startsWith(`${input}${sep}`)
112
- ) {
113
- throw new Error("site.output must not overlap a site input directory")
114
- }
315
+ assertInputOutputSeparation(input, settings.outputDirectory)
115
316
  }
116
317
  await Promise.all([
117
318
  assertDirectory(root, settings.pagesDirectory),
118
319
  ...settings.documentDirectories.map(path => assertDirectory(root, path)),
119
320
  assertDirectory(root, settings.layoutsDirectory, { optional: true }),
321
+ ...(settings.componentsDirectory ? [assertDirectory(root, settings.componentsDirectory)] : []),
120
322
  ...(settings.assetsDirectory ? [assertDirectory(root, settings.assetsDirectory)] : []),
121
323
  ])
122
324
  const documents = await collectDocuments(root, settings)
@@ -168,6 +370,7 @@ function normalizeSettings(config, root) {
168
370
  "pages",
169
371
  "documents",
170
372
  "layouts",
373
+ "components",
171
374
  "defaultLayout",
172
375
  "output",
173
376
  "format",
@@ -202,6 +405,10 @@ function normalizeSettings(config, root) {
202
405
  ]),
203
406
  ]
204
407
  const layoutsDirectory = resolveDirectory(site.layouts, "layouts", "layouts")
408
+ const componentsDirectory =
409
+ site.components === undefined
410
+ ? undefined
411
+ : resolveDirectory(site.components, "components", site.components)
205
412
  const outputDirectory = resolveDirectory(site.output, "output", "dist")
206
413
  const assetsDirectory =
207
414
  site.assets === undefined ? undefined : resolveDirectory(site.assets, "assets", site.assets)
@@ -226,6 +433,7 @@ function normalizeSettings(config, root) {
226
433
  pagesDirectory,
227
434
  documentDirectories,
228
435
  layoutsDirectory,
436
+ componentsDirectory,
229
437
  outputDirectory,
230
438
  assetsDirectory,
231
439
  defaultLayout: site.defaultLayout === undefined ? false : site.defaultLayout,
@@ -371,6 +579,11 @@ async function collectPages(root, settings, documents, layouts) {
371
579
  layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, path),
372
580
  })
373
581
  }
582
+ sortAndValidateRoutes(pages)
583
+ return pages
584
+ }
585
+
586
+ function sortAndValidateRoutes(pages) {
374
587
  pages.sort((left, right) => left.route.localeCompare(right.route, "en"))
375
588
  const routes = new Set()
376
589
  for (const page of pages) {
@@ -378,7 +591,6 @@ async function collectPages(root, settings, documents, layouts) {
378
591
  if (routes.has(key)) throw new Error(`Duplicate route: ${page.route}`)
379
592
  routes.add(key)
380
593
  }
381
- return pages
382
594
  }
383
595
 
384
596
  function parseFrontMatter(source, path) {
@@ -492,17 +704,22 @@ async function renderPage(page, settings) {
492
704
  const value = await runLiterate(page.bundle, {
493
705
  globals: globalsFor(page, settings, []),
494
706
  moduleRoot: settings.root,
707
+ components: settings.components,
495
708
  })
496
709
  return staticValueToAST(value)
497
710
  }
498
711
 
499
712
  async function renderLayout(layout, content, page, settings) {
500
713
  if (content.tag === "html") {
501
- throw new TypeError(`${page.source}: a complete HTML document cannot be placed inside a layout`)
714
+ throw new TypeError(`${page.path}: a complete HTML document cannot be placed inside a layout`)
502
715
  }
503
716
  const pageContent = content.tag === "$root" ? content.children : [content]
504
717
  const globals = globalsFor(page, settings, pageContent)
505
- const value = await runLiterate(layout.bundle, { globals, moduleRoot: settings.root })
718
+ const value = await runLiterate(layout.bundle, {
719
+ globals,
720
+ moduleRoot: settings.root,
721
+ components: settings.components,
722
+ })
506
723
  return staticValueToAST(value)
507
724
  }
508
725
 
@@ -522,7 +739,9 @@ function globalsFor(page, settings, content) {
522
739
 
523
740
  function resolveMarkdownLink(href, kind, page, settings) {
524
741
  if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/.test(href) || href.startsWith("#")) return href
525
- const [pathname, suffix = ""] = href.split(/(?=[?#])/, 2)
742
+ const suffixStart = href.search(/[?#]/)
743
+ const pathname = suffixStart === -1 ? href : href.slice(0, suffixStart)
744
+ const suffix = suffixStart === -1 ? "" : href.slice(suffixStart)
526
745
  if (!pathname) return href
527
746
  if (pathname.startsWith("/")) {
528
747
  const route = normalizeRoute(pathname, settings.format, page.path)
@@ -545,7 +764,7 @@ function resolveMarkdownLink(href, kind, page, settings) {
545
764
  const assetPath = relative(assetRoot, target).split(sep).join("/")
546
765
  return `/assets/${assetPath}${suffix}`
547
766
  }
548
- if (extname(target) === ".md" || pathname.endsWith(".matra.md")) {
767
+ if (settings.routes.has(target) || extname(target) === ".md" || pathname.endsWith(".matra.md")) {
549
768
  const route = settings.routes.get(target)
550
769
  if (!route) throw new Error(`${page.path}: local Markdown link does not resolve: ${href}`)
551
770
  return `${route}${suffix}`
@@ -807,15 +1026,32 @@ function rejectUnknownKeys(value, allowed, label) {
807
1026
  function assertPlainData(value, label, active = new Set()) {
808
1027
  if (value === null || typeof value === "string" || typeof value === "boolean") return
809
1028
  if (typeof value === "number" && Number.isFinite(value)) return
810
- if (typeof value !== "object" || active.has(value)) {
1029
+ if (typeof value !== "object" || active.has(value) || types.isProxy(value)) {
811
1030
  throw new TypeError(`${label} must contain only finite plain data`)
812
1031
  }
813
1032
  if (!Array.isArray(value) && !isRecord(value)) {
814
1033
  throw new TypeError(`${label} must contain only plain objects and arrays`)
815
1034
  }
1035
+ const descriptors = Object.getOwnPropertyDescriptors(value)
1036
+ const keys = Reflect.ownKeys(descriptors)
1037
+ const array = Array.isArray(value)
1038
+ if (
1039
+ array &&
1040
+ (keys.length !== value.length + 1 ||
1041
+ keys.some(
1042
+ key => key !== "length" && (typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key)),
1043
+ ))
1044
+ ) {
1045
+ throw new TypeError(`${label} must contain dense arrays without extra properties`)
1046
+ }
816
1047
  active.add(value)
817
- for (const item of Array.isArray(value) ? value : Object.values(value)) {
818
- assertPlainData(item, label, active)
1048
+ for (const key of keys) {
1049
+ if (array && key === "length") continue
1050
+ const descriptor = descriptors[key]
1051
+ if (typeof key !== "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) {
1052
+ throw new TypeError(`${label} must contain enumerable string-keyed data properties`)
1053
+ }
1054
+ assertPlainData(descriptor.value, label, active)
819
1055
  }
820
1056
  active.delete(value)
821
1057
  }