meodp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +28 -1
  2. package/dist/check/cli.cjs +130 -39
  3. package/dist/check/cli.mjs +130 -39
  4. package/dist/check/index.cjs +12 -8
  5. package/dist/check/index.d.cts +5 -68
  6. package/dist/check/index.d.mts +5 -68
  7. package/dist/check/index.d.ts +5 -68
  8. package/dist/check/index.mjs +4 -2
  9. package/dist/cli/main.cjs +57 -5
  10. package/dist/cli/main.mjs +57 -5
  11. package/dist/config/index.cjs +7 -0
  12. package/dist/config/index.d.cts +47 -0
  13. package/dist/config/index.d.mts +47 -0
  14. package/dist/config/index.d.ts +47 -0
  15. package/dist/config/index.mjs +5 -0
  16. package/dist/notify/cli.cjs +107 -0
  17. package/dist/notify/cli.d.cts +3 -0
  18. package/dist/notify/cli.d.mts +3 -0
  19. package/dist/notify/cli.d.ts +3 -0
  20. package/dist/notify/cli.mjs +101 -0
  21. package/dist/notify/email.cjs +38 -0
  22. package/dist/notify/email.d.cts +29 -0
  23. package/dist/notify/email.d.mts +29 -0
  24. package/dist/notify/email.d.ts +29 -0
  25. package/dist/notify/email.mjs +35 -0
  26. package/dist/notify/feishu.cjs +162 -0
  27. package/dist/notify/feishu.d.cts +74 -0
  28. package/dist/notify/feishu.d.mts +74 -0
  29. package/dist/notify/feishu.d.ts +74 -0
  30. package/dist/notify/feishu.mjs +157 -0
  31. package/dist/notify/index.cjs +64 -0
  32. package/dist/notify/index.d.cts +27 -0
  33. package/dist/notify/index.d.mts +27 -0
  34. package/dist/notify/index.d.ts +27 -0
  35. package/dist/notify/index.mjs +62 -0
  36. package/dist/shared/{meodp.a0bcc3e7.cjs → meodp.2b00b0ae.cjs} +13 -365
  37. package/dist/shared/meodp.4f1da070.d.cts +41 -0
  38. package/dist/shared/meodp.63483e20.cjs +30 -0
  39. package/dist/shared/meodp.80ff918d.mjs +465 -0
  40. package/dist/shared/meodp.8369c4c1.d.ts +41 -0
  41. package/dist/shared/meodp.93e06e00.d.cts +64 -0
  42. package/dist/shared/meodp.93e06e00.d.mts +64 -0
  43. package/dist/shared/meodp.93e06e00.d.ts +64 -0
  44. package/dist/shared/{meodp.d0916bc5.mjs → meodp.9c706389.mjs} +1 -350
  45. package/dist/shared/meodp.a704f8db.d.mts +41 -0
  46. package/dist/shared/meodp.c4c70565.cjs +477 -0
  47. package/dist/shared/meodp.f96d0510.mjs +24 -0
  48. package/package.json +48 -2
