@d-zero/beholder 0.1.29 → 2.0.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +172 -477
  3. package/package.json +7 -11
  4. package/src/debug.ts +5 -2
  5. package/src/dom-evaluation.ts +195 -65
  6. package/src/index.ts +27 -3
  7. package/src/is-error.spec.ts +33 -0
  8. package/src/is-error.ts +10 -0
  9. package/src/keyword-check.spec.ts +45 -4
  10. package/src/keyword-check.ts +5 -3
  11. package/src/parse-url.spec.ts +35 -0
  12. package/src/parse-url.ts +26 -0
  13. package/src/scraper.ts +338 -300
  14. package/src/types.ts +345 -258
  15. package/LICENSE +0 -21
  16. package/dist/debug.d.ts +0 -6
  17. package/dist/debug.js +0 -6
  18. package/dist/dom-evaluation.d.ts +0 -51
  19. package/dist/dom-evaluation.js +0 -147
  20. package/dist/events.d.ts +0 -32
  21. package/dist/events.js +0 -15
  22. package/dist/fetch-destination.d.ts +0 -8
  23. package/dist/fetch-destination.js +0 -145
  24. package/dist/index.d.ts +0 -4
  25. package/dist/index.js +0 -4
  26. package/dist/keyword-check.d.ts +0 -6
  27. package/dist/keyword-check.js +0 -15
  28. package/dist/net-timeout-error.d.ts +0 -3
  29. package/dist/net-timeout-error.js +0 -3
  30. package/dist/scraper.d.ts +0 -15
  31. package/dist/scraper.js +0 -621
  32. package/dist/sub-process-runner.d.ts +0 -12
  33. package/dist/sub-process-runner.js +0 -180
  34. package/dist/sub-process.d.ts +0 -1
  35. package/dist/sub-process.js +0 -67
  36. package/dist/types.d.ts +0 -271
  37. package/dist/types.js +0 -1
  38. package/dist/utils.d.ts +0 -16
  39. package/dist/utils.js +0 -69
  40. package/src/events.ts +0 -21
  41. package/src/fetch-destination.ts +0 -173
  42. package/src/net-timeout-error.ts +0 -3
  43. package/src/sub-process-runner.ts +0 -220
  44. package/src/sub-process.ts +0 -86
  45. package/src/utils.ts +0 -89
  46. package/tsconfig.tsbuildinfo +0 -1
