@matra/markdown-unified 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/package.json +45 -3
  4. package/src/index.mjs +129 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Matra contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @matra/markdown-unified
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official, optional Markdown preset for `@matra/site-generation` **0.2.x** (CLI **0.3.3**).
4
+ Install the preset **in the site project**, not in the language core or globally alongside the CLI:
5
+
6
+ ```sh
7
+ npm install @matra/markdown-unified@^0.1.0
8
+ ```
9
+
10
+ The global CLI provides the generator: installing this preset alone does not install a second copy.
11
+ For the JavaScript API, also install `@matra/site-generation@^0.2.0` locally.
12
+ In a file-based site, set `site.markdown: unified`. In JavaScript, pass `markdown: "unified"` to
13
+ `generateSite()`, or use the factory to add trusted plugins:
14
+
15
+ ```js
16
+ import { createUnifiedMarkdown } from "@matra/markdown-unified"
17
+ import { generateSite } from "@matra/site-generation"
18
+
19
+ await generateSite({
20
+ markdown: createUnifiedMarkdown(),
21
+ layouts: { post: { source: "html { head { title { page.data.title } }; body { article.matra-prose { ...page.content } } }" } },
22
+ defaultLayout: "post",
23
+ pages: [{
24
+ kind: "markdown", document: "posts/first.md", route: "/first/",
25
+ source: "---\ntitle: First post\n---\n## Energy\n\nThe equation is $E=mc^2$.",
26
+ }],
27
+ })
28
+ ```
29
+
30
+ The site engine reads optional YAML frontmatter. The preset adds GFM (including tables, task lists
31
+ and strikethrough), inline and display math as MathML (no client JS or KaTeX stylesheet), and heading IDs.
32
+ `page.data.toc` is an ordered list of `{ depth, title, id, href }` for `h1`–`h6`.
33
+ Heading IDs support Unicode, distinguish duplicate titles and preserve IDs assigned by plugins.
34
+ `page.data.excerpt` is the first top-level paragraph as text, or the paragraphs preceding a standalone
35
+ `<!--more-->`. Whitespace is collapsed; after 180 Unicode code points an ellipsis is appended.
36
+ These fields are also available on `site.documents` entries as `metadata.toc` and `metadata.excerpt`.
37
+
38
+ The hook returns document nodes, **not HTML**. Source HTML is escaped as text; code fences are not
39
+ executed. Plugins are trusted build-time JavaScript, not a way to turn on arbitrary article HTML.
40
+ Pass unified plugin lists as `remarkPlugins` (Markdown tree) or `rehypePlugins` (HTML tree).
41
+ The VFile has the logical article path and `file.data.metadata`. Plugin diagnostics fail the build.
42
+
43
+ For example, a site can allow **one specific embed** by replacing a standalone link in a rehype plugin:
44
+
45
+ ```js
46
+ function featuredDemo() {
47
+ const allowed = "https://video.example/embed/introduction"
48
+ return tree => {
49
+ for (const paragraph of tree.children) {
50
+ const link = paragraph.children?.[0]
51
+ if (paragraph.tagName !== "p" || paragraph.children.length !== 1 ||
52
+ link?.tagName !== "a" || link.properties.href !== allowed) continue
53
+ paragraph.children = [{
54
+ type: "element", tagName: "iframe", position: link.position, children: [],
55
+ properties: { src: allowed, title: "Introduction", loading: "lazy", sandbox: "" },
56
+ }]
57
+ }
58
+ }
59
+ }
60
+
61
+ const markdown = createUnifiedMarkdown({ rehypePlugins: [featuredDemo] })
62
+ ```
63
+
64
+ Keep original node positions when replacing links or images. Matra resolves their URLs after **all**
65
+ plugins and reports the original filename and line. Legacy cards, embeds, ads and analytics remain
66
+ site-specific. See the [site contract](../../spec/site-generation.md) / [日本語](../../spec/site-generation.ja.md).
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@matra/markdown-unified",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Official unified Markdown preset for Matra site generation",
5
+ "type": "module",
6
+ "exports": "./src/index.mjs",
7
+ "files": [
8
+ "src"
9
+ ],
10
+ "dependencies": {
11
+ "github-slugger": "^2.0.0",
12
+ "mdast-util-to-string": "^4.0.0",
13
+ "property-information": "^7.2.0",
14
+ "rehype-katex": "^7.0.1",
15
+ "remark-gfm": "^4.0.1",
16
+ "remark-math": "^6.0.0",
17
+ "remark-parse": "^11.0.0",
18
+ "remark-rehype": "^11.1.2",
19
+ "unified": "^11.0.5",
20
+ "vfile": "^6.0.3"
21
+ },
22
+ "devDependencies": {
23
+ "@matra/site-generation": "^0.2.0"
24
+ },
25
+ "peerDependencies": {
26
+ "@matra/site-generation": "^0.2.0"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "@matra/site-generation": {
30
+ "optional": true
31
+ }
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/matralang/matra.git",
36
+ "directory": "packages/markdown-unified"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "registry": "https://registry.npmjs.org"
41
+ },
42
+ "license": "MIT",
43
+ "scripts": {
44
+ "build": "node --check src/index.mjs",
45
+ "check": "pnpm run build",
46
+ "test": "node --test"
47
+ }
6
48
  }