@@ -0,0 +1,64 @@
1
+ interface LinkTarget {
2
+ url: string;
3
+ name?: string;
4
+ }
5
+ type Availability = 'reachable' | 'restricted' | 'unavailable';
6
+ type FailureReason = 'http' | 'dns' | 'tls' | 'timeout' | 'network' | 'redirect';
7
+ interface LinkObservation extends LinkTarget {
8
+ status: Availability;
9
+ checkedAt: string;
10
+ durationMs: number;
11
+ attempts: number;
12
+ finalUrl: string;
13
+ httpStatus?: number;
14
+ redirects: {
15
+ url: string;
16
+ status: number;
17
+ location: string;
18
+ }[];
19
+ reason?: FailureReason;
20
+ detail?: string;
21
+ consecutiveFailures: number;
22
+ firstFailureAt?: string;
23
+ lastSuccessAt?: string;
24
+ changed: boolean;
25
+ recovered: boolean;
26
+ }
27
+ interface CheckReport {
28
+ schemaVersion: 1;
29
+ observer: string;
30
+ startedAt: string;
31
+ completedAt: string;
32
+ summary: Record<Availability, number> & {
33
+ total: number;
34
+ redirected: number;
35
+ recovered: number;
36
+ };
37
+ results: LinkObservation[];
38
+ }
39
+ interface CheckOptions {
40
+ /** Maximum simultaneous site checks. Default: 5. */
41
+ concurrency?: number;
42
+ /** Timeout for each HTTP request, including its body. Default: 10000 ms. */
43
+ timeoutMs?: number;
44
+ /** Retries for transport errors and 5xx responses. Default: 1; 429 is not retried. */
45
+ retries?: number;
46
+ /** Maximum followed redirects per attempt. Default: 5. */
47
+ maxRedirects?: number;
48
+ /** Identifies the network/environment. Must match previousReport.observer. */
49
+ observer?: string;
50
+ previousReport?: CheckReport;
51
+ onResult?: (result: LinkObservation) => void | Promise<void>;
52
+ }
53
+ interface SitemapOptions extends CheckOptions {
54
+ /** Treat the input as a site URL: read robots.txt, falling back to /sitemap.xml. */
55
+ discover?: boolean;
56
+ /** Reject before page checks if discovery exceeds this many unique pages. Default: 10000. */
57
+ maxUrls?: number;
58
+ /** Maximum number of unique sitemap documents to read. Default: 100. */
59
+ maxSitemaps?: number;
60
+ /** Maximum downloaded and decompressed size per discovery document. Default: 10 MiB. */
61
+ maxSitemapBytes?: number;
62
+ }
63
+
64
+ export type { Availability as A, CheckReport as C, FailureReason as F, LinkTarget as L, SitemapOptions as S, CheckOptions as a, LinkObservation as b };
@@ -1,185 +1,6 @@
1
- import { setTimeout } from 'node:timers/promises';
2
- import { LinkChecker } from 'linkinator';
3
- import { hostname } from 'node:os';
4
1
  import { randomUUID } from 'node:crypto';
5
2
  import { mkdir, writeFile, readFile, rename } from 'node:fs/promises';
6
3
  import { join, dirname } from 'node:path';
