markdown-parity-check 0.2.38 → 0.2.40

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 CHANGED
@@ -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.38 on 2026-11-13. The exact command is in the Development section below. The text report ends with a list of limitations, which is omitted here:
81
+ This is the text report for the matching fixture pair in this repository, run with version 0.2.40 on 2026-11-15. 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.38 (offline mode)
84
+ markdown-parity-check 0.2.40 (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)
@@ -114,6 +114,8 @@ Headings, paragraphs, list items, tables, code blocks and links are compared blo
114
114
 
115
115
  Content that is hidden or sits inside a left-out element is left out on both sides. This also holds 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.
116
116
 
117
+ Hidden means the `hidden` attribute, `aria-hidden="true"` and a `template` element, whose content a browser never renders. An element with `aria-hidden="true"` counts as hidden although a sighted reader still sees it, so text that only the HTML carries inside such an element is not reported as missing from the Markdown. A style that hides an element, such as `display: none`, is not evaluated, because CSS is not read. In the Markdown, an HTML comment and an unused link reference definition, which is one that no link uses, are not content and give no finding, not even with `--strict`. A definition that a link uses is compared through that link.
118
+
117
119
  - 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.
118
120
  - Warnings: a checkbox that is present on one side only, a difference in order and a difference in heading level, case, punctuation, list kind or nesting level. A difference in order is also reported for a block that moved and changed only in case, punctuation or typographic characters. 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. Examples are 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.
119
121
  - Information: each skipped comparison, which does not fail a check, not even with `--strict`.
@@ -147,7 +149,11 @@ The choice follows the type of the response, not the request. Any other response
147
149
 
148
150
  ### Limits of the method
149
151
 
150
- JavaScript is not executed. Content that a page builds in the browser is compared as the server sent it. Block matching is heuristic, so some layouts need an explicit selector. Reports mask URL query values and fragments and remove any user name or password from a URL. Excerpts may still contain private page content. Review a report before you share it.
152
+ JavaScript is not executed. Content that a page builds in the browser is compared as the server sent it. Block matching is heuristic, so some layouts need an explicit selector. Reports mask URL query values and fragments and remove the user name and password of an address with a scheme, such as `https://user:password@host/`. Excerpts may still contain private page content. Review a report before you share it.
153
+
154
+ The masking is a display safeguard that does not hide ordinary text, so it has limits, and this paragraph is the full list. It removes the user name and password even when a tab, a line break or a space sits inside the user information, provided that the user information holds a colon, as in `user:password`. A user name alone, with no colon, is masked when a tab, a vertical tab or a form feed sits inside it, and is shown when a space, a no-break space, a line feed or a carriage return does, because a line break or a space between an address and an e-mail address is ordinary text. On a bare host name without a scheme, a query or a fragment is masked only when it holds an equals sign, so an anchor such as `example.com/docs/guide#step-3` and a path segment are shown. Not masked: a bracketed IPv6 host, a host with a trailing dot, a name with no dot other than `localhost` and an scp-style `git@host:path`. A scheme-less `user:password@host.example/path` is masked as `user:***@host.example/path`, and so is the e-mail link that the Markdown parser reads out of it, when a path, a query that holds a value or a fragment that holds an equals sign follows the host name. Without one, as in `user:password@host.example` or `Contact:jane@example.com`, it is shown, because text alone cannot tell a user name from a label. The scheme-less form is also shown when its host name holds a letter outside ASCII, or when its colon or at sign is written as a character reference or a fullwidth character. An address after `mailto:`, `xmpp:`, `sip:`, `sips:`, `acct:` or `im:` is shown as written. A plain space or a no-break space right after the colon of the user information, and a password of digits only that is followed by white space, are read as text and shown. The masking changes what a report shows and never what is compared, and a number difference inside a masked part still gives the number finding, with the values left out. In both formats U+200E, U+200F, U+061C, U+2028, U+2029 and the tag characters are removed from report text. The text report shows a line feed or a carriage return inside a string from a page or an argument as `\n` or `\r`.
155
+
156
+ A link target longer than 8192 characters stops the run with exit code 2 and an error that names the limit and does not repeat the target. The comparison handles a target once for every link, block or reference that touches it, so the time grew with the length of the target times that count. The limit applies to the target as the page or the Markdown wrote it, before any resolution.
151
157
 
152
158
  ## Command line and hosted page
153
159
 
@@ -167,6 +173,7 @@ Some limits are not in the table:
167
173
 
168
174
  - 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.
169
175
  - 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.