package/LICENSE DELETED
@@ -1,21 +0,0 @@
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/dist/debug.d.ts DELETED
@@ -1,6 +0,0 @@
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 DELETED
@@ -1,6 +0,0 @@
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');
@@ -1,51 +0,0 @@
1
- import type { AnchorData, ImageElement, ParseURLOptions } from './types.js';
2
- import type { ElementHandle, Page } from 'puppeteer';
3
- /**
4
- *
5
- * @param $el
6
- * @param propName
7
- * @param fallback
8
- */
9
- export declare function getProp<T>($el: ElementHandle<Element>, propName: string, fallback: T): Promise<T>;
10
- /**
11
- *
12
- * @param page
13
- * @param selector
14
- * @param propName
15
- * @param fallback
16
- */
17
- export declare function getPropBySelector<T>(page: Page, selector: string, propName: string, fallback: T): Promise<T>;
18
- /**
19
- *
20
- * @param page
21
- * @param viewportWidth
22
- */
23
- export declare function getImageList(page: Page, viewportWidth: number): Promise<ImageElement[]>;
24
- /**
25
- *
26
- * @param page
27
- * @param options
28
- */
29
- export declare function getAnchorList(page: Page, options?: ParseURLOptions): Promise<AnchorData[]>;
30
- /**
31
- *
32
- * @param page
33
- */
34
- export declare function getMeta(page: Page): Promise<{
35
- title: string;
36
- lang: string;
37
- description: string;
38
- keywords: string;
39
- noindex: boolean;
40
- nofollow: boolean;
41
- noarchive: boolean;
42
- canonical: string;
43
- alternate: string;
44
- 'og:type': string;
45
- 'og:title': string;
46
- 'og:site_name': string;
47
- 'og:description': string;
48
- 'og:url': string;
49
- 'og:image': string;
50
- 'twitter:card': string;
51
- }>;
@@ -1,147 +0,0 @@
1
- import { parseUrl } from '@d-zero/shared/parse-url';
2
- import { domDetailsLog, domLog } from './debug.js';
3
- const pid = `${process.pid}`;
4
- const log = domLog.extend(pid);
5
- const dLog = domDetailsLog.extend(pid);
6
- /**
7
- *
8
- * @param $el
9
- * @param propName
10
- * @param fallback
11
- */
12
- export async function getProp($el, propName, fallback) {
13
- return Promise.race([
14
- _getProp($el, propName, fallback),
15
- new Promise((res) => setTimeout(() => res(fallback), 10 * 1000)),
16
- ]);
17
- }
18
- /**
19
- *
20
- * @param $el
21
- * @param propName
22
- * @param fallback
23
- */
24
- async function _getProp($el, propName, fallback) {
25
- try {
26
- const prop = await $el.getProperty(propName);
27
- if (!prop) {
28
- return fallback;
29
- }
30
- const value = (await prop.jsonValue());
31
- return value;
32
- }
33
- catch {
34
- return fallback;
35
- }
36
- }
37
- /**
38
- *
39
- * @param page
40
- * @param selector
41
- * @param propName
42
- * @param fallback
43
- */
44
- export async function getPropBySelector(page, selector, propName, fallback) {
45
- const $el = await page.$(selector);
46
- if (!$el) {
47
- return fallback;
48
- }
49
- return getProp($el, propName, fallback);
50
- }
51
- /**
52
- *
53
- * @param page
54
- * @param viewportWidth
55
- */
56
- export async function getImageList(page, viewportWidth) {
57
- log('Getting images (Viewport: %dpx)', viewportWidth);
58
- const $images = await page.$$('img');
59
- const imageList = [];
60
- for (const $image of $images) {
61
- const boundingBox = await $image.boundingBox();
62
- const width = boundingBox?.width || 0;
63
- const height = boundingBox?.height || 0;
64
- const src = await getProp($image, 'src', '');
65
- const currentSrc = await getProp($image, 'currentSrc', '');
66
- const alt = await getProp($image, 'alt', '');
67
- const naturalWidth = await getProp($image, 'naturalWidth', 0);
68
- const naturalHeight = await getProp($image, 'naturalHeight', 0);
69
- const loading = await getProp($image, 'loading', '');
70
- const sourceCode = await getProp($image, 'outerHTML', '');
71
- const isLazy = loading.toLowerCase().trim() === 'lazy';
72
- imageList.push({
73
- src,
74
- currentSrc,
75
- alt,
76
- width,
77
- height,
78
- naturalWidth,
79
- naturalHeight,
80
- isLazy,
81
- viewportWidth,
82
- sourceCode,
83
- });
84
- }
85
- log('Got %d images (Viewport: %dpx)', imageList.length, viewportWidth);
86
- dLog('Images are: %O', imageList.map((i) => i.src));
87
- return imageList;
88
- }
89
- /**
90
- *
91
- * @param page
92
- * @param options
93
- */
94
- export async function getAnchorList(page, options) {
95
- log('Getting anchors');
96
- const $anchors = await page.$$('a[href], area[href]');
97
- const anchorList = [];
98
- for (const $anchor of $anchors) {
99
- const $href = await getProp($anchor, 'href', '');
100
- const hrefVal = $href.toString();
101
- const href = parseUrl(hrefVal, options);
102
- if (!href || !href.isHTTP) {
103
- continue;
104
- }
105
- const axNode = await page.accessibility.snapshot({ root: $anchor });
106
- const textContent = await getProp($anchor, 'textContent', '');
107
- const accessibleName = axNode ? axNode.name || '' : textContent.trim();
108
- const link = {
109
- href,
110
- textContent: accessibleName,
111
- };
112
- anchorList.push(link);
113
- }
114
- log('Got %d anchors', anchorList.length);
115
- dLog('Anchors are: %O', anchorList.map((a) => a.href.href));
116
- return anchorList;
117
- }
118
- /**
119
- *
120
- * @param page
121
- */
122
- export async function getMeta(page) {
123
- log('Getting Meta');
124
- const robotsVal = await getPropBySelector(page, 'meta[name="robots"]', 'content', '');
125
- const robots = new Set(robotsVal.split(',').map((robot) => robot.trim().toLowerCase()));
126
- const meta = {
127
- title: await getPropBySelector(page, 'title', 'textContent', ''),
128
- lang: await getPropBySelector(page, 'html', 'lang', ''),
129
- description: await getPropBySelector(page, 'meta[name="description"]', 'content', ''),
130
- keywords: await getPropBySelector(page, 'meta[name="keywords"]', 'content', ''),
131
- noindex: robots.has('noindex'),
132
- nofollow: robots.has('nofollow'),
133
- noarchive: robots.has('noarchive'),
134
- canonical: await getPropBySelector(page, 'link[rel="canonical"]', 'content', ''),
135
- alternate: await getPropBySelector(page, 'link[rel="alternate"]', 'content', ''),
136
- 'og:type': await getPropBySelector(page, 'meta[property="og:type"]', 'content', ''),
137
- 'og:title': await getPropBySelector(page, 'meta[property="og:title"]', 'content', ''),
138
- 'og:site_name': await getPropBySelector(page, 'meta[property="og:site_name"]', 'content', ''),
139
- 'og:description': await getPropBySelector(page, 'meta[property="og:description"]', 'content', ''),
140
- 'og:url': await getPropBySelector(page, 'meta[property="og:url"]', 'content', ''),
141
- 'og:image': await getPropBySelector(page, 'meta[property="og:image"]', 'content', ''),
142
- 'twitter:card': await getPropBySelector(page, 'meta[name="twitter:card"]', 'content', ''),
143
- };
144
- log('Got meta');
145
- dLog('Meta data are: %O', meta);
146
- return meta;
147
- }
package/dist/events.d.ts DELETED
@@ -1,32 +0,0 @@
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 DELETED
@@ -1,15 +0,0 @@
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
- };
@@ -1,8 +0,0 @@
1
- import type { PageData, ExURL } from './types.js';
2
- /**
3
- *
4
- * @param url
5
- * @param isExternal
6
- * @param method
7
- */
8
- export declare function fetchDestination(url: ExURL, isExternal: boolean, method?: string): Promise<PageData>;
@@ -1,145 +0,0 @@
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
- /**
6
- *
7
- * @param url
8
- * @param isExternal
9
- * @param method
10
- */
11
- export async function fetchDestination(url, isExternal, method = 'HEAD') {
12
- if (cacheMap.has(url.withoutHash)) {
13
- const cache = cacheMap.get(url.withoutHash);
14
- if (cache instanceof Error) {
15
- throw cache;
16
- }
17
- return cache;
18
- }
19
- const result = await Promise.race([
20
- _fetchHead(url, isExternal, method).catch((error) => new Error(error)),
21
- (async () => {
22
- await delay(10 * 1000);
23
- return new NetTimeoutError();
24
- })(),
25
- ]);
26
- cacheMap.set(url.withoutHash, result);
27
- if (result instanceof Error) {
28
- throw result;
29
- }
30
- return result;
31
- }
32
- /**
33
- *
34
- * @param url
35
- * @param isExternal
36
- * @param method
37
- */
38
- async function _fetchHead(url, isExternal, method) {
39
- return new Promise((resolve, reject) => {
40
- const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
41
- const request = {
42
- protocol: url.protocol,
43
- hostname: url.hostname,
44
- port: url.port || undefined,
45
- path: url.pathname,
46
- method,
47
- headers: {
48
- host: hostHeader,
49
- Connection: 'keep-alive',
50
- Pragma: 'no-cache',
51
- 'Cache-Control': 'no-cache',
52
- 'Upgrade-Insecure-Requests': 1,
53
- // TODO: 'User-Agent': userAgent,
54
- 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
55
- 'Accept-Encoding': 'gzip, deflate',
56
- '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',
57
- },
58
- };
59
- if (url.username && url.password) {
60
- request.auth = `${url.username}:${url.password}`;
61
- }
62
- let req;
63
- const response = (res) => {
64
- res.on('data', () => { });
65
- res.on('end', async () => {
66
- const redirectPaths = res.redirects.map((r) => r.url);
67
- const _contentLength = Number.parseInt(res.headers['content-length'] || '');
68
- const contentLength = Number.isFinite(_contentLength) ? _contentLength : null;
69
- let rep = {
70
- url,
71
- isTarget: !isExternal,
72
- isExternal,
73
- redirectPaths,
74
- status: res.statusCode || 0,
75
- statusText: res.statusMessage || '',
76
- contentType: res.headers['content-type']?.split(';')[0] || null,
77
- contentLength,
78
- responseHeaders: res.headers,
79
- meta: {
80
- title: '',
81
- },
82
- imageList: [],
83
- anchorList: [],
84
- html: '',
85
- isSkipped: false,
86
- };
87
- if (rep.status === 405) {
88
- if (method === 'GET') {
89
- reject(`Method Not Allowed: ${url} ${rep.statusText}`);
90
- return;
91
- }
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 === 501) {
101
- if (method === 'GET') {
102
- reject(`Method Not Implemented: ${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
- if (rep.status === 503) {
115
- if (method === 'GET') {
116
- reject(`Retrying failed: ${url} ${rep.statusText}`);
117
- return;
118
- }
119
- await delay(5 * 1000);
120
- const rr = await fetchDestination(url, isExternal, 'GET').catch((error) => error);
121
- if (rr) {
122
- rep = rr;
123
- }
124
- else {
125
- reject(rr);
126
- }
127
- }
128
- resolve(rep);
129
- });
130
- };
131
- if (url.protocol === 'https:') {
132
- req = redirects.https.request({
133
- ...request,
134
- rejectUnauthorized: false,
135
- }, response);
136
- }
137
- else {
138
- req = redirects.http.request(request, response);
139
- }
140
- req.on('error', (error) => {
141
- reject(error);
142
- });
143
- req.end();
144
- });
145
- }
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
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 DELETED
@@ -1,4 +0,0 @@
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';
@@ -1,6 +0,0 @@
1
- /**
2
- *
3
- * @param html
4
- * @param excludeKeywords
5
- */
6
- export declare function keywordCheck(html: string, excludeKeywords: string[]): string | false;
@@ -1,15 +0,0 @@
1
- import { strToRegex } from '@d-zero/shared/str-to-regex';
2
- /**
3
- *
4
- * @param html
5
- * @param excludeKeywords
6
- */
7
- export function keywordCheck(html, excludeKeywords) {
8
- for (const keyword of excludeKeywords) {
9
- const pattern = strToRegex(keyword);
10
- if (pattern.test(html)) {
11
- return keyword;
12
- }
13
- }
14
- return false;
15
- }
@@ -1,3 +0,0 @@
1
- export default class NetTimeoutError extends Error {
2
- name: string;
3
- }
@@ -1,3 +0,0 @@
1
- export default class NetTimeoutError extends Error {
2
- name = 'NetTimeoutError';
3
- }
package/dist/scraper.d.ts DELETED
@@ -1,15 +0,0 @@
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
- }