7
- import { Buffer } from 'node:buffer';
8
- import { promisify } from 'node:util';
9
- import { gunzip } from 'node:zlib';
10
- import { XMLValidator, XMLParser } from 'fast-xml-parser';
11
-
12
- function normalizeUrl(value) {
13
- const url = new URL(value);
14
- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
15
- throw new Error("Expected an HTTP(S) URL without embedded credentials");
16
- url.hash = "";
17
- return url.href;
18
- }
19
- function normalizeTargets(input) {
20
- if (!Array.isArray(input))
21
- throw new TypeError("Input must be an array of URLs or objects with a url field");
22
- const seen = /* @__PURE__ */ new Set();
23
- return input.map((item, index) => {
24
- const value = typeof item === "string" ? { url: item } : item;
25
- if (!value || typeof value !== "object" || !("url" in value) || typeof value.url !== "string")
26
- throw new TypeError(`Invalid link at index ${index}: expected a url string`);
27
- let url;
28
- try {
29
- url = normalizeUrl(value.url.trim());
30
- } catch {
31
- throw new TypeError(`Invalid HTTP(S) URL at index ${index}`);
32
- }
33
- if ("name" in value && value.name !== void 0 && typeof value.name !== "string")
34
- throw new TypeError(`Invalid name at index ${index}: expected a string`);
35
- return { url, ..."name" in value && typeof value.name === "string" ? { name: value.name } : {} };
36
- }).filter((item) => {
37
- if (seen.has(item.url))
38
- return false;
39
- seen.add(item.url);
40
- return true;
41
- });
42
- }
43
-
44
- function integerOption(value, fallback, name, minimum, maximum) {
45
- const result = value ?? fallback;
46
- if (!Number.isInteger(result) || result < minimum || result > maximum)
47
- throw new RangeError(`${name} must be an integer between ${minimum} and ${maximum}`);
48
- return result;
49
- }
50
- function normalizeCheckOptions(options) {
51
- const concurrency = integerOption(options.concurrency, 5, "concurrency", 1, 100);
52
- const timeoutMs = integerOption(options.timeoutMs, 1e4, "timeoutMs", 1, 3e5);
53
- const retries = integerOption(options.retries, 1, "retries", 0, 5);
54
- const maxRedirects = integerOption(options.maxRedirects, 5, "maxRedirects", 0, 20);
55
- const observer = options.observer ?? hostname();
56
- if (!observer.trim())
57
- throw new TypeError("observer must not be empty");
58
- if (options.previousReport && options.previousReport.observer !== observer)
59
- throw new Error("Previous report belongs to another observer; use a separate history file");
60
- return { concurrency, timeoutMs, retries, maxRedirects, observer };
61
- }
62
-
63
- function failureDetail(result) {
64
- const error = result.failureDetails?.find((item) => item instanceof Error);
65
- const parts = [];
66
- let current = error;
67
- for (let depth = 0; current && typeof current === "object" && depth < 5; depth++) {
68
- for (const key of ["name", "code", "message"]) {
69
- const value = Reflect.get(current, key);
70
- if (typeof value === "string")
71
- parts.push(value);
72
- }
73
- current = "cause" in current ? current.cause : void 0;
74
- }
75
- const detail = parts.join(": ") || `HTTP ${result.status ?? 0}`;
76
- if (/ENOTFOUND|EAI_AGAIN|EAI_FAIL/.test(detail))
77
- return { reason: "dns", detail };
78
- if (/CERT|TLS|SSL/i.test(detail))
79
- return { reason: "tls", detail };
80
- if (/timeout|timed out|ETIMEDOUT|UND_ERR_.*TIMEOUT/i.test(detail))
81
- return { reason: "timeout", detail };
82
- return { reason: result.status ? "http" : "network", detail };
83
- }
84
- async function probe(url, timeoutMs, maxRedirects) {
85
- const redirects = [];
86
- const visited = /* @__PURE__ */ new Set();
87
- let current = url;
88
- for (; ; ) {
89
- visited.add(current);
90
- const checker = new LinkChecker();
91
- const { links } = await checker.check({
92
- path: current,
93
- recurse: false,
94
- concurrency: 1,
95
- timeout: timeoutMs,
96
- retry: false,
97
- retryErrors: false,
98
- redirects: "error",
99
- linksToSkip: async (candidate) => candidate !== current
100
- });
101
- const result = links.find((item) => item.url === current && !item.parent);
102
- if (!result)
103
- throw new Error("The HTTP checker returned no result for the requested URL");
104
- const httpStatus = result.status || void 0;
105
- const base = { finalUrl: current, httpStatus, redirects };
106
- if (httpStatus && [301, 302, 303, 307, 308].includes(httpStatus)) {
107
- const response = result.failureDetails?.find((item) => "headers" in item);
108
- const location = response && "headers" in response ? response.headers.location : void 0;
109
- let next;
110
- try {
111
- if (!location)
112
- throw new Error("Missing redirect location");
113
- next = normalizeUrl(new URL(location, current).href);
114
- } catch {
115
- return { ...base, status: "unavailable", reason: "redirect", detail: "Missing or invalid HTTP(S) redirect destination" };
116
- }
117
- redirects.push({ url: current, status: httpStatus, location: next });
118
- if (visited.has(next) || redirects.length > maxRedirects) {
119
- return {
120
- ...base,
121
- status: "unavailable",
122
- reason: "redirect",
123
- detail: visited.has(next) ? "Redirect loop" : "Redirect limit exceeded"
124
- };
125
- }
126
- current = next;
127
- continue;
128
- }
129
- if (httpStatus && httpStatus >= 200 && httpStatus < 300)
130
- return { ...base, status: "reachable" };
131
- if (httpStatus && [401, 403, 429, 451, 999].includes(httpStatus))
132
- return { ...base, status: "restricted", reason: "http", detail: `HTTP ${httpStatus}: access requires review` };
133
- return { ...base, status: "unavailable", ...failureDetail(result) };
134
- }
135
- }
136
- async function checkLinks(input, options = {}) {
137
- const targets = normalizeTargets(input);
138
- const { concurrency, timeoutMs, retries, maxRedirects, observer } = normalizeCheckOptions(options);
139
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
140
- const previous = new Map(options.previousReport?.results.map((item) => [item.url, item]));
141
- const results = [];
142
- let cursor = 0;
143
- await Promise.all(Array.from({ length: Math.min(concurrency, targets.length) }, async () => {
144
- while (cursor < targets.length) {
145
- const index = cursor++;
146
- const target = targets[index];
147
- const start = Date.now();
148
- let attempts = 0;
149
- let observation;
150
- do {
151
- if (attempts > 0)
152
- await setTimeout(500 * 2 ** (attempts - 1));
153
- attempts++;
154
- observation = await probe(target.url, timeoutMs, maxRedirects);
155
- } while (attempts <= retries && observation.status === "unavailable" && observation.reason !== "redirect" && (!observation.httpStatus || observation.httpStatus >= 500));
156
- const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
157
- const old = previous.get(target.url);
158
- const failed = observation.status === "unavailable";
159
- const result = {
160
- ...target,
161
- ...observation,
162
- checkedAt,
163
- durationMs: Date.now() - start,
164
- attempts,
165
- consecutiveFailures: failed ? (old?.status === "unavailable" ? old.consecutiveFailures : 0) + 1 : 0,
166
- firstFailureAt: failed ? old?.status === "unavailable" ? old.firstFailureAt ?? checkedAt : checkedAt : void 0,
167
- lastSuccessAt: observation.status === "reachable" ? checkedAt : old?.lastSuccessAt,
168
- changed: Boolean(old && (old.status !== observation.status || old.finalUrl !== observation.finalUrl)),
169
- recovered: observation.status === "reachable" && old?.status === "unavailable"
170
- };
171
- results[index] = result;
172
- await options.onResult?.(result);
173
- }
174
- }));
175
- const summary = { total: results.length, reachable: 0, restricted: 0, unavailable: 0, redirected: 0, recovered: 0 };
176
- for (const result of results) {
177
- summary[result.status]++;
178
- summary.redirected += Number(result.redirects.length > 0);
179
- summary.recovered += Number(result.recovered);
180
- }
181
- return { schemaVersion: 1, observer, startedAt, completedAt: (/* @__PURE__ */ new Date()).toISOString(), summary, results };
182
- }
183
4
 
