@merlon-docs/merlon-docs-core
v1.2.0
Published
Merlon Docs core: compile, refs and validation library for a sharded documentation tree
Maintainers
Readme
@merlon-docs/merlon-docs-core
About @merlon-docs/merlon-docs-core
The programmatic core library for Merlon Docs, a documentation system for software projects. It compiles sharded Markdown guides and validates their structure. From the compiled output it also builds the registry of section links (refs.json).
Use this package when you need compile, validation, and refs APIs in scripts, CI, editors, or other tools without shelling out to the CLI.
Not the CLI or the Agent Skill
- This library: the TypeScript/Node API from
@merlon-docs/merlon-docs-coreon npm - CLI: the command-line wrapper around this library,
@merlon-docs/merlon-docs-cli - Agent Skill: the host instructions an agent loads for
/merlon-docs, installed as Get started in the project README describes
@merlon-docs/merlon-docs-cli depends on this package, so install @merlon-docs/merlon-docs-core directly only when you need the programmatic API. The Agent Skill is a separate install: this library doesn't depend on it, and installing the skill does not install this library.
Requirements
- Node.js 22 or later. Use the latest release of your major version for its security fixes.
Install
npm install @merlon-docs/merlon-docs-coreStability
On 1.0.0 and later, exported functions, types, the merlon.config.json schema, and compile output follow semver: breaking changes ship only in major releases, as Versioning and releases describes for the move past 1.0.0. On 0.x.y, those surfaces had no API stability guarantee under that policy. Stability in the CLI README says what to read before upgrading.
Quick example
This script compiles every guide and writes the outputs, then regenerates the refs registry from them. Run it from the directory that holds docs/merlon.config.json.
import { join } from 'node:path';
import {
loadConfig,
resolveDocsRoot,
resolveOutputPath,
compileGuideResults,
compileGuidesFromResults,
writeCompiledGuidesFromResults,
refsOutputTexts,
resolveRefsPath,
genRefsFromCompiled,
} from '@merlon-docs/merlon-docs-core';
const config = loadConfig('docs/merlon.config.json', process.cwd());
const docsRoot = join(process.cwd(), 'docs');
const options = {
guidesRoot: resolveDocsRoot(config, docsRoot),
compileOrder: config.compileOrder,
banner: config.banner,
guides: config.guides,
docsRoot,
config,
};
const results = compileGuideResults(options);
writeCompiledGuidesFromResults(results, options, resolveOutputPath(config, docsRoot));
const compiled = compileGuidesFromResults(results, options);
const outputs = refsOutputTexts(results, options);
const refsPath = resolveRefsPath(docsRoot, config.outputDir, config.refs.registryFile);
genRefsFromCompiled(compiled, refsPath, outputs);In CI, call checkRefsRegistry(compiled, refsPath, outputs) in place of genRefsFromCompiled. It returns ok: false when the registry on disk is missing or stale. The Compile API lists the fields of each result and says when compile writes the monolith, the one file that top-level outputFile names. The Config API says which base each path resolves from.
Config API
| Export | Purpose |
| -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| loadConfig(path, configBase) | Load and validate merlon.config.json (path is resolved from configBase) |
| parseConfig(raw) | Validate a config object that is already parsed, as loadConfig does after it reads the file |
| resolveOutputPath, resolveRefsPath, resolveGuideDir, resolveUnderOutputDir | Path resolvers for docs root and outputDir |
| defaultGuideOutputFile, effectiveGuideOutputFile | A guide's default output file name, and its compile.outputFile or that default |
| resolveDocsRoot(config, docsRoot) | The docs root, which is docsRoot as given |
| resolveGuideLinkBase(config, docsRoot, name, compileOrderLength, compile) | The output a publish output links to for a guide |
| getGuideConfig, guideScanDirs, shardLintPaths | In-scope guide fileset and shard lint helpers |
| MerlonConfigSchema, MerlonConfig, MerlonConfigInput, GuideConfig, GuideConfigInput | Zod schema and types |
| DEFAULT_COMPILE_HOOKS, resolveCompileHooks | Default built-in hook pipeline and guide-level resolution |
resolveGuideLinkBase returns the guide's compile.outputFile when the guide sets one. Without one, it returns the monolith when the config has one, and the guide's compiled guide otherwise. Despite its name, the result is the link base of only the assembly that writes that file. A guide in the monolith has one link base per document, and its own compiled guide rebases on its own path rather than on the monolith this returns.
Path resolution: configBase vs docs root
| Concern | Base | Example |
| ---------------------------- | ----------------------------- | -------------------------------------------------------------------------------- |
| Finding merlon.config.json | configBase (invocation dir) | --config docs/merlon.config.json → <repo>/docs/merlon.config.json |
| Guide shards (default) | Docs root (--docs-root) | resolveGuideDir('features', config, docsRoot) → absolute <docsRoot>/features |
resolveOutputPath and resolveRefsPath resolve a generated path with resolveUnderOutputDir(docsRoot, outputDir, file). Resolution bases in Config essentials gives the base of outputDir and of each generated path.
import { loadConfig, resolveGuideDir } from '@merlon-docs/merlon-docs-core';
const config = loadConfig('docs/merlon.config.json', process.cwd());
const featuresDir = resolveGuideDir('features', config, join(process.cwd(), 'docs'));Pass process.cwd() as configBase for loadConfig. Pass the docs root as docsRoot to resolveGuideDir, resolveOutputPath, and resolveRefsPath.
resolveGuideDir and guideScanDirs return absolute paths. A relative docsRoot such as docs resolves against the process cwd. The CLI runs markdownlint-cli2 and Vale with the docs root as their cwd, where a relative docs/features would name docs/docs/features, a directory that doesn't exist.
shardLintPaths(config, docsRoot) returns paths for markdownlint-cli2 run with the docs root as its cwd, as merlon lint and merlon check run it. From another cwd, the relative paths match the wrong files or none. Without lint.markdownlint.shardsGlobs, it returns one glob per guide directory, as In-scope guide fileset describes, and **/*.{md,markdown} for a guide whose directory is the docs root. A relative glob that would start with !, # or : gets a leading ./, so markdownlint-cli2 doesn't read it as a negation or a literal path. Use guideScanDirs for the directories themselves.
With shardsGlobs, it returns each entry as written, negated entries included, with two exceptions. A . entry becomes **. An entry that starts with ../ gets the escaped absolute directory those segments name in their place, then /** when the entry is a directory, and a negated one gets ** in front.
loadConfig validates the file with MerlonConfigFileSchema through parseConfig, and fills the top-level defaults, such as outputDir, banner, sourceTags, scan, backup, refs and review. A key inside an omitted optional object, such as lint, lint.links, vale or a guide's compile, is undefined after loading, and the code that reads it applies the documented default. Config essentials lists the output layout and its defaults under Path layout. Source tags and default banner gives the default banner text and the per-guide compile.includeBanner and compile.sourceTags keys.
A config file declares the config format version it follows in configVersion. DEFAULT_CONFIG_VERSION is the format version of the installed package, its own version from package.json. parseConfig rejects a file that declares no version, and its error names the line to add. A file written before the key's rename declares standardVersion or protocolVersion instead; parseConfig migrates it to DEFAULT_CONFIG_VERSION and sets both former keys to the result until 2.0.0. MerlonConfigFileSchema is the file format, and MerlonConfigSchema, the in-memory config the compile API takes, doesn't require the version.
Publish outputs and link paths
Guides with compile.outputFile publish outside the shard tree (npm READMEs, DEVELOPERS.md, and similar).
After the cross-guide and intra-guide rewrites, compile resolves the ../ links a shard still has and writes them relative to the guide's link base. Publish-relative exclusions lists the links it leaves as written, such as a path that leads to no file. A guide doesn't need path-prefix config for this. Link passes lists the passes in order, and Publish-relative link rewriting has examples from Merlon Docs’ own docs.
compile.hooks
resolveCompileHooks(compile) returns the list of hooks a guide runs, which is DEFAULT_COMPILE_HOOKS when compile.hooks is omitted. Configuration in the hooks overview covers the config keys.
compile.crossGuideLinks
Assembly-time cross-guide link options on the compiling guide (not a compile hook):
ignoreGuides:string[]of guide names. Links from the compiling guide to shards of a listed guide keep source.mdpaths instead of rewriting to#slugtargets, except where a link to a shard the compiling guide stitches takes its in-document anchor, as ignoreGuides says.
See Cross-guide link rewriting.
Compile API
| Export | Purpose |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| compileGuides, compileGuideResults | Stitch shards into compiled guide text |
| compileGuideResultsWithContext | The results of compileGuideResults, with the guide link index, the shard cache it built and the shards each guide compiles, its manifest's and those the linked-shard walk finds (linkedFilesByGuide) |
| compileGuidesFromResults | What compileGuides returns, from results already compiled |
| writeCompiledGuides, writeCompiledGuidesFromResults | Write compiled guides and the optional monolith to disk, the second from results already compiled |
| compiledOutputDocuments | Each file compile writes, with the text written there |
| buildGuideLinkIndex | The guide link index alone, with the shard cache it filled |
| createShardCache, loadShardSnapshot | A cache of shard reads that compile and link lint can share |
| writeOutputFile, resolveBackupPath | Opt-in backup before overwrite; backup path resolver |
| resolveBackupOptions | Merge config and CLI backup settings |
| WriteOutputBackupOptions | Backup options type |
| sectionFiles, processSection, assembleGuide | Lower-level assemble pipeline |
| formatCompileTitle, extractFirstHeading, … | Optional compile.title injection and deduplication |
| demoteHeadings, stripAboutThisGuideHeading, … | Heading transforms |
| rewriteCrossGuideFileLinks, rewriteIntraGuideFileLinks, slugForSectionFile | Two of the link passes, and the slug of a shard's demoted first heading, before guide numbering |
| stripExplicitAnchorMarkers | The stripAnchors transform on a string |
| registerCompileHook, applyCompileHooks | Extension hooks (stripAnchors, inlineInserts, …) |
compileGuideResults returns one result per guide. Its text is the guide's compiled guide, with links and source tags relative to that file. The monolith is the one file that top-level outputFile names, and it stitches each guide without compile.outputFile. A guide in the monolith also has a copy there, and its result stores that copy in monolithText, with paths and section slugs as the monolith has them.
A result's knownSlugs holds the section slugs of text, the slug of each section it stitches, such as a FIND-* finding id or a declared {#id}. monolithKnownSlugs does the same for monolithText: the section slugs of every copy in the monolith, a set each copy shares. Broken-link marking and lintLinks accept a #fragment that matches one of these slugs or a heading, as BROKEN LINK marker says. A fragment on a link from another output has to match a heading there, so neither set counts for it, as Validation phases says.
compiledOutputDocuments(results, options) returns each file that compile writes from the same results and options: every compiled guide in compileOrder, then the monolith when the config sets top-level outputFile and at least one guide is stitched into it. The monolith's path is the config's outputFile under outputDir, the path that resolveOutputPath gives and the CLI passes to writeCompiledGuidesFromResults. Each entry has the absolute path and the text written there, banner included, so a line number in the text is a line of the file. A compiled guide's entry names its result in guide. The monolith's entry lists each guide's copy in copies, with the line the copy starts on. lintLinks reads the outputs through it, and so does refsOutputTexts, which gives the refs registry each output's text.
When top-level outputFile is set, compileGuides returns the monolith text, which leaves out guides with compile.outputFile. Otherwise it returns every compiled guide joined in the order of compileOrder. compileGuidesFromResults does the same from results, and it stitches the monolith from each result's monolithText. writeCompiledGuides writes each compiled guide to its output path. It also writes the monolith when you pass its path and at least one guide has no compile.outputFile.
writeOutputFile writes compile targets. Default: overwrite. When backup.enabled is true, it moves an existing file to the path that Backup path layout gives before writing. Pass backup on CompileOptions or resolve via resolveBackupOptions(config, cliOverrides).
When compile.title is set, assembleGuide injects a ## heading followed by a blank line before the first section. Feature settings in Config reference says which spec covers each feature's config keys, backup included.
Locale packs
A locale pack holds the words compile writes and reads in prose, such as the BROKEN LINK marker and the line-range words of codeEvidence. Compile and lintLinks use the en-US pack, the only one getLocalePack resolves. buildSlugRegistry and stripAboutThisGuideHeading take a pack as an argument, and markBrokenLinks and lintCompiledLinks take one as their locale option. Each uses en-US without one.
| Export | Purpose |
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| getLocalePack(id), listLocalePackIds, DEFAULT_LOCALE_ID, enUS | Resolve a built-in pack by its BCP 47 id, en-US by default |
| createLocalePack(options), createBrokenLinksCopy, createInsertsCopy, formatTemplate | Build a pack from message templates |
Refs and validation API
Refs (cross-links)
| Export | Purpose |
| -------------------------------------------------------------- | ----------------------------------------------------------------------- |
| headingTextToPlain, githubSlugify, buildSlugRegistry | GitHub heading slugs via github-slugger |
| genRefsFromCompiled, readRefsRegistry, checkRefsRegistry | refs.json lifecycle |
| refsOutputTexts, buildRefsRegistry | Each compiled output for the registry, and the registry built in memory |
| resolveRefsPath, writeRefsRegistry | Path and I/O helpers |
refsOutputTexts(results, options)
Returns each file compile writes from results, in the order compiledOutputDocuments gives them. Each entry has file, the path relative to options.docsRoot with / separators, and text, what compile writes there, banner included. A compiled guide's entry also names its guide in guideName. Pass the list as the last argument of genRefsFromCompiled(compiledText, registryPath, outputs) and checkRefsRegistry(compiledText, registryPath, outputs). The registry then has an outputs entry for each file, with that file's headings slugged on their own and each line counted in that file. buildRefsRegistry(compiledText, outputs) returns the same registry without writing it.
The registry's top-level headings and slugs come from compiledText alone, the text compileGuidesFromResults returns. Without outputs, the registry has no outputs field. checkRefsRegistry compares the file with the registry its own arguments give, so a registry written with outputs is stale to a check without them, and the reverse. Registry contents lists the fields.
resolveRefsPath(docsRoot, outputDir, registryFile)
Resolves the on-disk path for the refs registry. Implemented via the same outputDir-relative helper as resolveOutputPath. Pass the docs root (the CLI --docs-root value).
outputDiris relative todocsRoot.registryFileresolves by the rule in Path layout (default.caches/refs.json).
resolveRefsPath('/docs', '_build', '.caches/refs.json');
// → /docs/_build/.caches/refs.json
resolveRefsPath('/docs', '.', 'refs.json');
// → /docs/refs.jsonHeading slugs (github-slugger)
githubSlugify, headingTextToPlain, and buildSlugRegistry derive #fragment targets from compiled headings using github-slugger, which matches the anchors GitHub renders for headings. GFM does not define auto-generated heading IDs. Treat github-slugger parity as the contract.
| Export | Purpose |
| -------------------- | ---------------------------------------------------- |
| headingTextToPlain | Strip ids and inline markup before slugging |
| githubSlugify | Single-heading slug via github-slugger |
| buildSlugRegistry | Document-wide slugs; duplicates get numeric suffixes |
buildSlugRegistry reads only headings outside fenced code blocks, which it finds with the fence scan. A # comment in a shell example doesn't get a slug, and it doesn't change the guide that later headings belong to. Compile numbers section slugs through the same reader, so a rewritten section link and the registry agree, apart from the limits that page lists. Heading demotion, in compile and in demoteHeadings, leaves each line that the same scan reads as code as written. Fence scan limits says when demotion and buildSlugRegistry can disagree about a shard.
import { githubSlugify, headingTextToPlain } from '@merlon-docs/merlon-docs-core';
headingTextToPlain('**Authored GFM** `{#gfm}`');
// → 'Authored GFM'
githubSlugify('Preprocessor / templating (out of scope)');
// → 'preprocessor--templating-out-of-scope'
githubSlugify('`--config` vs `--docs-root`');
// → '--config-vs---docs-root'CLI authoring rules: Cross-links and refs — heading slugs.
Validation
| Export | Purpose |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| checkOrphansForGuides | Detect unlinked or missing shard files; a relative dir resolves against the process cwd |
| lintLinks | Internal markdown link validation |
| reviewDocs | Sprawl signals behind merlon review (formatReviewReport renders the text report) |
| computeCoverage | Markdown files no guide captures, behind the check coverage report |
| probeDocumentPaths | Backtick-path resolution behind lint.paths (ILLUSTRATIVE_MARKER opts out) |
| DEFAULT_CODE_EXTENSIONS, DEFAULT_DATA_EXTENSIONS, codeExtensionSet, dataExtensionSet, fileExtensionSet, hasCodeExtension, hasFileExtension | The code and data extensions that link validation and codeEvidence read, with lint.codeExtensions and lint.dataExtensions added |
Shard and peers API
Shard (split)
| Export | Purpose |
| -------------------------------- | ---------------------------------------------- |
| shardFromMonolith, runMdTree | Split a source document into guide directories |
shardFromMonolith reads a source document such as a legacy README, not the compiled monolith. It splits the source at its H1 headings. Each mappings entry either picks H1 sections for one guide (h1Index or mergeH1Indices) and splits them as Map the document to guides describes, or copies an existing directory (directoryPath). merlon shard builds the mappings from each guide's source config.
Peer tools
| Export | Purpose |
| --------------------------- | ----------------------------------------------------------------- |
| findPeerBinary, runPeer | Locate and run host-repo linters (markdownlint-cli2, vale, …) |
findPeerBinary(name, cwd) returns source: 'local' for a node_modules/.bin binary found from cwd upward, 'path' for one on PATH, and found: false otherwise. runPeer then skips the tool with an info line unless require is set, which makes a missing tool an error. Peer linters is the policy.
Compile hooks
Per-shard transforms run during assembleGuide before sections are stitched. Hooks receive each shard body after heading demotion and preamble stripping. The diagram below shows the steps around the hooks.
Hooks assemble authored GFM. They don't do variable substitution or template logic. See Preprocessor / templating (out of scope).
Architecture
assembleGuide (per guide, once for each document it is written to)
│
├─ for each shard (manifest order, then linked shards)
│ ├─ processSection (demote headings, strip about-this-guide)
│ ├─ applyCompileHooks (named hooks from config, in order)
│ ├─ mark the paths codeEvidence rebased
│ ├─ cross-guide pass (automatic when link index present, marks what it writes)
│ ├─ rewriteIntraGuideFileLinks (same-guide links, from the shard directory)
│ └─ rewritePublishRelativeLinks (every guide, relative to its link base, marks what it writes)
│
├─ stitch → stripAnchors (default) → intra-guide .md → unmark
│
└─ markBrokenLinks → realignTables (the last step)Guide link index: compileGuideResults builds it once from every guide in compileOrder, and the cross-guide pass reads it. Guide link index says which shards have an entry.
Per-assembly hook state: mutable hookState on CompileHookContext (such as inlineInserts counters and first-anchor map) shared across shard invocations within one assembly. Each assembly starts with fresh hookState, and a guide in the monolith has one assembly for each document, as When it runs says. So every hook it runs, a registered custom hook included, sees each of its shards twice, and a hook with side effects beyond its return value repeats them.
The Features Guide's Compile pipeline specifies the assembly steps that aren't hooks, and the rules they share with the hooks. Its Path lookup order gives the directories each hook and pass tries when it follows a link to a file.
Extension pattern
A custom hook runs only in a process that registers it with registerCompileHook before it calls compileGuideResults or compileGuides. Importing the core registers the built-in hooks and identity, which returns the body unchanged. The Merlon Docs CLI doesn't load a custom hook, so merlon compile and merlon check compile without one. Register yours in your own build script:
import { registerCompileHook } from '@merlon-docs/merlon-docs-core';
registerCompileHook('myHook', (ctx) => {
return ctx.body.replace(/TODO/g, 'DONE');
});Then list it in the array form of compile.hooks next to the built-in hooks the guide keeps, such as ["stripAnchors", "codeEvidence", "inlineInserts", "myHook"]. Explicit override says the array replaces the default pipeline, so it has to list them.
Compile skips any name in compile.hooks that has no registered hook, and it doesn't warn. A misspelled name, such as codeEvidense, compiles as if the list left it out, and no check reports it. Registering a hook under a name already in use replaces that hook, a built-in one included.
A hook gets a CompileHookContext and returns the new body. Assembly always sets hookState, and passes {} as config when the caller doesn't give one. compileGuideResults sets every other field, and scopeRoot only when the guide sets compile.scopeRoot. A direct assembleGuide call sets outputFile, outputBasename, scopeRoot and linkIndex only when its options give them.
| Field | Value |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| body | The shard body, after heading demotion, preamble stripping and the hooks listed before this one |
| guideName | The configured name of the guide being compiled |
| filename | The shard's file name |
| sourceFile | The shard's absolute path |
| config | The config the caller passed as CompileOptions.config (an MerlonConfigInput), or {} |
| outputFile | Optional. The absolute path of the guide's link base |
| outputBasename | Optional. The file name of outputFile |
| scopeRoot | Optional. The absolute compile.scopeRoot, unset when the guide doesn't set it |
| hookState | State that the hook calls of one assembly share, from one shard to the next. Always set, though the type marks it optional |
| linkIndex | Optional. The guide link index |
Hook implementations should be pure on ctx.body except when intentionally using shared hookState. Leave unmatched links unchanged.
Configuration
Built-in hooks run by default, so omit compile.hooks for the common case. Default compile hooks gives the forms compile.hooks takes to turn a hook off or replace the list. Per-hook settings go under guides[].compile.hooksConfig, as inlineInserts config shows, and the config API covers resolveCompileHooks. stripAnchors purpose says what compile.stripAnchors does.
For manifest compile order and compile.sectionsHeading, see Manifest compile order.
Built-in hooks
stripAnchors: per shard. stripAnchors: removes{#id}markers outside code, and every marker on a heading line.codeEvidence: per shard. codeEvidence: repo source links →#Lfragments.inlineInserts: per shard. inlineInserts: inline captioned insert libraries.
Assembly also runs the link passes, which aren't hooks. Its last step, after broken-link marking, is table re-alignment, which prints an aligned table again once its links change width.
stripAnchors
Specification for the stripAnchors compile hook. The Spec-to-test map names the tests behind this spec.
stripAnchors purpose
The hook removes {#id} anchor markers from each shard body. With compile.stripAnchors (default true), the same strip runs once more on the stitched guide.
A marker goes with the whitespace before it on the same line. When a marker opens a line's text, the whitespace after it goes instead, and the line keeps its indent. The strip drops a line that contains only a marker, and when that line opens the text or follows a blank line, the blank line right after it goes too.
stripAnchors heading lines
A line that Merlon Docs reads as a heading, an ATX heading at column 0, loses every marker, even inside a fenced code block or a code span. Heading slugs drop every marker from a title and skip the lines that the fence scan reads as code. The scan ignores HTML and can misread a fence there, so stripping every heading line keeps a marker off a rendered heading even then.
To show the syntax on a heading inside a fenced example, start the heading line one to three spaces in. Merlon Docs doesn't read that line as a heading. The strip treats it as fenced text and keeps its marker. Outside a fence the same line is prose, and its marker goes.
stripAnchors code
On any other line, a {#id} inside a fenced code block or an inline code span stays. The hook finds both with the fence scan.
stripAnchors limits
The strip reads an indented code block as prose, as the fence scan does. It removes a marker there unless the marker is inside a code span on its line. The hook runs the scan without the blockquote text, so a fence behind > is prose to it too, and a marker there goes unless a code span on its line holds it. Where the fence scan limits misread a fence or shift the pairing of code spans, the strip can drop a quoted marker or keep a prose one.
codeEvidence
Specification for the codeEvidence compile hook. The Spec-to-test map names the tests behind this spec.
codeEvidence purpose
Architecture and technical review shards cite repo source files as evidence. At compile time, the hook:
- Resolves line ranges from link text (for example
L6-L8,lines 12–15,:42) - Resolves symbols from the URL fragment (
file.ts#symbol) or from the link label when no fragment is present, such as[`countItems`](../../src/counts.ts) - Appends GitHub-style
#Lfragments (#L6,#L6-L8) to the link target - Rewrites the target path to be relative to the guide's link base
The publish-relative pass then rebases the ../ links whose path the hook leaves as the shard wrote it, against the same link base. Such a link can lead to a Markdown file or to another path the hook doesn't read, like .nvmrc. It can also lead to a source file that the hook doesn't find, even when the hook added a line fragment to it. In DEVELOPERS.md, the hook rebases ../../package.json to package.json, and the publish-relative pass rebases ../../.nvmrc to .nvmrc. Publish-relative exclusions lists the links that pass leaves alone, a link the hook rebased among them.
codeEvidence link matching
A link is rewritten when all of the following hold:
- Standard markdown link syntax:
[label](path) - Target path names a file in the repository: one with a code or data extension like
.tsor.yaml, or a path with no.in it likeMakefile - Target is not
http://,https://, or#… - The link is outside fenced code and code spans
Markdown (.md) links, external URLs, and same-guide shard links are left unchanged.
The hook skips a path to an extensionless file when the path has a . anywhere in it, such as ../../Makefile or ./Makefile. A line range in the label of such a link doesn't add an #L fragment. The publish-relative pass still rebases the ../ path.
The hook finds fenced code and code spans as the link passes do, and it reads a label and a target as they do. It reads each run of lines between two fences at once, so a label outside code can still wrap onto the next line, and an unfinished link such as [x](see doesn't take in a link on the next line. In a label that contains an image, such as a linked image's, the hook reads a line range or a symbol only from the text outside the image.
Code and data differ in what the hook adds. A code file can be cited by line, so symbol lookup can give it an #L fragment. A data file, such as configuration or records, is resolved and rebased for the output path. It gets an #L fragment only from a line range the shard writes in the label, the path or the fragment, because symbol lookup runs for code files only. Link validation uses the same code and data extension lists. To look symbols up in a data format, list its extension in lint.codeExtensions. See Built-in link validation.
codeEvidence line ranges
Line ranges are parsed from the link label first, then from the path (before any # fragment). The hook always emits GitHub-style #L… fragments (a fixed format that isn't localized).
Language-neutral forms (always recognized). A bare range such as 1-2 isn't one: it could as well be a version or page range, so a line range needs L, : or a locale word:
| Form in label or path | Fragment |
| --------------------- | ------------------ |
| L6-L8, L6–L8 | #L6-L8 |
| L42 | #L42 |
| :10-20, :10 | #L10-L20, #L10 |
Locale word forms come from the active locale pack (lineRangeWords). Default en-US recognizes line / lines (case-insensitive), for example line 42 → #L42 and lines 12–15 → #L12-L15. Other locales may supply different authored words; they are not part of the Merlon Docs format. See Locale and language boundary.
If the URL already has a line fragment such as #L6 or #L6-L8, the hook keeps it and writes each l in it as L, so #l6-l8 becomes #L6-L8.
codeEvidence symbols
When no line range is found:
- If the URL has a
#fragmentthat is not already#L…, treat the fragment as a symbol name and look it up in the resolved source file. - Otherwise, treat the link label as the symbol (backticks and surrounding whitespace stripped).
Symbol lookup links the first line where the symbol appears as a whole word. That line can be an import, a call or a comment above the declaration. To cite the declaration, write its line range in the label or the fragment. Lookup runs for code files only, and a data file skips both steps.
When neither step finds a line, the hook drops the #fragment, and the link points at the whole file.
codeEvidence path resolution
The hook finds the source file in the order Path lookup order gives for codeEvidence. When a source file is resolved, the hook rewrites the link target to a POSIX path relative to the guide's link base, preserving any #L… fragment added by the hook. You don't configure the hook for this. It resolves a shard-relative path as written, then rebases it to that link base.
When no directory has the file, the path stays as written, and the line range rules still set the fragment. The hook keeps an existing #L fragment, and otherwise adds one from a line range in the label or path. Symbol lookup has no file to scan, so without a line range the hook drops any other #fragment.
codeEvidence exclusions
The hook does not transform:
- Markdown shard links (
.md) - External URLs
- Link syntax in fenced code or in a code span
- The path of a source link whose file can't be resolved (see codeEvidence path resolution for its fragment)
- A symbol in a data-file link into an
#Lfragment, unless the extension is listed inlint.codeExtensions - Body text when
codeEvidenceis disabled viacompile.hooks: { "codeEvidence": false }or an explicit hook override that omits it
codeEvidence config
Path rewriting rebases each path to the guide's link base, the file being assembled: its compiled guide or the monolith. Runs by default, so an empty compile keeps it on:
{
"name": "architecture-review",
"path": "review",
"compile": {}
}compile.outputFile publishes the guide to a path you choose, and the hook rebases each path to that file. The path resolves relative to outputDir. With outputDir: "_build" and the docs root at docs/, "../../architecture-review.md" is a file at the repository root. Set compile.scopeRoot too when the guide stitches shards outside its directory, or cites files that resolve only from that root. The linked-shard walk keeps a shard under it, and evidence lookup tries it last, as Path lookup order says. compile.scopeRoot resolves from the docs root, and "." is the docs root itself:
{
"name": "architecture-review",
"path": "review",
"compile": {
"scopeRoot": ".",
"outputFile": "../../architecture-review.md"
}
}Opt out: "hooks": { "codeEvidence": false }. See Default compile hooks.
codeEvidence compile example
Shard input (docs/review/claim.md):
Evidence: [`countItems`](../../src/counts.ts)
See [access.rules L6-L8](../../config/access.rules).Compiled output, when the first line of src/counts.ts with the word countItems is line 6 and the guide's output is architecture-review.md at the repository root:
Evidence: [`countItems`](src/counts.ts#L6)
See [access.rules L6-L8](config/access.rules#L6-L8).inlineInserts
Specification for the inlineInserts compile hook. The Spec-to-test map names the tests behind this spec.
inlineInserts purpose
Guides link to captioned insert shards (.md files) in typed libraries under the docs root. Shard bodies may be markdown tables, prose, or media embeds (images, video, audio). At compile time, the hook:
- Inlines insert markdown at the first link (per guide, per file)
- Adds a numbered
####heading (GFM only — no HTML, no directives) - Rewrites later links to the same file as markdown back-links (
[label](#slug))
inlineInserts layout
One library directory per insert type (library-science convention):
docs/
diagrams/ # flow charts, sequence diagrams (markdown tables or images)
tables/ # reference tables, comparison matrices
figures/ # screenshots, static diagrams
media/ # video, audio, and other captioned media embeds
inserts/ # optional generic captioned blocks
review/
insert-catalog.md # links to ../diagrams/…, ../tables/…, ../figures/…, ../media/…Link targets are always .md insert shards. Put binary assets alongside the shard (or under the same library) and reference them from the shard body with  or an HTML <video> / <audio> block when your renderer supports it.
Shards link with normal markdown — no <!-- directives -->.
inlineInserts link matching
A link is an insert reference when all of the following hold:
- Inline link syntax,
[label](path), with the label and target read as the link passes read them. An image,, isn't an insert reference. - Target starts with an insert library directory and a
/, after an optional./or run of../. The directories arediagram,diagrams,table,tables,figure,figures,media,insertandinserts, in any case. Nohttp://orhttps://URL starts that way. - The path after the directory doesn't start with
#or whitespace. It ends in.mdin any case, with at least one character before the.md. - An optional
#fragmentafter the.mdcan't be empty, and file lookup ignores it.
The hook reads the whole shard body, fenced code and code spans included. So it inlines an insert, or writes a back-link, for an insert link in a code example too, where the link passes leave a link as written.
inlineInserts exclusions
The hook does not transform:
- Regular shard links, such as
./intro.mdor../glossary/term.md - Direct links to binary assets such as
../figures/architecture.pngor../figures/demo.mp4; see layout - External URLs, even when the path contains
diagrams/ - Links to missing insert files (left unchanged)
- Body text when
inlineInsertsis disabled viacompile.hooks: { "inlineInserts": false }or an explicit hook override that omits it
inlineInserts first inline
The first reference to an insert file (document order across all shards in the guide) is replaced with:
#### {Kind} {n}. {caption}
{insert shard body — tables, prose, images, video, audio, …}- Kind —
Diagram,Table,Figure,Media, orInsert(from parent library directory) - n — serial number for that kind in this guide (see Numbered captions below)
- caption — link label, or a humanized basename when the label is empty
- Anchor slug — GitHub-style slug of the full heading (for example
Table 1. Status codes→#table-1-status-codes)
The label of a linked image, [](../diagrams/d.md), contains the image. The heading then reads #### Diagram 1. , and a back-link to it uses the slug of that text, #diagram-1-iipng.
Output uses GFM headings and back-links for captions. The hook inlines each shard body as written. The assembly passes after the hooks then treat that body as part of the shard, from link rewriting to table re-alignment. A body can contain markdown tables and .
The heading and body replace the link, so a first reference in a table cell breaks the table, as the compile example shows. Give the first reference a paragraph of its own, ahead of any table cell that links to the insert.
In the compiled markdownlint pass of merlon check, the broken row fails MD056 (table-column-count). That pass lints only the outputs that the globs in its lint.markdownlint.compiledConfig file match, and a table broken in any other output passes the check.
inlineInserts numbered captions
Serial counters are per insert kind and per guide compile:
| Kind | First inline heading example | Second inline (same kind) |
| ------- | ------------------------------ | ------------------------- |
| diagram | #### Diagram 1. Request flow | #### Diagram 2. … |
| table | #### Table 1. Status codes | #### Table 2. … |
| figure | #### Figure 1. Component map | #### Figure 2. … |
| media | #### Media 1. Walkthrough | #### Media 2. … |
Rules:
- Diagram and table counters are independent (
Diagram 1thenTable 1thenDiagram 2is valid) - Counters continue across shards via shared per-guide hook state
- Each guide starts at 1 for each kind (two guides sharing one insert file each get their own
Diagram 1) - Repeat links to an already inlined file do not consume a new number (back-link only)
inlineInserts deduplication
Within one guide:
- First link to
../diagrams/flow.md→ inline under numbered heading - Later links to the same resolved file (any path spelling, with or without
#fragment) →`[label](#diagram-1-…)` - Same basename in different libraries (
diagrams/overview.mdvstables/overview.md) → separate headings and anchors
inlineInserts path resolution
The hook finds each insert shard in the order Path lookup order gives for inlineInserts.
inlineInserts config
Runs by default. Optional search roots, each the parent of an insert library directory such as diagrams/:
{
"name": "architecture-review",
"compile": {
"hooksConfig": {
"inlineInserts": { "searchRoots": ["shared"] }
}
}
}A link to diagrams/flow.md that no earlier root in the lookup order resolves then finds shared/diagrams/flow.md.
Opt out: "hooks": { "inlineInserts": false }. See Default compile hooks.
inlineInserts compile example
Shard input:
| Insert | Summary |
| ------------------------------------------- | ----------- |
| [Request flow](../diagrams/request-flow.md) | Client path |
See [Request flow](../diagrams/request-flow.md) again in prose.Compiled fragment (first guide mention), with trailing spaces trimmed. The header and delimiter rows keep the shard's widths, and the insert splits the row with the link:
| Insert | Summary |
| ------------------------------------------- | ----------- |
|
#### Diagram 1. Request flow
| Step | Actor |
| ---- | ------ |
| 1 | Client |
| Client path |
See [Request flow](#diagram-1-request-flow) again in prose.Example fixture: examples/sample-guides/inserts-demo/. Its catalog gives each insert's first reference a paragraph of its own, and its table links to each insert again. Compile turns those table links into back-links and re-aligns the table. See GitHub media reference for a format matrix (PNG, JPEG, GIF, SVG, MP4, MP3/WAV, Mermaid, tables, lists) and minimal generated sample assets under figures/ and media/.
Figure with embedded image (shard figures/component-map.md):
Catalog link `[Component map](../figures/component-map.md)` compiles to a numbered #### Figure 1. … heading followed by that image markdown.
Media with embedded video (shard media/walkthrough.md):
<video src="./walkthrough.mp4" controls></video>Catalog link `[Walkthrough](../media/walkthrough.md)` compiles to #### Media 1. Walkthrough followed by the video embed.
Related packages
@merlon-docs/merlon-docs-cli: themerloncommand-line interface@merlon-docs/merlon-docs-presets: starter markdownlint configs and the Merlon Docs Vale style
Further reading
- CLI commands reference
- Project README: the Agent Skill landing page
- Design constraints
License
MIT
ignoreGuides
ignoreGuides is a list of guide names on the compiling guide, under compile.crossGuideLinks.ignoreGuides. Cross-guide links to a listed guide keep pointing at the source shard instead of rewriting to a #slug target. A link to a shard the compiling guide stitches can still take its in-document anchor. Same compiled output preference says when the cross-guide pass gives it one. ignoreGuides interaction says how compile rebases a kept path, and when a ./ or bare link to a stitched shard takes #slug. The listed guide stays in compileOrder and in the link index.
Read Cross-guide link rewriting for how other links rewrite, and the publish-only link policy for how link validation treats kept shard paths.
locale pack
A locale pack is Merlon Docs’ compile-time bundle of natural-language data that is not part of the GFM format. It covers:
- Generated wording: text such as US-English insert captions (
Table 1. …) andBROKEN LINKmarker copy - Locale-specific patterns: optional heading-key patterns for semantic refs
- Parse-input word cues: authored words a compile hook may recognize (such as en-US
line/linesfor codeEvidence line ranges) - Preamble heading title: a title such as en-US
About this guidefor strip/promote defaults (aboutThisGuideTitle)
Default en-US (one BCP 47 JSON file per locale under src/locale/locales/). Language-neutral markup forms and GitHub-style #L… fragment output stay outside the pack.
authored GFM
Shard markdown as written before compile, with no preprocessor substitution or template conditionals. Compile hooks may transform it during assembly. Read Preprocessor / templating (out of scope).
