markdown-parity-check 0.2.33 → 0.2.35
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/README.md +16 -12
- package/SECURITY.md +2 -2
- package/dist/src/align.d.ts +3 -2
- package/dist/src/align.js +25 -6
- package/dist/src/cli.d.ts +1 -1
- package/dist/src/cli.js +16 -1
- package/dist/src/compare.d.ts +7 -5
- package/dist/src/compare.js +71 -76
- package/dist/src/fetch.js +59 -3
- package/dist/src/html.d.ts +1 -0
- package/dist/src/html.js +22 -8
- package/dist/src/markdown.js +115 -29
- package/dist/src/normalize.d.ts +17 -3
- package/dist/src/normalize.js +49 -11
- package/dist/src/run.js +33 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -2
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ npx --yes markdown-parity-check --html-file page.html --markdown-file page.md --
|
|
|
51
51
|
| --- | --- |
|
|
52
52
|
| `0` | The comparison completed without a rejecting finding. |
|
|
53
53
|
| `1` | The comparison completed and found rejecting content or delivery differences. |
|
|
54
|
-
| `2` | An input, fetch, parse or report error prevented a reliable comparison. |
|
|
54
|
+
| `2` | An input, fetch, parse or report error prevented a reliable comparison. A standard output that is closed before the report is written also gives 2. |
|
|
55
55
|
|
|
56
56
|
Exit code 0 means the implemented checks found nothing to reject. It does not prove that the two versions mean the same thing.
|
|
57
57
|
|
|
@@ -78,10 +78,10 @@ A value that is outside these ranges, or that is not a plain run of digits, stop
|
|
|
78
78
|
|
|
79
79
|
### Example output
|
|
80
80
|
|
|
81
|
-
This is the text report for the matching fixture pair in this repository, run with version 0.2.
|
|
81
|
+
This is the text report for the matching fixture pair in this repository, run with version 0.2.35 on 2026-11-07. The exact command is in the Development section below. The text report ends with a list of limitations, which is omitted here:
|
|
82
82
|
|
|
83
83
|
```text
|
|
84
|
-
markdown-parity-check 0.2.
|
|
84
|
+
markdown-parity-check 0.2.35 (offline mode)
|
|
85
85
|
Result: PASS (0 error(s), 0 warning(s), 1 info)
|
|
86
86
|
|
|
87
87
|
HTML: test/fixtures/same/page.html (file, 1,017 bytes, base https://example.com/page)
|
|
@@ -110,10 +110,10 @@ Front matter is kept by default and compared as content. If the HTML does not ca
|
|
|
110
110
|
|
|
111
111
|
### Blocks and severities
|
|
112
112
|
|
|
113
|
-
Headings, paragraphs, list items, tables, code blocks and links are compared block by block. A link that wraps block elements, such as a linked card with a heading and a paragraph, is compared as those blocks: each keeps its own type and heading level and carries the link, and the Markdown side is read the same way, so `## [Title](url)` is a heading with a link. In a table cell the link is read as part of the cell text. Content
|
|
113
|
+
Headings, paragraphs, list items, tables, code blocks and links are compared block by block. A link that wraps block elements, such as a linked card with a heading and a paragraph, is compared as those blocks: each keeps its own type and heading level and carries the link, and the Markdown side is read the same way, so `## [Title](url)` is a heading with a link. In a table cell the link is read as part of the cell text. Content that is hidden or sits inside a left-out element is left out on both sides, also when the raw HTML wrapper, such as `<div hidden>` or `<nav>`, is opened in one Markdown block and closed in a later one. A table caption counts as a paragraph before the table.
|
|
114
114
|
|
|
115
115
|
- Errors: missing and added blocks, a change in text or numbers, a changed table or link, and a list item that shows another number or a different checked or unchecked state.
|
|
116
|
-
- Warnings: a checkbox that is present on one side only, a difference in order, which is also reported for a block that moved and changed only in case, punctuation or typographic characters, and a difference in heading level, case, punctuation, list kind or nesting level. Each footnote in the Markdown is a warning, because footnotes are not compared. These are the main cases, and the `code` of each finding names the exact rule. A missing or extra copy of a repeated block is reported as a missing or added block, which is an error.
|
|
116
|
+
- Warnings: a checkbox that is present on one side only, a difference in order, which is also reported for a block that moved and changed only in case, punctuation or typographic characters, and a difference in heading level, case, punctuation, list kind or nesting level. A block that moved and also changed in its words or numbers gets the finding for that change and no order finding. A changed accent mark, vowel sign, symbol or emoji is a change in text and not in punctuation, so it is an error. A swapped symbol is an error also when a reader sees the same meaning, for example an ASCII arrow made of a hyphen and a greater-than sign against an arrow character, or a dropped trademark sign. An invisible variation selector alone is not. Each footnote in the Markdown is a warning, because footnotes are not compared. These are the main cases, and the `code` of each finding names the exact rule. A missing or extra copy of a repeated block is reported as a missing or added block, which is an error.
|
|
117
117
|
- Information: each skipped comparison, which does not fail a check, not even with `--strict`.
|
|
118
118
|
|
|
119
119
|
The cell-by-cell comparison of a table is skipped when one of its cells has a rowspan or colspan above 1, a rowspan of 0, or a value that is empty or does not begin with a number. The number is read from the value's leading digits, so `2abc` counts as 2. A colspan of 0 and a rowspan or colspan of 1 do not trigger it. The links and the caption of such a table are still compared. The numbering of a reversed list is not compared either.
|
|
@@ -129,13 +129,15 @@ Some content is left out even when it sits inside the main content, in code bloc
|
|
|
129
129
|
|
|
130
130
|
The `starlight` profile keeps an iframe that has a source and a title, as a link. The same list applies to inline raw HTML in the Markdown and to the checkbox of a task list item, which must belong to the item itself.
|
|
131
131
|
|
|
132
|
-
A left-out tag in a Markdown paragraph, such as a `<button>` or a `<script>`, is skipped through its matching closing tag in the same paragraph.
|
|
132
|
+
A left-out tag in a Markdown paragraph, such as a `<button>` or a `<script>`, is skipped through its matching closing tag in the same paragraph. Inside a paragraph, a left-out tag with no closing tag is reported as a warning and its text is compared as visible. A left-out wrapper such as `<nav>` or `<form>` that is opened in its own Markdown block and never closed hides every block after it, the way an unclosed element does in HTML, and a Markdown document left with no content ends with exit code 2. The void tags `input` and `embed` need no closing tag and are skipped on their own. A self-closing `<svg/>` counts as closed by itself, as in HTML, and `<button/>` does not.
|
|
133
133
|
|
|
134
134
|
A `<br>` in a code block is a line break. A code block that differs only in whitespace is a warning, where whitespace means the ASCII whitespace characters and the Unicode space separators such as the no-break space. Any other difference in code, an invisible character such as a soft hyphen included, is an error. An image is compared by its alt text only, not by its address, so two different images with the same alt text compare equal.
|
|
135
135
|
|
|
136
136
|
### Delivery in URL mode
|
|
137
137
|
|
|
138
|
-
In URL mode the Markdown response is checked first. An HTTP error or an HTML page in place of Markdown fails the check, and nothing is compared. A Markdown response labelled `text/plain` is a warning, and any other content type than `text/markdown` or `text/x-markdown` is an error. If the HTML request itself returns an HTTP error, the run ends with exit code 2.
|
|
138
|
+
In URL mode the Markdown response is checked first. An HTTP error or an HTML page in place of Markdown fails the check, and nothing is compared. A Markdown response labelled `text/plain` is a warning, and any other content type than `text/markdown` or `text/x-markdown` is an error. A comment, an XML declaration or another declaration before the doctype does not hide an HTML page from this check. If the HTML request itself returns an HTTP error, the run ends with exit code 2.
|
|
139
|
+
|
|
140
|
+
An HTML response is decoded by its byte order mark first, then by the charset of its Content-Type header, then by a meta charset declaration in its first 1024 bytes, and as UTF-8 when none of them names a known encoding. A Markdown response is decoded by the charset of its header, or as UTF-8.
|
|
139
141
|
|
|
140
142
|
### Limits of the method
|
|
141
143
|
|
|
@@ -158,9 +160,10 @@ The hosted page also answers a JSON POST, described on the page. It runs the rel
|
|
|
158
160
|
Some limits are not in the table:
|
|
159
161
|
|
|
160
162
|
- A URL that contains a user name or password is refused even when its host is public, and the same holds for a redirect target.
|
|
163
|
+
- A host written as an IPv6 literal in brackets is checked against the same address policy as a resolved address and is not looked up in DNS.
|
|
161
164
|
- The tool sends `Accept-Encoding: gzip, deflate, br` and decodes responses with no Content-Encoding, `identity`, `gzip`, `x-gzip`, `deflate` or `br`. A response with any other Content-Encoding, `zstd` for example, is rejected, and the run ends with exit code 2.
|
|
162
165
|
- The command-line tool follows at most 5 redirects.
|
|
163
|
-
- When elements are nested more than 1024 levels deep, in the HTML page, in a raw HTML block written inside the Markdown or in the Markdown's own structure, the extraction stops with exit code 2.
|
|
166
|
+
- When elements are nested more than 1024 levels deep, in the HTML page, in a raw HTML block written inside the Markdown, across raw elements left open between Markdown blocks, or in the Markdown's own structure, the extraction stops with exit code 2.
|
|
164
167
|
- The matching stops the same way when more than 1 000 000 similar block pairs would have to be considered. The library `limits` default to the same two values for block pairs and similar block pairs. `maxSimilarityWork` has no default bound.
|
|
165
168
|
- The hosted page uses lower nesting and matching limits: 512 levels and 50 000 similar block pairs.
|
|
166
169
|
|
|
@@ -199,18 +202,19 @@ The options type is `RunOptions`. It takes `selector`, `frontMatter`, `strict`,
|
|
|
199
202
|
|
|
200
203
|
When the Markdown source has `kind: 'url'` in its `meta`, the delivery check runs first and reads the HTTP `status` and `contentType` from that `meta`.
|
|
201
204
|
|
|
202
|
-
A host with a smaller CPU or memory budget can pass lower `limits`, typed as `RunLimits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The nesting limit also applies to raw HTML blocks inside the Markdown. Set `maxSimilarityWork` when the library compares untrusted documents: with the default limits one
|
|
205
|
+
A host with a smaller CPU or memory budget can pass lower `limits`, typed as `RunLimits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The nesting limit also applies to raw HTML blocks inside the Markdown. Set `maxSimilarityWork` when the library compares untrusted documents: with the default limits one worst case at the full 4 000 000 block pairs (100 HTML blocks of 870 distinct words against 40 000 Markdown blocks of one word each) took between 26 and 30 seconds in hand timings on development machines, and a value of 2 000 000 made the pairing step stop after about 70 milliseconds, on top of the parse time. The test suite runs the bounded case and asserts no time. When a limit is exceeded, `run` throws a `RunError` whose message names the limit, and the command line reports it with exit code 2.
|
|
203
206
|
|
|
204
207
|
The caller fetches the pages and decides which addresses are allowed. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
|
|
205
208
|
|
|
206
209
|
### Report format
|
|
207
210
|
|
|
208
|
-
The JSON report is the `Report` type. Its
|
|
211
|
+
The JSON report is the `Report` type. Its top-level fields are:
|
|
209
212
|
|
|
210
213
|
| Field | Content |
|
|
211
214
|
| --- | --- |
|
|
212
215
|
| `schemaVersion` | The number `1`. |
|
|
213
216
|
| `toolVersion` | The release that produced the report. |
|
|
217
|
+
| `generatedAt` | The time the report was made, as an ISO 8601 timestamp in UTC. |
|
|
214
218
|
| `mode` | `url` or `offline`. |
|
|
215
219
|
| `sources` | The metadata of the HTML and the Markdown input. |
|
|
216
220
|
| `extraction` | How each side was extracted. It is `null` in an error report and in a result that failed at the delivery check, because no extraction result is reported then. |
|
|
@@ -245,10 +249,10 @@ Only after that check does it create the GitHub release with the verified tarbal
|
|
|
245
249
|
GitHub Actions publishes every version from 0.1.2 on with npm trusted publishing, and each one carries a provenance attestation. To check one, install it in an empty directory and ask npm to verify the signatures. Replace the version with the one you want to check.
|
|
246
250
|
|
|
247
251
|
```sh
|
|
248
|
-
mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.
|
|
252
|
+
mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.35 --ignore-scripts && npm audit signatures
|
|
249
253
|
```
|
|
250
254
|
|
|
251
|
-
`npm audit signatures` checks the registry signature and the provenance attestation of each installed package that has one. The attestation of this package names three things to compare with what you expect: the repository `github.com/erekola/markdown-parity-check`, the workflow file `.github/workflows/release.yml` and the commit that produced the tarball. The npm version page shows them under Provenance. Tag `v0.2.
|
|
255
|
+
`npm audit signatures` checks the registry signature and the provenance attestation of each installed package that has one. The attestation of this package names three things to compare with what you expect: the repository `github.com/erekola/markdown-parity-check`, the workflow file `.github/workflows/release.yml` and the commit that produced the tarball. The npm version page shows them under Provenance. Tag `v0.2.35` must point at that same commit, and `gh api repos/erekola/markdown-parity-check/commits/v0.2.35 --jq .sha` prints it. A mismatch is a reason not to use that version. Provenance proves which workflow built a release and from which commit. It does not prove that the code is safe, so reading the source and the dependencies stays your job.
|
|
252
256
|
|
|
253
257
|
## Security
|
|
254
258
|
|
package/SECURITY.md
CHANGED
|
@@ -14,7 +14,7 @@ Please do not open a public issue for security reports. You can expect an initia
|
|
|
14
14
|
|
|
15
15
|
URL mode requests HTML and Markdown over HTTP or HTTPS. Non-public network targets are blocked, including targets reached through DNS and redirects. Each fetch has a deadline and a limit on decoded response bytes. The defaults are 15 seconds and 5 MiB. In the command line the same deadline also covers parsing and comparison, which run in a worker thread that is stopped when the deadline passes, and the tool then exits with code 2. The library entry point has no such deadline, so a program that compares untrusted documents with it needs a time limit of its own. JavaScript from fetched pages is not executed.
|
|
16
16
|
|
|
17
|
-
The number of block pairs is bounded by the product of the two block counts, at most 4 000 000. The time spent on each pair is not: the similarity search walks the distinct words of the HTML block once per pair, so the work grows with block pairs times distinct words per HTML block. One
|
|
17
|
+
The number of block pairs is bounded by the product of the two block counts, at most 4 000 000. The time spent on each pair is not: the similarity search walks the distinct words of the HTML block once per pair, so the work grows with block pairs times distinct words per HTML block. One case, 100 HTML blocks of 870 distinct words each against 40 000 Markdown blocks of one word each, which is 4 000 000 pairs, took between 26 and 30 seconds with default limits on development machines, in two hand timings by two people that the test suite does not repeat. The command line stops such a run at its deadline. The number of similar block pairs kept for matching is bounded as well. Above either limit the tool stops with exit code 2 and an error message instead of reporting a pass for a comparison it did not complete. The pairing of links inside one block is not separately bounded by default: with the default limits it has no budget of its own, and a block with thousands of links that cannot be resolved against a base URL can take time that grows with the square of the link count. The maxSimilarityWork limit is unbounded by default and covers both cases, so a library caller that compares untrusted documents should set it. In the case above, a limit of 2 000 000 made the pairing step stop after about 70 milliseconds, on top of the time spent parsing the two documents, and the whole call took under one second. `run` throws a `RunError` there, with a message that names the limit, and the command line reports it with exit code 2.
|
|
18
18
|
|
|
19
19
|
Offline mode reads the two files supplied by the caller. The output option writes a report to the selected path. Reports mask URL query values and fragments and remove any user name or password from a URL. Excerpts may contain private page content. Review reports before sharing them.
|
|
20
20
|
|
|
@@ -22,7 +22,7 @@ Offline mode reads the two files supplied by the caller. The output option write
|
|
|
22
22
|
|
|
23
23
|
The tool uses runtime dependencies to parse and compare content. Dependency versions and integrity hashes are recorded in package-lock.json. GitHub Actions installs locked dependencies with install scripts disabled and runs type checks and tests on Windows and Ubuntu.
|
|
24
24
|
|
|
25
|
-
The package is published on npm as `markdown-parity-check`. Each version has a matching GitHub release. The attached tarball is the registry copy after its integrity hash and content were checked against the freshly packed file. The first npm release was published from a maintainer machine and has no provenance attestation. Its npm metadata names commit 7e8fad9 as its source, while the tag of that release points at 3f3a599, the release commit that follows it and adds the license, this policy, the release workflow and the package manifest without changing src/ or test/. The tag stays where it is. Every version from 0.1.2 on is published from GitHub Actions with npm trusted publishing and carries a provenance attestation, which the registry served for each
|
|
25
|
+
The package is published on npm as `markdown-parity-check`. Each version has a matching GitHub release. The attached tarball is the registry copy after its integrity hash and content were checked against the freshly packed file. The first npm release was published from a maintainer machine and has no provenance attestation. Its npm metadata names commit 7e8fad9 as its source, while the tag of that release points at 3f3a599, the release commit that follows it and adds the license, this policy, the release workflow and the package manifest without changing src/ or test/. The tag stays where it is. Every version from 0.1.2 on is published from GitHub Actions with npm trusted publishing and carries a provenance attestation, which the registry served for each version up to 0.2.34 when it was last checked on 2026-11-07.
|
|
26
26
|
|
|
27
27
|
## Verify a release
|
|
28
28
|
|
package/dist/src/align.d.ts
CHANGED
|
@@ -19,8 +19,9 @@ export declare function strictKey(b: Block): string;
|
|
|
19
19
|
export declare const SIMILARITY_THRESHOLD = 0.6;
|
|
20
20
|
export declare const UNCERTAIN_THRESHOLD = 0.8;
|
|
21
21
|
/** Upper bound on the alignment work, as the product of the HTML and Markdown block counts. The LCS
|
|
22
|
-
* table holds (n+1)*(m+1) Uint32 cells
|
|
23
|
-
*
|
|
22
|
+
* table holds (n+1)*(m+1) Uint32 cells: 16 MiB for a square pair at the limit (2 000 by 2 000 blocks) and more for a
|
|
23
|
+
* lopsided pair with the same product (1 by 4 000 000 blocks is about 32 MB). The similarity search visits at most
|
|
24
|
+
* n*m block pairs. Above the limit the comparison stops with an error before any
|
|
24
25
|
* table is allocated, instead of growing without bound with the page size. */
|
|
25
26
|
export declare const MAX_ALIGNMENT_PAIRS = 4000000;
|
|
26
27
|
/** Upper bound on the similarity candidates kept for the greedy best-match pass. Only pairs at or above
|
package/dist/src/align.js
CHANGED
|
@@ -16,11 +16,17 @@ export function strictKey(b) {
|
|
|
16
16
|
function looseKey(b) {
|
|
17
17
|
return `${typeGroup(b)} ${b.loose}`;
|
|
18
18
|
}
|
|
19
|
+
/** The link targets of a block, with their texts, in order. Blocks with equal text and equal link signatures are the
|
|
20
|
+
* same block as far as the links go, so the alignment prefers them over equal-text blocks with other targets (MP-13). */
|
|
21
|
+
function linkSignature(b) {
|
|
22
|
+
return b.links.map((l) => `${l.text}\x1f${l.resolved ?? l.rawHref}`).join('\x1e');
|
|
23
|
+
}
|
|
19
24
|
export const SIMILARITY_THRESHOLD = 0.6;
|
|
20
25
|
export const UNCERTAIN_THRESHOLD = 0.8;
|
|
21
26
|
/** Upper bound on the alignment work, as the product of the HTML and Markdown block counts. The LCS
|
|
22
|
-
* table holds (n+1)*(m+1) Uint32 cells
|
|
23
|
-
*
|
|
27
|
+
* table holds (n+1)*(m+1) Uint32 cells: 16 MiB for a square pair at the limit (2 000 by 2 000 blocks) and more for a
|
|
28
|
+
* lopsided pair with the same product (1 by 4 000 000 blocks is about 32 MB). The similarity search visits at most
|
|
29
|
+
* n*m block pairs. Above the limit the comparison stops with an error before any
|
|
24
30
|
* table is allocated, instead of growing without bound with the page size. */
|
|
25
31
|
export const MAX_ALIGNMENT_PAIRS = 4_000_000;
|
|
26
32
|
/** Upper bound on the similarity candidates kept for the greedy best-match pass. Only pairs at or above
|
|
@@ -84,10 +90,17 @@ export function checkAlignmentLimit(htmlBlocks, markdownBlocks, maxPairs = MAX_A
|
|
|
84
90
|
throw new AlignmentLimitError(`Comparison limit exceeded: ${htmlBlocks} HTML blocks by ${markdownBlocks} Markdown blocks is ${pairs} block pairs, above the limit of ${maxPairs}. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
85
91
|
}
|
|
86
92
|
}
|
|
87
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Longest common subsequence of the strict keys. Among the chains of the same length it takes the one with the most
|
|
95
|
+
* pairs whose link signatures agree (MP-13): a match weighs W, a match with equal link signatures W + 1, and W is
|
|
96
|
+
* larger than the number of possible bonuses, so the length of the chain is decided first and the targets only break
|
|
97
|
+
* ties. Without links on either side every bonus is equal and the chain is the one the plain table gave.
|
|
98
|
+
*/
|
|
99
|
+
function lcs(keysA, keysB, sigA, sigB, maxPairs) {
|
|
88
100
|
const n = keysA.length;
|
|
89
101
|
const m = keysB.length;
|
|
90
102
|
checkAlignmentLimit(n, m, maxPairs);
|
|
103
|
+
const weight = Math.min(n, m) + 1;
|
|
91
104
|
const dp = [];
|
|
92
105
|
for (let i = 0; i <= n; i++)
|
|
93
106
|
dp.push(new Uint32Array(m + 1));
|
|
@@ -95,14 +108,20 @@ function lcs(keysA, keysB, maxPairs) {
|
|
|
95
108
|
const row = dp[i];
|
|
96
109
|
const next = dp[i + 1];
|
|
97
110
|
for (let j = m - 1; j >= 0; j--) {
|
|
98
|
-
|
|
111
|
+
let best = Math.max(next[j], row[j + 1]);
|
|
112
|
+
if (keysA[i] === keysB[j]) {
|
|
113
|
+
const take = next[j + 1] + weight + (sigA[i] === sigB[j] ? 1 : 0);
|
|
114
|
+
if (take > best)
|
|
115
|
+
best = take;
|
|
116
|
+
}
|
|
117
|
+
row[j] = best;
|
|
99
118
|
}
|
|
100
119
|
}
|
|
101
120
|
const out = [];
|
|
102
121
|
let i = 0;
|
|
103
122
|
let j = 0;
|
|
104
123
|
while (i < n && j < m) {
|
|
105
|
-
if (keysA[i] === keysB[j]) {
|
|
124
|
+
if (keysA[i] === keysB[j] && dp[i][j] === dp[i + 1][j + 1] + weight + (sigA[i] === sigB[j] ? 1 : 0)) {
|
|
106
125
|
out.push([i, j]);
|
|
107
126
|
i++;
|
|
108
127
|
j++;
|
|
@@ -172,7 +191,7 @@ export function align(a, b, limits) {
|
|
|
172
191
|
const usedB = new Set();
|
|
173
192
|
const keysA = a.map(strictKey);
|
|
174
193
|
const keysB = b.map(strictKey);
|
|
175
|
-
for (const [i, j] of lcs(keysA, keysB, lim.maxAlignmentPairs)) {
|
|
194
|
+
for (const [i, j] of lcs(keysA, keysB, a.map(linkSignature), b.map(linkSignature), lim.maxAlignmentPairs)) {
|
|
176
195
|
pairs.push({ a: i, b: j, kind: 'exact', similarity: 1 });
|
|
177
196
|
usedA.add(i);
|
|
178
197
|
usedB.add(j);
|
package/dist/src/cli.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { type FetchOptions, type FetchResult } from './fetch.js';
|
|
3
|
-
export declare const HELP = "markdown-parity-check 0.2.
|
|
3
|
+
export declare const HELP = "markdown-parity-check 0.2.35\nCompares the main content of a web page's HTML and Markdown representations and reports concrete\nmissing, added and changed blocks.\n\nUsage:\n markdown-parity-check --url <https://example.com/page> [--markdown-url <url>] [options]\n markdown-parity-check --html-file <page.html> --markdown-file <page.md> [--base-url <url>] [options]\n\nModes:\n --url <url> Fetch <url> twice: with Accept: text/html and with Accept: text/markdown.\n --markdown-url <url> Fetch the Markdown from this explicit address instead (requires --url).\n --html-file <path> Offline: local HTML file (requires --markdown-file).\n --markdown-file <path> Offline: local Markdown file (requires --html-file).\n --base-url <url> Offline: base for resolving relative links on both sides.\n\nOptions:\n --html-profile generic|starlight\n HTML extraction rules (default: generic). Starlight includes inactive tab panels.\n --selector <css> CSS selector for the HTML main content (default: main, article, [role=main], then body).\n --front-matter keep|strip\n Markdown front matter. keep (default) removes nothing and warns when the document\n starts with a YAML-looking fenced block; strip removes that leading block.\n --format text|json Report format (default: text).\n --output <path> Write the report to a file instead of stdout. Refuses to overwrite an input file.\n --timeout-ms <n> Timeout in milliseconds for each fetch and for the parse-and-compare step\n (default: 15000). When it runs out the exit code is 2.\n --max-bytes <n> Cap on decoded response bytes per fetch (default: 5242880).\n --strict Treat warnings as rejecting findings too.\n --help, -h Show this help.\n --version, -V Show the version.\n\nExit codes:\n 0 comparison completed, no rejecting finding\n 1 comparison completed, rejecting content or delivery differences found\n 2 input, fetch, parse or report error prevented a reliable comparison\n\nOnly http(s) URLs to public addresses are fetched; loopback, private, link-local and other non-public\naddresses are refused, also behind DNS and redirects. No JavaScript is executed. Exit 0 does not prove\nsemantic equivalence.\n";
|
|
4
4
|
export declare class CliError extends Error {
|
|
5
5
|
}
|
|
6
6
|
export interface CliArgs {
|
package/dist/src/cli.js
CHANGED
|
@@ -396,7 +396,22 @@ export async function main(argv, io = { stdout: (s) => process.stdout.write(s),
|
|
|
396
396
|
}
|
|
397
397
|
const invokedDirectly = process.argv[1] !== undefined && samePath(path.resolve(process.argv[1]), fileURLToPath(import.meta.url));
|
|
398
398
|
if (invokedDirectly) {
|
|
399
|
+
// A reader that closes the pipe before the report is written (head -c 0, a pager that quit) makes the write fail with
|
|
400
|
+
// EPIPE. The report could not be delivered, which is a failed run: exit 2, as for every other report that cannot be
|
|
401
|
+
// written (MP-21). Without a listener the error was an unhandled event and the exit code was 1.
|
|
402
|
+
let outputFailed = false;
|
|
403
|
+
process.stdout.on('error', (err) => {
|
|
404
|
+
outputFailed = true;
|
|
405
|
+
process.exitCode = 2;
|
|
406
|
+
try {
|
|
407
|
+
process.stderr.write(redactText(`Error: Cannot write the report to stdout: ${err.code ?? err.message}\n`));
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
// stderr may be closed as well; the exit code carries the failure.
|
|
411
|
+
}
|
|
412
|
+
});
|
|
399
413
|
main(process.argv.slice(2)).then((code) => {
|
|
400
|
-
|
|
414
|
+
if (!outputFailed)
|
|
415
|
+
process.exitCode = code;
|
|
401
416
|
});
|
|
402
417
|
}
|
package/dist/src/compare.d.ts
CHANGED
|
@@ -30,11 +30,13 @@ export declare function diffNumbers(a: string[], b: string[]): {
|
|
|
30
30
|
* 1. Links whose text occurs equally often on both sides pair in document order: the first "download" with the
|
|
31
31
|
* first "download". Up to 0.2.12 every link took any unused link with the same text and target, so two links with
|
|
32
32
|
* the same text and swapped targets passed with no finding (0.2.13, found by an outside review 2026-09-26).
|
|
33
|
-
* 2.
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
33
|
+
* 2. Links whose text occurs a different number of times pair in order of occurrence too (MP-14). When the targets of
|
|
34
|
+
* the shorter side appear in the same order among the targets of the longer side, they pair with those, so a link
|
|
35
|
+
* added or removed anywhere is one addition or one missing link and nothing else. Otherwise the first links of the
|
|
36
|
+
* two sides pair by position and the surplus is missing or added, so a swap that comes with an added link is two
|
|
37
|
+
* target changes and an addition. Up to 0.2.33 each HTML link took the first Markdown link with the same text and
|
|
38
|
+
* target, which paired such a swap as no change and hid it. Every target comparison counts as work, so maxWork bounds
|
|
39
|
+
* the total the way maxSimilarityWork bounds align's own similarity search (0.2.16).
|
|
38
40
|
* 3. What is still unpaired pairs by loosely normalized text, the same way as step 1 and then in order, so a link
|
|
39
41
|
* whose text differs only in case or punctuation is one changed text and not a missing and an added link (0.2.13).
|
|
40
42
|
* @internal Exported for test/compare-links.test.ts.
|
package/dist/src/compare.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The comparison core: aligns blocks and turns the alignment into findings. Pure and network-free.
|
|
2
2
|
import { align, resolveLimits, AlignmentLimitError, UNCERTAIN_THRESHOLD } from './align.js';
|
|
3
|
-
import { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, visibleNumbers } from './normalize.js';
|
|
3
|
+
import { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, textKey, trimHref, visibleNumbers } from './normalize.js';
|
|
4
4
|
// The excerpt masks the whole block text before it cuts it, so it is computed once per block. Up to 0.2.11 every
|
|
5
5
|
// finding computed it again, and a block with thousands of link findings did that thousands of times (0.2.12).
|
|
6
6
|
const sides = new WeakMap();
|
|
@@ -64,93 +64,86 @@ const linkHref = (l, href) => (l.masked ? '***' : maskHref(href));
|
|
|
64
64
|
* 1. Links whose text occurs equally often on both sides pair in document order: the first "download" with the
|
|
65
65
|
* first "download". Up to 0.2.12 every link took any unused link with the same text and target, so two links with
|
|
66
66
|
* the same text and swapped targets passed with no finding (0.2.13, found by an outside review 2026-09-26).
|
|
67
|
-
* 2.
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
67
|
+
* 2. Links whose text occurs a different number of times pair in order of occurrence too (MP-14). When the targets of
|
|
68
|
+
* the shorter side appear in the same order among the targets of the longer side, they pair with those, so a link
|
|
69
|
+
* added or removed anywhere is one addition or one missing link and nothing else. Otherwise the first links of the
|
|
70
|
+
* two sides pair by position and the surplus is missing or added, so a swap that comes with an added link is two
|
|
71
|
+
* target changes and an addition. Up to 0.2.33 each HTML link took the first Markdown link with the same text and
|
|
72
|
+
* target, which paired such a swap as no change and hid it. Every target comparison counts as work, so maxWork bounds
|
|
73
|
+
* the total the way maxSimilarityWork bounds align's own similarity search (0.2.16).
|
|
72
74
|
* 3. What is still unpaired pairs by loosely normalized text, the same way as step 1 and then in order, so a link
|
|
73
75
|
* whose text differs only in case or punctuation is one changed text and not a missing and an added link (0.2.13).
|
|
74
76
|
* @internal Exported for test/compare-links.test.ts.
|
|
75
77
|
*/
|
|
76
78
|
export function pairLinks(hLinks, mLinks, maxWork = Number.POSITIVE_INFINITY) {
|
|
77
79
|
const used = new Array(mLinks.length).fill(false);
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
80
|
+
const byText = (links) => {
|
|
81
|
+
const out = new Map();
|
|
82
|
+
links.forEach((l, i) => {
|
|
83
|
+
const list = out.get(l.text);
|
|
84
|
+
if (list)
|
|
85
|
+
list.push(i);
|
|
86
|
+
else
|
|
87
|
+
out.set(l.text, [i]);
|
|
88
|
+
});
|
|
89
|
+
return out;
|
|
87
90
|
};
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return
|
|
91
|
+
const hByText = byText(hLinks);
|
|
92
|
+
const mByText = byText(mLinks);
|
|
93
|
+
let work = 0;
|
|
94
|
+
const same = (hi, mi) => {
|
|
95
|
+
work++;
|
|
96
|
+
if (work > maxWork) {
|
|
97
|
+
throw new AlignmentLimitError(`Comparison limit exceeded: pairing links by shared text needs more than ${maxWork} comparisons among ${hLinks.length} HTML and ${mLinks.length} Markdown links. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
98
|
+
}
|
|
99
|
+
return sameTarget(hLinks[hi], mLinks[mi]);
|
|
97
100
|
};
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
101
|
+
/** For each index of `small`, in order, the index in `big` of the first later link with the same target; null when one has none. */
|
|
102
|
+
const inOrder = (small, big, match) => {
|
|
103
|
+
const out = [];
|
|
104
|
+
let j = 0;
|
|
105
|
+
for (const s of small) {
|
|
106
|
+
while (j < big.length && !match(s, big[j]))
|
|
107
|
+
j++;
|
|
108
|
+
if (j === big.length)
|
|
109
|
+
return null;
|
|
110
|
+
out.push(big[j]);
|
|
111
|
+
j++;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
110
114
|
};
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
hLinks.forEach((hl, hi) => {
|
|
121
|
-
let idx = -1;
|
|
122
|
-
const k = seenInH.get(hl.text) ?? 0;
|
|
123
|
-
seenInH.set(hl.text, k + 1);
|
|
124
|
-
if (hCount.get(hl.text) === mCount.get(hl.text)) {
|
|
125
|
-
idx = lists.get(key('text', hl.text))[k];
|
|
115
|
+
const planned = new Array(hLinks.length).fill(-1);
|
|
116
|
+
for (const [text, hIdx] of hByText) {
|
|
117
|
+
const mIdx = mByText.get(text);
|
|
118
|
+
if (!mIdx)
|
|
119
|
+
continue;
|
|
120
|
+
if (hIdx.length === mIdx.length) {
|
|
121
|
+
hIdx.forEach((hi, k) => {
|
|
122
|
+
planned[hi] = mIdx[k];
|
|
123
|
+
});
|
|
126
124
|
}
|
|
127
|
-
else if (
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
125
|
+
else if (hIdx.length < mIdx.length) {
|
|
126
|
+
const hit = inOrder(hIdx, mIdx, same);
|
|
127
|
+
hIdx.forEach((hi, k) => {
|
|
128
|
+
planned[hi] = hit ? hit[k] : mIdx[k];
|
|
129
|
+
});
|
|
132
130
|
}
|
|
133
131
|
else {
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
throw new AlignmentLimitError(`Comparison limit exceeded: pairing unresolved links by shared text needs more than ${maxWork} comparisons among ${hLinks.length} HTML and ${mLinks.length} Markdown links. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
139
|
-
}
|
|
140
|
-
if (!used[i] && sameTarget(hl, mLinks[i])) {
|
|
141
|
-
idx = i;
|
|
142
|
-
break;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
132
|
+
const hit = inOrder(mIdx, hIdx, (mi, hi) => same(hi, mi));
|
|
133
|
+
mIdx.forEach((mi, k) => {
|
|
134
|
+
planned[hit ? hit[k] : hIdx[k]] = mi;
|
|
135
|
+
});
|
|
145
136
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
137
|
+
}
|
|
138
|
+
const pairs = [];
|
|
139
|
+
let missing = [];
|
|
140
|
+
planned.forEach((mi, hi) => {
|
|
141
|
+
if (mi < 0) {
|
|
149
142
|
missing.push(hi);
|
|
150
143
|
return;
|
|
151
144
|
}
|
|
152
|
-
used[
|
|
153
|
-
pairs.push([hi,
|
|
145
|
+
used[mi] = true;
|
|
146
|
+
pairs.push([hi, mi]);
|
|
154
147
|
});
|
|
155
148
|
// Step 3: the links still unpaired, by loosely normalized text.
|
|
156
149
|
const looseLists = new Map();
|
|
@@ -264,7 +257,7 @@ function sameTarget(a, b) {
|
|
|
264
257
|
return a.resolved === b.resolved;
|
|
265
258
|
if (a.resolved === null && b.resolved === null)
|
|
266
259
|
return relativeHrefRelation(a.rawHref, b.rawHref) === 'same';
|
|
267
|
-
return a.rawHref
|
|
260
|
+
return trimHref(a.rawHref) === trimHref(b.rawHref);
|
|
268
261
|
}
|
|
269
262
|
/**
|
|
270
263
|
* Where a list item sits in its list (0.2.13): the list kind and the nesting level are warnings, a changed item
|
|
@@ -364,15 +357,17 @@ function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
|
|
|
364
357
|
out.push({ code: 'NUMBER_CHANGED', severity: 'error', direction: 'both', message: `Numeric value differs in the ${label(h)} inside a masked part of a URL (a query value, the fragment or user information), so the values are not shown.`, html: side(h), markdown: side(m) });
|
|
365
358
|
}
|
|
366
359
|
}
|
|
367
|
-
else if (h.
|
|
360
|
+
else if (textKey(h.text) === textKey(m.text)) {
|
|
361
|
+
// The text key keeps the marks and symbols the alignment key drops (MP-11).
|
|
368
362
|
out.push({ code: 'TEXT_MINOR_CHANGED', severity: 'warning', direction: 'both', message: `The ${label(h)} differs only in case, punctuation or typographic characters.`, html: side(h), markdown: side(m), before: excerpt(h.text), after: excerpt(m.text) });
|
|
369
363
|
}
|
|
370
364
|
else {
|
|
371
365
|
out.push({ code: 'TEXT_CHANGED', severity: 'error', direction: 'both', message: `The ${label(h)} text differs.`, html: side(h), markdown: side(m), before: excerpt(h.text), after: excerpt(m.text) });
|
|
372
366
|
}
|
|
373
367
|
}
|
|
374
|
-
|
|
375
|
-
|
|
368
|
+
// Any block can carry the list context of its item (a heading, code or a table that leads it, MP-06); the function
|
|
369
|
+
// returns at once for a block without one.
|
|
370
|
+
compareListItems(out, h, m);
|
|
376
371
|
compareLinks(out, h, m, bothBases, maxSimilarityWork);
|
|
377
372
|
}
|
|
378
373
|
const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
|
package/dist/src/fetch.js
CHANGED
|
@@ -6,7 +6,7 @@ import http from 'node:http';
|
|
|
6
6
|
import https from 'node:https';
|
|
7
7
|
import dns from 'node:dns';
|
|
8
8
|
import zlib from 'node:zlib';
|
|
9
|
-
import { assertPublicHost, assertPublicResolved, BlockedAddressError } from './netguard.js';
|
|
9
|
+
import { assertPublicHost, assertPublicResolved, BlockedAddressError, ipVersion } from './netguard.js';
|
|
10
10
|
import { maskUrl, redactText } from './normalize.js';
|
|
11
11
|
import { TOOL_NAME, TOOL_VERSION } from './version.js';
|
|
12
12
|
export class FetchError extends Error {
|
|
@@ -43,6 +43,16 @@ async function pickAddress(hostname, options) {
|
|
|
43
43
|
const allowed = (options.testAllowHosts ?? []).includes(hostname.toLowerCase());
|
|
44
44
|
if (!allowed)
|
|
45
45
|
assertPublicHost(hostname);
|
|
46
|
+
// A bracketed IPv6 literal is an address and not a name (MP-20): it never goes to DNS, where the brackets made the
|
|
47
|
+
// lookup a name lookup of a string that is no name. The policy runs on the literal itself before any connection.
|
|
48
|
+
if (hostname.startsWith('[') && hostname.endsWith(']')) {
|
|
49
|
+
const literal = hostname.slice(1, -1);
|
|
50
|
+
if (ipVersion(literal) === 6) {
|
|
51
|
+
if (!allowed)
|
|
52
|
+
assertPublicResolved(hostname, literal);
|
|
53
|
+
return { address: literal, family: 6 };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
46
56
|
const resolver = options.resolver ?? defaultResolver;
|
|
47
57
|
let answers;
|
|
48
58
|
try {
|
|
@@ -60,9 +70,55 @@ async function pickAddress(hostname, options) {
|
|
|
60
70
|
}
|
|
61
71
|
return answers[0];
|
|
62
72
|
}
|
|
63
|
-
|
|
73
|
+
/** A decoder for an encoding label, or null when the runtime does not know the label. */
|
|
74
|
+
function decoderFor(label) {
|
|
75
|
+
try {
|
|
76
|
+
return new TextDecoder(label, { fatal: false });
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function headerCharset(contentType) {
|
|
64
83
|
const m = /charset=([^;]+)/i.exec(contentType ?? '');
|
|
65
|
-
|
|
84
|
+
return m?.[1] === undefined ? null : m[1].trim().replace(/^"|"$/g, '').toLowerCase();
|
|
85
|
+
}
|
|
86
|
+
/** The encoding a HTML page declares in a meta element among its first 1024 bytes (the HTML standard's prescan). A
|
|
87
|
+
* comment is skipped, and a declared UTF-16 is read as UTF-8, because a page that can be read this far as ASCII is not
|
|
88
|
+
* UTF-16. */
|
|
89
|
+
function metaCharset(buf) {
|
|
90
|
+
const head = buf.subarray(0, 1024).toString('latin1').replace(/<!--[\s\S]*?(?:-->|$)/g, '');
|
|
91
|
+
for (const tag of head.matchAll(/<meta\b[^>]*>?/gi)) {
|
|
92
|
+
const m = /charset\s*=\s*["']?\s*([^\s"'>;/]+)/i.exec(tag[0]);
|
|
93
|
+
if (!m)
|
|
94
|
+
continue;
|
|
95
|
+
const label = m[1].toLowerCase();
|
|
96
|
+
if (decoderFor(label))
|
|
97
|
+
return label.startsWith('utf-16') ? 'utf-8' : label;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
/** HTML is decoded the way the HTML standard orders the evidence: a byte order mark, then the charset of the
|
|
102
|
+
* Content-Type header, then the meta declaration, and UTF-8 when none of them names an encoding the runtime knows
|
|
103
|
+
* (MP-18). The standard's own default is windows-1252; UTF-8 is this tool's default for pages that say nothing. */
|
|
104
|
+
function decodeHtml(buf, contentType) {
|
|
105
|
+
const bom = buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 'utf-8' : buf[0] === 0xff && buf[1] === 0xfe ? 'utf-16le' : buf[0] === 0xfe && buf[1] === 0xff ? 'utf-16be' : null;
|
|
106
|
+
const fromBom = bom === null ? null : decoderFor(bom);
|
|
107
|
+
if (fromBom)
|
|
108
|
+
return fromBom.decode(buf);
|
|
109
|
+
const header = headerCharset(contentType);
|
|
110
|
+
const fromHeader = header === null ? null : decoderFor(header);
|
|
111
|
+
if (fromHeader)
|
|
112
|
+
return fromHeader.decode(buf);
|
|
113
|
+
const meta = metaCharset(buf);
|
|
114
|
+
const fromMeta = meta === null ? null : decoderFor(meta);
|
|
115
|
+
return (fromMeta ?? new TextDecoder('utf-8')).decode(buf);
|
|
116
|
+
}
|
|
117
|
+
function decodeBody(buf, contentType) {
|
|
118
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
119
|
+
if (type === 'text/html' || type === 'application/xhtml+xml')
|
|
120
|
+
return decodeHtml(buf, contentType);
|
|
121
|
+
const charset = headerCharset(contentType) ?? 'utf-8';
|
|
66
122
|
try {
|
|
67
123
|
return new TextDecoder(charset, { fatal: false }).decode(buf);
|
|
68
124
|
}
|
package/dist/src/html.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export declare function nestingDepth(node: ParentNode): number;
|
|
|
29
29
|
* Markdown side asks it for inline raw HTML, so a button or a script in a Markdown paragraph is left out the way
|
|
30
30
|
* it is in an HTML paragraph (0.2.22, found by an outside review 2026-10-02). */
|
|
31
31
|
export declare function opensExcludedSubtree(name: string, attribs: Record<string, string>): boolean;
|
|
32
|
+
export declare const BLOCK_TAGS: Set<string>;
|
|
32
33
|
/** The nesting limit was exceeded. A subclass so a caller that otherwise tolerates a parse failure (raw HTML
|
|
33
34
|
* inside Markdown) can tell a limit from any other failure and let the limit through. */
|
|
34
35
|
export declare class HtmlDepthError extends HtmlExtractError {
|
package/dist/src/html.js
CHANGED
|
@@ -52,7 +52,7 @@ export function opensExcludedSubtree(name, attribs) {
|
|
|
52
52
|
return true;
|
|
53
53
|
return SKIP_ROLES.has((attribs['role'] ?? '').toLowerCase());
|
|
54
54
|
}
|
|
55
|
-
const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'summary', 'dd', 'dl', 'dt', 'div', 'fieldset', 'figcaption', 'figure', 'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'li', 'main', 'ol', 'p', 'pre', 'section', 'table', 'ul', 'body', 'html', 'center', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'caption']);
|
|
55
|
+
export const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'summary', 'dd', 'dl', 'dt', 'div', 'fieldset', 'figcaption', 'figure', 'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'li', 'main', 'ol', 'p', 'pre', 'section', 'table', 'ul', 'body', 'html', 'center', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'caption']);
|
|
56
56
|
const HEADING_RE = /^h([1-6])$/;
|
|
57
57
|
function lineOf(ctx, node) {
|
|
58
58
|
const idx = node.startIndex;
|
|
@@ -404,7 +404,7 @@ function listOrdinals(ctx, ol) {
|
|
|
404
404
|
n += reversed ? -1 : 1;
|
|
405
405
|
});
|
|
406
406
|
// A reversed list only gives its first item a browser-shown number (see above); Markdown has no reversed list,
|
|
407
|
-
// so the later numbers are never compared. Up to 0.2.15 that was silent; listInfo
|
|
407
|
+
// so the later numbers are never compared. Up to 0.2.15 that was silent; listInfo above now also leaves every
|
|
408
408
|
// item's ordinal out, not only the ones already undefined (0.2.16, found by an outside review 2026-09-28).
|
|
409
409
|
if (reversed && items.length > 0) {
|
|
410
410
|
ctx.issues.push({ code: 'EXTRACTION_LIST_REVERSED_NOT_COMPARED', severity: 'info', message: 'This list is reversed; its numbering is not compared, because Markdown has no reversed list to compare it against.', line: lineOf(ctx, ol) });
|
|
@@ -421,14 +421,16 @@ function taskState(li, profile = 'generic') {
|
|
|
421
421
|
while (stack.length > 0) {
|
|
422
422
|
const node = stack.pop();
|
|
423
423
|
// A <template> element's content is inert: the browser never renders it as part of the document, the
|
|
424
|
-
// same reason hiddenInPage
|
|
424
|
+
// same reason hiddenInPage below treats it like a hidden ancestor for the main extraction. taskState had
|
|
425
425
|
// no matching check, so a checkbox sitting in a <template> answered for a later, real checkbox in the
|
|
426
426
|
// same item (found by an outside review 2026-09-28).
|
|
427
427
|
if (!(node instanceof Element) || node.name === 'ul' || node.name === 'ol')
|
|
428
428
|
continue;
|
|
429
429
|
// The checkbox itself is the one skipped tag whose state is wanted; a hidden one is still ignored.
|
|
430
430
|
if (node.name === 'input' && (node.attribs['type'] ?? '').toLowerCase() === 'checkbox') {
|
|
431
|
-
|
|
431
|
+
// The checkbox's own role counts as well: a checkbox with an excluded role (navigation, dialog and the rest of
|
|
432
|
+
// SKIP_ROLES) is left out like any other element with that role, so it cannot answer for the item (MP-10).
|
|
433
|
+
if (hiddenAttr(node) || SKIP_ROLES.has((node.attribs['role'] ?? '').toLowerCase()))
|
|
432
434
|
continue;
|
|
433
435
|
return node.attribs['checked'] !== undefined;
|
|
434
436
|
}
|
|
@@ -452,6 +454,9 @@ function handleListItem(ctx, li) {
|
|
|
452
454
|
if (child instanceof Element && isSkipped(child, ctx.root, ctx.profile))
|
|
453
455
|
continue;
|
|
454
456
|
const blockAnchor = child instanceof Element && isBlockAnchor(ctx, child) && !isParagraphOnlyAnchor(ctx, child);
|
|
457
|
+
// An item with no text of its own that starts with a heading, code or a table carries its list context on that
|
|
458
|
+
// first block, as the Markdown side does for the first child of an item (MP-06).
|
|
459
|
+
let leading = false;
|
|
455
460
|
if (child instanceof Element && (BLOCK_TAGS.has(child.name) || blockAnchor || (ctx.profile === 'starlight' && child.name === 'starlight-tabs'))) {
|
|
456
461
|
if (!ownFlushed && child.name === 'p' && !hasBlockChild(ctx, child) && strictNormalize(run.text) === '') {
|
|
457
462
|
for (const c of child.children)
|
|
@@ -461,7 +466,9 @@ function handleListItem(ctx, li) {
|
|
|
461
466
|
continue;
|
|
462
467
|
}
|
|
463
468
|
if (!ownFlushed) {
|
|
469
|
+
const pushed = ctx.blocks.length;
|
|
464
470
|
flushRun(ctx, run, li, 'listItem', info);
|
|
471
|
+
leading = ctx.blocks.length === pushed && (HEADING_RE.test(child.name) || child.name === 'pre' || child.name === 'table');
|
|
465
472
|
ownFlushed = true;
|
|
466
473
|
run = newRun();
|
|
467
474
|
}
|
|
@@ -469,7 +476,11 @@ function handleListItem(ctx, li) {
|
|
|
469
476
|
flushRun(ctx, run, li, 'paragraph');
|
|
470
477
|
run = newRun();
|
|
471
478
|
}
|
|
479
|
+
const first = ctx.blocks.length;
|
|
472
480
|
handleBlock(ctx, child);
|
|
481
|
+
const lead = ctx.blocks[first];
|
|
482
|
+
if (leading && lead && ctx.blocks.length > first && lead.list === undefined)
|
|
483
|
+
lead.list = { ...info };
|
|
473
484
|
}
|
|
474
485
|
else {
|
|
475
486
|
inlineText(ctx, child, run);
|
|
@@ -705,7 +716,7 @@ function hiddenInPage(el) {
|
|
|
705
716
|
/** Whether the element, or any ancestor, is a subtree the extraction leaves out (navigation, a dialog, a banner
|
|
706
717
|
* role and the rest of isSkipped). A candidate root inside one is page chrome, not main content. A plain <form> is
|
|
707
718
|
* the one exception: a page-wide form (ASP.NET WebForms) wraps the real content, so a candidate inside it is kept
|
|
708
|
-
* (
|
|
719
|
+
* (the maintainer's decision of 2026-10-02). A form with a left-out role still counts. */
|
|
709
720
|
function inExcludedSubtree(el) {
|
|
710
721
|
for (let cur = el; cur instanceof Element; cur = cur.parent) {
|
|
711
722
|
if (cur.name === 'form' && cur !== el && !SKIP_ROLES.has((cur.attribs['role'] ?? '').toLowerCase()))
|
|
@@ -800,16 +811,19 @@ export function extractHtml(source, options = {}) {
|
|
|
800
811
|
}
|
|
801
812
|
const { root, strategy, confidence } = pickRoot(doc, options.selector, notes, issues);
|
|
802
813
|
const lineStarts = [0];
|
|
803
|
-
|
|
804
|
-
|
|
814
|
+
// A line break is LF, CRLF or a lone CR, as the Markdown parser counts them: the CR of a CRLF pair is not a second one.
|
|
815
|
+
for (let i = 0; i < source.length; i++) {
|
|
816
|
+
const c = source.charCodeAt(i);
|
|
817
|
+
if (c === 10 || (c === 13 && source.charCodeAt(i + 1) !== 10))
|
|
805
818
|
lineStarts.push(i + 1);
|
|
819
|
+
}
|
|
806
820
|
if (profile === 'starlight')
|
|
807
821
|
notes.push('Starlight profile: all associated tab panels are compared, including inactive panels; Expressive Code line boundaries and aside titles are retained.');
|
|
808
822
|
const ctx = { profile, base, source, lineStarts, blocks: [], notes, root, listBase: 0, ordinals: new Map(), segments: new Map(), issues };
|
|
809
823
|
// A selector that picks a heading, list item, table or pre keeps that block type, so the root goes
|
|
810
824
|
// through handleBlock. Every other root is read as a container, a list included: handleBlock's list
|
|
811
825
|
// branch reads only <li> children, and a root list would lose any other content it holds.
|
|
812
|
-
if (HEADING_RE.test(root.name) || root.name === 'li' || root.name === 'table' || root.name === 'pre')
|
|
826
|
+
if (HEADING_RE.test(root.name) || root.name === 'li' || root.name === 'table' || root.name === 'pre' || (profile === 'starlight' && root.name === 'starlight-tabs'))
|
|
813
827
|
handleBlock(ctx, root);
|
|
814
828
|
else
|
|
815
829
|
walk(ctx, root);
|
package/dist/src/markdown.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { fromMarkdown } from 'mdast-util-from-markdown';
|
|
3
3
|
import { gfm } from 'micromark-extension-gfm';
|
|
4
4
|
import { gfmFromMarkdown } from 'mdast-util-gfm';
|
|
5
|
-
import { extractHtml, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
|
|
5
|
+
import { BLOCK_TAGS, extractHtml, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
|
|
6
6
|
import { parseDocument, Parser } from 'htmlparser2';
|
|
7
7
|
import { Element, Text } from 'domhandler';
|
|
8
8
|
import { excerpt, extractNumbers, insideHiddenUrlPart, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
|
|
@@ -31,13 +31,33 @@ function parseInlineTag(value) {
|
|
|
31
31
|
const m = /^<\/([A-Za-z][A-Za-z0-9-]*)\s*>$/.exec(v);
|
|
32
32
|
return m ? { name: m[1].toLowerCase(), closing: true, attribs: {} } : null;
|
|
33
33
|
}
|
|
34
|
-
|
|
34
|
+
const tag = singleOpenTag(v);
|
|
35
|
+
if (!tag)
|
|
35
36
|
return null;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
return { name: tag.name.toLowerCase(), closing: false, selfClosing: /\/\s*>$/.test(v), attribs: tag.attribs };
|
|
38
|
+
}
|
|
39
|
+
/** The one opening tag a string consists of, found by the HTML tokenizer so that a quoted attribute value may hold a
|
|
40
|
+
* ">" (title="A > B"); null when the string is anything else: text after the tag, a comment, a tag still open at the
|
|
41
|
+
* end. The first version looked for the closing ">" with a pattern and cut the tag at a quoted one (MP-02). */
|
|
42
|
+
function singleOpenTag(v) {
|
|
43
|
+
if (!/^<[A-Za-z]/.test(v))
|
|
39
44
|
return null;
|
|
40
|
-
|
|
45
|
+
const seen = { tag: null, extra: false };
|
|
46
|
+
const parser = new Parser({
|
|
47
|
+
onopentag(name, attribs) {
|
|
48
|
+
if (seen.tag)
|
|
49
|
+
seen.extra = true;
|
|
50
|
+
else
|
|
51
|
+
seen.tag = { name, attribs, end: parser.endIndex };
|
|
52
|
+
},
|
|
53
|
+
ontext() { seen.extra = true; },
|
|
54
|
+
oncomment() { seen.extra = true; },
|
|
55
|
+
onprocessinginstruction() { seen.extra = true; },
|
|
56
|
+
}, { decodeEntities: true });
|
|
57
|
+
parser.write(v);
|
|
58
|
+
if (!seen.tag || seen.extra || seen.tag.end !== v.length - 1)
|
|
59
|
+
return null;
|
|
60
|
+
return { name: seen.tag.name, attribs: seen.tag.attribs };
|
|
41
61
|
}
|
|
42
62
|
/**
|
|
43
63
|
* Walks phrasing children in order so that inline HTML anchors (<a href="..">text</a>) become links with
|
|
@@ -129,6 +149,9 @@ function inlineChildren(ctx, children, run, line) {
|
|
|
129
149
|
i = end;
|
|
130
150
|
}
|
|
131
151
|
}
|
|
152
|
+
// Foreign elements that may close themselves with a trailing slash. Of the two, only svg is a left-out tag of its own
|
|
153
|
+
// (SKIP_TAGS in html.ts); math is left out only when it carries a left-out role such as navigation, so for math the
|
|
154
|
+
// self-closing rule above applies only in that case.
|
|
132
155
|
const FOREIGN_TAGS = new Set(['svg', 'math']);
|
|
133
156
|
const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
134
157
|
/**
|
|
@@ -229,9 +252,16 @@ function push(ctx, partial, node) {
|
|
|
229
252
|
numbers: extractNumbers(partial.text),
|
|
230
253
|
location: { line, blockIndex: ctx.blocks.length },
|
|
231
254
|
};
|
|
255
|
+
// A visible raw <a href> left open by an earlier raw HTML block links the blocks inside it, the way the HTML side
|
|
256
|
+
// gives every block of a block anchor the anchor's link with the block's own text; the outermost link comes first (MP-08).
|
|
257
|
+
for (let i = ctx.wrappers.length - 1; i >= 0; i--) {
|
|
258
|
+
const href = ctx.wrappers[i].href;
|
|
259
|
+
if (href !== undefined)
|
|
260
|
+
block.links.unshift({ text: strictNormalize(block.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
|
|
261
|
+
}
|
|
232
262
|
ctx.blocks.push(block);
|
|
233
263
|
}
|
|
234
|
-
function handleTable(ctx, table) {
|
|
264
|
+
function handleTable(ctx, table, listItem) {
|
|
235
265
|
const cells = [];
|
|
236
266
|
const links = [];
|
|
237
267
|
for (const row of table.children) {
|
|
@@ -247,8 +277,9 @@ function handleTable(ctx, table) {
|
|
|
247
277
|
if (cells.length === 0)
|
|
248
278
|
return;
|
|
249
279
|
const text = cells.map((r) => r.join(' | ')).join(' \n ');
|
|
250
|
-
push(ctx, { type: 'table', text: strictNormalize(text), cells, links }, table);
|
|
280
|
+
push(ctx, { type: 'table', text: strictNormalize(text), cells, links, ...(listItem ? { list: listItem } : {}) }, table);
|
|
251
281
|
}
|
|
282
|
+
const LEADING_TYPES = new Set(['paragraph', 'heading', 'code', 'table', 'html']);
|
|
252
283
|
function handle(ctx, node, listItem) {
|
|
253
284
|
switch (node.type) {
|
|
254
285
|
case 'heading': {
|
|
@@ -258,7 +289,7 @@ function handle(ctx, node, listItem) {
|
|
|
258
289
|
inlineChildren(ctx, node.children, run, node.position?.start.line);
|
|
259
290
|
const text = strictNormalize(run.text);
|
|
260
291
|
if (text !== '')
|
|
261
|
-
push(ctx, { type: 'heading', text, depth: node.depth, links: run.links }, node);
|
|
292
|
+
push(ctx, { type: 'heading', text, depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
|
|
262
293
|
return;
|
|
263
294
|
}
|
|
264
295
|
case 'paragraph': {
|
|
@@ -276,12 +307,12 @@ function handle(ctx, node, listItem) {
|
|
|
276
307
|
return;
|
|
277
308
|
const code = normalizeCode(node.value);
|
|
278
309
|
if (code.trim() !== '')
|
|
279
|
-
push(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, node);
|
|
310
|
+
push(ctx, { type: 'code', text: strictNormalize(code), code, links: [], ...(listItem ? { list: listItem } : {}) }, node);
|
|
280
311
|
return;
|
|
281
312
|
}
|
|
282
313
|
case 'table':
|
|
283
314
|
if (!hiddenWrapped(ctx))
|
|
284
|
-
handleTable(ctx, node);
|
|
315
|
+
handleTable(ctx, node, listItem);
|
|
285
316
|
return;
|
|
286
317
|
case 'list': {
|
|
287
318
|
// A Markdown list shows its start number and counts on; its items carry the list kind, the nesting level and
|
|
@@ -295,7 +326,9 @@ function handle(ctx, node, listItem) {
|
|
|
295
326
|
ctx.listDepth++;
|
|
296
327
|
let first = true;
|
|
297
328
|
for (const child of item.children) {
|
|
298
|
-
|
|
329
|
+
// The first child carries the item's list context whatever it is: a paragraph is the item text, a heading,
|
|
330
|
+
// code, a table or raw HTML keep their own type with the context on them (MP-05, MP-06).
|
|
331
|
+
handle(ctx, child, first && LEADING_TYPES.has(child.type) ? info : undefined);
|
|
299
332
|
first = false;
|
|
300
333
|
}
|
|
301
334
|
ctx.listDepth--;
|
|
@@ -307,7 +340,7 @@ function handle(ctx, node, listItem) {
|
|
|
307
340
|
handle(ctx, c);
|
|
308
341
|
return;
|
|
309
342
|
case 'html':
|
|
310
|
-
handleRawHtml(ctx, node.value, node.position?.start.line);
|
|
343
|
+
handleRawHtml(ctx, node.value, node.position?.start.line, listItem);
|
|
311
344
|
return;
|
|
312
345
|
case 'footnoteDefinition':
|
|
313
346
|
if (hiddenWrapped(ctx))
|
|
@@ -337,12 +370,19 @@ function footnoteText(node) {
|
|
|
337
370
|
}
|
|
338
371
|
/** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
|
|
339
372
|
* comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
|
|
340
|
-
function handleRawHtml(ctx, value, line) {
|
|
373
|
+
function handleRawHtml(ctx, value, line, listItem) {
|
|
341
374
|
// Wrappers an earlier raw block left open are written in front of this one, on the same line, so the extractor
|
|
342
|
-
// sees the same element tree a browser would and hides what a
|
|
343
|
-
|
|
344
|
-
const
|
|
345
|
-
|
|
375
|
+
// sees the same element tree a browser would and hides what a covering wrapper still holds (P07). A wrapper that
|
|
376
|
+
// hides is written with the hidden attribute whatever hid it, and an anchor with its href.
|
|
377
|
+
const prefix = ctx.wrappers.map((w) => `<${w.name}${w.covers ? ' hidden' : ''}${w.href !== undefined ? ` href="${w.href.replace(/&/g, '&').replace(/"/g, '"')}"` : ''}>`).join('');
|
|
378
|
+
// The stack always follows the prefix, because a closing tag here may end an element opened earlier. The extractor
|
|
379
|
+
// sees the prefix only while an open element hides content or links it: with nothing of the kind open the block is
|
|
380
|
+
// read on its own, as before (a long run of unclosed visible tags costs the stack but no tree per block).
|
|
381
|
+
const relevant = ctx.wrappers.some((w) => w.covers || w.href !== undefined);
|
|
382
|
+
ctx.wrappers = openWrappers(prefix + value);
|
|
383
|
+
if (ctx.wrappers.length > ctx.maxDepth)
|
|
384
|
+
throw new HtmlDepthError(ctx.wrappers.length, ctx.maxDepth);
|
|
385
|
+
const fragment = relevant ? prefix + value : value;
|
|
346
386
|
// Text check for the fallback warning, taken from the parsed DOM rather than from regex stripping:
|
|
347
387
|
// comments are not text, and script, style, template and noscript are page machinery on both sides,
|
|
348
388
|
// so their content does not count as skipped text. Hidden elements are left out, as in the extraction.
|
|
@@ -363,12 +403,24 @@ function handleRawHtml(ctx, value, line) {
|
|
|
363
403
|
}
|
|
364
404
|
const blocks = parsed?.blocks ?? [];
|
|
365
405
|
if (blocks.length > 0) {
|
|
406
|
+
let lead = listItem !== undefined && rawLeadsItem(value);
|
|
366
407
|
for (const b of blocks) {
|
|
367
408
|
// The wrapper <body> sits on the fragment's first line, so the extractor's line is 1-based within
|
|
368
409
|
// the fragment and maps onto the html node's start line.
|
|
369
410
|
const inner = b.location.line;
|
|
370
411
|
const absolute = line !== undefined && inner !== undefined ? line + inner - 1 : line;
|
|
371
|
-
|
|
412
|
+
let block = { ...b, location: { line: absolute, blockIndex: ctx.blocks.length } };
|
|
413
|
+
// A list inside a raw block sits below the Markdown list the block is in (MP-05).
|
|
414
|
+
if (block.list && ctx.listDepth > 0)
|
|
415
|
+
block = { ...block, list: { ...block.list, depth: block.list.depth + ctx.listDepth } };
|
|
416
|
+
// The first block of a raw block that leads a Markdown list item is the item's own text, or the item's leading
|
|
417
|
+
// heading, code or table, and carries the item's list context (MP-05, MP-06). A nested list there has its own.
|
|
418
|
+
if (lead) {
|
|
419
|
+
lead = false;
|
|
420
|
+
if (!block.list && listItem)
|
|
421
|
+
block = { ...block, ...(block.type === 'paragraph' ? { type: 'listItem' } : {}), list: { ...listItem } };
|
|
422
|
+
}
|
|
423
|
+
ctx.blocks.push(block);
|
|
372
424
|
}
|
|
373
425
|
// The nested extraction's own structural "not compared" issues (a spanned table, a reversed list) were
|
|
374
426
|
// read off parsed.blocks only up to here; parsed.issues was silently dropped, so a page whose span or
|
|
@@ -386,29 +438,61 @@ function handleRawHtml(ctx, value, line) {
|
|
|
386
438
|
ctx.issues.push({ code: 'MARKDOWN_RAW_HTML_SKIPPED', severity: 'warning', message: 'A raw HTML block in the Markdown carries text that could not be parsed into blocks; it was not compared.', line, excerpt: excerpt(textOnly) });
|
|
387
439
|
}
|
|
388
440
|
}
|
|
389
|
-
|
|
390
|
-
|
|
441
|
+
/**
|
|
442
|
+
* Whether a raw HTML block that leads a Markdown list item is read as the item's own content, by the rule of html.ts
|
|
443
|
+
* handleListItem: the item's own text or inline content, a paragraph without block children, a heading, a pre or a
|
|
444
|
+
* table. Any other block element (div, blockquote, section, details, a list) is a block child of the item and gets no
|
|
445
|
+
* list context, as on the HTML side (N-1).
|
|
446
|
+
*/
|
|
447
|
+
function rawLeadsItem(value) {
|
|
448
|
+
for (const node of parseDocument(value).children) {
|
|
449
|
+
if (node instanceof Text) {
|
|
450
|
+
if (node.data.trim() !== '')
|
|
451
|
+
return true;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (!(node instanceof Element))
|
|
455
|
+
continue;
|
|
456
|
+
const name = node.name.toLowerCase();
|
|
457
|
+
if (opensExcludedSubtree(name, node.attribs) || node.attribs['hidden'] !== undefined || node.attribs['aria-hidden'] === 'true')
|
|
458
|
+
continue;
|
|
459
|
+
if (name === 'p')
|
|
460
|
+
return !node.children.some((c) => c instanceof Element && BLOCK_TAGS.has(c.name.toLowerCase()));
|
|
461
|
+
if (/^h[1-6]$/.test(name) || name === 'pre' || name === 'table')
|
|
462
|
+
return true;
|
|
463
|
+
return !BLOCK_TAGS.has(name);
|
|
464
|
+
}
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
467
|
+
/** Whether a raw HTML wrapper from an earlier block that hides what it holds is still open. */
|
|
391
468
|
function hiddenWrapped(ctx) {
|
|
392
|
-
return ctx.wrappers.
|
|
469
|
+
return ctx.wrappers.some((w) => w.covers);
|
|
393
470
|
}
|
|
394
471
|
/**
|
|
395
|
-
* The elements still open at the end of a raw HTML fragment, from the outermost
|
|
396
|
-
*
|
|
397
|
-
*
|
|
472
|
+
* The elements still open at the end of a raw HTML fragment, all of them from the outermost. An element hides content
|
|
473
|
+
* when it is hidden or aria-hidden or the HTML side leaves its subtree out (a nav, a form, a role such as navigation);
|
|
474
|
+
* a visible anchor with an href links what it holds. The visible elements are kept as well, because an element opened
|
|
475
|
+
* in an earlier block can be hidden or linked only by a later one, and because their closing tags close what is open
|
|
476
|
+
* inside them: </ul> ends an open <li hidden> (MP-07). The parser is not ended, because ending it closes every open
|
|
477
|
+
* element and the open ones are the answer. The stack is written in front of every following raw block, so the caller
|
|
478
|
+
* stops the comparison when it is deeper than the nesting limit, as the same nesting is on the HTML side.
|
|
398
479
|
*/
|
|
399
480
|
function openWrappers(fragment) {
|
|
400
481
|
const stack = [];
|
|
401
482
|
const parser = new Parser({
|
|
402
483
|
onopentag(name, attribs) {
|
|
403
|
-
|
|
484
|
+
const covers = attribs['hidden'] !== undefined || attribs['aria-hidden'] === 'true' || opensExcludedSubtree(name, attribs);
|
|
485
|
+
const wrapper = { name, covers };
|
|
486
|
+
if (name === 'a' && attribs['href'] !== undefined && !covers)
|
|
487
|
+
wrapper.href = attribs['href'];
|
|
488
|
+
stack.push(wrapper);
|
|
404
489
|
},
|
|
405
490
|
onclosetag() {
|
|
406
491
|
stack.pop();
|
|
407
492
|
},
|
|
408
493
|
}, { decodeEntities: true });
|
|
409
494
|
parser.write(fragment);
|
|
410
|
-
|
|
411
|
-
return first < 0 ? [] : stack.slice(first);
|
|
495
|
+
return stack;
|
|
412
496
|
}
|
|
413
497
|
/** Strictly normalized text of an HTML fragment as a parser sees it: text nodes only, comments and
|
|
414
498
|
* machinery elements excluded. */
|
|
@@ -419,7 +503,9 @@ function visibleText(fragment) {
|
|
|
419
503
|
if (node instanceof Text)
|
|
420
504
|
parts.push(node.data);
|
|
421
505
|
else if (node instanceof Element) {
|
|
422
|
-
|
|
506
|
+
// The subtrees the HTML side leaves out (script, style, template, noscript, nav, form, dialog, a role such as
|
|
507
|
+
// navigation and the rest of opensExcludedSubtree) are not text that was left unread (MP-04).
|
|
508
|
+
if (opensExcludedSubtree(node.name.toLowerCase(), node.attribs))
|
|
423
509
|
continue;
|
|
424
510
|
if (node.attribs['hidden'] !== undefined || node.attribs['aria-hidden'] === 'true')
|
|
425
511
|
continue;
|
package/dist/src/normalize.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
export declare function strictNormalize(text: string): string;
|
|
2
|
+
/** The key that aligns blocks: everything that is not a letter, a number or white space becomes a space, so two
|
|
3
|
+
* blocks that differ in punctuation, marks or symbols still pair. */
|
|
2
4
|
export declare function looseNormalize(text: string): string;
|
|
5
|
+
/** The key that classifies a text difference: the loose text, except that the marks (\p{M}) and the symbols (\p{S})
|
|
6
|
+
* are kept, because a different vowel sign, check mark, arrow, comparison or plus sign shows the reader something
|
|
7
|
+
* else. Only case, punctuation, typographic quotes and dashes, joiners and invisible code points stay minor
|
|
8
|
+
* (MP-11). Two texts with the same key but different strict text are TEXT_MINOR_CHANGED; with different keys they
|
|
9
|
+
* are TEXT_CHANGED. The key is not used for alignment. */
|
|
10
|
+
export declare function textKey(text: string): string;
|
|
3
11
|
/** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
|
|
4
12
|
* whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
|
|
5
13
|
* Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
|
|
@@ -8,9 +16,10 @@ export declare function looseNormalize(text: string): string;
|
|
|
8
16
|
export declare function codeWhitespaceKey(code: string): string;
|
|
9
17
|
/** Code content: CRLF and CR line endings become LF and every trailing newline is removed; other whitespace is kept. */
|
|
10
18
|
export declare function normalizeCode(code: string): string;
|
|
11
|
-
/** Removes ANSI escape
|
|
12
|
-
*
|
|
13
|
-
* review 2026-09-28).
|
|
19
|
+
/** Removes the escape character (which starts an ANSI escape sequence), the other C0 and C1 controls and the Unicode
|
|
20
|
+
* bidi controls from a value that may come from a compared page or a raw argument, so a plain --format text report
|
|
21
|
+
* cannot replay them at the terminal (0.2.16, found by an outside review 2026-09-28). The printable rest of an escape
|
|
22
|
+
* sequence, such as the "[2J" of ESC [ 2 J, stays as inert text. */
|
|
14
23
|
export declare function stripControlChars(text: string): string;
|
|
15
24
|
/** Extracts numeric tokens (prices, percentages, dates, versions, signed values) in source order. */
|
|
16
25
|
export declare function extractNumbers(text: string): string[];
|
|
@@ -54,6 +63,11 @@ export declare function hideUrlSecrets(text: string): string;
|
|
|
54
63
|
* by an outside review 2026-09-22).
|
|
55
64
|
*/
|
|
56
65
|
export declare function visibleNumbers(text: string): string[];
|
|
66
|
+
/** An href with only the characters the URL standard strips from its ends removed: the C0 controls and the space
|
|
67
|
+
* (U+0000 to U+0020). JavaScript's trim() also removes the no-break space, the ideographic space and the other
|
|
68
|
+
* Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
|
|
69
|
+
* compared equal (MP-16). */
|
|
70
|
+
export declare function trimHref(href: string): string;
|
|
57
71
|
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
58
72
|
export declare function resolveHref(rawHref: string, base: string | null): string | null;
|
|
59
73
|
/** Masks query values, drops the fragment and removes user information for display in reports and logs.
|
package/dist/src/normalize.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Text normalization. Strict normalization preserves case, applies NFC, removes the characters in ZERO_WIDTH,
|
|
2
|
-
// maps the spaces in NBSP to a plain space and collapses whitespace. Loose normalization aligns blocks
|
|
3
|
-
// classifies minor text differences (TEXT_MINOR_CHANGED)
|
|
2
|
+
// maps the spaces in NBSP to a plain space and collapses whitespace. Loose normalization aligns blocks. The text key
|
|
3
|
+
// (textKey) classifies minor text differences (TEXT_MINOR_CHANGED): it keeps the marks and symbols that loose
|
|
4
|
+
// normalization drops, so a changed mark or symbol is a text change.
|
|
4
5
|
const NBSP = /[\u00a0\u2007\u202f]/g;
|
|
5
6
|
const WS = /[ \t\r\n\f\v]+/g;
|
|
6
7
|
// Zero width space, byte order mark and soft hyphen: invisible artefacts of editing and export. Up to 0.2.12 the
|
|
@@ -17,7 +18,9 @@ export function strictNormalize(text) {
|
|
|
17
18
|
.replace(WS, ' ')
|
|
18
19
|
.trim();
|
|
19
20
|
}
|
|
20
|
-
|
|
21
|
+
/** The folding the loose text and the text key share: joiners out, case folded, typographic quotes, dashes and the
|
|
22
|
+
* ellipsis in their plain forms. */
|
|
23
|
+
function fold(text) {
|
|
21
24
|
return strictNormalize(text)
|
|
22
25
|
.replace(JOINERS, '')
|
|
23
26
|
.toLowerCase()
|
|
@@ -25,11 +28,31 @@ export function looseNormalize(text) {
|
|
|
25
28
|
.replace(/[\u2018\u2019\u201a\u2032]/g, "'")
|
|
26
29
|
.replace(/[\u201c\u201d\u201e\u2033]/g, '"')
|
|
27
30
|
.replace(/[\u2010-\u2015\u2212]/g, '-')
|
|
28
|
-
.replace(/\u2026/g, '...')
|
|
31
|
+
.replace(/\u2026/g, '...');
|
|
32
|
+
}
|
|
33
|
+
/** The key that aligns blocks: everything that is not a letter, a number or white space becomes a space, so two
|
|
34
|
+
* blocks that differ in punctuation, marks or symbols still pair. */
|
|
35
|
+
export function looseNormalize(text) {
|
|
36
|
+
return fold(text)
|
|
29
37
|
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
|
|
30
38
|
.replace(/\s+/g, ' ')
|
|
31
39
|
.trim();
|
|
32
40
|
}
|
|
41
|
+
// Code points that render as nothing by default: variation selectors, the combining grapheme joiner, the word joiner
|
|
42
|
+
// and the like. They are not content, so a difference in them alone is not a text change.
|
|
43
|
+
const IGNORABLE = /\p{Default_Ignorable_Code_Point}/gu;
|
|
44
|
+
/** The key that classifies a text difference: the loose text, except that the marks (\p{M}) and the symbols (\p{S})
|
|
45
|
+
* are kept, because a different vowel sign, check mark, arrow, comparison or plus sign shows the reader something
|
|
46
|
+
* else. Only case, punctuation, typographic quotes and dashes, joiners and invisible code points stay minor
|
|
47
|
+
* (MP-11). Two texts with the same key but different strict text are TEXT_MINOR_CHANGED; with different keys they
|
|
48
|
+
* are TEXT_CHANGED. The key is not used for alignment. */
|
|
49
|
+
export function textKey(text) {
|
|
50
|
+
return fold(text)
|
|
51
|
+
.replace(IGNORABLE, '')
|
|
52
|
+
.replace(/[^\p{L}\p{N}\p{M}\p{S}\s]/gu, ' ')
|
|
53
|
+
.replace(/\s+/g, ' ')
|
|
54
|
+
.trim();
|
|
55
|
+
}
|
|
33
56
|
/** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
|
|
34
57
|
* whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
|
|
35
58
|
* Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
|
|
@@ -52,16 +75,18 @@ export function normalizeCode(code) {
|
|
|
52
75
|
// controls (U+202A to U+202E and U+2066 to U+2069) reorder the text a reader sees, so a quoted excerpt could read
|
|
53
76
|
// differently in a report than in the page. Both ranges match the hosted validator's stripControls(stripBidi()).
|
|
54
77
|
const CONTROL_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u202A-\u202E\u2066-\u2069]/g;
|
|
55
|
-
/** Removes ANSI escape
|
|
56
|
-
*
|
|
57
|
-
* review 2026-09-28).
|
|
78
|
+
/** Removes the escape character (which starts an ANSI escape sequence), the other C0 and C1 controls and the Unicode
|
|
79
|
+
* bidi controls from a value that may come from a compared page or a raw argument, so a plain --format text report
|
|
80
|
+
* cannot replay them at the terminal (0.2.16, found by an outside review 2026-09-28). The printable rest of an escape
|
|
81
|
+
* sequence, such as the "[2J" of ESC [ 2 J, stays as inert text. */
|
|
58
82
|
export function stripControlChars(text) {
|
|
59
83
|
return text.replace(CONTROL_CHARS, '');
|
|
60
84
|
}
|
|
61
85
|
// A numeric token: optional sign (ASCII hyphen, Unicode minus or plus) that is not preceded by a letter
|
|
62
|
-
// or digit (so the "-09" in 2026-09-10 is a separator, not a sign), digits
|
|
63
|
-
// (decimal, thousands, date, time, version),
|
|
64
|
-
|
|
86
|
+
// or digit (so the "-09" in 2026-09-10 is a separator, not a sign), digits of any script (\p{Nd}, so Arabic-Indic
|
|
87
|
+
// and fullwidth digits carry a sign too, MP-12) with inner separators (decimal, thousands, date, time, version),
|
|
88
|
+
// optional percent or currency sign on either side.
|
|
89
|
+
const NUMBER_RE = /(?<![\p{L}\p{N}])(?:[€$£]\s?)?[-\u2212+]?\p{Nd}+(?:[.,:\/\-\u2010-\u2015\u2212]\p{Nd}+)*\s?(?:%|€|\$|£)?/gu;
|
|
65
90
|
/** Extracts numeric tokens (prices, percentages, dates, versions, signed values) in source order. */
|
|
66
91
|
export function extractNumbers(text) {
|
|
67
92
|
const out = [];
|
|
@@ -444,9 +469,22 @@ export function hideUrlSecrets(text) {
|
|
|
444
469
|
export function visibleNumbers(text) {
|
|
445
470
|
return extractNumbers(hideUrlSecrets(text));
|
|
446
471
|
}
|
|
472
|
+
/** An href with only the characters the URL standard strips from its ends removed: the C0 controls and the space
|
|
473
|
+
* (U+0000 to U+0020). JavaScript's trim() also removes the no-break space, the ideographic space and the other
|
|
474
|
+
* Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
|
|
475
|
+
* compared equal (MP-16). */
|
|
476
|
+
export function trimHref(href) {
|
|
477
|
+
let start = 0;
|
|
478
|
+
let end = href.length;
|
|
479
|
+
while (start < end && href.charCodeAt(start) <= 0x20)
|
|
480
|
+
start++;
|
|
481
|
+
while (end > start && href.charCodeAt(end - 1) <= 0x20)
|
|
482
|
+
end--;
|
|
483
|
+
return href.slice(start, end);
|
|
484
|
+
}
|
|
447
485
|
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
448
486
|
export function resolveHref(rawHref, base) {
|
|
449
|
-
const href = rawHref
|
|
487
|
+
const href = trimHref(rawHref);
|
|
450
488
|
if (href === '')
|
|
451
489
|
return null;
|
|
452
490
|
if (base) {
|
package/dist/src/run.js
CHANGED
|
@@ -36,6 +36,38 @@ export const LIMITATIONS = [
|
|
|
36
36
|
function meta(e) {
|
|
37
37
|
return { strategy: e.strategy, confidence: e.confidence, blockCount: e.blocks.length, notes: e.notes };
|
|
38
38
|
}
|
|
39
|
+
/** The body after any comments, processing instructions (an XML declaration among them) and declarations other than
|
|
40
|
+
* a doctype html that come before its first content (MP-19). An unclosed comment or instruction leaves the rest as it is. */
|
|
41
|
+
function afterPrologue(body) {
|
|
42
|
+
let i = 0;
|
|
43
|
+
for (;;) {
|
|
44
|
+
while (i < body.length && /\s/.test(body[i]))
|
|
45
|
+
i++;
|
|
46
|
+
let end;
|
|
47
|
+
if (body.startsWith('<!--', i)) {
|
|
48
|
+
end = body.indexOf('-->', i + 4);
|
|
49
|
+
if (end < 0)
|
|
50
|
+
break;
|
|
51
|
+
i = end + 3;
|
|
52
|
+
}
|
|
53
|
+
else if (body.startsWith('<?', i)) {
|
|
54
|
+
end = body.indexOf('>', i + 2);
|
|
55
|
+
if (end < 0)
|
|
56
|
+
break;
|
|
57
|
+
i = end + 1;
|
|
58
|
+
}
|
|
59
|
+
else if (body.startsWith('<!', i) && !/^<!doctype\s+html/i.test(body.slice(i, i + 32))) {
|
|
60
|
+
end = body.indexOf('>', i + 2);
|
|
61
|
+
if (end < 0)
|
|
62
|
+
break;
|
|
63
|
+
i = end + 1;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return body.slice(i);
|
|
70
|
+
}
|
|
39
71
|
/** Findings about how the Markdown was delivered, produced by the URL mode before extraction. */
|
|
40
72
|
export function deliveryFindings(md, body) {
|
|
41
73
|
const out = [];
|
|
@@ -43,7 +75,7 @@ export function deliveryFindings(md, body) {
|
|
|
43
75
|
return out;
|
|
44
76
|
const ct = (md.contentType ?? '').toLowerCase();
|
|
45
77
|
const type = ct.split(';')[0].trim();
|
|
46
|
-
const looksHtml = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(body);
|
|
78
|
+
const looksHtml = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(afterPrologue(body));
|
|
47
79
|
if (md.status !== undefined && md.status >= 400) {
|
|
48
80
|
out.push({ code: 'DELIVERY_HTTP_ERROR', severity: 'error', direction: 'markdown_only', message: `The Markdown request returned HTTP ${md.status}; the error page is not treated as content.`, before: String(md.status) });
|
|
49
81
|
return out;
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const TOOL_NAME = "markdown-parity-check";
|
|
2
|
-
export declare const TOOL_VERSION = "0.2.
|
|
2
|
+
export declare const TOOL_VERSION = "0.2.35";
|
package/dist/src/version.js
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
// Cloudflare Worker as well as under Node.js. test/version.test.ts fails the build when these differ
|
|
3
3
|
// from package.json, which stays the version the release workflow publishes.
|
|
4
4
|
export const TOOL_NAME = 'markdown-parity-check';
|
|
5
|
-
export const TOOL_VERSION = '0.2.
|
|
5
|
+
export const TOOL_VERSION = '0.2.35';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markdown-parity-check",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.35",
|
|
4
4
|
"description": "Compares the main content of a web page's HTML and Markdown representations and reports concrete differences.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"markdown",
|
|
@@ -50,7 +50,6 @@
|
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"css-select": "^7.0.0",
|
|
52
52
|
"domhandler": "^6.0.1",
|
|
53
|
-
"domutils": "^4.0.2",
|
|
54
53
|
"htmlparser2": "^12.0.0",
|
|
55
54
|
"mdast-util-from-markdown": "^2.0.2",
|
|
56
55
|
"mdast-util-gfm": "^3.1.0",
|