184
5
  function parseReport(data) {
185
6
  const invalid = (field) => {
@@ -396,174 +217,4 @@ async function saveReport(report, path) {
396
217
  await rename(temporary, path);
397
218
  }
398
219
 
399
- const unzip = promisify(gunzip);
400
- class DocumentError extends Error {
401
- constructor(message, retryable = false) {
402
- super(message);
403
- this.retryable = retryable;
404
- }
405
- }
406
- function discoveryOptions(options) {
407
- const normalized = normalizeCheckOptions(options);
408
- if (options.discover !== void 0 && typeof options.discover !== "boolean")
409
- throw new TypeError("discover must be a boolean");
410
- return {
411
- ...normalized,
412
- maxUrls: integerOption(options.maxUrls, 1e4, "maxUrls", 1, 5e4),
413
- maxSitemaps: integerOption(options.maxSitemaps, 100, "maxSitemaps", 1, 1e4),
414
- maxSitemapBytes: integerOption(options.maxSitemapBytes, 10 * 1024 * 1024, "maxSitemapBytes", 1, 100 * 1024 * 1024)
415
- };
416
- }
417
- async function readDocument(source, options, allowMissing = false) {
418
- for (let attempt = 0; ; attempt++) {
419
- try {
420
- let url = source;
421
- const visited = /* @__PURE__ */ new Set();
422
- for (; ; ) {
423
- visited.add(url);
424
- const response = await fetch(url, {
425
- redirect: "manual",
426
- signal: AbortSignal.timeout(options.timeoutMs)
427
- });
428
- if ([301, 302, 303, 307, 308].includes(response.status)) {
429
- await response.body?.cancel();
430
- const location = response.headers.get("location");
431
- let next;
432
- try {
433
- if (!location)
434
- throw new Error("Missing location");
435
- next = normalizeUrl(new URL(location, url).href);
436
- } catch {
437
- throw new DocumentError(`Invalid sitemap/robots redirect from ${url}`);
438
- }
439
- if (visited.has(next) || visited.size > options.maxRedirects)
440
- throw new DocumentError(`Sitemap/robots redirect loop or limit exceeded: ${url}`);
441
- url = next;
442
- continue;
443
- }
444
- if (!response.ok) {
445
- await response.body?.cancel();
446
- if (allowMissing && [404, 410].includes(response.status))
447
- return void 0;
448
- throw new DocumentError(`Unable to read ${url}: HTTP ${response.status}`, response.status >= 500);
449
- }
450
- const chunks = [];
451
- let size = 0;
452
- if (response.body) {
453
- const reader = response.body.getReader();
454
- try {
455
- for (; ; ) {
456
- const { done, value } = await reader.read();
457
- if (done)
458
- break;
459
- size += value.byteLength;
460
- if (size > options.maxSitemapBytes)
461
- throw new DocumentError(`Discovery document exceeds maxSitemapBytes: ${url}`);
462
- chunks.push(value);
463
- }
464
- } finally {
465
- await reader.cancel().catch(() => {
466
- });
467
- reader.releaseLock();
468
- }
469
- }
470
- let body = Buffer.concat(chunks);
471
- if (body[0] === 31 && body[1] === 139) {
472
- try {
473
- body = await unzip(body, { maxOutputLength: options.maxSitemapBytes });
474
- } catch {
475
- throw new DocumentError(`Invalid gzip or decompressed document exceeds maxSitemapBytes: ${url}`);
476
- }
477
- }
478
- return { url, text: body.toString("utf8") };
479
- }
480
- } catch (error) {
481
- if (attempt >= options.retries || error instanceof DocumentError && !error.retryable)
482
- throw new Error(`Sitemap discovery failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
483
- await setTimeout(500 * 2 ** attempt);
484
- }
485
- }
486
- }
487
- function parseLocations(text, source) {
488
- if (/<!DOCTYPE|<!ENTITY/i.test(text) || XMLValidator.validate(text) !== true)
489
- throw new Error(`Invalid sitemap XML: ${source}`);
490
- const parser = new XMLParser({
491
- ignoreAttributes: true,
492
- removeNSPrefix: true,
493
- parseTagValue: false,
494
- isArray: (name) => name === "url" || name === "sitemap"
495
- });
496
- const document = parser.parse(text);
497
- const roots = Object.keys(document).filter((key) => !key.startsWith("?"));
498
- if (roots.length !== 1 || !["urlset", "sitemapindex"].includes(roots[0]))
499
- throw new Error(`Expected a sitemap urlset or sitemapindex: ${source}`);
500
- const isIndex = roots[0] === "sitemapindex";
501
- const root = document[roots[0]];
502
- if (root?.[isIndex ? "url" : "sitemap"])
503
- throw new Error(`Mixed sitemap index and page entries: ${source}`);
504
- const entries = root?.[isIndex ? "sitemap" : "url"] ?? [];
505
- const urls = entries.map((entry) => {
506
- if (!entry || typeof entry !== "object" || !("loc" in entry) || typeof entry.loc !== "string" || !entry.loc.trim())
507
- throw new Error(`Missing or invalid sitemap loc: ${source}`);
508
- try {
509
- return normalizeUrl(new URL(entry.loc.trim(), source).href);
510
- } catch {
511
- throw new Error(`Invalid HTTP(S) URL in sitemap: ${source}`);
512
- }
513
- });
514
- return { isIndex, urls };
515
- }
516
- async function readSitemapUrls(source, options = {}) {
517
- const input = normalizeUrl(source.trim());
518
- const config = discoveryOptions(options);
519
- let pending = [input];
520
- if (options.discover) {
521
- const robots = await readDocument(new URL("/robots.txt", input).href, config, true);
522
- const declared = robots?.text.split(/\r?\n/).flatMap((line) => {
523
- const match = line.match(/^\s*sitemap\s*:\s*(\S+)/i);
524
- return match ? [normalizeUrl(new URL(match[1], robots.url).href)] : [];
525
- }) ?? [];
526
- pending = declared.length ? declared : [new URL("/sitemap.xml", input).href];
527
- }
528
- const queued = new Set(pending);
529
- pending = [...queued];
530
- const visited = /* @__PURE__ */ new Set();
531
- const pages = /* @__PURE__ */ new Set();
532
- let documentCount = 0;
533
- for (let cursor = 0; cursor < pending.length; cursor++) {
534
- const url = pending[cursor];
535
- if (visited.has(url))
536
- continue;
537
- if (++documentCount > config.maxSitemaps)
538
- throw new Error("Sitemap discovery exceeds maxSitemaps; no pages were checked");
539
- visited.add(url);
540
- const document = await readDocument(url, config);
541
- if (!document)
542
- throw new Error(`Unable to read sitemap: ${url}`);
543
- visited.add(document.url);
544
- const { isIndex, urls } = parseLocations(document.text, document.url);
545
- for (const location of urls) {
546
- if (isIndex) {
547
- if (!queued.has(location) && !visited.has(location)) {
548
- queued.add(location);
549
- pending.push(location);
550
- }
551
- } else {
552
- pages.add(location);
553
- if (pages.size > config.maxUrls)
554
- throw new Error("Sitemap discovery exceeds maxUrls; no pages were checked");
555
- }
556
- }
557
- }
558
- if (!pages.size)
559
- throw new Error("Sitemap discovery found no page URLs; no pages were checked");
560
- return [...pages];
561
- }
562
- async function checkSitemap(source, options = {}) {
563
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
564
- const urls = await readSitemapUrls(source, options);
565
- const report = await checkLinks(urls, options);
566
- return { ...report, startedAt };
567
- }
568
-
569
- export { checkLinks as a, writeReportSite as b, checkSitemap as c, readSitemapUrls as d, formatReport as f, normalizeTargets as n, parseReport as p, readReport as r, saveReport as s, writeReports as w };
220
+ export { writeReportSite as a, createReportHtml as c, formatReport as f, parseReport as p, readReport as r, saveReport as s, writeReports as w };
@@ -0,0 +1,41 @@
1
+ import { C as CheckReport } from './meodp.93e06e00.mjs';
2
+
3
+ interface ReportSiteOptions {
4
+ /** Automatically load this HTTP(S) or relative JSON URL when hosted. */
5
+ dataUrl?: string;
6
+ }
7
+
8
+ type ReporterName = 'json' | 'markdown' | 'html';
9
+ type HtmlReporterOptions = ReportSiteOptions & ({
10
+ outputFolder?: string;
11
+ outputFile?: never;
12
+ } | {
13
+ outputFile: string;
14
+ outputFolder?: never;
15
+ });
16
+ type ReporterDescription = ReporterName | readonly ['json' | 'markdown', {
17
+ outputFile?: string;
18
+ }?] | readonly ['html', HtmlReporterOptions?];
19
+ /** A name, a list of names, or a list of [name, options] tuples. */
20
+ type ReporterConfig = ReporterName | readonly ReporterDescription[];
21
+ interface ReporterOutput {
22
+ reporter: ReporterName;
23
+ files: string[];
24
+ }
25
+ interface ReporterOptions extends ReportSiteOptions {
26
+ /** Default directory for reporters without explicit output paths. */
27
+ outputDir?: string;
28
+ /** Resolve relative output paths from this directory (default: working directory). */
29
+ cwd?: string;
30
+ }
31
+ /** Run built-in reporters on saved data; no network requests or browser launch. */
32
+ declare function writeReporters(report: CheckReport | undefined, reporter: ReporterConfig, options?: ReporterOptions): Promise<ReporterOutput[]>;
33
+
34
+ interface ReportVerificationOptions {
35
+ url: string;
36
+ attempts?: number;
37
+ delayMs?: number;
38
+ }
39
+ declare function waitForReport(expected: CheckReport, { url, attempts, delayMs }: ReportVerificationOptions): Promise<void>;
40
+
41
+ export { type HtmlReporterOptions as H, type ReporterConfig as R, type ReportVerificationOptions as a, type ReportSiteOptions as b, type ReporterDescription as c, type ReporterName as d, type ReporterOptions as e, type ReporterOutput as f, waitForReport as g, writeReporters as w };