package/src/index.mjs ADDED
@@ -0,0 +1,129 @@
1
+ import GithubSlugger, { slug } from "github-slugger"
2
+ import { toString as textContent } from "mdast-util-to-string"
3
+ import { find, html, svg } from "property-information"
4
+ import rehypeKatex from "rehype-katex"
5
+ import remarkGfm from "remark-gfm"
6
+ import remarkMath from "remark-math"
7
+ import remarkParse from "remark-parse"
8
+ import remarkRehype from "remark-rehype"
9
+ import { unified } from "unified"
10
+ import { VFile } from "vfile"
11
+
12
+ function articleExcerpt() {
13
+ return (tree, file) => {
14
+ const more = tree.children.findIndex(
15
+ node => node.type === "html" && node.value.trim() === "<!--more-->",
16
+ )
17
+ const paragraphs = tree.children
18
+ .slice(0, more === -1 ? undefined : more)
19
+ .filter(node => node.type === "paragraph")
20
+ const intro = (more === -1 ? paragraphs.slice(0, 1) : paragraphs)
21
+ .map(node => textContent(node, { includeHtml: false }))
22
+ .join(" ")
23
+ .replace(/\s+/g, " ")
24
+ .trim()
25
+ if (more !== -1) tree.children.splice(more, 1)
26
+ const characters = [...intro]
27
+ file.data.excerpt = characters.length > 180 ? `${characters.slice(0, 180).join("")}…` : intro
28
+ }
29
+ }
30
+
31
+ function headingText(node) {
32
+ if (node.type === "text") return node.value
33
+ if (node.tagName === "img") return node.properties.alt ?? ""
34
+ if (node.tagName === "semantics") {
35
+ const tex = node.children.find(
36
+ child => child.tagName === "annotation" && child.properties.encoding === "application/x-tex",
37
+ )
38
+ if (tex) return textContent(tex)
39
+ }
40
+ return node.children?.map(headingText).join("") ?? ""
41
+ }
42
+
43
+ function articleHeadings(tree, file) {
44
+ const slugger = new GithubSlugger()
45
+ const reserved = new Map()
46
+ const headings = []
47
+ function collect(node) {
48
+ if (node.type === "element") {
49
+ const id = String(node.properties.id ?? "")
50
+ if (id) reserved.set(id, (reserved.get(id) ?? 0) + 1)
51
+ if (/^h[1-6]$/.test(node.tagName)) headings.push(node)
52
+ }
53
+ node.children?.forEach(collect)
54
+ }
55
+ collect(tree)
56
+ return headings.map(node => {
57
+ const title = headingText(node).trim()
58
+ let id = String(node.properties.id ?? "")
59
+ if (id && reserved.get(id) > 1) file.fail(`Duplicate heading ID: ${id}`, node.position)
60
+ if (!id) {
61
+ const base = slug(title) || "section"
62
+ do {
63
+ id = slugger.slug(base)
64
+ } while (reserved.has(id))
65
+ node.properties.id = id
66
+ }
67
+ return { depth: Number(node.tagName[1]), title, id, href: `#${id}` }
68
+ })
69
+ }
70
+
71
+ function toNodes(children, schema = html) {
72
+ return children.flatMap(child => {
73
+ if (child.type === "text") return [child.value]
74
+ if (child.type === "comment") return []
75
+ if (child.type !== "element")
76
+ throw new TypeError(`Unsupported Markdown output node: ${child.type}`)
77
+ const tag = child.tagName
78
+ const namespace = tag === "svg" ? svg : schema
79
+ const props = Object.fromEntries(
80
+ Object.entries(child.properties).map(([name, value]) => {
81
+ const info = find(namespace, name)
82
+ return [
83
+ info.attribute,
84
+ Array.isArray(value) ? value.join(info.commaSeparated ? ", " : " ") : value,
85
+ ]
86
+ }),
87
+ )
88
+ return [
89
+ {
90
+ tag,
91
+ props,
92
+ children: toNodes(child.children, tag === "foreignObject" ? html : namespace),
93
+ ...(child.position ? { position: child.position } : {}),
94
+ },
95
+ ]
96
+ })
97
+ }
98
+
99
+ export function createUnifiedMarkdown({ remarkPlugins = [], rehypePlugins = [] } = {}) {
100
+ const processor = unified()
101
+ .use(remarkParse)
102
+ .use(remarkGfm)
103
+ .use(remarkMath)
104
+ .use(remarkPlugins)
105
+ .use(articleExcerpt)
106
+ .use(remarkRehype, {
107
+ handlers: {
108
+ html: (_state, node) => ({ type: "text", value: node.value, position: node.position }),
109
+ },
110
+ })
111
+ .use(rehypeKatex, { output: "mathml", trust: false })
112
+ .use(rehypePlugins)
113
+ .freeze()
114
+ return async ({ body, document, metadata }) => {
115
+ const file = new VFile({ path: document, value: body, data: { metadata } })
116
+ const tree = await processor.run(processor.parse(file), file)
117
+ const [diagnostic] = file.messages
118
+ if (diagnostic) {
119
+ const place =
120
+ diagnostic.place ?? diagnostic.ancestors?.findLast(node => node.position)?.position
121
+ file.fail(
122
+ diagnostic.cause ? `${diagnostic.reason}: ${diagnostic.cause.message}` : diagnostic.reason,
123
+ { place, cause: diagnostic },
124
+ )
125
+ }
126
+ const toc = articleHeadings(tree, file)
127
+ return { content: toNodes(tree.children), data: { toc, excerpt: file.data.excerpt } }
128
+ }
129
+ }