@catheadowl/md-tools 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +94 -2
- package/cli/config.mjs +86 -0
- package/cli/doc-link.mjs +145 -0
- package/cli/kernel.mjs +86 -0
- package/cli/normalize.mjs +91 -0
- package/cli/rename.mjs +390 -0
- package/conformance/cases.json +55 -0
- package/lib/gate-check.d.ts +87 -0
- package/lib/gate-check.js +233 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +8 -0
- package/lib/links/anchors.d.ts +43 -0
- package/lib/links/anchors.js +93 -0
- package/lib/links/cli.d.ts +33 -0
- package/lib/links/cli.js +86 -0
- package/lib/links/git.d.ts +156 -0
- package/lib/links/git.js +329 -0
- package/lib/links/index.d.ts +33 -0
- package/lib/links/index.js +25 -0
- package/lib/links/markdown.d.ts +127 -0
- package/lib/links/markdown.js +253 -0
- package/lib/links/normalize.d.ts +40 -0
- package/lib/links/normalize.js +102 -0
- package/lib/links/rebase.d.ts +24 -0
- package/lib/links/rebase.js +44 -0
- package/lib/links/rename.d.ts +257 -0
- package/lib/links/rename.js +864 -0
- package/lib/links/resolve.d.ts +145 -0
- package/lib/links/resolve.js +297 -0
- package/lib/links/scheme.d.ts +115 -0
- package/lib/links/scheme.js +209 -0
- package/lib/links/textual.d.ts +26 -0
- package/lib/links/textual.js +144 -0
- package/lib/measure/count.d.ts +47 -0
- package/lib/measure/count.js +91 -0
- package/lib/measure/document.d.ts +105 -0
- package/lib/measure/document.js +173 -0
- package/lib/measure/index.d.ts +22 -0
- package/lib/measure/index.js +18 -0
- package/lib/measure/sections.d.ts +38 -0
- package/lib/measure/sections.js +37 -0
- package/lib/measure/structure.d.ts +53 -0
- package/lib/measure/structure.js +186 -0
- package/package.json +82 -4
- package/skills/md-tools/SKILL.md +42 -0
- package/skills/md-tools/references/freeze.md +17 -0
- package/skills/md-tools/references/payload.md +28 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse seam of doc-core — locates Markdown link/image/definition
|
|
3
|
+
* destinations as byte offsets over mdast. This module keeps only the
|
|
4
|
+
* parse/locate primitives the kernel needs.
|
|
5
|
+
*
|
|
6
|
+
* `markdownLabel` locates the label span of a reference (the `[text]` part
|
|
7
|
+
* of a link/image/definition); it is a self-written extension and reuses the
|
|
8
|
+
* module's own `labelBounds` scanner. `scanWikiLinks` is a self-written
|
|
9
|
+
* extension too: a raw-text `[[wikilink]]` scan, excluded inside the code
|
|
10
|
+
* ranges `markdownCodeRanges` supplies — a parse change re-flows those
|
|
11
|
+
* exclusions automatically. `isExternalOrAbsoluteMarkdownUrl` gates Windows
|
|
12
|
+
* drive letters before the scheme test.
|
|
13
|
+
*/
|
|
14
|
+
import { fromMarkdown } from 'mdast-util-from-markdown';
|
|
15
|
+
import { gfmFromMarkdown } from 'mdast-util-gfm';
|
|
16
|
+
import { gfm } from 'micromark-extension-gfm';
|
|
17
|
+
/** Parse GitHub-flavored Markdown with the repository's standard extensions. */
|
|
18
|
+
export function parseMarkdown(source) {
|
|
19
|
+
return fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Visit a Markdown tree depth-first; returning false prunes a node's children.
|
|
23
|
+
* @param node - current tree node.
|
|
24
|
+
* @param visitor - callback invoked before each node's children.
|
|
25
|
+
*/
|
|
26
|
+
export function visitMarkdown(node, visitor) {
|
|
27
|
+
if (visitor(node) === false)
|
|
28
|
+
return;
|
|
29
|
+
if ('children' in node) {
|
|
30
|
+
for (const child of node.children)
|
|
31
|
+
visitMarkdown(child, visitor);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Single letter + ':' + '/' or '\' is a Windows drive, never a scheme: the
|
|
36
|
+
* IANA registry (~450 entries) holds no single-letter scheme, and RFC 8089
|
|
37
|
+
* fixes `file:///<drive>/…` as the global unambiguous local-absolute form.
|
|
38
|
+
* A bare `D:` without a separator still classifies as a scheme. Pandoc and
|
|
39
|
+
* docling-core fixed the same drive-as-scheme bug the same way.
|
|
40
|
+
*/
|
|
41
|
+
export function isWindowsDriveUrl(url) {
|
|
42
|
+
return /^[a-zA-Z]:[\\/]/.test(url);
|
|
43
|
+
}
|
|
44
|
+
/** Whether a Markdown URL is external, repository-root absolute, or purely in-page. */
|
|
45
|
+
export function isExternalOrAbsoluteMarkdownUrl(url) {
|
|
46
|
+
return url === ''
|
|
47
|
+
|| url.startsWith('#')
|
|
48
|
+
|| url.startsWith('//')
|
|
49
|
+
|| url.startsWith('/')
|
|
50
|
+
|| (!isWindowsDriveUrl(url) && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url));
|
|
51
|
+
}
|
|
52
|
+
/** Split one Markdown URL without normalizing its query or fragment suffix. */
|
|
53
|
+
export function splitMarkdownUrlTarget(url) {
|
|
54
|
+
const boundary = url.search(/[?#]/);
|
|
55
|
+
if (boundary === -1)
|
|
56
|
+
return { path: url, suffix: '' };
|
|
57
|
+
return { path: url.slice(0, boundary), suffix: url.slice(boundary) };
|
|
58
|
+
}
|
|
59
|
+
function skipWhitespace(source, start) {
|
|
60
|
+
let index = start;
|
|
61
|
+
while (/\s/.test(source[index] ?? ''))
|
|
62
|
+
index += 1;
|
|
63
|
+
return index;
|
|
64
|
+
}
|
|
65
|
+
/** Offsets of a node's `[...]` label inside its source slice: the `[` and the matching `]`. */
|
|
66
|
+
function labelBounds(rawNode) {
|
|
67
|
+
const open = rawNode.indexOf('[');
|
|
68
|
+
if (open === -1)
|
|
69
|
+
return undefined;
|
|
70
|
+
let depth = 0;
|
|
71
|
+
for (let index = open; index < rawNode.length; index += 1) {
|
|
72
|
+
const char = rawNode[index];
|
|
73
|
+
if (char === '\\')
|
|
74
|
+
index += 1;
|
|
75
|
+
else if (char === '[')
|
|
76
|
+
depth += 1;
|
|
77
|
+
else if (char === ']') {
|
|
78
|
+
depth -= 1;
|
|
79
|
+
if (depth === 0)
|
|
80
|
+
return { open, close: index };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
function labelEnd(source) {
|
|
86
|
+
return labelBounds(source)?.close ?? -1;
|
|
87
|
+
}
|
|
88
|
+
function destinationRange(rawNode, type) {
|
|
89
|
+
const endOfLabel = labelEnd(rawNode);
|
|
90
|
+
if (endOfLabel === -1)
|
|
91
|
+
throw new Error(`markdown: cannot locate label end in ${JSON.stringify(rawNode)}`);
|
|
92
|
+
let start;
|
|
93
|
+
if (type === 'definition') {
|
|
94
|
+
const colon = rawNode.indexOf(':', endOfLabel + 1);
|
|
95
|
+
if (colon === -1)
|
|
96
|
+
throw new Error(`markdown: cannot locate definition separator in ${JSON.stringify(rawNode)}`);
|
|
97
|
+
start = skipWhitespace(rawNode, colon + 1);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
if (rawNode[endOfLabel + 1] !== '(') {
|
|
101
|
+
throw new Error(`markdown: cannot locate inline destination in ${JSON.stringify(rawNode)}`);
|
|
102
|
+
}
|
|
103
|
+
start = skipWhitespace(rawNode, endOfLabel + 2);
|
|
104
|
+
}
|
|
105
|
+
if (rawNode[start] === '<') {
|
|
106
|
+
for (let index = start + 1; index < rawNode.length; index += 1) {
|
|
107
|
+
if (rawNode[index] === '\\')
|
|
108
|
+
index += 1;
|
|
109
|
+
else if (rawNode[index] === '>')
|
|
110
|
+
return { start: start + 1, end: index };
|
|
111
|
+
}
|
|
112
|
+
throw new Error(`markdown: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}`);
|
|
113
|
+
}
|
|
114
|
+
let depth = 0;
|
|
115
|
+
for (let index = start; index < rawNode.length; index += 1) {
|
|
116
|
+
const char = rawNode[index];
|
|
117
|
+
if (char === '\\')
|
|
118
|
+
index += 1;
|
|
119
|
+
else if (char === '(')
|
|
120
|
+
depth += 1;
|
|
121
|
+
else if (char === ')') {
|
|
122
|
+
if (depth === 0)
|
|
123
|
+
return { start, end: index };
|
|
124
|
+
depth -= 1;
|
|
125
|
+
}
|
|
126
|
+
else if (/\s/.test(char ?? '') && depth === 0) {
|
|
127
|
+
return { start, end: index };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return { start, end: rawNode.length };
|
|
131
|
+
}
|
|
132
|
+
/** Locate one parsed destination in the original Markdown without reserializing it. */
|
|
133
|
+
export function markdownDestination(source, node) {
|
|
134
|
+
const start = node.position?.start.offset;
|
|
135
|
+
const end = node.position?.end.offset;
|
|
136
|
+
if (start === undefined || end === undefined) {
|
|
137
|
+
throw new Error(`markdown: destination ${JSON.stringify(node.url)} has no source offsets`);
|
|
138
|
+
}
|
|
139
|
+
const range = destinationRange(source.slice(start, end), node.type);
|
|
140
|
+
const absolute = { start: start + range.start, end: start + range.end };
|
|
141
|
+
return { ...absolute, url: source.slice(absolute.start, absolute.end) };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Locate one parsed node's label in the original Markdown, the way
|
|
145
|
+
* `markdownDestination` locates its destination. Textual only: whether a label
|
|
146
|
+
* may be rewritten is the caller's judgment, taken next to the AST (it needs
|
|
147
|
+
* the node's children and the reference kind).
|
|
148
|
+
*/
|
|
149
|
+
export function markdownLabel(source, node) {
|
|
150
|
+
const start = node.position?.start.offset;
|
|
151
|
+
const end = node.position?.end.offset;
|
|
152
|
+
if (start === undefined || end === undefined) {
|
|
153
|
+
throw new Error(`markdown: label ${JSON.stringify(node.type)} has no source offsets`);
|
|
154
|
+
}
|
|
155
|
+
const bounds = labelBounds(source.slice(start, end));
|
|
156
|
+
if (bounds === undefined) {
|
|
157
|
+
throw new Error(`markdown: cannot locate a label in ${JSON.stringify(source.slice(start, end))}`);
|
|
158
|
+
}
|
|
159
|
+
const absolute = { start: start + bounds.open + 1, end: start + bounds.close };
|
|
160
|
+
return { ...absolute, text: source.slice(absolute.start, absolute.end) };
|
|
161
|
+
}
|
|
162
|
+
/** Text a reader sees from one Markdown node; raw HTML itself contributes none. */
|
|
163
|
+
export function renderedText(node) {
|
|
164
|
+
if (node.type === 'text' || node.type === 'inlineCode')
|
|
165
|
+
return node.value;
|
|
166
|
+
if (node.type === 'image' || node.type === 'imageReference')
|
|
167
|
+
return node.alt ?? '';
|
|
168
|
+
if (node.type === 'break')
|
|
169
|
+
return ' ';
|
|
170
|
+
if ('children' in node)
|
|
171
|
+
return node.children.map(child => renderedText(child)).join('');
|
|
172
|
+
return '';
|
|
173
|
+
}
|
|
174
|
+
/** Return every parsed Markdown heading with its rendered text and source line. */
|
|
175
|
+
export function markdownHeadingLines(source) {
|
|
176
|
+
const rawLines = source.split('\n');
|
|
177
|
+
const headings = [];
|
|
178
|
+
visitMarkdown(parseMarkdown(source), (node) => {
|
|
179
|
+
if (node.type !== 'heading' || node.position === undefined)
|
|
180
|
+
return;
|
|
181
|
+
headings.push({
|
|
182
|
+
depth: node.depth,
|
|
183
|
+
index: node.position.start.line,
|
|
184
|
+
raw: rawLines[node.position.start.line - 1] ?? '',
|
|
185
|
+
text: renderedText(node),
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
return headings;
|
|
189
|
+
}
|
|
190
|
+
// Target stops at the first `#`, `|`, `[`, or `]`; the fragment and alias are
|
|
191
|
+
// optional tail groups. An embed prefix (`!`) is not part of the pattern, so
|
|
192
|
+
// `![[note]]` matches the `[[note]]` span and rewriting the target preserves it.
|
|
193
|
+
const WIKI_LINK = /\[\[([^\[\]|#]+)(?:#([^\[\]|]*))?(?:\|([^\[\]]*))?\]\]/g;
|
|
194
|
+
/**
|
|
195
|
+
* Byte ranges of fenced code blocks and inline code spans — the
|
|
196
|
+
* mention-protection law as one producing function: a match inside these
|
|
197
|
+
* ranges is the syntax being mentioned as a term, not a reference. Consumers
|
|
198
|
+
* (wiki scanning here, prose lints elsewhere) share this one truth by import
|
|
199
|
+
* instead of re-deriving the exclusion set from the parse, so the law can
|
|
200
|
+
* never drift between them. The shape is deliberately the narrow current
|
|
201
|
+
* law — if the mention protection ever widens (e.g. to rendered-away HTML
|
|
202
|
+
* comments), it widens in this function and every consumer inherits.
|
|
203
|
+
*/
|
|
204
|
+
export function markdownCodeRanges(source) {
|
|
205
|
+
const ranges = [];
|
|
206
|
+
visitMarkdown(parseMarkdown(source), (node) => {
|
|
207
|
+
if (node.type !== 'code' && node.type !== 'inlineCode')
|
|
208
|
+
return;
|
|
209
|
+
const start = node.position?.start.offset;
|
|
210
|
+
const end = node.position?.end.offset;
|
|
211
|
+
if (typeof start === 'number' && typeof end === 'number')
|
|
212
|
+
ranges.push({ start, end });
|
|
213
|
+
});
|
|
214
|
+
return ranges;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Scan every `[[wiki-link]]` in document order. Wiki syntax is raw text the
|
|
218
|
+
* GFM parse does not model, so the scan is a regex over the source — but a
|
|
219
|
+
* match inside fenced code or a code span is the syntax being mentioned as a
|
|
220
|
+
* term, not a reference: `markdownCodeRanges` supplies those ranges, and
|
|
221
|
+
* matches inside them are skipped. Offset-bearing output only; whether a
|
|
222
|
+
* target resolves, and what an ambiguous one means, is the caller's judgment.
|
|
223
|
+
*/
|
|
224
|
+
export function scanWikiLinks(source) {
|
|
225
|
+
const codeRanges = markdownCodeRanges(source);
|
|
226
|
+
const links = [];
|
|
227
|
+
WIKI_LINK.lastIndex = 0;
|
|
228
|
+
let match;
|
|
229
|
+
while ((match = WIKI_LINK.exec(source)) !== null) {
|
|
230
|
+
if (codeRanges.some((range) => match.index >= range.start && match.index < range.end))
|
|
231
|
+
continue;
|
|
232
|
+
const rawTarget = match[1];
|
|
233
|
+
const target = rawTarget.trim();
|
|
234
|
+
// A target of only whitespace names nothing.
|
|
235
|
+
if (target === '')
|
|
236
|
+
continue;
|
|
237
|
+
const lead = rawTarget.length - rawTarget.trimStart().length;
|
|
238
|
+
const targetStart = match.index + '[['.length + lead;
|
|
239
|
+
links.push({
|
|
240
|
+
start: match.index,
|
|
241
|
+
end: match.index + match[0].length,
|
|
242
|
+
target,
|
|
243
|
+
targetStart,
|
|
244
|
+
targetEnd: targetStart + target.length,
|
|
245
|
+
fragment: match[2] ?? null,
|
|
246
|
+
alias: match[3] ?? null,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return links;
|
|
250
|
+
}
|
|
251
|
+
/*
|
|
252
|
+
* Fork duty details live in the development-face fork duty record.
|
|
253
|
+
*/
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type GitLsFiles } from './git.js';
|
|
2
|
+
/** One planned rewrite (a `/`-prefixed reference migrated to document-relative). */
|
|
3
|
+
export interface RootRelativeRewrite {
|
|
4
|
+
/** POSIX root-relative source file. */
|
|
5
|
+
file: string;
|
|
6
|
+
/** 1-based source line. */
|
|
7
|
+
line: number;
|
|
8
|
+
/** Original `/`-prefixed destination. */
|
|
9
|
+
url: string;
|
|
10
|
+
/** Computed document-relative href (path part; suffix re-appended on apply). */
|
|
11
|
+
href: string;
|
|
12
|
+
}
|
|
13
|
+
/** One `/`-prefixed reference left untouched, with why. */
|
|
14
|
+
export interface RootRelativeSkip {
|
|
15
|
+
file: string;
|
|
16
|
+
line: number;
|
|
17
|
+
url: string;
|
|
18
|
+
reason: string;
|
|
19
|
+
}
|
|
20
|
+
export interface RootRelativePlan {
|
|
21
|
+
/** Git worktree root — carried so apply needs no re-discovery. */
|
|
22
|
+
root: string;
|
|
23
|
+
/** Absolute source path → fully rewritten content (only files with ≥1 rewrite). */
|
|
24
|
+
editsByFile: Map<string, string>;
|
|
25
|
+
rewrites: RootRelativeRewrite[];
|
|
26
|
+
skips: RootRelativeSkip[];
|
|
27
|
+
}
|
|
28
|
+
export interface RootRelativeApplyResult {
|
|
29
|
+
/** Root-relative paths whose content was rewritten. */
|
|
30
|
+
edited: string[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Plan the root-relative → document-relative normalization without writing
|
|
34
|
+
* anything. Iterates every git-visible Markdown source (so the submodule and
|
|
35
|
+
* gitignored artifacts never enter), locates `/`-prefixed references
|
|
36
|
+
* byte-exactly, and rewrites only those whose target is a tracked path.
|
|
37
|
+
*/
|
|
38
|
+
export declare function planRootRelativeNormalization(root: string, git?: GitLsFiles): RootRelativePlan;
|
|
39
|
+
/** Apply a plan: write every rewritten file (pure content rewrite, no git move). */
|
|
40
|
+
export declare function applyRootRelativeNormalization(plan: RootRelativePlan): RootRelativeApplyResult;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Root-relative link normalization seam (self-written, reverses the earlier
|
|
3
|
+
* "存量原地保留" stance): a `/`-prefixed reference whose target is a tracked
|
|
4
|
+
* repository path is rewritten to document-relative form. Rationale: the
|
|
5
|
+
* resolver (resolve.ts) treats `/` as site-root/external and skips it, so an
|
|
6
|
+
* internal `/` link silently rots across renames (the archive move exposed
|
|
7
|
+
* this). After normalization every internal reference resolves through
|
|
8
|
+
* `checkRepository` again instead of being skipped.
|
|
9
|
+
*
|
|
10
|
+
* Scope is deliberately narrow: only `link`/`image`/`definition` references
|
|
11
|
+
* whose destination starts with `/` (and not `//`) AND whose stripped path is a
|
|
12
|
+
* tracked file or a tracked directory are rewritten. Everything else — site-root
|
|
13
|
+
* paths (`/gates`, `/api`), protocol-relative (`//`), scheme URLs, and
|
|
14
|
+
* unresolved `/` links — is left verbatim and reported as a skip. The rewrite is
|
|
15
|
+
* byte-preserving via `rebaseDestination`, so the `#fragment` / `?query` suffix
|
|
16
|
+
* and every other byte survive.
|
|
17
|
+
*/
|
|
18
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import { dirname, resolve } from 'node:path';
|
|
20
|
+
import { gitLsFiles, gitTopLevel } from './git.js';
|
|
21
|
+
import { rebaseDestination } from './rebase.js';
|
|
22
|
+
import { collectMarkdownSources, extractReferences, posixRelative } from './resolve.js';
|
|
23
|
+
/** Tracked files plus every ancestor directory, as POSIX root-relative keys. */
|
|
24
|
+
function trackedPathKeys(root, git) {
|
|
25
|
+
const files = new Set();
|
|
26
|
+
const dirs = new Set();
|
|
27
|
+
for (const rel of git(root)) {
|
|
28
|
+
files.add(rel);
|
|
29
|
+
let cursor = rel;
|
|
30
|
+
for (;;) {
|
|
31
|
+
const slash = cursor.lastIndexOf('/');
|
|
32
|
+
if (slash === -1)
|
|
33
|
+
break;
|
|
34
|
+
cursor = cursor.slice(0, slash);
|
|
35
|
+
dirs.add(cursor);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { files, dirs };
|
|
39
|
+
}
|
|
40
|
+
function skipOf(root, sourceFile, ref, url, reason) {
|
|
41
|
+
return { file: posixRelative(root, sourceFile), line: ref.line, url, reason };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Plan the root-relative → document-relative normalization without writing
|
|
45
|
+
* anything. Iterates every git-visible Markdown source (so the submodule and
|
|
46
|
+
* gitignored artifacts never enter), locates `/`-prefixed references
|
|
47
|
+
* byte-exactly, and rewrites only those whose target is a tracked path.
|
|
48
|
+
*/
|
|
49
|
+
export function planRootRelativeNormalization(root, git = gitLsFiles) {
|
|
50
|
+
const repoRoot = gitTopLevel(root);
|
|
51
|
+
const { files, dirs } = trackedPathKeys(repoRoot, git);
|
|
52
|
+
const editsByFile = new Map();
|
|
53
|
+
const rewrites = [];
|
|
54
|
+
const skips = [];
|
|
55
|
+
for (const sourceFile of collectMarkdownSources(repoRoot, git)) {
|
|
56
|
+
const source = readFileSync(sourceFile, 'utf8');
|
|
57
|
+
const perFile = [];
|
|
58
|
+
for (const ref of extractReferences(source)) {
|
|
59
|
+
const url = ref.url;
|
|
60
|
+
if (!url.startsWith('/') || url.startsWith('//'))
|
|
61
|
+
continue; // only /-prefixed, never protocol-relative
|
|
62
|
+
const bare = url.slice(1).replace(/[#?].*$/, ''); // strip leading / and any suffix
|
|
63
|
+
if (bare === '')
|
|
64
|
+
continue; // link to the repository root itself (`/` or `/#frag`)
|
|
65
|
+
const hadTrailingSlash = bare.endsWith('/');
|
|
66
|
+
const key = hadTrailingSlash ? bare.slice(0, -1) : bare;
|
|
67
|
+
let targetRel;
|
|
68
|
+
if (files.has(key))
|
|
69
|
+
targetRel = key;
|
|
70
|
+
else if (dirs.has(key))
|
|
71
|
+
targetRel = key;
|
|
72
|
+
else {
|
|
73
|
+
skips.push(skipOf(repoRoot, sourceFile, ref, url, 'not a tracked repository path (site-root or unresolved)'));
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (ref.start === undefined || ref.end === undefined) {
|
|
77
|
+
skips.push(skipOf(repoRoot, sourceFile, ref, url, 'no rebasable destination (autolink / bare URL)'));
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
let href = posixRelative(dirname(sourceFile), resolve(repoRoot, targetRel));
|
|
81
|
+
if (hadTrailingSlash && !href.endsWith('/'))
|
|
82
|
+
href += '/';
|
|
83
|
+
rewrites.push({ file: posixRelative(repoRoot, sourceFile), line: ref.line, url, href });
|
|
84
|
+
perFile.push({ reference: ref, href });
|
|
85
|
+
}
|
|
86
|
+
if (perFile.length > 0) {
|
|
87
|
+
// Non-overlapping AST nodes: apply in descending start order keeps offsets valid.
|
|
88
|
+
const ordered = [...perFile].sort((a, b) => (b.reference.start ?? 0) - (a.reference.start ?? 0));
|
|
89
|
+
let out = source;
|
|
90
|
+
for (const { reference, href } of ordered)
|
|
91
|
+
out = rebaseDestination(out, reference, href);
|
|
92
|
+
editsByFile.set(sourceFile, out);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { root: repoRoot, editsByFile, rewrites, skips };
|
|
96
|
+
}
|
|
97
|
+
/** Apply a plan: write every rewritten file (pure content rewrite, no git move). */
|
|
98
|
+
export function applyRootRelativeNormalization(plan) {
|
|
99
|
+
for (const [file, content] of plan.editsByFile)
|
|
100
|
+
writeFileSync(file, content);
|
|
101
|
+
return { edited: [...plan.editsByFile.keys()].map(file => posixRelative(plan.root, file)) };
|
|
102
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { LinkReference } from './resolve.js';
|
|
2
|
+
/**
|
|
3
|
+
* Rewrite one reference's destination in `source`, preserving the fragment /
|
|
4
|
+
* query suffix and every other byte. The reference must carry byte offsets from
|
|
5
|
+
* `extractReferences` (via `markdownDestination`), never a re-serialized
|
|
6
|
+
* position — this is the byte-preserving contract.
|
|
7
|
+
* @param source - the document the reference was extracted from.
|
|
8
|
+
* @param reference - the located reference whose destination changes.
|
|
9
|
+
* @param newPath - the replacement destination path (its suffix is preserved).
|
|
10
|
+
* @returns the source with exactly the destination substring replaced.
|
|
11
|
+
*/
|
|
12
|
+
export declare function rebaseDestination(source: string, reference: LinkReference, newPath: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* Rewrite one reference's label in `source`, byte-preserving everything else
|
|
15
|
+
* (the destination, the brackets, the rest of the document). The reference must
|
|
16
|
+
* carry a located label from `extractReferences` — definitions, markup labels,
|
|
17
|
+
* and forms with no label range are not relabelable and fail fast rather than
|
|
18
|
+
* guess a range.
|
|
19
|
+
* @param source - the document the reference was extracted from.
|
|
20
|
+
* @param reference - the located reference whose label changes.
|
|
21
|
+
* @param newLabel - the replacement label text (no brackets; written verbatim).
|
|
22
|
+
* @returns the source with exactly the label substring replaced.
|
|
23
|
+
*/
|
|
24
|
+
export declare function rebaseLabel(source: string, reference: LinkReference, newLabel: string): string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rebase seam — byte-preserving rewrite of one reference: replace only the
|
|
3
|
+
* destination substring, or only the label substring, keeping the
|
|
4
|
+
* fragment/query suffix and every other byte. Callers that rewrite both (a
|
|
5
|
+
* mirrored label — see `relabelFor`) splice the destination first: inside
|
|
6
|
+
* one reference the label range always sits strictly BEFORE the destination
|
|
7
|
+
* range, so descending-offset order keeps every remaining offset valid.
|
|
8
|
+
*/
|
|
9
|
+
import { splitMarkdownUrlTarget } from './markdown.js';
|
|
10
|
+
/**
|
|
11
|
+
* Rewrite one reference's destination in `source`, preserving the fragment /
|
|
12
|
+
* query suffix and every other byte. The reference must carry byte offsets from
|
|
13
|
+
* `extractReferences` (via `markdownDestination`), never a re-serialized
|
|
14
|
+
* position — this is the byte-preserving contract.
|
|
15
|
+
* @param source - the document the reference was extracted from.
|
|
16
|
+
* @param reference - the located reference whose destination changes.
|
|
17
|
+
* @param newPath - the replacement destination path (its suffix is preserved).
|
|
18
|
+
* @returns the source with exactly the destination substring replaced.
|
|
19
|
+
*/
|
|
20
|
+
export function rebaseDestination(source, reference, newPath) {
|
|
21
|
+
if (reference.start === undefined || reference.end === undefined) {
|
|
22
|
+
throw new Error('rebaseDestination requires a reference with byte offsets (autolinks and bare URLs are not rebasable)');
|
|
23
|
+
}
|
|
24
|
+
const { suffix } = splitMarkdownUrlTarget(reference.url);
|
|
25
|
+
return source.slice(0, reference.start) + newPath + suffix + source.slice(reference.end);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Rewrite one reference's label in `source`, byte-preserving everything else
|
|
29
|
+
* (the destination, the brackets, the rest of the document). The reference must
|
|
30
|
+
* carry a located label from `extractReferences` — definitions, markup labels,
|
|
31
|
+
* and forms with no label range are not relabelable and fail fast rather than
|
|
32
|
+
* guess a range.
|
|
33
|
+
* @param source - the document the reference was extracted from.
|
|
34
|
+
* @param reference - the located reference whose label changes.
|
|
35
|
+
* @param newLabel - the replacement label text (no brackets; written verbatim).
|
|
36
|
+
* @returns the source with exactly the label substring replaced.
|
|
37
|
+
*/
|
|
38
|
+
export function rebaseLabel(source, reference, newLabel) {
|
|
39
|
+
const label = reference.label;
|
|
40
|
+
if (label === undefined) {
|
|
41
|
+
throw new Error('rebaseLabel requires a reference with a located label (definitions, markup labels, and link forms without one are not relabelable)');
|
|
42
|
+
}
|
|
43
|
+
return source.slice(0, label.start) + newLabel + source.slice(label.end);
|
|
44
|
+
}
|