176
+ - Of the IPv6 addresses, only the block 2000::/3, which is the global unicast space the IANA has allocated, can be public. Inside it the blocks that the IANA special-purpose registry does not mark as globally reachable are refused too. An address anywhere else, such as `8000::1` or `0:1::1`, is refused, with one exception: the forms that carry an IPv4 address are decided by that IPv4 address, as before. These are the IPv4-mapped form `::ffff:a.b.c.d`, the IPv4-translated form `::ffff:0:a.b.c.d`, the deprecated IPv4-compatible form `::a.b.c.d` and NAT64 `64:ff9b::a.b.c.d`, which all lie outside 2000::/3, and 6to4 and Teredo, which lie inside it. So `::ffff:8.8.8.8` and `64:ff9b::8.8.8.8` are public and `::ffff:127.0.0.1` is not.
170
177
  - 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.
171
178
  - The command-line tool follows at most 5 redirects.
172
179
  - When elements are nested more than 1024 levels deep, the extraction stops with exit code 2. This holds 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.
@@ -210,11 +217,15 @@ When the Markdown source has `kind: 'url'` in its `meta`, the delivery check run
210
217
 
211
218
  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.
212
219
 
213
- 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. In the same case, a value of 2 000 000 made the pairing step stop after about 70 milliseconds, on top of the parse time.
220
+ 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 tens of seconds in hand timings on development machines. In the same case, a value of 2 000 000 made the pairing step stop, and the whole call, parsing included, took about a second.
214
221
 
215
222
  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.
216
223
 
217
- The caller fetches the pages and decides which addresses are allowed. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
224
+ The library has no time limit and no memory limit of its own. A program that compares untrusted documents needs a time limit and a memory limit of its own, enforced outside the calling thread, for example in a worker thread, in a separate process or in an isolate with a CPU limit. `run` is synchronous, so a timer in the same thread cannot interrupt it, and the command line uses a worker thread for that reason. A link target over 8192 characters is a `RunError`, as described under the limits of the method.
225
+
226
+ Some costs come from the parsers and are not bounded by this package. The table rule of `micromark-extension-gfm` and the bare link rule of `mdast-util-find-and-replace` take more than linear time on very large inputs. In hand timings on one development machine, a Markdown table of 10 000 one-cell rows and one row of 30 000 cells, under 250 kB, took tens of seconds to parse, and 100 000 bare links in one paragraph, 2.8 MB, took tens of seconds as well. A deeply nested HTML document needs memory in proportion to its blocks times their nesting depth. A document of 650 000 paragraphs inside 1 000 nested elements, 5 MiB, ran out of memory at about 4 GB, which ends a library process. The command line stops the same run with exit code 2, and the test suite does not repeat these timings.
227
+
228
+ The caller fetches the pages and decides which addresses are allowed. The address policy that the command applies is exported as `assertPublicHost` and `isPublicAddress`. `assertPublicHost` takes `url.hostname` of a parsed `URL`, because the URL parser has already written a literal such as `2130706433` or `0x7f.0.0.1` as dotted decimal by then. A caller that checks the host and the resolved addresses and then lets `fetch()` resolve the name again can be sent to another address by a DNS answer that changes in between. The package exports no helper that pins the checked address. The command connects to the address it checked.
218
229
 
219
230
  ### Report format
220
231
 
@@ -261,12 +272,12 @@ Only after that check does it create the GitHub release with the verified tarbal
261
272
  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.
262
273
 
263
274
  ```sh
264
- mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.38 --ignore-scripts && npm audit signatures
275
+ mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.40 --ignore-scripts && npm audit signatures
265
276
  ```
266
277
 
