@headwall/markdown-to-blocks 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.0.0] - 2026-06-28
11
+
12
+ First stable release. Output is validated against WordPress core's own block
13
+ parser and confirmed to import into the block editor with no recovery prompts.
14
+
15
+ ### Added
16
+
17
+ - `markdownToBlocks(markdown, options?)` — convert Markdown to a single
18
+ serialised core-block markup string.
19
+ - `markdownToBlockList(markdown, options?)` — convert to one string per
20
+ top-level block.
21
+ - `parseMarkdownDocument(markdown, options?)` — strip YAML frontmatter and
22
+ convert only the body, returning `{ frontmatter, blocks }`.
23
+ - Block coverage: paragraph, heading, code, list (incl. nesting), quote,
24
+ separator, table (GFM), image, and raw-HTML fallback (`core/html`).
25
+ - Inline coverage: bold, italic, inline code, strikethrough, links, hard line
26
+ breaks, and GFM task-list glyphs (`☐` / `☑`).
27
+ - `ConvertOptions`: `headingShift`, `minHeadingLevel`, `resolveImage`,
28
+ `codeLanguage`, `unsupported`, `gfm`.
29
+ - Resolver-driven images via `resolveImage`, with an external-image fallback
30
+ when no attachment id is supplied.
31
+ - `md2blocks` CLI: `-i/--input`, `-o/--output`, bare-filename input, stdin
32
+ (`-`), `--frontmatter` JSON mode, and conversion flags
33
+ (`--heading-shift`, `--min-heading-level`, `--code-language`,
34
+ `--unsupported`, `--no-gfm`).
35
+ - WordPress validation harness (`@wordpress/blocks` + `@wordpress/block-library`
36
+ under jsdom, dev-only) asserting every fixture's output is `isValid`.
37
+
38
+ ### Notes
39
+
40
+ - ESM-only. Requires Node ≥ 18.
41
+ - Zero runtime dependencies — all bundled into the published package.
42
+
43
+ [Unreleased]: https://github.com/headwalluk/markdown-to-blocks/compare/v1.0.0...HEAD
44
+ [1.0.0]: https://github.com/headwalluk/markdown-to-blocks/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Faulkner
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 ADDED
@@ -0,0 +1,260 @@
1
+ # markdown-to-blocks
2
+
3
+ > Convert Markdown into serialised WordPress/Gutenberg **block markup** — HTML with `<!-- wp:… -->` delimiters that drops straight into the block editor with no "Convert to blocks" or "this block contains unexpected content" prompts.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@headwall/markdown-to-blocks.svg)](https://www.npmjs.com/package/@headwall/markdown-to-blocks)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@headwall/markdown-to-blocks.svg)](https://www.npmjs.com/package/@headwall/markdown-to-blocks)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
8
+ [![Node.js](https://img.shields.io/node/v/@headwall/markdown-to-blocks.svg)](https://nodejs.org)
9
+ [![Types](https://img.shields.io/npm/types/@headwall/markdown-to-blocks.svg)](https://www.typescriptlang.org/)
10
+
11
+ `markdown-to-blocks` turns a Markdown string into **core-block** markup that WordPress parses into discrete native blocks. It was built so an AI agent (or any script) can read Markdown and `POST` reliable Gutenberg content to WordPress via the REST API — no browser, no `@wordpress/*` runtime dependency, no DOM.
12
+
13
+ - **Validated against core.** Every supported block is checked against WordPress's own block parser in the test suite, so the output validates first time.
14
+ - **Pure & deterministic.** The converter touches no network, filesystem, or global state. Same input → same output. All I/O lives in the CLI.
15
+ - **Zero runtime dependencies.** Everything is bundled into the published package.
16
+ - **Library + CLI.** Import it, or shell out to `md2blocks`.
17
+
18
+ ---
19
+
20
+ ## Installation
21
+
22
+ ### As a CLI (global)
23
+
24
+ ```bash
25
+ npm install -g @headwall/markdown-to-blocks
26
+ ```
27
+
28
+ This puts the `md2blocks` command on your `PATH`. Requires **Node ≥ 18**.
29
+
30
+ ### As a library
31
+
32
+ ```bash
33
+ npm install @headwall/markdown-to-blocks
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Quick start
39
+
40
+ ### Command line
41
+
42
+ ```bash
43
+ # Convert a file to block markup
44
+ md2blocks -i BLOG-POST.md -o blog-post.html
45
+
46
+ # Or write to stdout and redirect
47
+ md2blocks -i BLOG-POST.md > blog-post.html
48
+
49
+ # Or pipe via stdin
50
+ cat BLOG-POST.md | md2blocks - > blog-post.html
51
+ ```
52
+
53
+ ### Library
54
+
55
+ ```ts
56
+ import { markdownToBlocks } from "@headwall/markdown-to-blocks";
57
+
58
+ const html = markdownToBlocks("# Hello\n\nThis is **bold**.");
59
+ // <!-- wp:heading -->
60
+ // <h2 class="wp-block-heading">Hello</h2>
61
+ // <!-- /wp:heading -->
62
+ //
63
+ // <!-- wp:paragraph -->
64
+ // <p>This is <strong>bold</strong>.</p>
65
+ // <!-- /wp:paragraph -->
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Posting to WordPress
71
+
72
+ The converter produces the `content` field; your script owns the REST call. A minimal example using the REST API with an [application password](https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/) and [`jq`](https://jqlang.github.io/jq/):
73
+
74
+ ```bash
75
+ # Pull title/slug from frontmatter and the body as blocks in one shot
76
+ DOC=$(md2blocks -i post.md --frontmatter)
77
+ TITLE=$(printf '%s' "$DOC" | jq -r '.frontmatter.title')
78
+ CONTENT=$(printf '%s' "$DOC" | jq -r '.blocks')
79
+
80
+ curl -s -X POST "https://example.com/wp-json/wp/v2/posts" \
81
+ -u "USERNAME:APPLICATION_PASSWORD" \
82
+ -H "Content-Type: application/json" \
83
+ -d "$(jq -n --arg t "$TITLE" --arg c "$CONTENT" \
84
+ '{title: $t, status: "draft", content: $c}')"
85
+ ```
86
+
87
+ ---
88
+
89
+ ## CLI reference
90
+
91
+ ```
92
+ md2blocks [options]
93
+
94
+ Input/output:
95
+ -i, --input <file> Input Markdown file (use "-" or omit for stdin)
96
+ -o, --output <file> Output file (default: stdout)
97
+ md2blocks <file.md> A bare filename is treated as --input
98
+
99
+ Modes:
100
+ --frontmatter Emit JSON { frontmatter, blocks } instead of markup
101
+
102
+ Conversion options:
103
+ --heading-shift <n> Shift all heading levels by n (default 0)
104
+ --min-heading-level <n> Clamp heading levels to [n, 6] (default 2)
105
+ --code-language <mode> 'drop' (default) or 'class' (emit language-xxx)
106
+ --unsupported <mode> 'html' (default, wrap in core/html) or 'skip'
107
+ --no-gfm Disable GFM (tables, strikethrough, autolinks)
108
+
109
+ -h, --help Show help
110
+ -v, --version Show version
111
+ ```
112
+
113
+ Examples:
114
+
115
+ ```bash
116
+ # Docs that open with a single "#" title — shift so "#" → h2, never body h1
117
+ md2blocks -i README.md --heading-shift 1 -o readme.html
118
+
119
+ # Keep code-fence languages as language-xxx classes for a highlighter plugin
120
+ md2blocks -i snippet.md --code-language class
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Library API
126
+
127
+ All functions are pure and synchronous.
128
+
129
+ ### `markdownToBlocks(markdown, options?) → string`
130
+
131
+ Convert Markdown to a single serialised block-markup string (blocks joined by a blank line, matching WordPress's own spacing).
132
+
133
+ ### `markdownToBlockList(markdown, options?) → string[]`
134
+
135
+ Same conversion, but returns one string per top-level block — handy if you want to compose or post blocks individually.
136
+
137
+ ### `parseMarkdownDocument(markdown, options?) → { frontmatter, blocks }`
138
+
139
+ Strip YAML frontmatter off the top of the document and convert only the body. Use the returned `frontmatter` to populate REST fields (title, slug, date…); those must never appear in `post_content`.
140
+
141
+ ```ts
142
+ import { parseMarkdownDocument } from "@headwall/markdown-to-blocks";
143
+
144
+ const { frontmatter, blocks } = parseMarkdownDocument(`---
145
+ title: Hello World
146
+ slug: hello-world
147
+ ---
148
+
149
+ # Intro
150
+
151
+ Body text.
152
+ `);
153
+
154
+ // frontmatter → { title: "Hello World", slug: "hello-world" }
155
+ // blocks → "<!-- wp:heading -->\n<h2 …>Intro</h2>\n…"
156
+ ```
157
+
158
+ ### `ConvertOptions`
159
+
160
+ | Option | Type | Default | Description |
161
+ |---|---|---|---|
162
+ | `headingShift` | `number` | `0` | Shift every heading level by this amount before clamping. |
163
+ | `minHeadingLevel` | `number` | `2` | Clamp resulting heading levels into `[min, 6]`. The default of `2` keeps body content from emitting an `h1`. |
164
+ | `resolveImage` | `(src, alt, title?) => ResolvedImage \| undefined` | — | Resolve a Markdown image to a WordPress image (see [Images](#images)). |
165
+ | `codeLanguage` | `'drop' \| 'class'` | `'drop'` | `'drop'` discards the fence language (core behaviour). `'class'` emits `<code class="language-xxx">` for a syntax-highlighting plugin. |
166
+ | `unsupported` | `'html' \| 'skip'` | `'html'` | How to handle raw/unsupported nodes: wrap in `core/html`, or omit. |
167
+ | `gfm` | `boolean` | `true` | Enable GFM (tables, strikethrough, autolinks). |
168
+
169
+ ### `ResolvedImage`
170
+
171
+ ```ts
172
+ interface ResolvedImage {
173
+ url: string;
174
+ alt?: string;
175
+ id?: number; // WordPress attachment ID → enables wp-image-{id} + size class
176
+ sizeSlug?: string; // e.g. 'large', 'full'; only used when id is present
177
+ caption?: string;
178
+ }
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Images
184
+
185
+ The converter never touches the network, so it can't upload media. Instead, your agent uploads each image to the media library (REST `wp/v2/media`) and supplies a `resolveImage` callback:
186
+
187
+ ```ts
188
+ import { markdownToBlocks } from "@headwall/markdown-to-blocks";
189
+
190
+ const html = markdownToBlocks(markdown, {
191
+ resolveImage(src, alt) {
192
+ const media = mediaMap.get(src); // your upload bookkeeping
193
+ if (!media) return undefined; // → external <img> fallback
194
+ return { url: media.url, id: media.id, sizeSlug: "large", alt };
195
+ },
196
+ });
197
+ ```
198
+
199
+ - When `resolveImage` returns an object **with an `id`**, you get the attachment shape: `wp:image {"id":…,"sizeSlug":…,"linkDestination":"none"}`, a `size-<slug>` figure class, and a `wp-image-<id>` class on the `<img>`.
200
+ - When it returns `undefined`, you get the **external** fallback: a plain `<figure class="wp-block-image">` / `<img>` with no attachment id.
201
+
202
+ ---
203
+
204
+ ## Heading policy (avoid duplicate titles)
205
+
206
+ Docs often open with a single `#` title *and* carry that same title in frontmatter. If you send the frontmatter `title` to WordPress **and** leave the `#` in the body, the title appears twice. Pick one:
207
+
208
+ - **Let frontmatter own the title** and don't repeat it as an in-body heading. Simplest.
209
+ - **Keep a `#` title in the body** and convert with `headingShift: 1` (`--heading-shift 1`), so the `#` becomes `h2` and your real sections shift down accordingly.
210
+
211
+ By default `headingShift` is `0` and `minHeadingLevel` is `2`, so a body `#` becomes `h2` (never `h1`).
212
+
213
+ ---
214
+
215
+ ## Supported Markdown
216
+
217
+ | Markdown | Result |
218
+ |---|---|
219
+ | Paragraphs | `core/paragraph` |
220
+ | Headings `#`–`######` | `core/heading` (shift + clamp applied) |
221
+ | Fenced / indented code | `core/code` |
222
+ | Unordered / ordered lists, nested | `core/list` + `core/list-item` |
223
+ | Blockquotes | `core/quote` (with inner paragraph blocks) |
224
+ | Thematic breaks `---` `***` `___` | `core/separator` |
225
+ | Tables (GFM) | `core/table` |
226
+ | Images | `core/image` (resolver-driven) |
227
+ | Raw HTML in source | `core/html` |
228
+ | **bold**, *italic*, `code`, ~~strike~~, links, hard breaks | inline HTML |
229
+ | GFM task lists | leading `☐` / `☑` glyph (not interactive inputs) |
230
+
231
+ ### Limitations
232
+
233
+ - **No syntax highlighting** — core `core/code` has none. Use `codeLanguage: 'class'` plus a highlighter plugin if you need it.
234
+ - **No per-column table alignment** yet.
235
+ - **No interactive task-list checkboxes** — a glyph is rendered instead.
236
+ - **No media uploads** — your agent uploads and feeds results via `resolveImage`.
237
+ - **No block-theme / Site Editor constructs** (columns, groups, cover, etc.). Core content blocks only.
238
+
239
+ ---
240
+
241
+ ## How validation works
242
+
243
+ WordPress marks a block "invalid" when the saved markup doesn't match what the block's `save()` function would produce — that's what triggers the editor's recovery prompts. This library's test suite parses every fixture's output through WordPress's own parser (`@wordpress/blocks` + `@wordpress/block-library`, a dev-only dependency) and asserts every block reports `isValid` with zero validation issues. So "validates first time" is verified empirically, not by eye.
244
+
245
+ ---
246
+
247
+ ## Development
248
+
249
+ ```bash
250
+ npm install
251
+ npm run build # tsup → dist/ (ESM + .d.ts), deps bundled in
252
+ npm test # vitest: unit + golden fixtures + WP validation harness
253
+ npm run typecheck # tsc --noEmit
254
+ ```
255
+
256
+ ---
257
+
258
+ ## License
259
+
260
+ [MIT](./LICENSE) © Paul Faulkner