markdown-parity-check 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -0
- package/SECURITY.md +23 -0
- package/dist/src/align.js +160 -0
- package/dist/src/cli.js +269 -0
- package/dist/src/compare.js +188 -0
- package/dist/src/fetch.js +275 -0
- package/dist/src/html.js +315 -0
- package/dist/src/markdown.js +320 -0
- package/dist/src/model.js +2 -0
- package/dist/src/netguard.js +129 -0
- package/dist/src/normalize.js +136 -0
- package/dist/src/report.js +88 -0
- package/dist/src/run.js +113 -0
- package/dist/src/version.js +5 -0
- package/package.json +55 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// The comparison core: aligns blocks and turns the alignment into findings. Pure and network-free.
|
|
2
|
+
import { align, UNCERTAIN_THRESHOLD } from './align.js';
|
|
3
|
+
import { excerpt, hrefDifference, maskHref, redactText } from './normalize.js';
|
|
4
|
+
function side(b) {
|
|
5
|
+
return { line: b.location.line, path: b.location.path, blockIndex: b.location.blockIndex, excerpt: excerpt(b.type === 'code' ? (b.code ?? b.text) : b.text) };
|
|
6
|
+
}
|
|
7
|
+
function label(b) {
|
|
8
|
+
switch (b.type) {
|
|
9
|
+
case 'heading':
|
|
10
|
+
return `heading (h${b.depth ?? '?'})`;
|
|
11
|
+
case 'listItem':
|
|
12
|
+
return 'list item';
|
|
13
|
+
case 'code':
|
|
14
|
+
return 'code block';
|
|
15
|
+
default:
|
|
16
|
+
return b.type;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function diffNumbers(a, b) {
|
|
20
|
+
if (a.length === b.length && a.every((v, i) => v === b[i]))
|
|
21
|
+
return null;
|
|
22
|
+
const remB = [...b];
|
|
23
|
+
const before = [];
|
|
24
|
+
for (const v of a) {
|
|
25
|
+
const k = remB.indexOf(v);
|
|
26
|
+
if (k >= 0)
|
|
27
|
+
remB.splice(k, 1);
|
|
28
|
+
else
|
|
29
|
+
before.push(v);
|
|
30
|
+
}
|
|
31
|
+
const remA = [...a];
|
|
32
|
+
const after = [];
|
|
33
|
+
for (const v of b) {
|
|
34
|
+
const k = remA.indexOf(v);
|
|
35
|
+
if (k >= 0)
|
|
36
|
+
remA.splice(k, 1);
|
|
37
|
+
else
|
|
38
|
+
after.push(v);
|
|
39
|
+
}
|
|
40
|
+
if (before.length === 0 && after.length === 0)
|
|
41
|
+
return { before: a, after: b }; // same multiset, different order
|
|
42
|
+
return { before, after };
|
|
43
|
+
}
|
|
44
|
+
function compareLinks(out, h, m, bothBases) {
|
|
45
|
+
// Link targets are compared unmasked; every value that reaches a finding goes through maskHref.
|
|
46
|
+
const remaining = [...m.links];
|
|
47
|
+
for (const hl of h.links) {
|
|
48
|
+
let idx = remaining.findIndex((ml) => ml.text === hl.text && sameTarget(hl, ml));
|
|
49
|
+
if (idx < 0)
|
|
50
|
+
idx = remaining.findIndex((ml) => ml.text === hl.text);
|
|
51
|
+
if (idx < 0) {
|
|
52
|
+
out.push({ code: 'LINK_MISSING', severity: 'error', direction: 'html_only', message: `Link "${redactText(hl.text)}" (${maskHref(hl.rawHref)}) is in the HTML block but not in the Markdown block.`, html: side(h), markdown: side(m), before: maskHref(hl.rawHref) });
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const ml = remaining.splice(idx, 1)[0];
|
|
56
|
+
if (sameTarget(hl, ml))
|
|
57
|
+
continue;
|
|
58
|
+
if (hl.resolved !== null && ml.resolved !== null) {
|
|
59
|
+
const diff = hrefDifference(hl.resolved, ml.resolved);
|
|
60
|
+
out.push({ code: 'LINK_TARGET_CHANGED', severity: 'error', direction: 'both', message: `Link "${redactText(hl.text)}" points to a different target (${diff} differs).`, html: side(h), markdown: side(m), before: maskHref(hl.resolved), after: maskHref(ml.resolved) });
|
|
61
|
+
}
|
|
62
|
+
else if (hl.resolved === null && ml.resolved === null) {
|
|
63
|
+
// Both relative and textually different: they differ under any common base.
|
|
64
|
+
const diff = hrefDifference(hl.rawHref, ml.rawHref);
|
|
65
|
+
out.push({ code: 'LINK_TARGET_CHANGED', severity: 'error', direction: 'both', message: `Link "${redactText(hl.text)}" points to a different relative target (${diff} differs).`, html: side(h), markdown: side(m), before: maskHref(hl.rawHref), after: maskHref(ml.rawHref) });
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
out.push({ code: 'LINK_UNVERIFIED', severity: 'warning', direction: 'both', message: bothBases ? `Link "${redactText(hl.text)}" could not be resolved on one side.` : `Link "${redactText(hl.text)}" differs textually and no base URL is known, so relative and absolute forms cannot be confirmed equal.`, html: side(h), markdown: side(m), before: maskHref(hl.rawHref), after: maskHref(ml.rawHref) });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
for (const ml of remaining) {
|
|
72
|
+
out.push({ code: 'LINK_ADDED', severity: 'error', direction: 'markdown_only', message: `Link "${redactText(ml.text)}" (${maskHref(ml.rawHref)}) is in the Markdown block but not in the HTML block.`, html: side(h), markdown: side(m), after: maskHref(ml.rawHref) });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function sameTarget(a, b) {
|
|
76
|
+
if (a.resolved !== null && b.resolved !== null)
|
|
77
|
+
return a.resolved === b.resolved;
|
|
78
|
+
return a.rawHref.trim() === b.rawHref.trim();
|
|
79
|
+
}
|
|
80
|
+
function compareTables(out, h, m) {
|
|
81
|
+
const hc = h.cells ?? [];
|
|
82
|
+
const mc = m.cells ?? [];
|
|
83
|
+
const hCols = Math.max(0, ...hc.map((r) => r.length));
|
|
84
|
+
const mCols = Math.max(0, ...mc.map((r) => r.length));
|
|
85
|
+
if (hc.length !== mc.length || hCols !== mCols) {
|
|
86
|
+
out.push({ code: 'TABLE_SHAPE_CHANGED', severity: 'error', direction: 'both', message: `Table shape differs: HTML ${hc.length}x${hCols}, Markdown ${mc.length}x${mCols} (rows x columns).`, html: side(h), markdown: side(m), before: `${hc.length}x${hCols}`, after: `${mc.length}x${mCols}` });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
for (let r = 0; r < hc.length; r++) {
|
|
90
|
+
for (let c = 0; c < hCols; c++) {
|
|
91
|
+
const hv = hc[r]?.[c] ?? '';
|
|
92
|
+
const mv = mc[r]?.[c] ?? '';
|
|
93
|
+
if (hv !== mv) {
|
|
94
|
+
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 });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function comparePair(out, p, h, m, bothBases) {
|
|
100
|
+
if (p.kind === 'moved') {
|
|
101
|
+
out.push({ code: 'ORDER_CHANGED', severity: 'warning', direction: 'both', message: `The ${label(h)} appears in a different position in the Markdown.`, html: side(h), markdown: side(m) });
|
|
102
|
+
}
|
|
103
|
+
if (h.type !== m.type) {
|
|
104
|
+
out.push({ code: 'STRUCTURE_CHANGED', severity: 'warning', direction: 'both', message: `Same text, different structure: ${label(h)} in HTML, ${label(m)} in Markdown.`, html: side(h), markdown: side(m), before: h.type, after: m.type });
|
|
105
|
+
}
|
|
106
|
+
if (h.type === 'heading' && m.type === 'heading' && h.depth !== m.depth) {
|
|
107
|
+
out.push({ code: 'HEADING_LEVEL_CHANGED', severity: 'warning', direction: 'both', message: `Heading level differs: h${h.depth} in HTML, h${m.depth} in Markdown.`, html: side(h), markdown: side(m), before: `h${h.depth}`, after: `h${m.depth}` });
|
|
108
|
+
}
|
|
109
|
+
const sameShapeTable = h.type === 'table' && m.type === 'table' && (h.cells ?? []).length === (m.cells ?? []).length;
|
|
110
|
+
if (p.kind === 'similar' && p.similarity < UNCERTAIN_THRESHOLD && !sameShapeTable) {
|
|
111
|
+
out.push({ code: 'ALIGNMENT_UNCERTAIN', severity: 'warning', direction: 'both', message: `These blocks were aligned with ${(p.similarity * 100).toFixed(0)} % token similarity; the differences reported for this pair may be a rewrite rather than an edit.`, html: side(h), markdown: side(m) });
|
|
112
|
+
}
|
|
113
|
+
if (h.type === 'table' && m.type === 'table') {
|
|
114
|
+
compareTables(out, h, m);
|
|
115
|
+
}
|
|
116
|
+
else if (h.type === 'code' && m.type === 'code') {
|
|
117
|
+
const hc = h.code ?? '';
|
|
118
|
+
const mc = m.code ?? '';
|
|
119
|
+
if (hc !== mc) {
|
|
120
|
+
if (h.text === m.text)
|
|
121
|
+
out.push({ code: 'CODE_WHITESPACE_CHANGED', severity: 'warning', direction: 'both', message: 'Code block differs only in whitespace or indentation.', html: side(h), markdown: side(m) });
|
|
122
|
+
else
|
|
123
|
+
out.push({ code: 'TEXT_CHANGED', severity: 'error', direction: 'both', message: 'Code block content differs.', html: side(h), markdown: side(m), before: excerpt(hc), after: excerpt(mc) });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
else if (h.text !== m.text) {
|
|
127
|
+
const nd = diffNumbers(h.numbers, m.numbers);
|
|
128
|
+
if (nd) {
|
|
129
|
+
out.push({ code: 'NUMBER_CHANGED', severity: 'error', direction: 'both', message: `Numeric value differs in the ${label(h)}: ${nd.before.join(', ') || '(none)'} in HTML, ${nd.after.join(', ') || '(none)'} in Markdown.`, html: side(h), markdown: side(m), before: nd.before.join(', '), after: nd.after.join(', ') });
|
|
130
|
+
}
|
|
131
|
+
else if (h.loose === m.loose) {
|
|
132
|
+
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) });
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
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) });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
compareLinks(out, h, m, bothBases);
|
|
139
|
+
}
|
|
140
|
+
const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
|
|
141
|
+
export function compare(html, markdown, options = {}) {
|
|
142
|
+
const a = html.blocks;
|
|
143
|
+
const b = markdown.blocks;
|
|
144
|
+
const al = align(a, b);
|
|
145
|
+
const findings = [];
|
|
146
|
+
const bothBases = options.bothBases ?? false;
|
|
147
|
+
if (html.confidence === 'low') {
|
|
148
|
+
findings.push({ code: 'EXTRACTION_LOW_CONFIDENCE', severity: 'warning', direction: 'html_only', message: 'HTML main content was taken from <body> because no <main>, <article> or [role=main] element exists; page chrome may leak into the comparison. Use --selector to narrow it.' });
|
|
149
|
+
}
|
|
150
|
+
for (const i of html.issues)
|
|
151
|
+
findings.push({ code: i.code, severity: i.severity, direction: 'html_only', message: i.message, html: { line: i.line, excerpt: i.excerpt } });
|
|
152
|
+
for (const i of markdown.issues)
|
|
153
|
+
findings.push({ code: i.code, severity: i.severity, direction: 'markdown_only', message: i.message, markdown: { line: i.line, excerpt: i.excerpt } });
|
|
154
|
+
for (const p of al.pairs)
|
|
155
|
+
comparePair(findings, p, a[p.a], b[p.b], bothBases);
|
|
156
|
+
for (const i of al.unmatchedA) {
|
|
157
|
+
const h = a[i];
|
|
158
|
+
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) });
|
|
159
|
+
}
|
|
160
|
+
for (const j of al.unmatchedB) {
|
|
161
|
+
const m = b[j];
|
|
162
|
+
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) });
|
|
163
|
+
}
|
|
164
|
+
// Deterministic order: by HTML position, then Markdown position, then severity, then code.
|
|
165
|
+
findings.sort((x, y) => {
|
|
166
|
+
const xa = x.html?.blockIndex ?? Number.MAX_SAFE_INTEGER;
|
|
167
|
+
const ya = y.html?.blockIndex ?? Number.MAX_SAFE_INTEGER;
|
|
168
|
+
if (xa !== ya)
|
|
169
|
+
return xa - ya;
|
|
170
|
+
const xb = x.markdown?.blockIndex ?? Number.MAX_SAFE_INTEGER;
|
|
171
|
+
const yb = y.markdown?.blockIndex ?? Number.MAX_SAFE_INTEGER;
|
|
172
|
+
if (xb !== yb)
|
|
173
|
+
return xb - yb;
|
|
174
|
+
const s = SEVERITY_ORDER[x.severity] - SEVERITY_ORDER[y.severity];
|
|
175
|
+
if (s !== 0)
|
|
176
|
+
return s;
|
|
177
|
+
return x.code < y.code ? -1 : x.code > y.code ? 1 : 0;
|
|
178
|
+
});
|
|
179
|
+
const coverage = {
|
|
180
|
+
htmlBlocks: a.length,
|
|
181
|
+
markdownBlocks: b.length,
|
|
182
|
+
htmlMatched: a.length - al.unmatchedA.length,
|
|
183
|
+
markdownMatched: b.length - al.unmatchedB.length,
|
|
184
|
+
htmlRatio: a.length === 0 ? 0 : (a.length - al.unmatchedA.length) / a.length,
|
|
185
|
+
markdownRatio: b.length === 0 ? 0 : (b.length - al.unmatchedB.length) / b.length,
|
|
186
|
+
};
|
|
187
|
+
return { findings, coverage };
|
|
188
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Bounded HTTP(S) fetch for the URL mode. Only the given URL and its redirects are fetched, never a site
|
|
2
|
+
// crawl. The address policy in netguard.ts is applied to the URL host, to every DNS answer and to every
|
|
3
|
+
// redirect target, and the validated address is handed to the socket through a custom lookup so that a
|
|
4
|
+
// separate re-resolution cannot bypass the check (DNS rebinding).
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import https from 'node:https';
|
|
7
|
+
import dns from 'node:dns';
|
|
8
|
+
import zlib from 'node:zlib';
|
|
9
|
+
import { assertPublicHost, assertPublicResolved, BlockedAddressError } from './netguard.js';
|
|
10
|
+
import { maskUrl } from './normalize.js';
|
|
11
|
+
export class FetchError extends Error {
|
|
12
|
+
kind;
|
|
13
|
+
url;
|
|
14
|
+
constructor(kind, url, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'FetchError';
|
|
17
|
+
this.kind = kind;
|
|
18
|
+
this.url = maskUrl(url);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const defaultResolver = async (hostname) => {
|
|
22
|
+
const answers = await dns.promises.lookup(hostname, { all: true, verbatim: true });
|
|
23
|
+
return answers.map((a) => ({ address: a.address, family: a.family }));
|
|
24
|
+
};
|
|
25
|
+
export function validateUrl(input) {
|
|
26
|
+
let u;
|
|
27
|
+
try {
|
|
28
|
+
u = new URL(input);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new FetchError('invalid_url', input, `Not a valid absolute URL: ${maskUrl(input)}`);
|
|
32
|
+
}
|
|
33
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
34
|
+
throw new FetchError('protocol', input, `Only http and https URLs are fetched (got ${u.protocol}).`);
|
|
35
|
+
}
|
|
36
|
+
if (u.username !== '' || u.password !== '') {
|
|
37
|
+
throw new FetchError('invalid_url', input, 'URLs with embedded credentials are refused.');
|
|
38
|
+
}
|
|
39
|
+
return u;
|
|
40
|
+
}
|
|
41
|
+
async function pickAddress(hostname, options) {
|
|
42
|
+
const allowed = (options.testAllowHosts ?? []).includes(hostname.toLowerCase());
|
|
43
|
+
if (!allowed)
|
|
44
|
+
assertPublicHost(hostname);
|
|
45
|
+
const resolver = options.resolver ?? defaultResolver;
|
|
46
|
+
let answers;
|
|
47
|
+
try {
|
|
48
|
+
answers = await resolver(hostname);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
throw new FetchError('network', hostname, `DNS lookup failed for ${hostname}: ${err.message}`);
|
|
52
|
+
}
|
|
53
|
+
if (answers.length === 0)
|
|
54
|
+
throw new FetchError('network', hostname, `DNS lookup returned no address for ${hostname}.`);
|
|
55
|
+
if (!allowed) {
|
|
56
|
+
// Every answer must be public: an attacker who controls the name can otherwise mix answers.
|
|
57
|
+
for (const a of answers)
|
|
58
|
+
assertPublicResolved(hostname, a.address);
|
|
59
|
+
}
|
|
60
|
+
return answers[0];
|
|
61
|
+
}
|
|
62
|
+
function decodeBody(buf, contentType) {
|
|
63
|
+
const m = /charset=([^;]+)/i.exec(contentType ?? '');
|
|
64
|
+
const charset = (m?.[1] ?? 'utf-8').trim().replace(/^"|"$/g, '').toLowerCase();
|
|
65
|
+
try {
|
|
66
|
+
return new TextDecoder(charset, { fatal: false }).decode(buf);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return new TextDecoder('utf-8').decode(buf);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function decompressor(encoding) {
|
|
73
|
+
switch ((encoding ?? '').trim().toLowerCase()) {
|
|
74
|
+
case 'gzip':
|
|
75
|
+
case 'x-gzip':
|
|
76
|
+
return zlib.createGunzip();
|
|
77
|
+
case 'deflate':
|
|
78
|
+
return zlib.createInflate();
|
|
79
|
+
case 'br':
|
|
80
|
+
return zlib.createBrotliDecompress();
|
|
81
|
+
case '':
|
|
82
|
+
case 'identity':
|
|
83
|
+
return null;
|
|
84
|
+
default:
|
|
85
|
+
throw new FetchError('protocol', '', `Unsupported Content-Encoding: ${encoding}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* One wall-clock deadline for a whole fetchUrl call: DNS, connect, headers, body, decompression and every
|
|
90
|
+
* redirect hop. When it fires, the active request is destroyed and the pending step rejects.
|
|
91
|
+
*/
|
|
92
|
+
class Deadline {
|
|
93
|
+
timer;
|
|
94
|
+
expired = false;
|
|
95
|
+
active = null;
|
|
96
|
+
waiters = new Set();
|
|
97
|
+
error;
|
|
98
|
+
constructor(url, timeoutMs) {
|
|
99
|
+
this.error = new FetchError('timeout', url, `Timed out after ${timeoutMs} ms (whole fetch including DNS, redirects and body).`);
|
|
100
|
+
this.timer = setTimeout(() => this.fire(), timeoutMs);
|
|
101
|
+
}
|
|
102
|
+
fire() {
|
|
103
|
+
this.expired = true;
|
|
104
|
+
if (this.active)
|
|
105
|
+
this.active.destroy(this.error);
|
|
106
|
+
for (const w of this.waiters)
|
|
107
|
+
w(this.error);
|
|
108
|
+
this.waiters.clear();
|
|
109
|
+
}
|
|
110
|
+
attach(req) {
|
|
111
|
+
this.active = req;
|
|
112
|
+
if (this.expired)
|
|
113
|
+
req.destroy(this.error);
|
|
114
|
+
}
|
|
115
|
+
detach() {
|
|
116
|
+
this.active = null;
|
|
117
|
+
}
|
|
118
|
+
/** Races a promise against the deadline. */
|
|
119
|
+
race(p) {
|
|
120
|
+
if (this.expired)
|
|
121
|
+
return Promise.reject(this.error);
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
const waiter = (err) => reject(err);
|
|
124
|
+
this.waiters.add(waiter);
|
|
125
|
+
p.then((v) => {
|
|
126
|
+
this.waiters.delete(waiter);
|
|
127
|
+
resolve(v);
|
|
128
|
+
}, (e) => {
|
|
129
|
+
this.waiters.delete(waiter);
|
|
130
|
+
reject(this.expired ? this.error : e);
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
close() {
|
|
135
|
+
clearTimeout(this.timer);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function requestOnce(url, address, options, deadline) {
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
const lib = url.protocol === 'https:' ? https : http;
|
|
141
|
+
const lookup = (_hostname, opts, cb) => {
|
|
142
|
+
// Hand the validated address to the socket; no second DNS resolution takes place. Node may ask
|
|
143
|
+
// for all addresses (autoSelectFamily); answer with the single validated one in either shape.
|
|
144
|
+
const callback = cb;
|
|
145
|
+
if (opts.all)
|
|
146
|
+
callback(null, [{ address: address.address, family: address.family }]);
|
|
147
|
+
else
|
|
148
|
+
callback(null, address.address, address.family);
|
|
149
|
+
};
|
|
150
|
+
const req = lib.request(url, {
|
|
151
|
+
method: 'GET',
|
|
152
|
+
lookup,
|
|
153
|
+
agent: options.agent ?? false,
|
|
154
|
+
headers: {
|
|
155
|
+
Accept: options.accept,
|
|
156
|
+
'Accept-Encoding': 'gzip, deflate, br',
|
|
157
|
+
'User-Agent': options.userAgent ?? 'markdown-parity-check/0.1 (+local content comparison)',
|
|
158
|
+
},
|
|
159
|
+
// Explicit default: TLS verification is never disabled.
|
|
160
|
+
rejectUnauthorized: true,
|
|
161
|
+
}, (res) => {
|
|
162
|
+
const chunks = [];
|
|
163
|
+
let bytes = 0;
|
|
164
|
+
let done = false;
|
|
165
|
+
let stream = res;
|
|
166
|
+
let dec;
|
|
167
|
+
try {
|
|
168
|
+
dec = decompressor(res.headers['content-encoding']);
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
res.resume();
|
|
172
|
+
reject(new FetchError('protocol', url.href, err.message));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (dec) {
|
|
176
|
+
stream = res.pipe(dec);
|
|
177
|
+
dec.on('error', (err) => finish(new FetchError('protocol', url.href, `Decompression failed: ${err.message}`)));
|
|
178
|
+
}
|
|
179
|
+
const finish = (err) => {
|
|
180
|
+
if (done)
|
|
181
|
+
return;
|
|
182
|
+
done = true;
|
|
183
|
+
if (err) {
|
|
184
|
+
req.destroy();
|
|
185
|
+
reject(err);
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks), bytes });
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
stream.on('data', (chunk) => {
|
|
192
|
+
bytes += chunk.length;
|
|
193
|
+
if (bytes > options.maxBytes) {
|
|
194
|
+
finish(new FetchError('too_large', url.href, `Response body exceeded --max-bytes (${options.maxBytes} bytes of decoded content).`));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
chunks.push(chunk);
|
|
198
|
+
});
|
|
199
|
+
stream.on('end', () => finish(null));
|
|
200
|
+
stream.on('error', (err) => finish(new FetchError('network', url.href, err.message)));
|
|
201
|
+
});
|
|
202
|
+
req.on('error', (err) => {
|
|
203
|
+
if (err instanceof FetchError)
|
|
204
|
+
reject(err);
|
|
205
|
+
else
|
|
206
|
+
reject(new FetchError('network', url.href, err.message));
|
|
207
|
+
});
|
|
208
|
+
req.on('close', () => deadline.detach());
|
|
209
|
+
deadline.attach(req);
|
|
210
|
+
req.end();
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
214
|
+
/**
|
|
215
|
+
* Fetches one URL with the given Accept header, following at most maxRedirects redirects. Every hop is
|
|
216
|
+
* validated by the address policy. Returns the decoded body; the raw response is not stored.
|
|
217
|
+
*/
|
|
218
|
+
export async function fetchUrl(input, options) {
|
|
219
|
+
const maxRedirects = options.maxRedirects ?? 5;
|
|
220
|
+
const deadline = new Deadline(input, options.timeoutMs);
|
|
221
|
+
try {
|
|
222
|
+
return await fetchWithDeadline(input, options, maxRedirects, deadline);
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
deadline.close();
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async function fetchWithDeadline(input, options, maxRedirects, deadline) {
|
|
229
|
+
let url = validateUrl(input);
|
|
230
|
+
const visited = new Set();
|
|
231
|
+
let redirects = 0;
|
|
232
|
+
for (;;) {
|
|
233
|
+
if (visited.has(url.href))
|
|
234
|
+
throw new FetchError('redirect_loop', url.href, `Redirect loop detected at ${maskUrl(url.href)}.`);
|
|
235
|
+
visited.add(url.href);
|
|
236
|
+
let address;
|
|
237
|
+
try {
|
|
238
|
+
address = await deadline.race(pickAddress(url.hostname, options));
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
if (err instanceof BlockedAddressError)
|
|
242
|
+
throw new FetchError('blocked', url.href, err.message);
|
|
243
|
+
throw err;
|
|
244
|
+
}
|
|
245
|
+
const res = await deadline.race(requestOnce(url, address, options, deadline));
|
|
246
|
+
if (REDIRECT_STATUSES.has(res.status)) {
|
|
247
|
+
const loc = res.headers['location'];
|
|
248
|
+
if (!loc)
|
|
249
|
+
throw new FetchError('protocol', url.href, `HTTP ${res.status} without a Location header.`);
|
|
250
|
+
if (redirects >= maxRedirects)
|
|
251
|
+
throw new FetchError('too_many_redirects', url.href, `More than ${maxRedirects} redirects.`);
|
|
252
|
+
let next;
|
|
253
|
+
try {
|
|
254
|
+
next = new URL(loc, url);
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
throw new FetchError('protocol', url.href, `Invalid redirect target: ${maskUrl(loc)}`);
|
|
258
|
+
}
|
|
259
|
+
url = validateUrl(next.href);
|
|
260
|
+
redirects++;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const ct = res.headers['content-type'] ?? null;
|
|
264
|
+
return {
|
|
265
|
+
requestedUrl: input,
|
|
266
|
+
finalUrl: url.href,
|
|
267
|
+
status: res.status,
|
|
268
|
+
contentType: ct,
|
|
269
|
+
body: decodeBody(res.body, ct),
|
|
270
|
+
bytes: res.bytes,
|
|
271
|
+
redirects,
|
|
272
|
+
accept: options.accept,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
}
|