267
278
  `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.
268
279
 
269
- Tag `v0.2.38` must point at that same commit, and `gh api repos/erekola/markdown-parity-check/commits/v0.2.38 --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.
280
+ Tag `v0.2.40` must point at that same commit, and `gh api repos/erekola/markdown-parity-check/commits/v0.2.40 --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.
270
281
 
271
282
  ## Security
272
283
 
package/SECURITY.md CHANGED
@@ -12,11 +12,11 @@ Please do not open a public issue for security reports. You can expect an initia
12
12
 
13
13
  ## Network and file access
14
14
 
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.
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 and a memory limit of its own, enforced outside the calling thread, for example in a worker thread, in a separate process or in an isolate with a CPU limit. `run` is synchronous, so a timer in the same thread cannot interrupt it. 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 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.
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 tens of seconds with default limits on development machines, in hand timings 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. With the default limits the pairing of links inside one block 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, and the whole call, parsing included, took about a second. `run` throws a `RunError` there, with a message that names the limit, and the command line reports it with exit code 2. A link target longer than 8192 characters stops the run in the same way, because the time of the comparison grew with the length of a target times the number of links that handle it.
18
18
 
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.
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 the user name and password of an address with a scheme. The masking has limits: some shapes are shown on purpose because nothing tells them from ordinary text. The README section "Limits of the method" lists what is masked and what is not. Excerpts may contain private page content. Review reports before sharing them.
20
20
 
21
21
  ## Dependencies and releases
22
22
 
package/dist/src/align.js CHANGED
@@ -19,7 +19,16 @@ function looseKey(b) {
19
19
  /** The link targets of a block, with their texts, in order. Blocks with equal text and equal link signatures are the
20
20
  * same block as far as the links go, so the alignment prefers them over equal-text blocks with other targets (MP-13). */
21
21
  function linkSignature(b) {
22
- return b.links.map((l) => `${l.text}\x1f${l.resolved ?? l.rawHref}`).join('\x1e');
22
+ try {
23
+ return b.links.map((l) => `${l.text}\x1f${l.resolved ?? l.rawHref}`).join('\x1e');
24
+ }
25
+ catch (err) {
26
+ // The targets of one block together are longer than a string can be. Up to 0.2.38 the RangeError reached the caller
27
+ // as an unexpected error with a stack; it is a limit of the comparison like the others.
28
+ if (err instanceof RangeError)
29
+ throw new AlignmentLimitError(`Comparison limit exceeded: the link targets of one block (${b.links.length} links) are too long together to compare.`);
30
+ throw err;
31
+ }
23
32
  }
24
33
  export const SIMILARITY_THRESHOLD = 0.6;
25
34
  export const UNCERTAIN_THRESHOLD = 0.8;
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.38\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";
3
+ export declare const HELP = "markdown-parity-check 0.2.40\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 {
@@ -21,6 +21,20 @@ export interface CliArgs {
21
21
  version: boolean;
22
22
  }
23
23
  export declare function parseCliArgs(argv: string[]): CliArgs;
24
+ /**
25
+ * Whether the module file is the entry point Node was started with. process.argv[1] is the path as it was typed,
26
+ * made absolute and nothing more, so `node dist/src/cli` gives a path without the .js extension that the module file
27
+ * has, and up to 0.2.38 the two did not compare equal: the command ran no code and exited 0 without a word. The path
28
+ * is compared as it is and with .js added, each followed through realpath where the file exists (a link such as
29
+ * node_modules/.bin/markdown-parity-check names the file it points at), and without regard to case where the file
30
+ * system is case-insensitive. The path functions can be passed in, so the check is tested on POSIX and Windows paths
31
+ * on any system.
32
+ */
33
+ export declare function isEntryPoint(argv1: string | undefined, moduleFile: string, deps?: {
34
+ resolve?: (p: string) => string;
35
+ realpath?: (p: string) => string;
36
+ caseInsensitive?: boolean;
37
+ }): boolean;
24
38
  export type FetchFn = (url: string, options: FetchOptions) => Promise<FetchResult>;
25
39
  export interface CliIo {
26
40
  stdout: (s: string) => void;
package/dist/src/cli.js CHANGED
@@ -102,6 +102,13 @@ const MAX_TIMEOUT_MS = 2147483647;
102
102
  * marks or hashes come before it, as the hosted maskLocation does. What follows the last '@' has its query values
103
103
  * masked and its fragment dropped. */
104
104
  function maskOption(value) {
105
+ return oneLineText(maskOptionRaw(value));
106
+ }
107
+ /** A line feed or a carriage return of an argument, written as \n or \r, so an error stays one line on stderr. */
108
+ function oneLineText(value) {
109
+ return value.replace(/[\r\n]/g, (c) => (c === '\n' ? '\\n' : '\\r'));
110
+ }
111
+ function maskOptionRaw(value) {
105
112
  const plain = value.replace(/[\t\n\r]/g, '');
106
113
  let hasHost = false;
107
114
  try {
@@ -118,6 +125,39 @@ function maskOption(value) {
118
125
  const tail = stop < 0 ? rest : rest.slice(0, stop) + (rest[stop] === '?' ? '?***' : '');
119
126
  return '***@' + tail;
120
127
  }
128
+ /** A value from the command line, as an error may repeat it. A path is shown as it is. Anything that holds an '@', a
129
+ * question mark, a number sign or "://" goes through maskOption in one piece: the run-based masking of redactText cuts a
130
+ * value at a raw space, and the part after it, such as the end of a password, reached the output unmasked
131
+ * (0.2.39, found by an outside review 2026-11-14). */
132
+ function echoValue(value) {
133
+ return /[@?#]|:\/\//.test(value) ? maskOption(value) : oneLineText(value);
134
+ }
135
+ /** What the system says of a failed file operation, without the path it quotes: the path is the argument, echoed on its
136
+ * own through echoValue, and the system's copy of it is the resolved form that no masking recognises. */
137
+ function errnoText(err) {
138
+ const message = err.message;
139
+ const quote = message.indexOf("'");
140
+ return (quote < 0 ? message : message.slice(0, quote)).trim();
141
+ }
142
+ /** The message of an argument error. A positional argument is echoed by Node's own message, so it is masked here. */
143
+ function argumentError(err) {
144
+ if (err.code === 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL') {
145
+ const m = /^Unexpected argument '([\s\S]*)'\. This command does not take positional arguments/.exec(err.message);
146
+ return m ? `Unexpected argument '${echoValue(m[1])}'. This command does not take positional arguments` : 'Unexpected argument; its value is not shown.';
147
+ }
148
+ if (err.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
149
+ // The name of an unknown option is the argument as it was typed, so it is masked like a value.
150
+ const m = /^Unknown option '([\s\S]*)'$/.exec(err.message);
151
+ return m ? `Unknown option '${echoValue(m[1])}'` : 'Unknown option; its name is not shown.';
152
+ }
153
+ return err.message;
154
+ }
155
+ /** Text for stderr: every line break but the one that ends the text is written as \n or \r, so an argument that an
156
+ * error repeats cannot add a line, whichever option or error repeats it. */
157
+ function oneLineStderr(text) {
158
+ const end = text.endsWith('\n') ? text.length - 1 : text.length;
159
+ return oneLineText(text.slice(0, end)) + text.slice(end);
160
+ }
121
161
  function positiveInt(name, raw, fallback, max = Number.MAX_SAFE_INTEGER) {
122
162
  if (raw === undefined)
123
163
  return fallback;
@@ -164,7 +204,7 @@ export function parseCliArgs(argv) {
164
204
  });
165
205
  }
166
206
  catch (err) {
167
- throw new CliError(err.message);
207
+ throw new CliError(argumentError(err));
168
208
  }
169
209
  const v = parsed.values;
170
210
  const htmlProfile = v['html-profile'];
@@ -237,11 +277,40 @@ export function parseCliArgs(argv) {
237
277
  const out = path.resolve(args.output);
238
278
  for (const input of [args.htmlFile, args.markdownFile]) {
239
279
  if (input !== undefined && (samePath(out, path.resolve(input)) || sameFile(out, path.resolve(input))))
240
- throw new CliError(`--output must not point at an input file (${args.output}).`);
280
+ throw new CliError(`--output must not point at an input file (${echoValue(args.output)}).`);
241
281
  }
242
282
  }
243
283
  return args;
244
284
  }
285
+ /**
286
+ * Whether the module file is the entry point Node was started with. process.argv[1] is the path as it was typed,
287
+ * made absolute and nothing more, so `node dist/src/cli` gives a path without the .js extension that the module file
288
+ * has, and up to 0.2.38 the two did not compare equal: the command ran no code and exited 0 without a word. The path
289
+ * is compared as it is and with .js added, each followed through realpath where the file exists (a link such as
290
+ * node_modules/.bin/markdown-parity-check names the file it points at), and without regard to case where the file
291
+ * system is case-insensitive. The path functions can be passed in, so the check is tested on POSIX and Windows paths
292
+ * on any system.
293
+ */
294
+ export function isEntryPoint(argv1, moduleFile, deps = {}) {
295
+ if (argv1 === undefined || argv1 === '')
296
+ return false;
297
+ const resolve = deps.resolve ?? ((p) => path.resolve(p));
298
+ const realpath = deps.realpath ?? ((p) => fs.realpathSync.native(p));
299
+ const fold = deps.caseInsensitive ?? process.platform === 'win32';
300
+ const norm = (p) => {
301
+ let real = p;
302
+ try {
303
+ real = realpath(p);
304
+ }
305
+ catch {
306
+ // The file does not exist under this name, as for a path typed without its extension: compare the name as it is.
307
+ }
308
+ return fold ? real.toLowerCase() : real;
309
+ };
310
+ const target = norm(moduleFile);
311
+ const typed = resolve(argv1);
312
+ return norm(typed) === target || norm(`${typed}.js`) === target;
313
+ }
245
314
  function samePath(a, b) {
246
315
  const norm = (p) => {
247
316
  try {
@@ -277,7 +346,7 @@ function readFileInput(file, base) {
277
346
  body = fs.readFileSync(file, 'utf8');
278
347
  }
279
348
  catch (err) {
280
- throw new CliError(`Cannot read ${file}: ${err.message}`);
349
+ throw new CliError(`Cannot read ${echoValue(file)}: ${errnoText(err)}`);
281
350
  }
282
351
  if (body.charCodeAt(0) === 0xfeff)
283
352
  body = body.slice(1);
@@ -312,7 +381,7 @@ function emit(report, args, io) {
312
381
  catch {
313
382
  // Nothing more to do: the error below names the target.
314
383
  }
315
- throw new CliError(`Cannot write report to ${args.output}: ${err.message}`);
384
+ throw new CliError(`Cannot write report to ${echoValue(args.output)}: ${errnoText(err)}`);
316
385
  }
317
386
  io.stderr(`Report written to ${args.output} (${report.summary.result.toUpperCase()}, exit ${report.summary.exitCode}).\n`);
318
387
  }
@@ -323,7 +392,7 @@ export async function main(argv, io = { stdout: (s) => process.stdout.write(s),
323
392
  // gave or a header a server sent, and up to 0.2.11 stderr printed both as they were (found by an outside review
324
393
  // 2026-09-26).
325
394
  const raw = io;
326
- io = { stdout: raw.stdout, stderr: (s) => raw.stderr(redactText(s)) };
395
+ io = { stdout: raw.stdout, stderr: (s) => raw.stderr(oneLineStderr(redactText(s))) };
327
396
  let args;
328
397
  try {
329
398
  args = parseCliArgs(argv);
@@ -415,7 +484,7 @@ export async function main(argv, io = { stdout: (s) => process.stdout.write(s),
415
484
  }
416
485
  return report.summary.exitCode;
417
486
  }
418
- const invokedDirectly = process.argv[1] !== undefined && samePath(path.resolve(process.argv[1]), fileURLToPath(import.meta.url));
487
+ const invokedDirectly = isEntryPoint(process.argv[1], fileURLToPath(import.meta.url));
419
488
  if (invokedDirectly) {
420
489
  // A reader that closes the pipe before the report is written (head -c 0, a pager that quit) makes the write fail with
421
490
  // EPIPE. The report could not be delivered, which is a failed run: exit 2, as for every other report that cannot be
@@ -425,7 +494,7 @@ if (invokedDirectly) {
425
494
  outputFailed = true;
426
495
  process.exitCode = 2;
427
496
  try {
428
- process.stderr.write(redactText(`Error: Cannot write the report to stdout: ${err.code ?? err.message}\n`));
497
+ process.stderr.write(oneLineStderr(redactText(`Error: Cannot write the report to stdout: ${err.code ?? err.message}\n`)));
429
498
  }
430
499
  catch {
431
500
  // stderr may be closed as well; the exit code carries the failure.
@@ -1,13 +1,16 @@
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, textKey, trimHref, visibleNumbers } from './normalize.js';
3
+ import { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskBareUserinfo, 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();
7
+ /** The text of a block as a report shows it: the display text when the credential masking needed one, else the
8
+ * comparison text. Nothing is compared through it. */
9
+ const shownText = (b) => b.shown ?? b.text;
7
10
  function side(b) {
8
11
  let s = sides.get(b);
9
12
  if (!s) {
10
- s = { line: b.location.line, path: b.location.path, blockIndex: b.location.blockIndex, excerpt: excerpt(b.type === 'code' ? (b.code ?? b.text) : b.text) };
13
+ s = { line: b.location.line, path: b.location.path, blockIndex: b.location.blockIndex, excerpt: excerpt(b.type === 'code' ? (b.code ?? b.text) : shownText(b)) };
11
14
  sides.set(b, s);
12
15
  }
13
16
  return { ...s };
@@ -56,8 +59,10 @@ export function diffNumbers(a, b) {
56
59
  return { before, after };
57
60
  }
58
61
  // What a finding shows of a link. A link GFM made out of a hidden part of a URL shows neither text nor target.
59
- const linkText = (l, other) => (l.masked || other?.masked ? '***' : redactText(l.text));
60
- const linkHref = (l, href) => (l.masked ? '***' : maskHref(href));
62
+ const linkText = (l, other) => (l.masked || other?.masked ? '***' : redactText(l.shown ?? l.text));
63
+ // maskBareUserinfo runs before maskHref as well as after it: maskHref drops the fragment, and a target such as
64
+ // `user:secret@host.example#a=b` has no other delimiter, so after maskHref the shape would no longer be recognised.
65
+ const linkHref = (l, href) => (l.masked ? '***' : maskBareUserinfo(maskHref(maskBareUserinfo(href))));
61
66
  /**
62
67
  * Pairs the HTML block's links with the Markdown block's, in three steps.
63
68
  *
@@ -298,11 +303,17 @@ function compareTables(out, h, m) {
298
303
  return;
299
304
  }
300
305
  for (let r = 0; r < hc.length; r++) {
301
- for (let c = 0; c < hCols; c++) {
306
+ // Only the cells a row has: a cell past the end of both rows is empty on both sides and cannot differ. Up to 0.2.38
307
+ // every row was walked to the width of the widest one, so one wide row among many narrow ones cost rows times width.
308
+ const width = Math.max(hc[r]?.length ?? 0, mc[r]?.length ?? 0);
309
+ for (let c = 0; c < width; c++) {
302
310
  const hv = hc[r]?.[c] ?? '';
303
311
  const mv = mc[r]?.[c] ?? '';
304
312
  if (hv !== mv) {
305
- out.push({ code: 'TABLE_CELL_CHANGED', severity: 'error', direction: 'both', message: `Table cell (row ${r + 1}, column ${c + 1}) differs.`, html: side(h), markdown: side(m), before: hv, after: mv });
313
+ // The values are shown as excerpts, like every other text of a finding: a cell of a megabyte is not copied whole.
314
+ const hShown = h.cellsShown?.[r]?.[c] ?? hv;
315
+ const mShown = m.cellsShown?.[r]?.[c] ?? mv;
316
+ out.push({ code: 'TABLE_CELL_CHANGED', severity: 'error', direction: 'both', message: `Table cell (row ${r + 1}, column ${c + 1}) differs.`, html: side(h), markdown: side(m), before: excerpt(hShown), after: excerpt(mShown) });
306
317
  }
307
318
  }
308
319
  }
@@ -343,7 +354,7 @@ function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
343
354
  // information, so a change there is still a number change and the classification does not move. What the
344
355
  // finding shows is read again from the text with those parts taken out, because the report masks them and
345
356
  // a bare number is not recognisable as part of a URL at the reporting boundary (0.2.10).
346
- const shown = diffNumbers(visibleNumbers(h.text), visibleNumbers(m.text));
357
+ const shown = diffNumbers(visibleNumbers(shownText(h)), visibleNumbers(shownText(m)));
347
358
  if (shown) {
348
359
  out.push({ code: 'NUMBER_CHANGED', severity: 'error', direction: 'both', message: `Numeric value differs in the ${label(h)}: ${shown.before.join(', ') || '(none)'} in HTML, ${shown.after.join(', ') || '(none)'} in Markdown.`, html: side(h), markdown: side(m), before: shown.before.join(', '), after: shown.after.join(', ') });
349
360
  }
@@ -353,10 +364,10 @@ function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
353
364
  }
354
365
  else if (textKey(h.text) === textKey(m.text)) {
355
366
  // The text key keeps the marks and symbols the alignment key drops (MP-11).
356
- 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) });
367
+ 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(shownText(h)), after: excerpt(shownText(m)) });
357
368
  }
358
369
  else {
359
- 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) });
370
+ out.push({ code: 'TEXT_CHANGED', severity: 'error', direction: 'both', message: `The ${label(h)} text differs.`, html: side(h), markdown: side(m), before: excerpt(shownText(h)), after: excerpt(shownText(m)) });
360
371
  }
361
372
  }
362
373
  // Any block can carry the list context of its item (a heading, code or a table that leads it, MP-06); the function
@@ -383,11 +394,11 @@ export function compare(html, markdown, options = {}) {
383
394
  comparePair(findings, p, a[p.a], b[p.b], bothBases, lim.maxSimilarityWork);
384
395
  for (const i of al.unmatchedA) {
385
396
  const h = a[i];
386
- findings.push({ code: 'BLOCK_MISSING', severity: 'error', direction: 'html_only', message: `The ${label(h)} is in the HTML but not in the Markdown.`, html: side(h), before: excerpt(h.type === 'code' ? (h.code ?? h.text) : h.text) });
397
+ findings.push({ code: 'BLOCK_MISSING', severity: 'error', direction: 'html_only', message: `The ${label(h)} is in the HTML but not in the Markdown.`, html: side(h), before: excerpt(h.type === 'code' ? (h.code ?? h.text) : shownText(h)) });
387
398
  }
388
399
  for (const j of al.unmatchedB) {
389
400
  const m = b[j];
390
- findings.push({ code: 'BLOCK_ADDED', severity: 'error', direction: 'markdown_only', message: `The ${label(m)} is in the Markdown but not in the HTML.`, markdown: side(m), after: excerpt(m.type === 'code' ? (m.code ?? m.text) : m.text) });
401
+ findings.push({ code: 'BLOCK_ADDED', severity: 'error', direction: 'markdown_only', message: `The ${label(m)} is in the Markdown but not in the HTML.`, markdown: side(m), after: excerpt(m.type === 'code' ? (m.code ?? m.text) : shownText(m)) });
391
402
  }
392
403
  // Deterministic order: by HTML position, then Markdown position, then severity, then code.
393
404
  findings.sort((x, y) => {
package/dist/src/html.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { parseDocument } from 'htmlparser2';
4
4
  import { selectAll, selectOne } from 'css-select';
5
5
  import { Element, Text } from 'domhandler';
6
- import { extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
6
+ import { extractNumbers, looseNormalize, normalizeCode, redactText, resolveHref, shownField, shownNormalize, stripControlChars, strictNormalize } from './normalize.js';
7
7
  export class HtmlExtractError extends Error {
8
8
  /** The user-supplied value the message names (here, --selector), capped the way the hosted validator's cut()
9
9
  * (src/worker.ts in turva-worker) caps a reflected value: in its own field, not only interpolated into the sentence, and bounded so an
@@ -96,8 +96,18 @@ function segment(ctx, el) {
96
96
  same.forEach((c, i) => ctx.segments.set(c, same.length > 1 ? `${c.name}:nth-of-type(${i + 1})` : c.name));
97
97
  return ctx.segments.get(el) ?? el.name;
98
98
  }
99
+ // The class names of each element, split once. hasClass runs on every ancestor of every block of a Starlight page,
100
+ // and up to 0.2.38 it split the class attribute again at each call, so a page with one element carrying a long class
101
+ // attribute and many pre blocks took time in the product of the two.
102
+ // The tree is not changed after parsing, so the answer for an element stays the same.
103
+ const classSets = new WeakMap();
99
104
  function hasClass(el, name) {
100
- return (el.attribs.class ?? '').split(/\s+/).includes(name);
105
+ let set = classSets.get(el);
106
+ if (set === undefined) {
107
+ set = new Set((el.attribs.class ?? '').split(/\s+/));
108
+ classSets.set(el, set);
109
+ }
110
+ return set.has(name);
101
111
  }
102
112
  function ancestor(el, predicate) {
103
113
  let parent = el.parent;
@@ -209,7 +219,7 @@ function inlineText(ctx, node, run) {
209
219
  for (const child of node.children)
210
220
  inlineText(ctx, child, inner);
211
221
  const raw = node.attribs['href'] ?? '';
212
- run.links.push({ text: strictNormalize(inner.text), rawHref: raw, resolved: resolveHref(raw, ctx.base) });
222
+ run.links.push({ text: strictNormalize(inner.text), ...shownField(inner.text), rawHref: raw, resolved: resolveHref(raw, ctx.base) });
213
223
  run.links.push(...inner.links);
214
224
  run.text += inner.text;
215
225
  return;
@@ -235,7 +245,7 @@ function flushRun(ctx, run, container, type = 'paragraph', list) {
235
245
  if (text === '')
236
246
  return;
237
247
  const node = run.firstNode ?? container;
238
- pushBlock(ctx, { type, text, links: run.links, ...(type === 'listItem' && list ? { list } : {}) }, node, container);
248
+ pushBlock(ctx, { type, text, ...shownField(run.text), links: run.links, ...(type === 'listItem' && list ? { list } : {}) }, node, container);
239
249
  }
240
250
  /**
241
251
  * A link whose children hold a block element, such as a linked card (<a href><h2>..</h2><p>..</p></a>). Up to 0.2.29
@@ -265,7 +275,7 @@ function walkBlockAnchor(ctx, a) {
265
275
  const resolved = resolveHref(rawHref, ctx.base);
266
276
  for (let i = start; i < ctx.blocks.length; i++) {
267
277
  const block = ctx.blocks[i];
268
- block.links.unshift({ text: strictNormalize(block.text), rawHref, resolved });
278
+ block.links.unshift({ text: strictNormalize(block.text), ...(block.shown !== undefined ? { shown: block.shown } : {}), rawHref, resolved });
269
279
  }
270
280
  }
271
281
  /** In a list item, a link whose only content is one plain paragraph is the item's own text, as before: the item
@@ -308,7 +318,7 @@ function handleBlock(ctx, el) {
308
318
  inlineText(ctx, c, run);
309
319
  const text = strictNormalize(run.text);
310
320
  if (text !== '')
311
- pushBlock(ctx, { type: 'heading', text, depth: Number(m[1]), links: run.links }, el, el);
321
+ pushBlock(ctx, { type: 'heading', text, ...shownField(run.text), depth: Number(m[1]), links: run.links }, el, el);
312
322
  return;
313
323
  }
314
324
  if (el.name === 'p' || el.name === 'dt' || el.name === 'dd' || el.name === 'figcaption' || el.name === 'summary' || el.name === 'caption' || el.name === 'address') {
@@ -382,7 +392,7 @@ function listInfo(ctx, li) {
382
392
  * The numbers the visible items of a numbered list show, the way a browser's list counter counts them: from the
383
393
  * list's start, or from the item count for a reversed list without one, and an item's value attribute sets the
384
394
  * number from that item on. One pass per list, kept in ctx; the first version counted again for every item, and
385
- * a list of 20 000 items took ten seconds (found by an independent review before 0.2.13 was released). A reversed
395
+ * a list of 20 000 items took seconds (found by an independent review before 0.2.13 was released). A reversed
386
396
  * list gives only its first item a number: Markdown has no reversed list and numbers every item from the first,
387
397
  * so the later numbers of a faithful Markdown copy can never match.
388
398
  */
