@d-zero/beholder 0.1.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 (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +5 -0
  4. package/dist/debug.d.ts +6 -0
  5. package/dist/debug.js +6 -0
  6. package/dist/dom-evaluation.d.ts +24 -0
  7. package/dist/dom-evaluation.js +114 -0
  8. package/dist/events.d.ts +32 -0
  9. package/dist/events.js +15 -0
  10. package/dist/fetch-destination.d.ts +2 -0
  11. package/dist/fetch-destination.js +132 -0
  12. package/dist/index.d.ts +4 -0
  13. package/dist/index.js +4 -0
  14. package/dist/keyword-check.d.ts +1 -0
  15. package/dist/keyword-check.js +10 -0
  16. package/dist/net-timeout-error.d.ts +3 -0
  17. package/dist/net-timeout-error.js +3 -0
  18. package/dist/network.d.ts +2 -0
  19. package/dist/network.js +132 -0
  20. package/dist/scraper.d.ts +15 -0
  21. package/dist/scraper.js +678 -0
  22. package/dist/sub-process-runner.d.ts +12 -0
  23. package/dist/sub-process-runner.js +180 -0
  24. package/dist/sub-process.d.ts +1 -0
  25. package/dist/sub-process.js +67 -0
  26. package/dist/types.d.ts +271 -0
  27. package/dist/types.js +1 -0
  28. package/dist/utils.d.ts +5 -0
  29. package/dist/utils.js +142 -0
  30. package/package.json +34 -0
  31. package/src/debug.ts +7 -0
  32. package/src/dom-evaluation.ts +175 -0
  33. package/src/events.ts +21 -0
  34. package/src/fetch-destination.ts +160 -0
  35. package/src/index.ts +4 -0
  36. package/src/keyword-check.spec.ts +8 -0
  37. package/src/keyword-check.ts +12 -0
  38. package/src/net-timeout-error.ts +3 -0
  39. package/src/scraper.ts +733 -0
  40. package/src/sub-process-runner.ts +220 -0
  41. package/src/sub-process.ts +86 -0
  42. package/src/types.ts +341 -0
  43. package/src/utils.ts +171 -0
  44. package/tsconfig.json +15 -0
  45. package/tsconfig.tsbuildinfo +1 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 0.1.0 (2024-05-22)
7
+
8
+ ### Features
9
+
10
+ - **beholder:** add `@d-zero/beholder` ([99b47c8](https://github.com/d-zero-dev/tools/commit/99b47c8693f6007f2a45dcfa66f4fd4ada42c5b2))
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 D-ZERO Co., Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # `@d-zero/beholder`
2
+
3
+ The tool for scraping and recording web pages.
4
+
5
+ Name Origin: The name **[Beholder](https://forgottenrealms.fandom.com/wiki/Beholder)** comes from a mythical creature with many eyes, symbolizing its ability to observe everything around it. Like this creature, our tool scrapes and records web pages with precision and thoroughness, ensuring no detail is missed.
@@ -0,0 +1,6 @@
1
+ import debug from 'debug';
2
+ export declare const log: debug.Debugger;
3
+ export declare const scraperLog: debug.Debugger;
4
+ export declare const resourceLog: debug.Debugger;
5
+ export declare const domLog: debug.Debugger;
6
+ export declare const domDetailsLog: debug.Debugger;
package/dist/debug.js ADDED
@@ -0,0 +1,6 @@
1
+ import debug from 'debug';
2
+ export const log = debug('Beholder');
3
+ export const scraperLog = log.extend('Scraper');
4
+ export const resourceLog = scraperLog.extend('Resource');
5
+ export const domLog = scraperLog.extend('DOM');
6
+ export const domDetailsLog = domLog.extend('Details');
@@ -0,0 +1,24 @@
1
+ import type { AnchorData, ImageElement, ParseURLOptions } from './types.js';
2
+ import type { ElementHandle, Page } from 'puppeteer';
3
+ export declare function getProp<T>($el: ElementHandle<Element>, propName: string, fallback: T): Promise<T>;
4
+ export declare function getPropBySelector<T>(page: Page, selector: string, propName: string, fallback: T): Promise<T>;
5
+ export declare function getImageList(page: Page, viewportWidth: number): Promise<ImageElement[]>;
6
+ export declare function getAnchorList(page: Page, options?: ParseURLOptions): Promise<AnchorData[]>;
7
+ export declare function getMeta(page: Page): Promise<{
8
+ title: string;
9
+ lang: string;
10
+ description: string;
11
+ keywords: string;
12
+ noindex: boolean;
13
+ nofollow: boolean;
14
+ noarchive: boolean;
15
+ canonical: string;
16
+ alternate: string;
17
+ 'og:type': string;
18
+ 'og:title': string;
19
+ 'og:site_name': string;
20
+ 'og:description': string;
21
+ 'og:url': string;
22
+ 'og:image': string;
23
+ 'twitter:card': string;
24
+ }>;
@@ -0,0 +1,114 @@
1
+ import { domDetailsLog, domLog } from './debug.js';
2
+ import { parseUrl } from './utils.js';
3
+ const pid = `${process.pid}`;
4
+ const log = domLog.extend(pid);
5
+ const dLog = domDetailsLog.extend(pid);
6
+ export async function getProp($el, propName, fallback) {
7
+ return Promise.race([
8
+ _getProp($el, propName, fallback),
9
+ new Promise((res) => setTimeout(() => res(fallback), 10 * 1000)),
10
+ ]);
11
+ }
12
+ async function _getProp($el, propName, fallback) {
13
+ try {
14
+ const prop = await $el.getProperty(propName);
15
+ if (!prop) {
16
+ return fallback;
17
+ }
18
+ const value = (await prop.jsonValue());
19
+ return value;
20
+ }
21
+ catch {
22
+ return fallback;
23
+ }
24
+ }
25
+ export async function getPropBySelector(page, selector, propName, fallback) {
26
+ const $el = await page.$(selector);
27
+ if (!$el) {
28
+ return fallback;
29
+ }
30
+ return getProp($el, propName, fallback);
31
+ }
32
+ export async function getImageList(page, viewportWidth) {
33
+ log('Getting images (Viewport: %dpx)', viewportWidth);
34
+ const $images = await page.$$('img');
35
+ const imageList = [];
36
+ for (const $image of $images) {
37
+ const boundingBox = await $image.boundingBox();
38
+ const width = boundingBox?.width || 0;
39
+ const height = boundingBox?.height || 0;
40
+ const src = await getProp($image, 'src', '');
41
+ const currentSrc = await getProp($image, 'currentSrc', '');
42
+ const alt = await getProp($image, 'alt', '');
43
+ const naturalWidth = await getProp($image, 'naturalWidth', 0);
44
+ const naturalHeight = await getProp($image, 'naturalHeight', 0);
45
+ const loading = await getProp($image, 'loading', '');
46
+ const sourceCode = await getProp($image, 'outerHTML', '');
47
+ const isLazy = loading.toLowerCase().trim() === 'lazy';
48
+ imageList.push({
49
+ src,
50
+ currentSrc,
51
+ alt,
52
+ width,
53
+ height,
54
+ naturalWidth,
55
+ naturalHeight,
56
+ isLazy,
57
+ viewportWidth,
58
+ sourceCode,
59
+ });
60
+ }
61
+ log('Got %d images (Viewport: %dpx)', imageList.length, viewportWidth);
62
+ dLog('Images are: %O', imageList.map((i) => i.src));
63
+ return imageList;
64
+ }
65
+ export async function getAnchorList(page, options) {
66
+ log('Getting anchors');
67
+ const $anchors = await page.$$('a[href], area[href]');
68
+ const anchorList = [];
69
+ for (const $anchor of $anchors) {
70
+ const $href = await getProp($anchor, 'href', '');
71
+ const hrefVal = $href.toString();
72
+ const href = parseUrl(hrefVal, options);
73
+ if (!href || !href.isHTTP) {
74
+ continue;
75
+ }
76
+ const axNode = await page.accessibility.snapshot({ root: $anchor });
77
+ const textContent = await getProp($anchor, 'textContent', '');
78
+ const accessibleName = axNode ? axNode.name || '' : textContent.trim();
79
+ const link = {
80
+ href,
81
+ textContent: accessibleName,
82
+ };
83
+ anchorList.push(link);
84
+ }
85
+ log('Got %d anchors', anchorList.length);
86
+ dLog('Anchors are: %O', anchorList.map((a) => a.href.href));
87
+ return anchorList;
88
+ }
89
+ export async function getMeta(page) {
90
+ log('Getting Meta');
91
+ const robotsVal = await getPropBySelector(page, 'meta[name="robots"]', 'content', '');
92
+ const robots = new Set(robotsVal.split(',').map((robot) => robot.trim().toLowerCase()));
93
+ const meta = {
94
+ title: await getPropBySelector(page, 'title', 'textContent', ''),
95
+ lang: await getPropBySelector(page, 'html', 'lang', ''),
96
+ description: await getPropBySelector(page, 'meta[name="description"]', 'content', ''),
97
+ keywords: await getPropBySelector(page, 'meta[name="keywords"]', 'content', ''),
98
+ noindex: robots.has('noindex'),
99
+ nofollow: robots.has('nofollow'),
100
+ noarchive: robots.has('noarchive'),
101
+ canonical: await getPropBySelector(page, 'link[rel="canonical"]', 'content', ''),
102
+ alternate: await getPropBySelector(page, 'link[rel="alternate"]', 'content', ''),
103
+ 'og:type': await getPropBySelector(page, 'meta[property="og:type"]', 'content', ''),
104
+ 'og:title': await getPropBySelector(page, 'meta[property="og:title"]', 'content', ''),
105
+ 'og:site_name': await getPropBySelector(page, 'meta[property="og:site_name"]', 'content', ''),
106
+ 'og:description': await getPropBySelector(page, 'meta[property="og:description"]', 'content', ''),
107
+ 'og:url': await getPropBySelector(page, 'meta[property="og:url"]', 'content', ''),
108
+ 'og:image': await getPropBySelector(page, 'meta[property="og:image"]', 'content', ''),
109
+ 'twitter:card': await getPropBySelector(page, 'meta[name="twitter:card"]', 'content', ''),
110
+ };
111
+ log('Got meta');
112
+ dLog('Meta data are: %O', meta);
113
+ return meta;
114
+ }
@@ -0,0 +1,32 @@
1
+ export declare const subProcessEvent: {
2
+ start: import("typescript-fsa").ActionCreator<{
3
+ url: import("./types.js").ExURL;
4
+ isExternal: boolean;
5
+ isGettingImages: boolean;
6
+ excludeKeywords: string[];
7
+ executablePath: string | null;
8
+ isSkip: boolean;
9
+ isTitleOnly: boolean;
10
+ screenshot: string | null;
11
+ } & Required<import("./types.js").ParseURLOptions>>;
12
+ destroy: import("typescript-fsa").ActionCreator<void>;
13
+ };
14
+ export declare const scraperEvent: {
15
+ ignoreAndSkip: import("typescript-fsa").ActionCreator<import("./types.js").ScrapeEvent & {
16
+ reason: {
17
+ matchedText: string;
18
+ excludeKeywords: string[];
19
+ };
20
+ }>;
21
+ resourceResponse: import("typescript-fsa").ActionCreator<import("./types.js").ScrapeEvent & {
22
+ log: import("./types.js").NetworkLog;
23
+ resource: Omit<import("./types.js").Resource, "uid">;
24
+ }>;
25
+ scrapeEnd: import("typescript-fsa").ActionCreator<import("./types.js").ScrapeEvent & {
26
+ timestamp: number;
27
+ result: import("./types.js").PageData;
28
+ }>;
29
+ destroyed: import("typescript-fsa").ActionCreator<Omit<import("./types.js").ScrapeEvent, "url">>;
30
+ error: import("typescript-fsa").ActionCreator<import("./types.js").ScrapeErrorEvent>;
31
+ changePhase: import("typescript-fsa").ActionCreator<import("./types.js").ChangePhaseEvent>;
32
+ };
package/dist/events.js ADDED
@@ -0,0 +1,15 @@
1
+ import { actionCreatorFactory } from 'typescript-fsa';
2
+ const scraperEventCreator = actionCreatorFactory('@@scraper');
3
+ const subProcessEventCreator = actionCreatorFactory('@@sub-process');
4
+ export const subProcessEvent = {
5
+ start: subProcessEventCreator('start'),
6
+ destroy: subProcessEventCreator('destroy'),
7
+ };
8
+ export const scraperEvent = {
9
+ ignoreAndSkip: scraperEventCreator('ignoreAndSkip'),
10
+ resourceResponse: scraperEventCreator('resourceResponse'),
11
+ scrapeEnd: scraperEventCreator('scrapeEnd'),
12
+ destroyed: scraperEventCreator('destroyed'),
13
+ error: scraperEventCreator('error'),
14
+ changePhase: scraperEventCreator('changePhase'),
15
+ };
@@ -0,0 +1,2 @@
1
+ import type { PageData, ExURL } from './types.js';
2
+ export declare function fetchDestination(url: ExURL, isExternal: boolean, method?: string): Promise<PageData>;
@@ -0,0 +1,132 @@
1
+ import { delay } from '@d-zero/shared/delay';
2
+ import redirects from 'follow-redirects';
3
+ import NetTimeoutError from './net-timeout-error.js';
4
+ const cacheMap = new Map();
5
+ export async function fetchDestination(url, isExternal, method = 'HEAD') {
6
+ if (cacheMap.has(url.withoutHash)) {
7
+ const cache = cacheMap.get(url.withoutHash);
8
+ if (cache instanceof Error) {
9
+ throw cache;
10
+ }
11
+ return cache;
12
+ }
13
+ const result = await Promise.race([
14
+ _fetchHead(url, isExternal, method).catch((error) => new Error(error)),
15
+ (async () => {
16
+ await delay(10 * 1000);
17
+ return new NetTimeoutError();
18
+ })(),
19
+ ]);
20
+ cacheMap.set(url.withoutHash, result);
21
+ if (result instanceof Error) {
22
+ throw result;
23
+ }
24
+ return result;
25
+ }
26
+ async function _fetchHead(url, isExternal, method) {
27
+ return new Promise((resolve, reject) => {
28
+ const request = {
29
+ protocol: url.protocol,
30
+ host: url.hostname,
31
+ path: url.pathname,
32
+ method,
33
+ headers: {
34
+ host: url.hostname,
35
+ Connection: 'keep-alive',
36
+ Pragma: 'no-cache',
37
+ 'Cache-Control': 'no-cache',
38
+ 'Upgrade-Insecure-Requests': 1,
39
+ // TODO: 'User-Agent': userAgent,
40
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', // cspell:disable-line
41
+ 'Accept-Encoding': 'gzip, deflate',
42
+ 'Accept-Language': 'ja,en;q=0.9,zh;q=0.8,en-US;q=0.7,pl;q=0.6,de;q=0.5,zh-CN;q=0.4,zh-TW;q=0.3,th;q=0.2,ko;q=0.1,fr;q=0.1',
43
+ },
44
+ };
45
+ if (url.username && url.password) {
46
+ request.auth = `${url.username}:${url.password}`;
47
+ }
48
+ let req;
49
+ const response = (res) => {
50
+ res.on('data', () => { });
51
+ res.on('end', async () => {
52
+ const redirectPaths = res.redirects.map((r) => r.url);
53
+ const _contentLength = Number.parseInt(res.headers['content-length'] || '');
54
+ const contentLength = Number.isFinite(_contentLength) ? _contentLength : null;
55
+ let rep = {
56
+ url,
57
+ isTarget: !isExternal,
58
+ isExternal,
59
+ redirectPaths,
60
+ status: res.statusCode || 0,
61
+ statusText: res.statusMessage || '',
62
+ contentType: res.headers['content-type']?.split(';')[0] || null,
63
+ contentLength,
64
+ responseHeaders: res.headers,
65
+ meta: {
66
+ title: '',
67
+ },
68
+ imageList: [],
69
+ anchorList: [],
70
+ html: '',
71
+ isSkipped: false,
72
+ };
73
+ if (rep.status === 405) {
74
+ if (method === 'GET') {
75
+ reject(`Method Not Allowed: ${url} ${rep.statusText}`);
76
+ return;
77
+ }
78
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
79
+ if (rr) {
80
+ rep = rr;
81
+ }
82
+ else {
83
+ reject(rr);
84
+ }
85
+ }
86
+ if (rep.status === 501) {
87
+ if (method === 'GET') {
88
+ reject(`Method Not Implemented: ${url} ${rep.statusText}`);
89
+ return;
90
+ }
91
+ await delay(5 * 1000);
92
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
93
+ if (rr) {
94
+ rep = rr;
95
+ }
96
+ else {
97
+ reject(rr);
98
+ }
99
+ }
100
+ if (rep.status === 503) {
101
+ if (method === 'GET') {
102
+ reject(`Retrying failed: ${url} ${rep.statusText}`);
103
+ return;
104
+ }
105
+ await delay(5 * 1000);
106
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
107
+ if (rr) {
108
+ rep = rr;
109
+ }
110
+ else {
111
+ reject(rr);
112
+ }
113
+ }
114
+ resolve(rep);
115
+ });
116
+ };
117
+ if (url.protocol === 'https:') {
118
+ req = redirects.https.request({
119
+ ...request,
120
+ rejectUnauthorized: false,
121
+ }, response);
122
+ }
123
+ else {
124
+ req = redirects.http.request(request, response);
125
+ }
126
+ req.on('error', (error) => {
127
+ reject(error);
128
+ });
129
+ req.write('head');
130
+ req.end();
131
+ });
132
+ }
@@ -0,0 +1,4 @@
1
+ export { default as SubProcessRunner } from './sub-process-runner.js';
2
+ export { default as default } from './scraper.js';
3
+ export * from './types.js';
4
+ export * from './events.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { default as SubProcessRunner } from './sub-process-runner.js';
2
+ export { default as default } from './scraper.js';
3
+ export * from './types.js';
4
+ export * from './events.js';
@@ -0,0 +1 @@
1
+ export declare function keywordCheck(html: string, excludeKeywords: string[]): string | false;
@@ -0,0 +1,10 @@
1
+ import { strToRegex } from '@d-zero/shared/str-to-regex';
2
+ export function keywordCheck(html, excludeKeywords) {
3
+ for (const keyword of excludeKeywords) {
4
+ const pattern = strToRegex(keyword);
5
+ if (pattern.test(html)) {
6
+ return keyword;
7
+ }
8
+ }
9
+ return false;
10
+ }
@@ -0,0 +1,3 @@
1
+ export default class NetTimeoutError extends Error {
2
+ name: string;
3
+ }
@@ -0,0 +1,3 @@
1
+ export default class NetTimeoutError extends Error {
2
+ name = 'NetTimeoutError';
3
+ }
@@ -0,0 +1,2 @@
1
+ import type { PageData, ExURL } from './types.js';
2
+ export declare function fetchDestination(url: ExURL, isExternal: boolean, method?: string): Promise<PageData>;
@@ -0,0 +1,132 @@
1
+ import { delay } from '@d-zero/shared/delay';
2
+ import redirects from 'follow-redirects';
3
+ import NetTimeoutError from './net-timeout-error.js';
4
+ const cacheMap = new Map();
5
+ export async function fetchDestination(url, isExternal, method = 'HEAD') {
6
+ if (cacheMap.has(url.withoutHash)) {
7
+ const cache = cacheMap.get(url.withoutHash);
8
+ if (cache instanceof Error) {
9
+ throw cache;
10
+ }
11
+ return cache;
12
+ }
13
+ const result = await Promise.race([
14
+ _fetchHead(url, isExternal, method).catch((error) => new Error(error)),
15
+ (async () => {
16
+ await delay(10 * 1000);
17
+ return new NetTimeoutError();
18
+ })(),
19
+ ]);
20
+ cacheMap.set(url.withoutHash, result);
21
+ if (result instanceof Error) {
22
+ throw result;
23
+ }
24
+ return result;
25
+ }
26
+ async function _fetchHead(url, isExternal, method) {
27
+ return new Promise((resolve, reject) => {
28
+ const request = {
29
+ protocol: url.protocol,
30
+ host: url.hostname,
31
+ path: url.pathname,
32
+ method,
33
+ headers: {
34
+ host: url.hostname,
35
+ Connection: 'keep-alive',
36
+ Pragma: 'no-cache',
37
+ 'Cache-Control': 'no-cache',
38
+ 'Upgrade-Insecure-Requests': 1,
39
+ // TODO: 'User-Agent': userAgent,
40
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
41
+ 'Accept-Encoding': 'gzip, deflate',
42
+ 'Accept-Language': 'ja,en;q=0.9,zh;q=0.8,en-US;q=0.7,pl;q=0.6,de;q=0.5,zh-CN;q=0.4,zh-TW;q=0.3,th;q=0.2,ko;q=0.1,fr;q=0.1',
43
+ },
44
+ };
45
+ if (url.username && url.password) {
46
+ request.auth = `${url.username}:${url.password}`;
47
+ }
48
+ let req;
49
+ const response = (res) => {
50
+ res.on('data', () => { });
51
+ res.on('end', async () => {
52
+ const redirectPaths = res.redirects.map((r) => r.url);
53
+ const _contentLength = Number.parseInt(res.headers['content-length'] || '');
54
+ const contentLength = Number.isFinite(_contentLength) ? _contentLength : null;
55
+ let rep = {
56
+ url,
57
+ isTarget: !isExternal,
58
+ isExternal,
59
+ redirectPaths,
60
+ status: res.statusCode || 0,
61
+ statusText: res.statusMessage || '',
62
+ contentType: res.headers['content-type']?.split(';')[0] || null,
63
+ contentLength,
64
+ responseHeaders: res.headers,
65
+ meta: {
66
+ title: '',
67
+ },
68
+ imageList: [],
69
+ anchorList: [],
70
+ html: '',
71
+ isSkipped: false,
72
+ };
73
+ if (rep.status === 405) {
74
+ if (method === 'GET') {
75
+ reject(`Method Not Allowed: ${url} ${rep.statusText}`);
76
+ return;
77
+ }
78
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
79
+ if (rr) {
80
+ rep = rr;
81
+ }
82
+ else {
83
+ reject(rr);
84
+ }
85
+ }
86
+ if (rep.status === 501) {
87
+ if (method === 'GET') {
88
+ reject(`Method Not Implemented: ${url} ${rep.statusText}`);
89
+ return;
90
+ }
91
+ await delay(5 * 1000);
92
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
93
+ if (rr) {
94
+ rep = rr;
95
+ }
96
+ else {
97
+ reject(rr);
98
+ }
99
+ }
100
+ if (rep.status === 503) {
101
+ if (method === 'GET') {
102
+ reject(`Retrying failed: ${url} ${rep.statusText}`);
103
+ return;
104
+ }
105
+ await delay(5 * 1000);
106
+ const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
107
+ if (rr) {
108
+ rep = rr;
109
+ }
110
+ else {
111
+ reject(rr);
112
+ }
113
+ }
114
+ resolve(rep);
115
+ });
116
+ };
117
+ if (url.protocol === 'https:') {
118
+ req = redirects.https.request({
119
+ ...request,
120
+ rejectUnauthorized: false,
121
+ }, response);
122
+ }
123
+ else {
124
+ req = redirects.http.request(request, response);
125
+ }
126
+ req.on('error', (error) => {
127
+ reject(error);
128
+ });
129
+ req.write('head');
130
+ req.end();
131
+ });
132
+ }
@@ -0,0 +1,15 @@
1
+ import type { ScrapeEventTypes, PageData, ParseURLOptions, ExURL } from './types.js';
2
+ import { TypedAwaitEventEmitter } from '@d-zero/shared/typed-await-event-emitter';
3
+ export type ScraperOptions = {
4
+ isExternal: boolean;
5
+ isGettingImages: boolean;
6
+ excludeKeywords: string[];
7
+ executablePath: string | null;
8
+ isTitleOnly: boolean;
9
+ screenshot: string | null;
10
+ } & ParseURLOptions;
11
+ export default class Scraper extends TypedAwaitEventEmitter<ScrapeEventTypes> {
12
+ #private;
13
+ destroy(isExternal: boolean): Promise<void>;
14
+ scrapeStart(url: ExURL, options?: Partial<ScraperOptions>, isSkip?: boolean): Promise<PageData | undefined>;
15
+ }