feat(slug): a slug policy seam — two live sites need different anchors (v0.2.4) (#26)

kivvi publishes `Geschäftsmodell` as `#das-geschaeftsmodell` (ASCII, ä→ae);
evig publishes `Kanäle` as `#ein-eingang-vier-kanäle` (unicode preserved, 8
locales). Both are correct for their site, so neither can be "the" behavior.
evig had to write its own re-slugging pass to get the second, because the
ASCII slugger would have renamed every published non-Latin anchor.

So the default does not move — a regression pin asserts today's outputs
byte-for-byte, including the German ä→ae case — and a policy is now an
option instead:

  parseContentBlocks(body, { slugify: unicodeSlugify })
  extractToc(blocks,   { slugify: unicodeSlugify })

`unicodeSlugify` ships ready-made (lowercase, punctuation stripped, letters
/numbers/marks of any script kept), verified byte-identical to evig's local
pass over all 725 headings in its 101 published post files. Any
`(text: string) => string` works as a third policy; de-duplication and the
`section` fallback are applied on top, so consumers compose rather than
reimplement.

Both callers now derive ids through the one `createSlugger`, deleting
extractToc's duplicate dedup loop: a heading's id and the TOC entry linking
to it are the same anchor and can no longer drift — the exact bug evig's
migration had to work around.

README also corrects two things real adopters hit: the slug policy is
documented with a warning that changing it on a published site renames every
anchor, and `parseFrontmatter` is now plainly described as a `key: value`
scanner rather than a YAML parser — quoted titles containing colons,
booleans, numbers and nesting need gray-matter, which is what kivvi keeps it
for. No YAML parser is being rewritten here.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
CatoandClaude Opus 5 authored and GitHub committed 2026-09-08 10:28:00 +00:00
1 parent 2610796dbb
commit e73a3c4f4b
8 files changed
+344 -24

No files matched your search

+56 -2
View File
@@ -73,7 +73,7 @@ One syntax example per block. Everything the v0.1 parser understood still parses
#### Detail → h4
```
Headings carry a slugified, de-duplicated, umlaut-aware `id` (`## Über uns` → `ueber-uns`) — anchors and TOC for free.
Headings carry a slugified, de-duplicated `id` (`## Über uns` → `ueber-uns`) — anchors and TOC for free. Which slug you get is a [policy you choose](#slug-policy).
### Paragraphs & inline markup — `p`
@@ -235,7 +235,27 @@ authors:
---
```
`parseFrontmatter` is still dependency-free `key: value` parsing — v0.2 adds inline `[a, b]` arrays and block `- item` lists. Scalar values parse exactly as before.
**`parseFrontmatter` is a `key: value` scanner, not a YAML parser.** It is dependency-free on purpose and handles exactly three shapes: scalar `key: value`, inline `key: [a, b]`, and block `- item` lists. Every value comes back as a `string` or `string[]` — nothing else.
It will get real YAML wrong, quietly:
```md
title: "Bitcoin: a peer-to-peer system" → "Bitcoin" ← splits on the FIRST colon
draft: true → "true" ← the string, not a boolean
order: 3 → "3" ← the string, not a number
author: ← nesting is not supported
name: Mao
```
If your frontmatter has quoted strings containing colons, booleans, numbers, dates, or nesting, use a real YAML parser — [`gray-matter`](https://www.npmjs.com/package/gray-matter) is what kivvi keeps in front of bip-kit for exactly this — and hand the `body` it returns to `parseContentBlocks`:
```ts
import matter from "gray-matter";
const { data: meta, content: body } = matter(raw);
const blocks = parseContentBlocks(body);
```
bip-kit will not grow a YAML parser; one already exists.
## Helpers
@@ -246,6 +266,40 @@ parseInline(text); // → Inline[] (the inline parser, standal
slugify("Über uns"); // → "ueber-uns"
```
## Slug policy
A slug policy is your site's **anchor contract**. `## Das Geschäftsmodell` becomes `<h2 id="…">`, and that id is the `#anchor` in every link anyone has ever shared to that section.
> [!WARNING]
> **Changing the policy on a published site renames every anchor.** Inbound links, bookmarks, and cross-post references to `#…` break silently — nothing 404s, readers just land at the top of the page. Choose a policy once, before you publish; treat a later change as a URL migration needing redirects.
Because of that, bip-kit's default never moves. Two policies ship:
| Policy | `Geschäftsmodell` → | `日本語` → | For |
| ----------------------- | ------------------- | ----------- | ----------------------------------------------- |
| `slugify` **(default)** | `geschaeftsmodell` | `section` | ASCII anchors; German transliteration (ä→ae, ß→ss) |
| `unicodeSlugify` | `geschäftsmodell` | `日本語` | Multilingual sites keeping non-Latin anchors |
Non-Latin headings have no ASCII spelling, so under the default they strip to nothing and fall back to `section`, `section-2`, … That is the reason `unicodeSlugify` exists.
Pass a policy through the `slugify` option — **to both calls**, since an id and the TOC link pointing at it are the same anchor:
```ts
import { parseContentBlocks, extractToc, unicodeSlugify } from "bip-kit";
const options = { slugify: unicodeSlugify };
const blocks = parseContentBlocks(body, options);
const toc = extractToc(blocks, options); // same policy, or the two drift apart
```
Any `SlugFn` (`(text: string) => string`) works, so you can compose rather than reimplement — de-duplication (`slug`, `slug-2`, …) and the `section` fallback for empty results are applied on top of whatever you return:
```ts
import { slugify, type SlugFn } from "bip-kit";
const prefixed: SlugFn = (text) => `sec-${slugify(text)}`;
```
## The renderer — `bip-kit/react`
Server components (RSC-first): `ArticleBody` (the one you usually need — an **async** server component that pre-awaits shiki/katex and emits a fully synchronous tree), plus `Figure`, `Gallery`, `Callout`, `PullQuote`, `Stats`, `Footnotes`, `CodeBlock`, `Chart`, `TableBlock`, `VideoEmbed`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bip-kit",
"version": "0.2.3",
"version": "0.2.4",
"description": "Building in Public, as a content contract: parse markdown into typed blocks and render them with a reference React renderer (bip-kit/react) \u2014 blog, roadmap, changelog on your product site, bring your own design tokens.",
"license": "MIT",
"author": "Mao Nakamoto",
+2 -1
View File
@@ -14,10 +14,11 @@ export type {
export type { Inline } from "./inline.js";
export type { ChartSpec, ChartSeries } from "./chart.js";
export type { SlugFn, SlugOptions } from "./slug.js";
export { parseContentBlocks, parseFrontmatter } from "./parse-content.js";
export { parseInline, inlineToText } from "./inline.js";
export { parseChartSpec, validateChartSpec } from "./chart.js";
export { slugify, createSlugger } from "./slug.js";
export { slugify, unicodeSlugify, createSlugger } from "./slug.js";
export { extractToc, readingTime } from "./toc.js";
export { parseVideoEmbed, videoEmbedSrc } from "./video-embed.js";
+7 -3
View File
@@ -1,7 +1,7 @@
import type { CalloutKind, ContentBlock } from "./types.js";
import { parseInline } from "./inline.js";
import { parseChartSpec } from "./chart.js";
import { createSlugger } from "./slug.js";
import { createSlugger, type SlugOptions } from "./slug.js";
/**
* Parse repo-authored markdown into typed blocks.
@@ -41,8 +41,12 @@ const CALLOUT_KINDS: Record<string, CalloutKind> = {
DANGER: "danger",
};
export function parseContentBlocks(body: string): ContentBlock[] {
const slug = createSlugger();
/**
* @param options.slugify Heading-id policy (default: ASCII `slugify`).
* Pass the SAME policy to `extractToc` — see `SlugOptions`.
*/
export function parseContentBlocks(body: string, options: SlugOptions = {}): ContentBlock[] {
const slug = createSlugger(options.slugify);
return parseBlocks(body.replace(/\r\n/g, "\n").split("\n"), slug);
}
+63 -5
View File
@@ -1,8 +1,36 @@
/**
* Heading slugs — umlaut-aware (ä→ae …), lowercase, hyphenated.
* Ported from kivvi's slugifyHeading, which the fleet already trusts.
* Heading slug policies.
*
* A slug policy is the anchor contract of a published site: change it and
* every `#anchor` URL already linked from the outside breaks. bip-kit
* therefore never changes its default — it lets a consumer supply its own.
*
* Two policies ship, and both are correct for the site that chose them:
*
* - `slugify` (the DEFAULT) transliterates to ASCII — `Geschäftsmodell` →
* `geschaeftsmodell`. Ported from kivvi's slugifyHeading, which the fleet
* already publishes against.
* - `unicodeSlugify` preserves letters of any script — `Kanäle` → `kanäle`,
* `日本語` → `日本語`. For multilingual sites whose non-Latin headings
* would otherwise collapse to nothing.
*
* Anything matching `SlugFn` works as a third policy; pass it through the
* `slugify` option on `parseContentBlocks` / `extractToc`.
*/
/** A heading-id policy: heading text in, slug out (may be empty). */
export type SlugFn = (text: string) => string;
/** Options for the helpers that assign heading ids. */
export interface SlugOptions {
/**
* Slug policy for heading ids. Defaults to `slugify` (ASCII).
* The same policy MUST be used for parsing and for the TOC, or the anchor
* a heading carries and the anchor the TOC links to drift apart.
*/
slugify?: SlugFn;
}
const UMLAUTS: Record<string, string> = {
ä: "ae",
ö: "oe",
@@ -12,6 +40,11 @@ const UMLAUTS: Record<string, string> = {
Ü: "ue",
};
/**
* The default policy: umlaut-aware (ä→ae …), lowercase, hyphenated, ASCII.
* Non-Latin scripts have no ASCII spelling and drop out entirely — use
* `unicodeSlugify` if that matters to your content.
*/
export function slugify(text: string): string {
return text
.toLowerCase()
@@ -22,12 +55,37 @@ export function slugify(text: string): string {
}
/**
* A per-document slugger: same heading text twice → `slug`, `slug-2`, `slug-3`.
* Unicode-preserving policy: lowercase, drop punctuation and symbols,
* collapse the rest to single hyphens, and keep letters, numbers and
* combining marks of ANY script.
*
* "Ein Eingang, vier Kanäle" → "ein-eingang-vier-kanäle"
* "日本語のはなし" → "日本語のはなし"
*
* Not the default: adopting it on a site already published under `slugify`
* renames every anchor.
*/
export function createSlugger(): (text: string) => string {
export function unicodeSlugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\p{L}\p{N}\p{M}]+/gu, "-")
.replace(/^-+|-+$/g, "");
}
/**
* A per-document slugger over a policy: same heading text twice → `slug`,
* `slug-2`, `slug-3`. A heading whose text is empty after the policy strips
* it (`"!!!"`, or a non-Latin heading under the ASCII policy) still gets a
* usable id — `section`, `section-2`, …
*
* This is the ONE place ids are assigned; `parseContentBlocks` and
* `extractToc` both go through it so a heading's id and its TOC entry can
* never disagree.
*/
export function createSlugger(slug: SlugFn = slugify): SlugFn {
const seen = new Map<string, number>();
return (text: string) => {
const base = slugify(text) || "section";
const base = slug(text) || "section";
const n = (seen.get(base) ?? 0) + 1;
seen.set(base, n);
return n === 1 ? base : `${base}-${n}`;
+10 -12
View File
@@ -1,23 +1,21 @@
import type { ContentBlock, TocEntry, ReadingTimeResult } from "./types.js";
import { slugify } from "./slug.js";
import { createSlugger, type SlugOptions } from "./slug.js";
/**
* Table of contents from parsed blocks. Headings parsed by v0.2 carry ids;
* for hand-built blocks without one, a slug is derived from the text
* (per-call de-duplication, same scheme as the parser).
* for hand-built blocks without one, a slug is derived from the text through
* the same slugger the parser uses (per-call de-duplication).
*
* @param options.slugify Heading-id policy (default: ASCII `slugify`). Pass
* whatever you passed to `parseContentBlocks`: an id and its TOC link are
* the same anchor, so they must come from one policy.
*/
export function extractToc(blocks: ContentBlock[]): TocEntry[] {
const seen = new Map<string, number>();
export function extractToc(blocks: ContentBlock[], options: SlugOptions = {}): TocEntry[] {
const slug = createSlugger(options.slugify);
const entries: TocEntry[] = [];
for (const block of blocks) {
if (block.type !== "h2" && block.type !== "h3" && block.type !== "h4") continue;
let id = block.id;
if (!id) {
const base = slugify(block.text) || "section";
const n = (seen.get(base) ?? 0) + 1;
seen.set(base, n);
id = n === 1 ? base : `${base}-${n}`;
}
const id = block.id || slug(block.text);
entries.push({
id,
text: block.text,
+1
View File
@@ -33,6 +33,7 @@ const PUBLIC_API = [
"parseInline",
"parseChartSpec",
"slugify",
"unicodeSlugify",
"createSlugger",
"extractToc",
"readingTime",
+204
View File
@@ -0,0 +1,204 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
parseContentBlocks,
extractToc,
slugify,
unicodeSlugify,
createSlugger,
} from "../dist/index.js";
// ── regression pin: the DEFAULT policy must never move ───────────────────────
//
// Two live sites publish anchors against the outputs below. A change here is
// not a refactor, it is every inbound link to those pages breaking. If a diff
// makes this file fail, the fix is a slug OPTION, not a new default.
test("default slugify is byte-for-byte what published sites already link to", () => {
// kivvi's pinned German case — ä→ae, ß→ss transliteration.
assert.equal(slugify("Geschäftsmodell"), "geschaeftsmodell");
assert.equal(slugify("Das Geschäftsmodell"), "das-geschaeftsmodell");
assert.equal(slugify("Über die Straße"), "ueber-die-strasse");
assert.equal(slugify("Kanäle"), "kanaele");
assert.equal(slugify("Ö und Ü"), "oe-und-ue");
// Plain ASCII, punctuation, edges.
assert.equal(slugify("Hello World!"), "hello-world");
assert.equal(slugify("What's next?"), "what-s-next");
assert.equal(slugify(" --- "), "");
assert.equal(slugify("v0.2.4 — release"), "v0-2-4-release");
// Non-Latin has no ASCII spelling and drops out — this is the documented
// reason unicodeSlugify exists, and is itself part of the pin.
assert.equal(slugify("日本語"), "");
assert.equal(slugify("Кириллица"), "");
});
test("default parse assigns the same ids it always has", () => {
const blocks = parseContentBlocks(
"## Das Geschäftsmodell\n\ntext\n\n### Über die Straße\n\n#### Hello World!",
);
assert.deepEqual(
blocks.filter((b) => b.id).map((b) => b.id),
["das-geschaeftsmodell", "ueber-die-strasse", "hello-world"],
);
assert.deepEqual(extractToc(blocks), [
{ id: "das-geschaeftsmodell", text: "Das Geschäftsmodell", level: 2 },
{ id: "ueber-die-strasse", text: "Über die Straße", level: 3 },
{ id: "hello-world", text: "Hello World!", level: 4 },
]);
});
// ── unicodeSlugify ──────────────────────────────────────────────────────────
test("unicodeSlugify preserves letters of any script", () => {
// de — the anchor evig publishes today.
assert.equal(unicodeSlugify("Ein Eingang, vier Kanäle"), "ein-eingang-vier-kanäle");
assert.equal(unicodeSlugify("Geräte"), "geräte");
assert.equal(unicodeSlugify("Über die Straße"), "über-die-straße");
// ja
assert.equal(unicodeSlugify("日本語のはなし"), "日本語のはなし");
assert.equal(unicodeSlugify("一つの入口、四つのチャネル"), "一つの入口-四つのチャネル");
// ko
assert.equal(unicodeSlugify("하나의 입구, 네 개의 채널"), "하나의-입구-네-개의-채널");
// ru
assert.equal(unicodeSlugify("Один вход, четыре канала"), "один-вход-четыре-канала");
// zh
assert.equal(unicodeSlugify("一个入口,四个渠道"), "一个入口-四个渠道");
// mixed script + digits survive together
assert.equal(unicodeSlugify("Release 0.2.4 — 日本語"), "release-0-2-4-日本語");
});
test("unicodeSlugify strips punctuation and edge hyphens, keeps combining marks", () => {
assert.equal(unicodeSlugify(" --- "), "");
assert.equal(unicodeSlugify("!!!"), "");
assert.equal(unicodeSlugify("What's next?"), "what-s-next");
// A decomposed é (e + U+0301) stays one word rather than splitting on the mark.
assert.equal(unicodeSlugify("Café crème"), "café-crème");
});
test("unicodeSlugify is what evig's ASCII-lossy headings needed", () => {
// The whole reason for the policy: under the default these are all empty
// and would collapse to section, section-2, section-3.
for (const text of ["日本語", "Кириллица", "채널"]) {
assert.equal(slugify(text), "");
assert.notEqual(unicodeSlugify(text), "");
}
});
// ── the seam: one policy, honored by BOTH parse and extractToc ───────────────
test("unicodeSlugify threads through parseContentBlocks and extractToc", () => {
const md = "## Ein Eingang, vier Kanäle\n\ntext\n\n### 日本語のはなし\n\n#### Один вход";
const blocks = parseContentBlocks(md, { slugify: unicodeSlugify });
assert.deepEqual(
blocks.filter((b) => b.id).map((b) => b.id),
["ein-eingang-vier-kanäle", "日本語のはなし", "один-вход"],
);
assert.deepEqual(extractToc(blocks, { slugify: unicodeSlugify }), [
{ id: "ein-eingang-vier-kanäle", text: "Ein Eingang, vier Kanäle", level: 2 },
{ id: "日本語のはなし", text: "日本語のはなし", level: 3 },
{ id: "один-вход", text: "Один вход", level: 4 },
]);
});
test("a custom slugify function is honored by both parse and extractToc", () => {
const shout = (text) => `x-${text.toLowerCase().replace(/[^a-z]+/g, "")}`;
const blocks = parseContentBlocks("## One\n\n### Two", { slugify: shout });
assert.deepEqual(
blocks.filter((b) => b.id).map((b) => b.id),
["x-one", "x-two"],
);
// Hand-built blocks (no ids) get the SAME policy from extractToc.
const handBuilt = [
{ type: "h2", text: "One" },
{ type: "h3", text: "Two" },
];
assert.deepEqual(extractToc(handBuilt, { slugify: shout }), [
{ id: "x-one", text: "One", level: 2 },
{ id: "x-two", text: "Two", level: 3 },
]);
});
test("heading id and TOC entry cannot drift — one policy drives both", () => {
const md = "## Kanäle\n\n### Geräte";
for (const policy of [undefined, unicodeSlugify]) {
const options = policy ? { slugify: policy } : {};
const blocks = parseContentBlocks(md, options);
const toc = extractToc(blocks, options);
const ids = blocks.filter((b) => b.id).map((b) => b.id);
assert.deepEqual(
toc.map((e) => e.id),
ids,
);
}
});
// ── uniqueness under both policies ──────────────────────────────────────────
test("ids stay unique under the default policy", () => {
const blocks = parseContentBlocks("## Setup\n\n### Setup\n\n#### Setup");
assert.deepEqual(
blocks.filter((b) => b.id).map((b) => b.id),
["setup", "setup-2", "setup-3"],
);
});
test("ids stay unique under the unicode policy", () => {
const blocks = parseContentBlocks("## Kanäle\n\n### Kanäle\n\n#### 日本語\n\n## 日本語", {
slugify: unicodeSlugify,
});
assert.deepEqual(
blocks.filter((b) => b.id).map((b) => b.id),
["kanäle", "kanäle-2", "日本語", "日本語-2"],
);
});
test("extractToc de-duplicates ids it derives itself, under either policy", () => {
const handBuilt = [
{ type: "h2", text: "Kanäle" },
{ type: "h2", text: "Kanäle" },
];
assert.deepEqual(
extractToc(handBuilt).map((e) => e.id),
["kanaele", "kanaele-2"],
);
assert.deepEqual(
extractToc(handBuilt, { slugify: unicodeSlugify }).map((e) => e.id),
["kanäle", "kanäle-2"],
);
});
// ── empty-after-strip headings still get a usable id ─────────────────────────
test("headings that strip to nothing still yield usable, unique ids", () => {
// "!!!" is empty under both policies; 日本語 is empty under the ASCII one.
const md = "## !!!\n\n### ???\n\n#### 日本語";
assert.deepEqual(
parseContentBlocks(md)
.filter((b) => b.id)
.map((b) => b.id),
["section", "section-2", "section-3"],
);
assert.deepEqual(
parseContentBlocks(md, { slugify: unicodeSlugify })
.filter((b) => b.id)
.map((b) => b.id),
["section", "section-2", "日本語"],
);
});
test("createSlugger takes a policy and still de-duplicates and back-fills", () => {
const slug = createSlugger(unicodeSlugify);
assert.equal(slug("Kanäle"), "kanäle");
assert.equal(slug("Kanäle"), "kanäle-2");
assert.equal(slug("!!!"), "section");
assert.equal(slug("???"), "section-2");
// No argument = the default policy, unchanged from v0.2.3.
const ascii = createSlugger();
assert.equal(ascii("Kanäle"), "kanaele");
assert.equal(ascii("!!!"), "section");
});