@@ -676,25 +686,35 @@ function handleTable(ctx, table) {
676
686
  ctx.issues.push({ code: 'EXTRACTION_TABLE_SPAN_NOT_COMPARED', severity: 'info', message: 'A table cell carries a rowspan or colspan attribute; a plain row/column reading cannot place its value reliably, so the table body was not compared.', line: lineOf(ctx, table) });
677
687
  }
678
688
  const cells = [];
689
+ const cellsShown = [];
690
+ let anyShown = false;
679
691
  const links = [];
680
692
  for (const tr of rows) {
681
693
  const row = [];
694
+ const rowShown = [];
682
695
  for (const cell of tr.children) {
683
696
  if (cell instanceof Element && (cell.name === 'td' || cell.name === 'th') && !isSkipped(cell, ctx.root, ctx.profile)) {
684
697
  const run = newRun();
685
698
  for (const c of cell.children)
686
699
  inlineText(ctx, c, run);
687
700
  row.push(strictNormalize(run.text));
701
+ const shownCell = shownNormalize(run.text);
702
+ if (shownCell !== undefined)
703
+ anyShown = true;
704
+ rowShown.push(shownCell ?? row[row.length - 1]);
688
705
  links.push(...run.links);
689
706
  }
690
707
  }
691
- if (row.length > 0)
708
+ if (row.length > 0) {
692
709
  cells.push(row);
710
+ cellsShown.push(rowShown);
711
+ }
693
712
  }
