@d-zero/beholder 2.1.5 → 3.0.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.
- package/CHANGELOG.md +44 -0
- package/README.md +9 -276
- package/dist/dom-evaluation.d.ts +100 -62
- package/dist/dom-evaluation.js +498 -195
- package/dist/index.d.ts +1 -1
- package/dist/meta/classify.d.ts +52 -0
- package/dist/meta/classify.js +731 -0
- package/dist/meta/id-extractors.d.ts +40 -0
- package/dist/meta/id-extractors.js +196 -0
- package/dist/meta/keys.d.ts +41 -0
- package/dist/meta/keys.js +507 -0
- package/dist/meta/parsers.d.ts +74 -0
- package/dist/meta/parsers.js +293 -0
- package/dist/meta/tag-detection.d.ts +59 -0
- package/dist/meta/tag-detection.js +120 -0
- package/dist/meta/types.d.ts +874 -0
- package/dist/meta/types.js +12 -0
- package/dist/scraper.js +22 -18
- package/dist/types.d.ts +8 -37
- package/package.json +5 -4
- package/src/dom-evaluation.spec.ts +521 -0
- package/src/dom-evaluation.ts +655 -227
- package/src/index.ts +43 -0
- package/src/meta/classify.spec.ts +281 -0
- package/src/meta/classify.ts +810 -0
- package/src/meta/id-extractors.spec.ts +69 -0
- package/src/meta/id-extractors.ts +206 -0
- package/src/meta/keys.ts +568 -0
- package/src/meta/parsers.spec.ts +178 -0
- package/src/meta/parsers.ts +304 -0
- package/src/meta/simple-wappalyzer.d.ts +37 -0
- package/src/meta/tag-detection.spec.ts +134 -0
- package/src/meta/tag-detection.ts +161 -0
- package/src/meta/types.ts +949 -0
- package/src/scraper.ts +32 -16
- package/src/types.ts +54 -54
- package/tsconfig.tsbuildinfo +1 -1
package/dist/dom-evaluation.js
CHANGED
|
@@ -3,28 +3,49 @@
|
|
|
3
3
|
*
|
|
4
4
|
* These functions are called by {@link ./scraper.ts | Scraper.#fetchData} to extract
|
|
5
5
|
* anchors, images, and meta information after page navigation completes.
|
|
6
|
+
*
|
|
7
|
+
* WHY timeouts everywhere: A page whose main thread is blocked (heavy JS, autoplay
|
|
8
|
+
* video players, infinite loops) makes every CDP round-trip hang. `getMeta` and
|
|
9
|
+
* `getImageList` therefore collect all data in a single `page.evaluate` and wrap it
|
|
10
|
+
* in {@link raceWithTimeout} so a blocked thread is abandoned after a bounded budget
|
|
11
|
+
* instead of accumulating per-property timeouts up to the caller's global timeout.
|
|
12
|
+
* Note that `page.evaluate` itself runs on the page's main thread and has no built-in
|
|
13
|
+
* timeout, so the surrounding race is what actually bounds the hang.
|
|
6
14
|
* @see {@link ./types.ts} for the data types returned by these functions
|
|
7
15
|
*/
|
|
16
|
+
import { raceWithTimeout } from '@d-zero/shared/race-with-timeout';
|
|
8
17
|
import { domDetailsLog, domLog } from './debug.js';
|
|
18
|
+
import { classify, emptyMeta } from './meta/classify.js';
|
|
19
|
+
import { detectTags } from './meta/tag-detection.js';
|
|
9
20
|
import { parseUrl } from './parse-url.js';
|
|
10
21
|
const pid = `${process.pid}`;
|
|
11
22
|
const log = domLog.extend(pid);
|
|
12
23
|
const dLog = domDetailsLog.extend(pid);
|
|
24
|
+
/**
|
|
25
|
+
* Default timeout (ms) applied to DOM evaluation operations when the caller does not
|
|
26
|
+
* specify one. Bounds how long a single `page.evaluate` / property read may hang on a
|
|
27
|
+
* page whose main thread is unresponsive.
|
|
28
|
+
*
|
|
29
|
+
* WHY 180s: Aligned with the upstream `Scraper#fetchData` retryable timeout (3 min) so
|
|
30
|
+
* a single phase does not exceed the retry budget while still tolerating large pages
|
|
31
|
+
* (e.g., 1000+ anchors) and slow main threads.
|
|
32
|
+
*/
|
|
33
|
+
export const DEFAULT_DOM_EVALUATION_TIMEOUT = 180_000;
|
|
13
34
|
/**
|
|
14
35
|
* Retrieves a DOM property value from a Puppeteer element handle with a timeout.
|
|
15
36
|
*
|
|
16
|
-
* Races the actual property retrieval against a
|
|
37
|
+
* Races the actual property retrieval against a timeout via {@link raceWithTimeout},
|
|
38
|
+
* which clears the loser-side timer so it cannot keep the event loop alive.
|
|
17
39
|
* If the property cannot be read or the timeout expires, the fallback value is returned.
|
|
18
40
|
* @template T - The expected type of the property value.
|
|
19
41
|
* @param params - Parameters containing the element, property name, and fallback.
|
|
20
|
-
* @
|
|
42
|
+
* @param timeout - Timeout in ms before falling back. Defaults to {@link DEFAULT_DOM_EVALUATION_TIMEOUT}.
|
|
43
|
+
* @returns The property value, or the fallback if retrieval fails or times out.
|
|
21
44
|
*/
|
|
22
|
-
export async function getProp(params) {
|
|
45
|
+
export async function getProp(params, timeout = DEFAULT_DOM_EVALUATION_TIMEOUT) {
|
|
23
46
|
const { $el, propName, fallback } = params;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
new Promise((res) => setTimeout(() => res(fallback), 10 * 1000)),
|
|
27
|
-
]);
|
|
47
|
+
const { result, timeout: timedOut } = await raceWithTimeout(() => _getProp($el, propName, fallback), timeout);
|
|
48
|
+
return timedOut ? fallback : result;
|
|
28
49
|
}
|
|
29
50
|
/**
|
|
30
51
|
* Internal implementation of property retrieval without timeout.
|
|
@@ -47,227 +68,509 @@ async function _getProp($el, propName, fallback) {
|
|
|
47
68
|
return fallback;
|
|
48
69
|
}
|
|
49
70
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Retrieves a DOM property value from the first element matching a CSS selector.
|
|
52
|
-
*
|
|
53
|
-
* Combines `page.$()` with {@link getProp} for convenient single-element lookups.
|
|
54
|
-
* @template T - The expected type of the property value.
|
|
55
|
-
* @param params - Parameters containing the page, selector, property name, and fallback.
|
|
56
|
-
* @returns The property value, or the fallback if the element is not found or retrieval fails.
|
|
57
|
-
*/
|
|
58
|
-
export async function getPropBySelector(params) {
|
|
59
|
-
const { page, selector, propName, fallback } = params;
|
|
60
|
-
const $el = await page.$(selector);
|
|
61
|
-
if (!$el) {
|
|
62
|
-
return fallback;
|
|
63
|
-
}
|
|
64
|
-
return getProp({ $el, propName, fallback });
|
|
65
|
-
}
|
|
66
71
|
/**
|
|
67
72
|
* Extracts all `<img>` elements from the page and returns their properties.
|
|
68
73
|
*
|
|
69
|
-
*
|
|
70
|
-
* natural dimensions, lazy-loading status, and
|
|
74
|
+
* Collects every image's `src`, `currentSrc`, `alt`, layout dimensions,
|
|
75
|
+
* natural dimensions, lazy-loading status, and outer HTML in a single
|
|
76
|
+
* `page.evaluate` call, wrapped in {@link raceWithTimeout}. On timeout (an
|
|
77
|
+
* unresponsive page) an empty array is returned rather than hanging.
|
|
71
78
|
* @param page - The Puppeteer page to extract images from.
|
|
72
79
|
* @param viewportWidth - The current viewport width in pixels, recorded alongside each image entry.
|
|
80
|
+
* @param timeout - Timeout in ms for the evaluation. Defaults to {@link DEFAULT_DOM_EVALUATION_TIMEOUT}.
|
|
73
81
|
* @returns An array of {@link ImageElement} objects describing each image on the page.
|
|
74
82
|
*/
|
|
75
|
-
export async function getImageList(page, viewportWidth) {
|
|
83
|
+
export async function getImageList(page, viewportWidth, timeout = DEFAULT_DOM_EVALUATION_TIMEOUT) {
|
|
76
84
|
log('Getting images (Viewport: %dpx)', viewportWidth);
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
fallback: 0,
|
|
94
|
-
});
|
|
95
|
-
const naturalHeight = await getProp({
|
|
96
|
-
$el: $image,
|
|
97
|
-
propName: 'naturalHeight',
|
|
98
|
-
fallback: 0,
|
|
99
|
-
});
|
|
100
|
-
const loading = await getProp({ $el: $image, propName: 'loading', fallback: '' });
|
|
101
|
-
const sourceCode = await getProp({
|
|
102
|
-
$el: $image,
|
|
103
|
-
propName: 'outerHTML',
|
|
104
|
-
fallback: '',
|
|
105
|
-
});
|
|
106
|
-
const isLazy = loading.toLowerCase().trim() === 'lazy';
|
|
107
|
-
imageList.push({
|
|
108
|
-
src,
|
|
109
|
-
currentSrc,
|
|
110
|
-
alt,
|
|
111
|
-
width,
|
|
112
|
-
height,
|
|
113
|
-
naturalWidth,
|
|
114
|
-
naturalHeight,
|
|
115
|
-
isLazy,
|
|
116
|
-
viewportWidth,
|
|
117
|
-
sourceCode,
|
|
85
|
+
const { result, timeout: timedOut } = await raceWithTimeout(() => page
|
|
86
|
+
.evaluate(() => {
|
|
87
|
+
/* global document */
|
|
88
|
+
return [...document.images].map((img) => {
|
|
89
|
+
const rect = img.getBoundingClientRect();
|
|
90
|
+
return {
|
|
91
|
+
src: img.src,
|
|
92
|
+
currentSrc: img.currentSrc,
|
|
93
|
+
alt: img.alt,
|
|
94
|
+
width: rect.width,
|
|
95
|
+
height: rect.height,
|
|
96
|
+
naturalWidth: img.naturalWidth,
|
|
97
|
+
naturalHeight: img.naturalHeight,
|
|
98
|
+
loading: img.loading,
|
|
99
|
+
sourceCode: img.outerHTML,
|
|
100
|
+
};
|
|
118
101
|
});
|
|
102
|
+
})
|
|
103
|
+
.catch(() => null), timeout);
|
|
104
|
+
if (timedOut || result == null) {
|
|
105
|
+
log('Image extraction timed out or failed (Viewport: %dpx); returning []', viewportWidth);
|
|
106
|
+
return [];
|
|
119
107
|
}
|
|
108
|
+
const imageList = result.map(({ loading, ...img }) => ({
|
|
109
|
+
...img,
|
|
110
|
+
isLazy: loading.toLowerCase().trim() === 'lazy',
|
|
111
|
+
viewportWidth,
|
|
112
|
+
}));
|
|
120
113
|
log('Got %d images (Viewport: %dpx)', imageList.length, viewportWidth);
|
|
121
114
|
dLog('Images are: %O', imageList.map((i) => i.src));
|
|
122
115
|
return imageList;
|
|
123
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* One-shot warning latch: only the first time `_client()` is missing in a
|
|
119
|
+
* process do we log the degradation. Subsequent calls stay silent to avoid
|
|
120
|
+
* spamming logs while every page in a crawl re-enters the fallback path.
|
|
121
|
+
*/
|
|
122
|
+
let warnedAboutMissingClient = false;
|
|
123
|
+
/**
|
|
124
|
+
* Returns puppeteer's internal CDP session for the page, or `null` if it is
|
|
125
|
+
* unreachable (e.g., test mocks, puppeteer wrappers that hide the internal API,
|
|
126
|
+
* or a future puppeteer release that renames `_client`).
|
|
127
|
+
*
|
|
128
|
+
* WHY a warning log: callers transparently fall back to textContent-only mode
|
|
129
|
+
* when this returns `null`, which masks a silent perf regression if a
|
|
130
|
+
* puppeteer update removes `_client`. The warning makes the degraded state
|
|
131
|
+
* observable in production logs so a maintainer can patch the access path.
|
|
132
|
+
*
|
|
133
|
+
* Callers fall back to a textContent-only path when this returns `null`.
|
|
134
|
+
* @param page - The Puppeteer page.
|
|
135
|
+
*/
|
|
136
|
+
function getInternalCDPClient(page) {
|
|
137
|
+
try {
|
|
138
|
+
const client = page._client?.();
|
|
139
|
+
if (!client) {
|
|
140
|
+
if (!warnedAboutMissingClient) {
|
|
141
|
+
warnedAboutMissingClient = true;
|
|
142
|
+
log('WARN: puppeteer Page._client() returned no session — getAnchorList ' +
|
|
143
|
+
'falls back to textContent-only mode. Verify the installed puppeteer ' +
|
|
144
|
+
'version still exposes the internal _client() accessor.');
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
return client;
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (!warnedAboutMissingClient) {
|
|
152
|
+
warnedAboutMissingClient = true;
|
|
153
|
+
log('WARN: puppeteer Page._client() threw — getAnchorList falls back to ' +
|
|
154
|
+
'textContent-only mode. Error: %O', error);
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Fetches the full accessibility tree once and builds a `backendDOMNodeId → accessibleName`
|
|
161
|
+
* map covering every AX node that exposes a backend DOM id.
|
|
162
|
+
*
|
|
163
|
+
* WHY include every non-ignored node (not just `role === 'link'`): the original
|
|
164
|
+
* `page.accessibility.snapshot({ root })` returned whatever AX node represented
|
|
165
|
+
* the anchor — including anchors whose computed role was overridden via ARIA
|
|
166
|
+
* (e.g., `<a role="button">`). Mapping every non-ignored node preserves that.
|
|
167
|
+
*
|
|
168
|
+
* WHY skip `ignored === true`: puppeteer's high-level snapshot uses
|
|
169
|
+
* `interestingOnly: true` by default and returns `null` for ignored nodes
|
|
170
|
+
* (aria-hidden, display:none, visibility:hidden). The old code then fell back
|
|
171
|
+
* to `textContent.trim()`. Including ignored nodes here would short-circuit
|
|
172
|
+
* that fallback with the AX tree's empty name and silently drop link text.
|
|
173
|
+
*
|
|
174
|
+
* On timeout or CDP failure, an empty map is returned so callers transparently
|
|
175
|
+
* fall back to `textContent.trim()` for every anchor.
|
|
176
|
+
* @param client - The CDP session attached to the page.
|
|
177
|
+
* @param timeout - Maximum time to wait for the AX tree fetch.
|
|
178
|
+
*/
|
|
179
|
+
async function buildAccessibleNameMap(client, timeout) {
|
|
180
|
+
const { result, timeout: timedOut } = await raceWithTimeout(() => client
|
|
181
|
+
.send('Accessibility.getFullAXTree')
|
|
182
|
+
.then((res) => res)
|
|
183
|
+
.catch((error) => {
|
|
184
|
+
log('Accessibility.getFullAXTree failed: %O', error);
|
|
185
|
+
return null;
|
|
186
|
+
}), timeout);
|
|
187
|
+
const map = new Map();
|
|
188
|
+
if (timedOut) {
|
|
189
|
+
log('Accessibility.getFullAXTree timed out after %dms', timeout);
|
|
190
|
+
return map;
|
|
191
|
+
}
|
|
192
|
+
if (!result?.nodes) {
|
|
193
|
+
return map;
|
|
194
|
+
}
|
|
195
|
+
for (const node of result.nodes) {
|
|
196
|
+
if (node.backendDOMNodeId == null || node.ignored === true) {
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const name = typeof node.name?.value === 'string' ? node.name.value : '';
|
|
200
|
+
map.set(node.backendDOMNodeId, name);
|
|
201
|
+
}
|
|
202
|
+
return map;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Resolves a CDP backend node id for a given element handle.
|
|
206
|
+
*
|
|
207
|
+
* Wrapped in {@link raceWithTimeout} so a single hung `DOM.describeNode` cannot
|
|
208
|
+
* stall the outer `Promise.all` over every anchor on the page.
|
|
209
|
+
* @param client - The CDP session attached to the page (must be the same session
|
|
210
|
+
* that owns the handle's `objectId`).
|
|
211
|
+
* @param objectId - The remote object id of the element handle.
|
|
212
|
+
* @param timeout - Maximum time to wait for the describeNode call.
|
|
213
|
+
* @returns The backend node id, or `null` if unavailable / timed out / failed.
|
|
214
|
+
*/
|
|
215
|
+
async function resolveBackendNodeId(client, objectId, timeout) {
|
|
216
|
+
const { result, timeout: timedOut } = await raceWithTimeout(() => client
|
|
217
|
+
.send('DOM.describeNode', { objectId })
|
|
218
|
+
.then((res) => res)
|
|
219
|
+
.catch(() => null), timeout);
|
|
220
|
+
if (timedOut || !result) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
return result.node?.backendNodeId ?? null;
|
|
224
|
+
}
|
|
124
225
|
/**
|
|
125
226
|
* Extracts all anchor (`<a>` and `<area>`) elements with `href` attributes from the page.
|
|
126
227
|
*
|
|
127
228
|
* For each anchor, resolves the `href` to an `ExURL` via `parseUrl`, retrieves
|
|
128
229
|
* the accessible name (from the accessibility tree, falling back to `textContent`),
|
|
129
230
|
* and filters out non-HTTP links.
|
|
231
|
+
*
|
|
232
|
+
* WHY Strategy F (single AX-tree fetch + parallel `DOM.describeNode`): the old
|
|
233
|
+
* implementation called `page.accessibility.snapshot({ root })` per anchor, which
|
|
234
|
+
* triggers a CDP round-trip *and* a Chrome-side AX subtree computation (~42ms
|
|
235
|
+
* each). On a page with 1181 anchors that compounded to ~53s. By fetching the
|
|
236
|
+
* full AX tree once and using `DOM.describeNode` in parallel to map element
|
|
237
|
+
* handles back to AX nodes by `backendDOMNodeId`, the same data is collected in
|
|
238
|
+
* ~150ms on the same page — a ~350× speed-up while preserving the original
|
|
239
|
+
* accessible-name semantics. See issue #876 for measurements.
|
|
240
|
+
*
|
|
241
|
+
* WHY the whole operation is wrapped in `raceWithTimeout`: even with bounded
|
|
242
|
+
* per-CDP-call timeouts, a degenerate page (blocked main thread, thousands of
|
|
243
|
+
* anchors, runaway describeNode latency) could chain enough sub-timeouts to
|
|
244
|
+
* exceed the caller's `timeout` budget. The outer race guarantees the function
|
|
245
|
+
* returns within `timeout`, surfacing whatever anchors were collected so far so
|
|
246
|
+
* the upstream scrape phase can continue rather than tripping a retryable retry.
|
|
130
247
|
* @param page - The Puppeteer page to extract anchors from.
|
|
131
248
|
* @param options - Optional URL parsing options (e.g., `disableQueries`).
|
|
249
|
+
* @param timeout - Total time budget in ms for the whole extraction. Defaults to {@link DEFAULT_DOM_EVALUATION_TIMEOUT}.
|
|
132
250
|
* @returns An array of {@link AnchorData} objects for all HTTP(S) links found on the page.
|
|
133
251
|
*/
|
|
134
|
-
export async function getAnchorList(page, options) {
|
|
252
|
+
export async function getAnchorList(page, options, timeout = DEFAULT_DOM_EVALUATION_TIMEOUT) {
|
|
135
253
|
log('Getting anchors');
|
|
136
254
|
const $anchors = await page.$$('a[href], area[href]');
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
255
|
+
if ($anchors.length === 0) {
|
|
256
|
+
log('Got 0 anchors');
|
|
257
|
+
return [];
|
|
258
|
+
}
|
|
259
|
+
const collected = [];
|
|
260
|
+
let axHits = 0;
|
|
261
|
+
let textFallbacks = 0;
|
|
262
|
+
// Set after the overall race trips so in-flight `resolveAnchor` calls can
|
|
263
|
+
// short-circuit instead of continuing to consume CDP capacity and pushing
|
|
264
|
+
// late entries into the already-returned `collected` array.
|
|
265
|
+
let cancelled = false;
|
|
266
|
+
const work = async () => {
|
|
267
|
+
const client = getInternalCDPClient(page);
|
|
268
|
+
if (cancelled)
|
|
269
|
+
return;
|
|
270
|
+
const nameByBackendId = client
|
|
271
|
+
? await buildAccessibleNameMap(client, timeout)
|
|
272
|
+
: new Map();
|
|
273
|
+
if (cancelled)
|
|
274
|
+
return;
|
|
275
|
+
await Promise.all($anchors.map(async ($anchor) => {
|
|
276
|
+
if (cancelled)
|
|
277
|
+
return;
|
|
278
|
+
const resolved = await resolveAnchor($anchor, client, nameByBackendId, options, timeout);
|
|
279
|
+
if (cancelled || !resolved) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (resolved.source === 'ax') {
|
|
283
|
+
axHits++;
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
textFallbacks++;
|
|
287
|
+
}
|
|
288
|
+
collected.push(resolved.anchor);
|
|
289
|
+
}));
|
|
290
|
+
};
|
|
291
|
+
const { timeout: timedOut } = await raceWithTimeout(work, timeout);
|
|
292
|
+
cancelled = true;
|
|
293
|
+
if (timedOut) {
|
|
294
|
+
log('getAnchorList timed out after %dms; returning %d anchors collected so far', timeout, collected.length);
|
|
295
|
+
}
|
|
296
|
+
// Snapshot so post-return mutations from any in-flight Promise.all callback
|
|
297
|
+
// (already gated by `cancelled`, but not synchronously cancellable) cannot
|
|
298
|
+
// alter the array the caller now holds.
|
|
299
|
+
const result = [...collected];
|
|
300
|
+
log('Got %d anchors (%d via AX, %d via textContent)', result.length, axHits, textFallbacks);
|
|
301
|
+
dLog('Anchors are: %O', result.map((a) => a.href.href));
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Resolves a single anchor handle into an {@link AnchorData} entry, or `null`
|
|
306
|
+
* if the anchor's href is not an HTTP(S) URL.
|
|
307
|
+
*
|
|
308
|
+
* Fires `getProp(href)` and `DOM.describeNode` in parallel, then looks up the
|
|
309
|
+
* accessible name from the pre-built AX map. If the anchor is not represented
|
|
310
|
+
* in the AX map (or CDP is unavailable), falls back to a lazy `textContent`
|
|
311
|
+
* fetch — only paying the extra CDP round-trip when actually needed.
|
|
312
|
+
* @param $anchor - The Puppeteer element handle for an anchor element.
|
|
313
|
+
* @param client - The shared CDP session, or `null` if unavailable.
|
|
314
|
+
* @param nameByBackendId - Map from `backendDOMNodeId` to accessible name.
|
|
315
|
+
* @param options - URL parsing options.
|
|
316
|
+
* @param timeout - Per-CDP-call timeout in ms.
|
|
317
|
+
* @returns The resolved anchor along with the name source, or `null` when the
|
|
318
|
+
* anchor's href is not crawlable.
|
|
319
|
+
*/
|
|
320
|
+
async function resolveAnchor($anchor, client, nameByBackendId, options, timeout) {
|
|
321
|
+
try {
|
|
322
|
+
const objectId = $anchor.remoteObject().objectId;
|
|
323
|
+
const [hrefVal, backendNodeId] = await Promise.all([
|
|
324
|
+
getProp({ $el: $anchor, propName: 'href', fallback: '' }, timeout),
|
|
325
|
+
client && objectId != null
|
|
326
|
+
? resolveBackendNodeId(client, objectId, timeout)
|
|
327
|
+
: Promise.resolve(null),
|
|
328
|
+
]);
|
|
329
|
+
const href = parseUrl(hrefVal.toString(), options);
|
|
142
330
|
if (!href || !href.isHTTP) {
|
|
143
|
-
|
|
331
|
+
return null;
|
|
144
332
|
}
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
333
|
+
const axName = backendNodeId == null ? undefined : nameByBackendId.get(backendNodeId);
|
|
334
|
+
if (axName !== undefined) {
|
|
335
|
+
return { anchor: { href, textContent: axName }, source: 'ax' };
|
|
336
|
+
}
|
|
337
|
+
const textContent = await getProp({ $el: $anchor, propName: 'textContent', fallback: '' }, timeout);
|
|
338
|
+
return { anchor: { href, textContent: textContent.trim() }, source: 'text' };
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
// `remoteObject()` (and other synchronous handle accesses) can throw when
|
|
342
|
+
// the handle is disposed (page navigated mid-extraction). Drop just this
|
|
343
|
+
// anchor rather than poisoning the Promise.all over every other anchor.
|
|
344
|
+
dLog('resolveAnchor failed for an anchor: %O', error);
|
|
345
|
+
return null;
|
|
157
346
|
}
|
|
158
|
-
log('Got %d anchors', anchorList.length);
|
|
159
|
-
dLog('Anchors are: %O', anchorList.map((a) => a.href.href));
|
|
160
|
-
return anchorList;
|
|
161
347
|
}
|
|
348
|
+
const WINDOW_GLOBALS_TO_CHECK = [
|
|
349
|
+
'dataLayer',
|
|
350
|
+
'gtag',
|
|
351
|
+
'ga',
|
|
352
|
+
'_gaq',
|
|
353
|
+
'fbq',
|
|
354
|
+
'_fbq',
|
|
355
|
+
'clarity',
|
|
356
|
+
'_hjSettings',
|
|
357
|
+
'_hjid',
|
|
358
|
+
'twq',
|
|
359
|
+
'ttq',
|
|
360
|
+
'_linkedin_partner_id',
|
|
361
|
+
'pintrk',
|
|
362
|
+
'amplitude',
|
|
363
|
+
'mixpanel',
|
|
364
|
+
'analytics',
|
|
365
|
+
'heap',
|
|
366
|
+
'posthog',
|
|
367
|
+
'plausible',
|
|
368
|
+
'fathom',
|
|
369
|
+
'_paq',
|
|
370
|
+
's_account',
|
|
371
|
+
's',
|
|
372
|
+
'ym',
|
|
373
|
+
'UET',
|
|
374
|
+
'optimizely',
|
|
375
|
+
'_hsq',
|
|
376
|
+
'Sentry',
|
|
377
|
+
'Intercom',
|
|
378
|
+
'intercomSettings',
|
|
379
|
+
'drift',
|
|
380
|
+
'Tawk_API',
|
|
381
|
+
'zE',
|
|
382
|
+
'OneTrust',
|
|
383
|
+
'Cookiebot',
|
|
384
|
+
'Stripe',
|
|
385
|
+
'grecaptcha',
|
|
386
|
+
];
|
|
162
387
|
/**
|
|
163
|
-
* Extracts comprehensive
|
|
388
|
+
* Extracts comprehensive metadata from the page.
|
|
389
|
+
*
|
|
390
|
+
* Two passes happen in parallel:
|
|
391
|
+
* 1. Browser-side `collectHead()` serializes every `<meta>`, `<link>`,
|
|
392
|
+
* relevant `<script>`, `<base>`, `<noscript>`/`<iframe>` and a curated
|
|
393
|
+
* set of `window` globals into a `RawHeadEntry[]`. Node-side `classify()`
|
|
394
|
+
* then maps those entries to typed `Meta` fields using the lookup tables
|
|
395
|
+
* in `./meta/keys.ts`, with unknown entries preserved in `Meta.others`.
|
|
396
|
+
* 2. `detectTags()` runs `simple-wappalyzer` over the page HTML to produce
|
|
397
|
+
* `Meta.tags` (technology detection + real-ID extraction).
|
|
164
398
|
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
399
|
+
* The whole call is wrapped in `raceWithTimeout`. On timeout an empty `Meta`
|
|
400
|
+
* (with `title: ''` and empty required arrays/objects) is returned.
|
|
401
|
+
* @param page
|
|
402
|
+
* @param context
|
|
403
|
+
* @param timeout
|
|
404
|
+
* @example
|
|
405
|
+
* ```ts
|
|
406
|
+
* const meta = await getMeta(page, {
|
|
407
|
+
* url: 'https://example.com/',
|
|
408
|
+
* html: await page.content(),
|
|
409
|
+
* statusCode: response.status,
|
|
410
|
+
* headers: response.headers,
|
|
411
|
+
* });
|
|
412
|
+
* console.log(meta.title); // <title> text
|
|
413
|
+
* console.log(meta.og?.image); // og:image[] array
|
|
414
|
+
* console.log(meta.robots?.noindex); // parsed robots
|
|
415
|
+
* console.log(meta.tags.detected.Analytics); // Wappalyzer hits
|
|
416
|
+
* console.log(meta.tags.entries.find(e => e.provider === 'Google Analytics')?.id);
|
|
417
|
+
* ```
|
|
177
418
|
*/
|
|
178
|
-
export async function getMeta(page) {
|
|
419
|
+
export async function getMeta(page, context, timeout = DEFAULT_DOM_EVALUATION_TIMEOUT) {
|
|
179
420
|
log('Getting Meta');
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
});
|
|
186
|
-
const robots = new Set(robotsVal.split(',').map((robot) => robot.trim().toLowerCase()));
|
|
187
|
-
const meta = {
|
|
188
|
-
title: await getPropBySelector({
|
|
189
|
-
page,
|
|
190
|
-
selector: 'title',
|
|
191
|
-
propName: 'textContent',
|
|
192
|
-
fallback: '',
|
|
193
|
-
}),
|
|
194
|
-
lang: await getPropBySelector({
|
|
195
|
-
page,
|
|
196
|
-
selector: 'html',
|
|
197
|
-
propName: 'lang',
|
|
198
|
-
fallback: '',
|
|
199
|
-
}),
|
|
200
|
-
description: await getPropBySelector({
|
|
201
|
-
page,
|
|
202
|
-
selector: 'meta[name="description"]',
|
|
203
|
-
propName: 'content',
|
|
204
|
-
fallback: '',
|
|
205
|
-
}),
|
|
206
|
-
keywords: await getPropBySelector({
|
|
207
|
-
page,
|
|
208
|
-
selector: 'meta[name="keywords"]',
|
|
209
|
-
propName: 'content',
|
|
210
|
-
fallback: '',
|
|
211
|
-
}),
|
|
212
|
-
noindex: robots.has('noindex'),
|
|
213
|
-
nofollow: robots.has('nofollow'),
|
|
214
|
-
noarchive: robots.has('noarchive'),
|
|
215
|
-
canonical: await getPropBySelector({
|
|
216
|
-
page,
|
|
217
|
-
selector: 'link[rel="canonical"]',
|
|
218
|
-
propName: 'href',
|
|
219
|
-
fallback: '',
|
|
220
|
-
}),
|
|
221
|
-
alternate: await getPropBySelector({
|
|
222
|
-
page,
|
|
223
|
-
selector: 'link[rel="alternate"]',
|
|
224
|
-
propName: 'href',
|
|
225
|
-
fallback: '',
|
|
226
|
-
}),
|
|
227
|
-
'og:type': await getPropBySelector({
|
|
228
|
-
page,
|
|
229
|
-
selector: 'meta[property="og:type"]',
|
|
230
|
-
propName: 'content',
|
|
231
|
-
fallback: '',
|
|
232
|
-
}),
|
|
233
|
-
'og:title': await getPropBySelector({
|
|
234
|
-
page,
|
|
235
|
-
selector: 'meta[property="og:title"]',
|
|
236
|
-
propName: 'content',
|
|
237
|
-
fallback: '',
|
|
238
|
-
}),
|
|
239
|
-
'og:site_name': await getPropBySelector({
|
|
240
|
-
page,
|
|
241
|
-
selector: 'meta[property="og:site_name"]',
|
|
242
|
-
propName: 'content',
|
|
243
|
-
fallback: '',
|
|
244
|
-
}),
|
|
245
|
-
'og:description': await getPropBySelector({
|
|
246
|
-
page,
|
|
247
|
-
selector: 'meta[property="og:description"]',
|
|
248
|
-
propName: 'content',
|
|
249
|
-
fallback: '',
|
|
250
|
-
}),
|
|
251
|
-
'og:url': await getPropBySelector({
|
|
252
|
-
page,
|
|
253
|
-
selector: 'meta[property="og:url"]',
|
|
254
|
-
propName: 'content',
|
|
255
|
-
fallback: '',
|
|
256
|
-
}),
|
|
257
|
-
'og:image': await getPropBySelector({
|
|
258
|
-
page,
|
|
259
|
-
selector: 'meta[property="og:image"]',
|
|
260
|
-
propName: 'content',
|
|
261
|
-
fallback: '',
|
|
262
|
-
}),
|
|
263
|
-
'twitter:card': await getPropBySelector({
|
|
264
|
-
page,
|
|
265
|
-
selector: 'meta[name="twitter:card"]',
|
|
266
|
-
propName: 'content',
|
|
267
|
-
fallback: '',
|
|
268
|
-
}),
|
|
269
|
-
};
|
|
421
|
+
const { result, timeout: timedOut } = await raceWithTimeout(() => runGetMeta(page, context), timeout);
|
|
422
|
+
if (timedOut || result == null) {
|
|
423
|
+
log('Meta extraction timed out or failed; returning fallback');
|
|
424
|
+
return emptyMeta();
|
|
425
|
+
}
|
|
270
426
|
log('Got meta');
|
|
271
|
-
dLog('Meta data are: %O',
|
|
272
|
-
return
|
|
427
|
+
dLog('Meta data are: %O', result);
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
*
|
|
432
|
+
* @param page
|
|
433
|
+
* @param context
|
|
434
|
+
*/
|
|
435
|
+
async function runGetMeta(page, context) {
|
|
436
|
+
try {
|
|
437
|
+
const rawPromise = collectHeadOnPage(page);
|
|
438
|
+
const htmlPromise = context.html === undefined
|
|
439
|
+
? page.content().catch(() => '')
|
|
440
|
+
: Promise.resolve(context.html);
|
|
441
|
+
const [raw, html] = await Promise.all([rawPromise, htmlPromise]);
|
|
442
|
+
const tags = await detectTags({
|
|
443
|
+
url: context.url,
|
|
444
|
+
html,
|
|
445
|
+
...(context.statusCode === undefined ? {} : { statusCode: context.statusCode }),
|
|
446
|
+
...(context.headers === undefined ? {} : { headers: context.headers }),
|
|
447
|
+
});
|
|
448
|
+
return classify(raw, {
|
|
449
|
+
tags,
|
|
450
|
+
...(context.includeRaw ? { includeRaw: true } : {}),
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
log('runGetMeta failed: %O', error);
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
*
|
|
460
|
+
* @param page
|
|
461
|
+
*/
|
|
462
|
+
async function collectHeadOnPage(page) {
|
|
463
|
+
const raw = await page
|
|
464
|
+
.evaluate((knownGlobals) => {
|
|
465
|
+
const entries = [];
|
|
466
|
+
const html = document.documentElement;
|
|
467
|
+
entries.push({
|
|
468
|
+
kind: 'html',
|
|
469
|
+
lang: html.lang || undefined,
|
|
470
|
+
dir: html.dir || undefined,
|
|
471
|
+
xmlns: html.getAttribute('xmlns') ?? undefined,
|
|
472
|
+
prefix: html.getAttribute('prefix') ?? undefined,
|
|
473
|
+
vocab: html.getAttribute('vocab') ?? undefined,
|
|
474
|
+
typeOf: html.getAttribute('typeof') ?? undefined,
|
|
475
|
+
itemscope: html.hasAttribute('itemscope') || undefined,
|
|
476
|
+
itemtype: html.getAttribute('itemtype') ?? undefined,
|
|
477
|
+
amp: html.hasAttribute('amp') || undefined,
|
|
478
|
+
lightning: html.hasAttribute('⚡') || undefined,
|
|
479
|
+
}, { kind: 'title', content: document.title });
|
|
480
|
+
for (const base of document.querySelectorAll('base')) {
|
|
481
|
+
if (!(base instanceof HTMLBaseElement))
|
|
482
|
+
continue;
|
|
483
|
+
entries.push({
|
|
484
|
+
kind: 'base',
|
|
485
|
+
href: base.getAttribute('href') ?? undefined,
|
|
486
|
+
target: base.getAttribute('target') ?? undefined,
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
for (const meta of document.querySelectorAll('meta')) {
|
|
490
|
+
if (!(meta instanceof HTMLMetaElement))
|
|
491
|
+
continue;
|
|
492
|
+
const name = meta.getAttribute('name');
|
|
493
|
+
const property = meta.getAttribute('property');
|
|
494
|
+
const httpEquiv = meta.getAttribute('http-equiv');
|
|
495
|
+
const itemprop = meta.getAttribute('itemprop');
|
|
496
|
+
const charset = meta.getAttribute('charset');
|
|
497
|
+
const content = meta.getAttribute('content');
|
|
498
|
+
const media = meta.getAttribute('media');
|
|
499
|
+
entries.push({
|
|
500
|
+
kind: 'meta',
|
|
501
|
+
name: name ? name.toLowerCase() : undefined,
|
|
502
|
+
property: property ? property.toLowerCase() : undefined,
|
|
503
|
+
httpEquiv: httpEquiv ? httpEquiv.toLowerCase() : undefined,
|
|
504
|
+
itemprop: itemprop ?? undefined,
|
|
505
|
+
charset: charset ?? undefined,
|
|
506
|
+
content: content ?? undefined,
|
|
507
|
+
media: media ?? undefined,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
for (const link of document.querySelectorAll('link[href]')) {
|
|
511
|
+
if (!(link instanceof HTMLLinkElement))
|
|
512
|
+
continue;
|
|
513
|
+
const relRaw = link.getAttribute('rel') ?? '';
|
|
514
|
+
const rel = relRaw.toLowerCase().split(/\s+/u).filter(Boolean);
|
|
515
|
+
entries.push({
|
|
516
|
+
kind: 'link',
|
|
517
|
+
rel,
|
|
518
|
+
href: link.getAttribute('href') ?? '',
|
|
519
|
+
type: link.getAttribute('type') ?? undefined,
|
|
520
|
+
media: link.getAttribute('media') ?? undefined,
|
|
521
|
+
sizes: link.getAttribute('sizes') ?? undefined,
|
|
522
|
+
title: link.getAttribute('title') ?? undefined,
|
|
523
|
+
hreflang: link.getAttribute('hreflang') ?? undefined,
|
|
524
|
+
as: link.getAttribute('as') ?? undefined,
|
|
525
|
+
crossorigin: link.getAttribute('crossorigin') ?? undefined,
|
|
526
|
+
color: link.getAttribute('color') ?? undefined,
|
|
527
|
+
blocking: link.getAttribute('blocking') ?? undefined,
|
|
528
|
+
imagesrcset: link.getAttribute('imagesrcset') ?? undefined,
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
const STRUCTURED_TYPES = new Set([
|
|
532
|
+
'application/ld+json',
|
|
533
|
+
'speculationrules',
|
|
534
|
+
'application/json+oembed',
|
|
535
|
+
'application/xml+oembed',
|
|
536
|
+
]);
|
|
537
|
+
for (const script of document.querySelectorAll('script[type]')) {
|
|
538
|
+
if (!(script instanceof HTMLScriptElement))
|
|
539
|
+
continue;
|
|
540
|
+
const scriptType = (script.getAttribute('type') ?? '').toLowerCase();
|
|
541
|
+
if (!STRUCTURED_TYPES.has(scriptType))
|
|
542
|
+
continue;
|
|
543
|
+
const src = script.getAttribute('src') ?? undefined;
|
|
544
|
+
const text = script.textContent ?? '';
|
|
545
|
+
const inHead = !!script.closest('head');
|
|
546
|
+
const inNoscript = !!script.closest('noscript');
|
|
547
|
+
const location = inHead ? 'head' : inNoscript ? 'noscript' : 'body';
|
|
548
|
+
entries.push({
|
|
549
|
+
kind: 'script',
|
|
550
|
+
scriptType,
|
|
551
|
+
content: text || undefined,
|
|
552
|
+
src,
|
|
553
|
+
location,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
for (const iframe of document.querySelectorAll('iframe[src]')) {
|
|
557
|
+
if (!(iframe instanceof HTMLIFrameElement))
|
|
558
|
+
continue;
|
|
559
|
+
const src = iframe.getAttribute('src') ?? '';
|
|
560
|
+
if (!src)
|
|
561
|
+
continue;
|
|
562
|
+
const inHead = !!iframe.closest('head');
|
|
563
|
+
const inNoscript = !!iframe.closest('noscript');
|
|
564
|
+
const location = inHead ? 'head' : inNoscript ? 'noscript' : 'body';
|
|
565
|
+
entries.push({ kind: 'iframe', src, location });
|
|
566
|
+
}
|
|
567
|
+
const win = window;
|
|
568
|
+
const presentGlobals = knownGlobals.filter((name) => win[name] !== undefined);
|
|
569
|
+
if (presentGlobals.length > 0) {
|
|
570
|
+
entries.push({ kind: 'window-global', names: presentGlobals });
|
|
571
|
+
}
|
|
572
|
+
return entries;
|
|
573
|
+
}, WINDOW_GLOBALS_TO_CHECK)
|
|
574
|
+
.catch(() => []);
|
|
575
|
+
return raw;
|
|
273
576
|
}
|