694
713
  if (cells.length === 0)
695
714
  return;
696
715
  const text = cells.map((r) => r.join(' | ')).join(' \n ');
697
- pushBlock(ctx, { type: 'table', text: strictNormalize(text), cells, links, ...(spanned ? { spanned: true } : {}) }, table, table);
716
+ const shownTable = anyShown ? { shown: strictNormalize(cellsShown.map((r) => r.join(' | ')).join(' \n ')), cellsShown } : {};
717
+ pushBlock(ctx, { type: 'table', text: strictNormalize(text), ...shownTable, cells, links, ...(spanned ? { spanned: true } : {}) }, table, table);
698
718
  }
699
719
  function closestTable(el) {
700
720
  let cur = el.parent;
@@ -733,13 +753,17 @@ function pickRoot(doc, selector, notes, issues) {
733
753
  matches = selectAll(selector, doc.children).filter((n) => n instanceof Element);
734
754
  }
735
755
  catch (err) {
736
- throw new HtmlExtractError(`Invalid selector: ${err.message}`, selector);
756
+ // The parser's message quotes the selector, so it is capped like the value (0.2.39, found by an outside review 2026-11-14).
757
+ // It quotes a piece of it in lower case or from the middle, where no masking can tell what the piece was, so a
758
+ // selector that holds a URL with a credential or a query value gets no quotation at all.
759
+ const quotes = redactText(selector) !== stripControlChars(selector);
760
+ throw new HtmlExtractError(`Invalid selector: ${quotes ? 'the selector is not repeated, because it holds a URL with user information, a query value or a fragment' : capValue(err.message)}`, selector);
737
761
  }
738
762
  if (matches.length === 0)
739
763
  throw new HtmlExtractError('Selector matched no element.', selector);
740
764
  if (matches.length > 1)
741
765
  notes.push(`Selector "${capValue(selector)}" matched ${matches.length} elements; the first in document order was used.`);
742
- return { root: matches[0], strategy: `selector:${selector}`, confidence: 'high' };
766
+ return { root: matches[0], strategy: `selector:${capValue(selector)}`, confidence: 'high' };
743
767
  }
744
768
  // A candidate the page hides is not its main content. Up to 0.2.12 the first candidate was taken as it was, so a
745
769
  // hidden <main> before the visible one was compared in its place and the visible content not at all. Candidates