Spaces:
Build error
Build error
File size: 48,794 Bytes
3b3a026 89d6d49 7ee2c32 3b3a026 67d4a9f ff595c2 3b3a026 89d6d49 c5abdf8 23a3b80 8597daa 3b3a026 3dc902e d2bebec 7ee2c32 89d6d49 a8e0628 b3fb4c5 a8e0628 b3fb4c5 a211366 94e6538 6e05ea2 94e6538 7af2bde 94e6538 ff595c2 ebc0900 94e6538 6e05ea2 a211366 94e6538 d3f3a85 b3fb4c5 33e14e5 1bcb5a7 6fb5df9 77c8480 f7dbadf 94e6538 7ee2c32 a8e0628 53821d0 a8e0628 7ee2c32 67d4a9f 94a7205 6f37e5d 33e14e5 165cce6 a9936d3 de50c93 7e6c2fc ebc0900 22647a0 2606c44 23a3b80 94e6538 23a3b80 7ee2c32 22647a0 77c8480 22647a0 3dc902e 77c8480 22647a0 77c8480 7af2bde 77c8480 ff595c2 77c8480 6fb5df9 77c8480 6fb5df9 f4f189c c19ca21 0a33207 f4f189c 6fb5df9 77c8480 6fb5df9 77c8480 6fb5df9 77c8480 102a168 f7dbadf ff595c2 f7dbadf ff595c2 77c8480 ff595c2 77c8480 6147a28 77c8480 3bb7315 77c8480 102a168 77c8480 6fb5df9 f7dbadf 77c8480 7af2bde a471a61 77c8480 22647a0 ff595c2 22647a0 77c8480 f7dbadf 3b3a026 f7dbadf 3b3a026 f7dbadf dd76cf3 b9ad4fa f7dbadf 3b3a026 89d6d49 df71c9a 89d6d49 df71c9a 6a58de5 df71c9a 2991e30 6b1bfda df71c9a f7dbadf 3b3a026 9a514cd f0668a9 8597daa 33e14e5 66db317 8597daa 23a3b80 33e14e5 89d6d49 6e78e38 df71c9a f0c3a9b df71c9a f0c3a9b df71c9a f0c3a9b df71c9a 89d6d49 6e78e38 5ed3f90 89d6d49 94e6538 528b3e5 94e6538 89d6d49 6a58de5 ff76124 cf24d84 3dc902e 12ba1bc 3dc902e b3fb4c5 dbeb695 9503382 dbeb695 d538726 5ed3f90 89d6d49 f0c3a9b 6f65083 89d6d49 2991e30 dc4605d 6b1bfda 89d6d49 23a3b80 528b3e5 23a3b80 528b3e5 3b3a026 9a514cd 3b3a026 9a514cd 23a3b80 df71c9a 6e05ea2 c5abdf8 f0c3a9b c5abdf8 3b3a026 f0c3a9b c5abdf8 94e6538 89d6d49 6b1bfda 5ed3f90 dbeb695 664d4b1 a211366 7ee2c32 94e6538 d8ad1cb 77c8480 ed9e9f4 bfc6d67 9e02080 43dee08 1bcb5a7 0a09aeb 43dee08 9a514cd 43dee08 0a09aeb ed9e9f4 607407f ed9e9f4 db27b38 e2a187d 4ca627c e2a187d 4ca627c e2a187d 339af19 d2bebec f0668a9 ed9e9f4 43dee08 0a09aeb 6a58de5 43dee08 6a58de5 0a09aeb 43dee08 d2bebec 0a09aeb 43dee08 ed9e9f4 5171e5f 3b3a026 5171e5f 9a514cd ed9e9f4 3b3a026 ed9e9f4 bfc6d67 22647a0 ff595c2 22647a0 ff595c2 22647a0 ff595c2 3bb7315 22647a0 ff595c2 22647a0 ff595c2 22647a0 ff595c2 22647a0 bfc6d67 89d6d49 df71c9a 23a3b80 df71c9a 6a58de5 df71c9a 89d6d49 df71c9a a8e0628 df71c9a ff595c2 df71c9a a8e0628 df71c9a 23a3b80 df71c9a 22647a0 df71c9a 3b3a026 df71c9a 6a58de5 df71c9a 23a3b80 78c8444 7ee2c32 94e6538 d3f3a85 607407f 6e05ea2 df71c9a 8597daa 6a58de5 607407f 23a3b80 6e05ea2 607407f 23a3b80 ff595c2 23a3b80 8597daa 23a3b80 8597daa d0e20cc 8597daa 23a3b80 8597daa ff595c2 8597daa 23a3b80 8597daa ff595c2 23a3b80 8597daa 23a3b80 8597daa ff595c2 8597daa d0e20cc 23a3b80 8597daa 23a3b80 8597daa 23a3b80 22647a0 23a3b80 22647a0 23a3b80 22647a0 df71c9a 9ac4060 23a3b80 ebc0900 23a3b80 ebc0900 de50c93 9a514cd 23a3b80 de50c93 9a514cd 23a3b80 de50c93 9a514cd de50c93 23a3b80 c7860e6 67d4a9f c7860e6 67d4a9f c7860e6 67d4a9f 3b3a026 67d4a9f 94e6538 23a3b80 165cce6 23a3b80 2606c44 94e6538 89d6d49 9e02080 33ca164 89d6d49 0a33207 f7dbadf 1bcb5a7 0a33207 6fb5df9 89d6d49 9e02080 89d6d49 43dee08 6a58de5 43dee08 94e6538 23a3b80 7e6c2fc a9936d3 ec7c2ab 7e6c2fc 23a3b80 7e6c2fc d2afa9d 33ca164 d2afa9d 33ca164 d2afa9d 22647a0 7e6c2fc 78c8444 ec7c2ab 3b3a026 ec7c2ab e2aed6d ec7c2ab 3b3a026 df127d0 78c8444 df127d0 ec7c2ab 22647a0 d2afa9d 94e6538 23a3b80 ec7c2ab d2afa9d ec7c2ab 33ca164 3b3a026 ec7c2ab 7bc70a1 6f65083 94e6538 89d6d49 7ee2c32 89d6d49 7bc70a1 23a3b80 33e14e5 0a09aeb 1bcb5a7 d2afa9d ec7c2ab 6e05ea2 89d6d49 23a3b80 9fbd751 7ee2c32 f6a183f 6e05ea2 23a3b80 6e05ea2 7ee2c32 0a09aeb d2afa9d 89d6d49 d2afa9d 89d6d49 6a58de5 d2afa9d 94e6538 df71c9a 94e6538 de22127 89d6d49 50ed9cc 3dc902e 6f65083 77c8480 89d6d49 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 | import _ from 'lodash';
import { isIP } from 'net';
import { readFile } from 'fs/promises';
import fs from 'fs';
import { container, singleton } from 'tsyringe';
import type { Browser, CookieParam, GoToOptions, HTTPRequest, HTTPResponse, Page, Viewport } from 'puppeteer';
import type { Cookie } from 'set-cookie-parser';
import puppeteer, { TimeoutError } from 'puppeteer';
import { Defer, Deferred } from 'civkit/defer';
import { AssertionFailureError, ParamValidationError } from 'civkit/civ-rpc';
import { AsyncService } from 'civkit/async-service';
import { FancyFile } from 'civkit/fancy-file';
import { delay } from 'civkit/timeout';
import { SecurityCompromiseError, ServiceCrashedError, ServiceNodeResourceDrainError } from '../shared/lib/errors';
import { CurlControl } from './curl';
import { BlackHoleDetector } from './blackhole-detector';
import { AsyncLocalContext } from './async-context';
import { GlobalLogger } from './logger';
import { minimalStealth } from './minimal-stealth';
const tldExtract = require('tld-extract');
const READABILITY_JS = fs.readFileSync(require.resolve('@mozilla/readability/Readability.js'), 'utf-8');
export interface ImgBrief {
src: string;
loaded?: boolean;
width?: number;
height?: number;
naturalWidth?: number;
naturalHeight?: number;
alt?: string;
}
export interface ReadabilityParsed {
title: string;
content: string;
textContent: string;
length: number;
excerpt: string;
byline: string;
dir: string;
siteName: string;
lang: string;
publishedTime: string;
}
export interface PageSnapshot {
title: string;
description?: string;
href: string;
rebase?: string;
html: string;
htmlSignificantlyModifiedByJs?: boolean;
shadowExpanded?: string;
text: string;
status?: number;
statusText?: string;
parsed?: Partial<ReadabilityParsed> | null;
screenshot?: Buffer;
pageshot?: Buffer;
imgs?: ImgBrief[];
pdfs?: string[];
maxElemDepth?: number;
elemCount?: number;
childFrames?: PageSnapshot[];
isIntermediate?: boolean;
isFromCache?: boolean;
lastMutationIdle?: number;
lastContentResourceLoaded?: number;
lastMediaResourceLoaded?: number;
}
export interface ExtendedSnapshot extends PageSnapshot {
links: [string, string][];
imgs: ImgBrief[];
}
export interface ScrappingOptions {
proxyUrl?: string;
cookies?: Cookie[];
favorScreenshot?: boolean;
waitForSelector?: string | string[];
minIntervalMs?: number;
overrideUserAgent?: string;
timeoutMs?: number;
locale?: string;
referer?: string;
extraHeaders?: Record<string, string>;
injectFrameScripts?: string[];
injectPageScripts?: string[];
viewport?: Viewport;
proxyResources?: boolean;
sideLoad?: {
impersonate: {
[url: string]: {
status: number;
headers: { [k: string]: string | string[]; };
contentType?: string;
body?: FancyFile;
};
};
proxyOrigin: { [origin: string]: string; };
};
}
const SIMULATE_SCROLL = `
(function () {
function createIntersectionObserverEntry(target, isIntersecting, timestamp) {
const targetRect = target.getBoundingClientRect();
const record = {
target,
isIntersecting,
time: timestamp,
// If intersecting, intersectionRect matches boundingClientRect
// If not intersecting, intersectionRect is empty (0x0)
intersectionRect: isIntersecting
? targetRect
: new DOMRectReadOnly(0, 0, 0, 0),
// Current bounding client rect of the target
boundingClientRect: targetRect,
// Intersection ratio is either 0 (not intersecting) or 1 (fully intersecting)
intersectionRatio: isIntersecting ? 1 : 0,
// Root bounds (viewport in our case)
rootBounds: new DOMRectReadOnly(
0,
0,
window.innerWidth,
window.innerHeight
)
};
Object.setPrototypeOf(record, window.IntersectionObserverEntry.prototype);
return record;
}
function cloneIntersectionObserverEntry(entry) {
const record = {
target: entry.target,
isIntersecting: entry.isIntersecting,
time: entry.time,
intersectionRect: entry.intersectionRect,
boundingClientRect: entry.boundingClientRect,
intersectionRatio: entry.intersectionRatio,
rootBounds: entry.rootBounds
};
Object.setPrototypeOf(record, window.IntersectionObserverEntry.prototype);
return record;
}
const orig = window.IntersectionObserver;
const kCallback = Symbol('callback');
const kLastEntryMap = Symbol('lastEntryMap');
const liveObservers = new Map();
class MangledIntersectionObserver extends orig {
constructor(callback, options) {
super((entries, observer) => {
const lastEntryMap = observer[kLastEntryMap];
const lastEntry = entries[entries.length - 1];
lastEntryMap.set(lastEntry.target, lastEntry);
return callback(entries, observer);
}, options);
this[kCallback] = callback;
this[kLastEntryMap] = new WeakMap();
liveObservers.set(this, new Set());
}
disconnect() {
liveObservers.get(this)?.clear();
liveObservers.delete(this);
return super.disconnect();
}
observe(target) {
const observer = liveObservers.get(this);
observer?.add(target);
return super.observe(target);
}
unobserve(target) {
const observer = liveObservers.get(this);
observer?.delete(target);
return super.unobserve(target);
}
}
Object.defineProperty(MangledIntersectionObserver, 'name', { value: 'IntersectionObserver', writable: false });
window.IntersectionObserver = MangledIntersectionObserver;
function simulateScroll() {
for (const [observer, targets] of liveObservers.entries()) {
const t0 = performance.now();
for (const target of targets) {
const entry = createIntersectionObserverEntry(target, true, t0);
observer[kCallback]([entry], observer);
setTimeout(() => {
const t1 = performance.now();
const lastEntry = observer[kLastEntryMap].get(target);
if (!lastEntry) {
return;
}
const entry2 = { ...cloneIntersectionObserverEntry(lastEntry), time: t1 };
observer[kCallback]([entry2], observer);
});
}
}
}
window.simulateScroll = simulateScroll;
})();
`;
const MUTATION_IDLE_WATCH = `
(function () {
let timeout;
const sendMsg = ()=> {
document.dispatchEvent(new CustomEvent('mutationIdle'));
};
const cb = () => {
if (timeout) {
clearTimeout(timeout);
timeout = setTimeout(sendMsg, 200);
}
};
const mutationObserver = new MutationObserver(cb);
document.addEventListener('DOMContentLoaded', () => {
mutationObserver.observe(document.documentElement, {
childList: true,
subtree: true,
});
timeout = setTimeout(sendMsg, 200);
}, { once: true })
})();
`;
const SCRIPT_TO_INJECT_INTO_FRAME = `
${READABILITY_JS}
${SIMULATE_SCROLL}
${MUTATION_IDLE_WATCH}
(${minimalStealth.toString()})();
(function(){
function briefImgs(elem) {
const imageTags = Array.from((elem || document).querySelectorAll('img[src],img[data-src]'));
return imageTags.map((x)=> {
let linkPreferredSrc = x.src;
if (linkPreferredSrc.startsWith('data:')) {
if (typeof x.dataset?.src === 'string' && !x.dataset.src.startsWith('data:')) {
linkPreferredSrc = x.dataset.src;
}
}
return {
src: new URL(linkPreferredSrc, document.baseURI).toString(),
loaded: x.complete,
width: x.width,
height: x.height,
naturalWidth: x.naturalWidth,
naturalHeight: x.naturalHeight,
alt: x.alt || x.title,
};
});
}
function getMaxDepthAndElemCountUsingTreeWalker(root=document.documentElement) {
let maxDepth = 0;
let currentDepth = 0;
let elementCount = 0;
const treeWalker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
(node) => {
const nodeName = node.nodeName?.toLowerCase();
return (nodeName === 'svg') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
},
false
);
while (true) {
maxDepth = Math.max(maxDepth, currentDepth);
elementCount++; // Increment the count for the current node
if (treeWalker.firstChild()) {
currentDepth++;
} else {
while (!treeWalker.nextSibling() && currentDepth > 0) {
treeWalker.parentNode();
currentDepth--;
}
if (currentDepth <= 0) {
break;
}
}
}
return {
maxDepth: maxDepth + 1,
elementCount: elementCount
};
}
function cloneAndExpandShadowRoots(rootElement = document.documentElement) {
// Create a shallow clone of the root element
const clone = rootElement.cloneNode(false);
// Function to process an element and its shadow root
function processShadowRoot(original, cloned) {
if (original.shadowRoot && original.shadowRoot.mode === 'open') {
shadowDomPresents = true;
const shadowContent = document.createDocumentFragment();
// Clone shadow root content normally
original.shadowRoot.childNodes.forEach(childNode => {
const clonedNode = childNode.cloneNode(true);
shadowContent.appendChild(clonedNode);
});
// Handle slots
const slots = shadowContent.querySelectorAll('slot');
slots.forEach(slot => {
const slotName = slot.getAttribute('name') || '';
const assignedElements = original.querySelectorAll(
slotName ? \`[slot="\${slotName}"]\` : ':not([slot])'
);
if (assignedElements.length > 0) {
const slotContent = document.createDocumentFragment();
assignedElements.forEach(el => {
const clonedEl = el.cloneNode(true);
slotContent.appendChild(clonedEl);
});
slot.parentNode.replaceChild(slotContent, slot);
} else if (!slotName) {
// Keep default slot content
// No need to do anything as it's already cloned
}
});
cloned.appendChild(shadowContent);
}
}
// Use a TreeWalker on the original root to clone the entire structure
const treeWalker = document.createTreeWalker(
rootElement,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
);
const elementMap = new Map([[rootElement, clone]]);
let currentNode;
while (currentNode = treeWalker.nextNode()) {
const parentClone = elementMap.get(currentNode.parentNode);
const clonedNode = currentNode.cloneNode(false);
parentClone.appendChild(clonedNode);
if (currentNode.nodeType === Node.ELEMENT_NODE) {
elementMap.set(currentNode, clonedNode);
processShadowRoot(currentNode, clonedNode);
}
}
return clone;
}
function shadowDomPresent(rootElement = document.documentElement) {
const elems = rootElement.querySelectorAll('*');
for (const x of elems) {
if (x.shadowRoot && x.shadowRoot.mode === 'open') {
return true;
}
}
return false;
}
let lastMutationIdle = 0;
let initialAnalytics;
document.addEventListener('mutationIdle', ()=> lastMutationIdle = Date.now());
function giveSnapshot(stopActiveSnapshot, overrideDomAnalysis) {
if (stopActiveSnapshot) {
window.haltSnapshot = true;
}
let parsed;
try {
parsed = new Readability(document.cloneNode(true)).parse();
} catch (err) {
void 0;
}
const domAnalysis = overrideDomAnalysis || getMaxDepthAndElemCountUsingTreeWalker(document.documentElement);
initialAnalytics ??= domAnalysis;
const thisElemCount = domAnalysis.elementCount;
const initialElemCount = initialAnalytics.elementCount;
Math.abs(thisElemCount - initialElemCount) / (initialElemCount + Number.EPSILON)
const r = {
title: document.title,
description: document.head?.querySelector('meta[name="description"]')?.getAttribute('content') ?? '',
href: document.location.href,
html: document.documentElement?.outerHTML,
htmlSignificantlyModifiedByJs: Boolean(Math.abs(thisElemCount - initialElemCount) / (initialElemCount + Number.EPSILON) > 0.05),
text: document.body?.innerText,
shadowExpanded: shadowDomPresent() ? cloneAndExpandShadowRoots()?.outerHTML : undefined,
parsed: parsed,
imgs: [],
maxElemDepth: domAnalysis.maxDepth,
elemCount: domAnalysis.elementCount,
lastMutationIdle,
};
if (document.baseURI !== r.href) {
r.rebase = document.baseURI;
}
r.imgs = briefImgs();
return r;
}
function waitForSelector(selectorText) {
return new Promise((resolve) => {
const existing = document.querySelector(selectorText);
if (existing) {
resolve(existing);
return;
}
const observer = new MutationObserver(() => {
const elem = document.querySelector(selectorText);
if (elem) {
resolve(document.querySelector(selectorText));
observer.disconnect();
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
window.getMaxDepthAndElemCountUsingTreeWalker = getMaxDepthAndElemCountUsingTreeWalker;
window.waitForSelector = waitForSelector;
window.giveSnapshot = giveSnapshot;
window.briefImgs = briefImgs;
})();
`;
const documentResourceTypes = new Set([
'document', 'script', 'xhr', 'fetch', 'prefetch', 'eventsource', 'websocket', 'preflight'
]);
const mediaResourceTypes = new Set([
'stylesheet', 'image', 'font', 'media'
]);
class PageReqCtrlKit {
reqSet: Set<HTTPRequest> = new Set();
blockers: Deferred<void>[] = [];
lastResourceLoadedAt: number = 0;
lastContentResourceLoadedAt: number = 0;
lastMediaResourceLoadedAt: number = 0;
constructor(
public concurrency: number,
) {
if (isNaN(concurrency) || concurrency < 1) {
throw new AssertionFailureError(`Invalid concurrency: ${concurrency}`);
}
}
onNewRequest(req: HTTPRequest) {
this.reqSet.add(req);
if (this.reqSet.size <= this.concurrency) {
return Promise.resolve();
}
const deferred = Defer();
this.blockers.push(deferred);
return deferred.promise;
}
onFinishRequest(req: HTTPRequest) {
this.reqSet.delete(req);
const deferred = this.blockers.shift();
deferred?.resolve();
const now = Date.now();
this.lastResourceLoadedAt = now;
// Beware req being undefined
// https://pptr.dev/api/puppeteer.pageevent#:~:text=For%20certain%20requests%2C%20might%20contain%20undefined.
const typ = req?.resourceType();
if (!typ) {
return;
}
if (documentResourceTypes.has(typ)) {
this.lastContentResourceLoadedAt = now;
}
if (mediaResourceTypes.has(typ)) {
this.lastMediaResourceLoadedAt = now;
}
}
}
@singleton()
export class PuppeteerControl extends AsyncService {
_sn = 0;
browser!: Browser;
logger = this.globalLogger.child({ service: this.constructor.name });
__loadedPage: Page[] = [];
finalizerMap = new WeakMap<Page, ReturnType<typeof setTimeout>>();
snMap = new WeakMap<Page, number>();
livePages = new Set<Page>();
pagePhase = new WeakMap<Page, 'idle' | 'active' | 'background'>();
lastPageCratedAt: number = 0;
ua: string = '';
effectiveUA: string = '';
concurrentRequestsPerPage: number = 32;
pageReqCtrl = new WeakMap<Page, PageReqCtrlKit>();
lastReqSentAt: number = 0;
circuitBreakerHosts: Set<string> = new Set();
lifeCycleTrack = new WeakMap();
constructor(
protected globalLogger: GlobalLogger,
protected asyncLocalContext: AsyncLocalContext,
protected curlControl: CurlControl,
protected blackHoleDetector: BlackHoleDetector,
) {
super(...arguments);
this.setMaxListeners(Infinity);
let crippledTimes = 0;
this.on('crippled', () => {
crippledTimes += 1;
this.__loadedPage.length = 0;
this.livePages.clear();
if (crippledTimes > 5) {
process.nextTick(() => {
this.emit('error', new Error('Browser crashed too many times, quitting...'));
// process.exit(1);
});
}
});
}
override async init() {
await this.dependencyReady();
if (process.env.NODE_ENV?.includes('dry-run')) {
this.emit('ready');
return;
}
if (this.browser) {
if (this.browser.connected) {
await this.browser.close();
} else {
this.browser.process()?.kill('SIGKILL');
}
}
this.browser = await puppeteer.launch({
timeout: 10_000,
headless: !Boolean(process.env.DEBUG_BROWSER),
executablePath: process.env.OVERRIDE_CHROME_EXECUTABLE_PATH,
args: [
'--disable-dev-shm-usage',
'--disable-blink-features=AutomationControlled'
]
}).catch((err: any) => {
this.logger.error(`Unknown firebase issue, just die fast.`, { err });
process.nextTick(() => {
this.emit('error', err);
// process.exit(1);
});
return Promise.reject(err);
});
this.browser.once('disconnected', () => {
this.logger.warn(`Browser disconnected`);
if (this.browser) {
this.emit('crippled');
}
process.nextTick(() => this.serviceReady());
});
this.ua = await this.browser.userAgent();
this.logger.info(`Browser launched: ${this.browser.process()?.pid}, ${this.ua}`);
this.effectiveUA = this.ua.replace(/Headless/i, '').replace('Mozilla/5.0 (X11; Linux x86_64)', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
this.curlControl.impersonateChrome(this.effectiveUA);
await this.newPage('beware_deadlock').then((r) => this.__loadedPage.push(r));
this.emit('ready');
}
protected getRpsControlKit(page: Page) {
let kit = this.pageReqCtrl.get(page);
if (!kit) {
kit = new PageReqCtrlKit(this.concurrentRequestsPerPage);
this.pageReqCtrl.set(page, kit);
}
return kit;
}
async newPage(bewareDeadLock: any = false) {
if (!bewareDeadLock) {
await this.serviceReady();
}
const sn = this._sn++;
let page;
try {
const dedicatedContext = await this.browser.createBrowserContext();
page = await dedicatedContext.newPage();
} catch (err: any) {
this.logger.warn(`Failed to create page ${sn}`, { err });
this.browser.process()?.kill('SIGKILL');
throw new ServiceNodeResourceDrainError(`This specific worker node failed to open a new page, try again.`);
}
const preparations = [];
preparations.push(page.setUserAgent(this.effectiveUA));
// preparations.push(page.setUserAgent(`Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)`));
// preparations.push(page.setUserAgent(`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.0; +https://openai.com/gptbot)`));
preparations.push(page.setBypassCSP(true));
preparations.push(page.setViewport({ width: 1024, height: 1024 }));
preparations.push(page.exposeFunction('reportSnapshot', (snapshot: PageSnapshot) => {
if (snapshot.href === 'about:blank') {
return;
}
page.emit('snapshot', snapshot);
}));
preparations.push(page.exposeFunction('setViewport', (viewport: Viewport | null) => {
page.setViewport(viewport).catch(() => undefined);
}));
preparations.push(page.evaluateOnNewDocument(SCRIPT_TO_INJECT_INTO_FRAME));
preparations.push(page.setRequestInterception(true));
await Promise.all(preparations);
await page.goto('about:blank', { waitUntil: 'domcontentloaded' });
const domainSet = new Set<string>();
let reqCounter = 0;
let t0: number | undefined;
let halt = false;
page.on('request', async (req) => {
reqCounter++;
if (halt) {
return req.abort('blockedbyclient', 1000);
}
const requestUrl = req.url();
if (!requestUrl.startsWith('http:') && !requestUrl.startsWith('https:') && !requestUrl.startsWith('chrome-extension:') && requestUrl !== 'about:blank') {
return req.abort('blockedbyclient', 1000);
}
t0 ??= Date.now();
const parsedUrl = new URL(requestUrl);
if (isIP(parsedUrl.hostname)) {
domainSet.add(parsedUrl.hostname);
} else {
try {
const tldParsed = tldExtract(requestUrl);
domainSet.add(tldParsed.domain);
} catch (_err) {
domainSet.add(parsedUrl.hostname);
}
}
if (this.circuitBreakerHosts.has(parsedUrl.hostname.toLowerCase())) {
page.emit('abuse', { url: requestUrl, page, sn, reason: `Abusive request: ${requestUrl}` });
return req.abort('blockedbyclient', 1000);
}
if (
parsedUrl.hostname === 'localhost' ||
parsedUrl.hostname.startsWith('127.')
) {
page.emit('abuse', { url: requestUrl, page, sn, reason: `Suspicious action: Request to localhost: ${requestUrl}` });
return req.abort('blockedbyclient', 1000);
}
const dt = Math.ceil((Date.now() - t0) / 1000);
const rps = reqCounter / dt;
// console.log(`rps: ${rps}`);
const pagePhase = this.pagePhase.get(page);
if (pagePhase === 'background') {
if (rps > 10 || reqCounter > 1000) {
halt = true;
return req.abort('blockedbyclient', 1000);
}
}
if (reqCounter > 1000) {
if (rps > 60 || reqCounter > 2000) {
page.emit('abuse', { url: requestUrl, page, sn, reason: `DDoS attack suspected: Too many requests` });
halt = true;
return req.abort('blockedbyclient', 1000);
}
}
if (domainSet.size > 200) {
page.emit('abuse', { url: requestUrl, page, sn, reason: `DDoS attack suspected: Too many domains` });
halt = true;
return req.abort('blockedbyclient', 1000);
}
if (requestUrl.startsWith('http')) {
const kit = this.getRpsControlKit(page);
await kit.onNewRequest(req);
}
if (req.isInterceptResolutionHandled()) {
return;
};
const continueArgs = req.continueRequestOverrides
? [req.continueRequestOverrides(), 0] as const
: [];
return req.continue(continueArgs[0], continueArgs[1]);
});
const reqFinishHandler = (req: HTTPRequest) => {
const kit = this.getRpsControlKit(page);
kit.onFinishRequest(req);
};
page.on('requestfinished', reqFinishHandler);
page.on('requestfailed', reqFinishHandler);
page.on('requestservedfromcache', reqFinishHandler);
await page.evaluateOnNewDocument(`
(function () {
if (window.self === window.top) {
let lastAnalytics;
let lastReportedAt = 0;
const handlePageLoad = () => {
const now = Date.now();
const dt = now - lastReportedAt;
const previousAnalytics = lastAnalytics;
const thisAnalytics = getMaxDepthAndElemCountUsingTreeWalker();
let dElem = 0;
if (window.haltSnapshot) {
return;
}
const thisElemCount = thisAnalytics.elementCount;
if (previousAnalytics) {
const previousElemCount = previousAnalytics.elementCount;
const delta = Math.abs(thisElemCount - previousElemCount);
dElem = delta /(previousElemCount + Number.EPSILON);
}
if (dt < 1200 && dElem < 0.05) {
return;
}
lastAnalytics = thisAnalytics;
lastReportedAt = now;
const r = giveSnapshot(false, lastAnalytics);
window.reportSnapshot(r);
};
document.addEventListener('readystatechange', ()=> {
if (document.readyState === 'interactive') {
handlePageLoad();
}
});
document.addEventListener('load', handlePageLoad);
window.addEventListener('load', handlePageLoad);
document.addEventListener('DOMContentLoaded', handlePageLoad);
document.addEventListener('mutationIdle', handlePageLoad);
}
document.addEventListener('DOMContentLoaded', ()=> window.simulateScroll(), { once: true });
})();
`);
this.snMap.set(page, sn);
this.logger.debug(`Page ${sn} created.`);
this.lastPageCratedAt = Date.now();
this.livePages.add(page);
this.pagePhase.set(page, 'idle');
return page;
}
async getNextPage() {
let thePage: Page | undefined;
if (this.__loadedPage.length) {
thePage = this.__loadedPage.shift();
if (this.__loadedPage.length <= 1) {
process.nextTick(() => {
this.newPage()
.then((r) => this.__loadedPage.push(r))
.catch((err) => {
this.logger.warn(`Failed to load new page ahead of time`, { err });
});
});
}
}
if (!thePage) {
thePage = await this.newPage();
}
const timer = setTimeout(() => {
this.logger.warn(`Page is not allowed to live past 5 minutes, ditching page ${this.snMap.get(thePage!)}...`);
this.ditchPage(thePage!);
}, 300 * 1000);
this.finalizerMap.set(thePage, timer);
return thePage;
}
async ditchPage(page: Page) {
if (this.finalizerMap.has(page)) {
clearTimeout(this.finalizerMap.get(page)!);
this.finalizerMap.delete(page);
}
if (page.isClosed()) {
return;
}
const sn = this.snMap.get(page);
this.logger.debug(`Closing page ${sn}`);
await Promise.race([
(async () => {
const ctx = page.browserContext();
try {
await page.close();
} finally {
await ctx.close();
}
})(),
delay(5000)
]).catch((err) => {
this.logger.error(`Failed to destroy page ${sn}`, { err });
});
this.livePages.delete(page);
this.pagePhase.delete(page);
}
async *scrap(parsedUrl: URL, options: ScrappingOptions = {}): AsyncGenerator<PageSnapshot | undefined> {
// parsedUrl.search = '';
const url = parsedUrl.toString();
let snapshot: PageSnapshot | undefined;
let screenshot: Buffer | undefined;
let pageshot: Buffer | undefined;
const pdfUrls: string[] = [];
let navigationResponse: HTTPResponse | undefined;
const page = await this.getNextPage();
this.lifeCycleTrack.set(page, this.asyncLocalContext.ctx);
this.pagePhase.set(page, 'active');
page.on('response', (resp) => {
this.blackHoleDetector.itWorked();
const req = resp.request();
if (req.frame() === page.mainFrame() && req.isNavigationRequest()) {
navigationResponse = resp;
}
if (!resp.ok()) {
return;
}
const headers = resp.headers();
const url = resp.url();
const contentType = headers['content-type'];
if (contentType?.toLowerCase().includes('application/pdf')) {
pdfUrls.push(url);
}
});
page.on('request', async (req) => {
if (req.isInterceptResolutionHandled()) {
return;
};
const reqUrlParsed = new URL(req.url());
if (!reqUrlParsed.protocol.startsWith('http')) {
const overrides = req.continueRequestOverrides();
return req.continue(overrides, 0);
}
const typ = req.resourceType();
if (typ === 'media') {
// Non-cooperative answer to block all media requests.
return req.abort('blockedbyclient');
}
if (!options.proxyResources) {
const isDocRequest = ['document', 'xhr', 'fetch', 'websocket', 'prefetch', 'eventsource', 'ping'].includes(typ);
if (!isDocRequest) {
if (options.extraHeaders) {
const overrides = req.continueRequestOverrides();
const continueArgs = [{
...overrides,
headers: {
...req.headers(),
...overrides?.headers,
...options.extraHeaders,
}
}, 1] as const;
return req.continue(continueArgs[0], continueArgs[1]);
}
const overrides = req.continueRequestOverrides();
return req.continue(overrides, 0);
}
}
const sideload = options.sideLoad;
const impersonate = sideload?.impersonate[reqUrlParsed.href];
if (impersonate) {
let body;
if (impersonate.body) {
body = await readFile(await impersonate.body.filePath);
if (req.isInterceptResolutionHandled()) {
return;
}
}
return req.respond({
status: impersonate.status,
headers: impersonate.headers,
contentType: impersonate.contentType,
body: body ? Uint8Array.from(body) : undefined,
}, 999);
}
const proxy = options.proxyUrl || sideload?.proxyOrigin?.[reqUrlParsed.origin];
const ctx = this.lifeCycleTrack.get(page);
if (proxy && ctx) {
return await this.asyncLocalContext.bridge(ctx, async () => {
try {
const curled = await this.curlControl.sideLoad(reqUrlParsed, {
...options,
method: req.method(),
body: req.postData(),
extraHeaders: {
...req.headers(),
...options.extraHeaders,
},
proxyUrl: proxy
});
if (req.isInterceptResolutionHandled()) {
return;
};
if (curled.chain.length === 1) {
if (!curled.file) {
return req.respond({
status: curled.status,
headers: _.omit(curled.headers, 'result'),
contentType: curled.contentType,
}, 3);
}
const body = await readFile(await curled.file.filePath);
if (req.isInterceptResolutionHandled()) {
return;
};
return req.respond({
status: curled.status,
headers: _.omit(curled.headers, 'result'),
contentType: curled.contentType,
body: Uint8Array.from(body),
}, 3);
}
options.sideLoad ??= curled.sideLoadOpts;
_.merge(options.sideLoad, curled.sideLoadOpts);
const firstReq = curled.chain[0];
return req.respond({
status: firstReq.result!.code,
headers: _.omit(firstReq, 'result'),
}, 3);
} catch (err: any) {
this.logger.warn(`Failed to sideload browser request ${reqUrlParsed.origin}`, { href: reqUrlParsed.href, err, proxy });
}
if (req.isInterceptResolutionHandled()) {
return;
};
const overrides = req.continueRequestOverrides();
const continueArgs = [{
...overrides,
headers: {
...req.headers(),
...overrides?.headers,
...options.extraHeaders,
}
}, 1] as const;
return req.continue(continueArgs[0], continueArgs[1]);
});
}
if (req.isInterceptResolutionHandled()) {
return;
};
const overrides = req.continueRequestOverrides();
const continueArgs = [{
...overrides,
headers: {
...req.headers(),
...overrides?.headers,
...options.extraHeaders,
}
}, 1] as const;
return req.continue(continueArgs[0], continueArgs[1]);
});
let pageScriptEvaluations: Promise<unknown>[] = [];
let frameScriptEvaluations: Promise<unknown>[] = [];
if (options.injectPageScripts?.length) {
page.on('framenavigated', (frame) => {
if (frame !== page.mainFrame()) {
return;
}
pageScriptEvaluations.push(
Promise.allSettled(options.injectPageScripts!.map((x) => frame.evaluate(x).catch((err) => {
this.logger.warn(`Error in evaluation of page scripts`, { err });
})))
);
});
}
if (options.injectFrameScripts?.length) {
page.on('framenavigated', (frame) => {
frameScriptEvaluations.push(
Promise.allSettled(options.injectFrameScripts!.map((x) => frame.evaluate(x).catch((err) => {
this.logger.warn(`Error in evaluation of frame scripts`, { err });
})))
);
});
}
const sn = this.snMap.get(page);
this.logger.info(`Page ${sn}: Scraping ${url}`, { url });
if (options.locale) {
// Add headers via request interception to walk around this bug
// https://github.com/puppeteer/puppeteer/issues/10235
// await page.setExtraHTTPHeaders({
// 'Accept-Language': options.locale
// });
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, "language", {
get: function () {
return options.locale;
}
});
Object.defineProperty(navigator, "languages", {
get: function () {
return [options.locale];
}
});
});
}
if (options.cookies) {
const mapped = options.cookies.map((x) => {
const draft: CookieParam = {
name: x.name,
value: encodeURIComponent(x.value),
secure: x.secure,
domain: x.domain,
path: x.path,
expires: x.expires ? Math.floor(x.expires.valueOf() / 1000) : undefined,
sameSite: x.sameSite as any,
};
if (!draft.expires && x.maxAge) {
draft.expires = Math.floor(Date.now() / 1000) + x.maxAge;
}
if (!draft.domain) {
draft.url = parsedUrl.toString();
}
return draft;
});
try {
await page.setCookie(...mapped);
} catch (err: any) {
this.logger.warn(`Page ${sn}: Failed to set cookies`, { err });
throw new ParamValidationError({
path: 'cookies',
message: `Failed to set cookies: ${err?.message}`
});
}
}
if (options.overrideUserAgent) {
await page.setUserAgent(options.overrideUserAgent);
}
if (options.viewport) {
await page.setViewport(options.viewport);
}
let nextSnapshotDeferred = Defer();
const crippleListener = () => nextSnapshotDeferred.reject(new ServiceCrashedError({ message: `Browser crashed, try again` }));
this.once('crippled', crippleListener);
nextSnapshotDeferred.promise.finally(() => {
this.off('crippled', crippleListener);
});
let successfullyDone;
const hdl = (s: any) => {
if (snapshot === s) {
return;
}
snapshot = s;
if (snapshot) {
const kit = this.pageReqCtrl.get(page);
snapshot.lastContentResourceLoaded = kit?.lastContentResourceLoadedAt;
snapshot.lastMediaResourceLoaded = kit?.lastMediaResourceLoadedAt;
}
if (s?.maxElemDepth && s.maxElemDepth > 256) {
return;
}
if (s?.elemCount && s.elemCount > 10_000) {
return;
}
nextSnapshotDeferred.resolve(s);
nextSnapshotDeferred = Defer();
this.once('crippled', crippleListener);
nextSnapshotDeferred.promise.finally(() => {
this.off('crippled', crippleListener);
});
};
page.on('snapshot', hdl);
page.once('abuse', (event: any) => {
this.emit('abuse', { ...event, url: parsedUrl });
if (snapshot?.href && parsedUrl.href !== snapshot.href) {
this.emit('abuse', { ...event, url: snapshot.href });
}
nextSnapshotDeferred.reject(
new SecurityCompromiseError(`Abuse detected: ${event.reason}`)
);
});
const timeout = options.timeoutMs || 30_000;
const goToOptions: GoToOptions = {
waitUntil: ['load', 'domcontentloaded', 'networkidle0'],
timeout,
};
if (options.referer) {
goToOptions.referer = options.referer;
}
let waitForPromise: Promise<any> | undefined;
let finalizationPromise: Promise<any> | undefined;
const doFinalization = async () => {
if (waitForPromise) {
// SuccessfullyDone is meant for the finish of the page.
// It doesn't matter if you are expecting something and it didn't show up.
await waitForPromise.catch(() => void 0);
}
successfullyDone ??= true;
try {
const pSubFrameSnapshots = this.snapshotChildFrames(page);
snapshot = await page.evaluate('giveSnapshot(true)') as PageSnapshot;
screenshot = (await this.takeScreenShot(page)) || screenshot;
pageshot = (await this.takeScreenShot(page, { fullPage: true })) || pageshot;
if (snapshot) {
snapshot.childFrames = await pSubFrameSnapshots;
}
} catch (err: any) {
this.logger.warn(`Page ${sn}: Failed to finalize ${url}`, { err });
}
if (!snapshot?.html) {
return;
}
this.logger.info(`Page ${sn}: Snapshot of ${url} done`, { url, title: snapshot?.title, href: snapshot?.href });
this.emit(
'crawled',
{
...snapshot,
status: navigationResponse?.status(),
statusText: navigationResponse?.statusText(),
pdfs: _.uniq(pdfUrls), screenshot, pageshot,
},
{ ...options, url: parsedUrl }
);
};
const delayPromise = delay(timeout);
const gotoPromise = page.goto(url, goToOptions)
.catch((err) => {
if (err instanceof TimeoutError) {
this.logger.warn(`Page ${sn}: Browsing of ${url} timed out`, { err });
return new AssertionFailureError({
message: `Failed to goto ${url}: ${err}`,
cause: err,
});
}
if (err?.message?.startsWith('net::ERR_ABORTED')) {
if (pdfUrls.length) {
// Not throw for pdf mode.
return;
}
}
this.logger.warn(`Page ${sn}: Browsing of ${url} failed`, { err });
return new AssertionFailureError({
message: `Failed to goto ${url}: ${err}`,
cause: err,
});
}).then(async (stuff) => {
// This check is necessary because without snapshot, the condition of the page is unclear
// Calling evaluate directly may stall the process.
if (!snapshot) {
if (stuff instanceof Error) {
throw stuff;
}
}
await Promise.race([Promise.allSettled([...pageScriptEvaluations, ...frameScriptEvaluations]), delayPromise])
.catch(() => void 0);
return stuff;
});
if (options.waitForSelector) {
const t0 = Date.now();
waitForPromise = nextSnapshotDeferred.promise.then(() => {
const t1 = Date.now();
const elapsed = t1 - t0;
const remaining = timeout - elapsed;
const thisTimeout = remaining > 100 ? remaining : 100;
const p = (Array.isArray(options.waitForSelector) ?
Promise.all(options.waitForSelector.map((x) => page.waitForSelector(x, { timeout: thisTimeout }))) :
page.waitForSelector(options.waitForSelector!, { timeout: thisTimeout }))
.then(() => {
successfullyDone = true;
})
.catch((err) => {
waitForPromise = undefined;
this.logger.warn(`Page ${sn}: Failed to wait for selector ${options.waitForSelector}`, { err });
});
return p as any;
});
finalizationPromise = Promise.allSettled([waitForPromise, gotoPromise]).then(doFinalization);
} else {
finalizationPromise = gotoPromise.then(doFinalization);
}
try {
let lastHTML = snapshot?.html;
while (true) {
const ckpt = [nextSnapshotDeferred.promise, waitForPromise ?? gotoPromise];
if (options.minIntervalMs) {
ckpt.push(delay(options.minIntervalMs));
}
let error;
await Promise.race(ckpt).catch((err) => error = err);
if (successfullyDone && !error) {
if (!snapshot && !screenshot) {
throw new AssertionFailureError(`Could not extract any meaningful content from the page`);
}
yield {
...snapshot,
status: navigationResponse?.status(),
statusText: navigationResponse?.statusText(),
pdfs: _.uniq(pdfUrls), screenshot, pageshot
} as PageSnapshot;
break;
}
if (options.favorScreenshot && snapshot?.title && snapshot?.html !== lastHTML) {
screenshot = (await this.takeScreenShot(page)) || screenshot;
pageshot = (await this.takeScreenShot(page, { fullPage: true })) || pageshot;
lastHTML = snapshot.html;
}
if (snapshot || screenshot) {
yield {
...snapshot,
status: navigationResponse?.status(),
statusText: navigationResponse?.statusText(),
pdfs: _.uniq(pdfUrls), screenshot, pageshot,
isIntermediate: true,
} as PageSnapshot;
}
if (error) {
throw error;
}
if (successfullyDone) {
break;
}
}
await finalizationPromise;
yield {
...snapshot,
status: navigationResponse?.status(),
statusText: navigationResponse?.statusText(),
pdfs: _.uniq(pdfUrls), screenshot, pageshot
} as PageSnapshot;
} finally {
this.pagePhase.set(page, 'background');
Promise.allSettled([gotoPromise, waitForPromise, finalizationPromise]).finally(() => {
page.off('snapshot', hdl);
this.ditchPage(page);
});
nextSnapshotDeferred.resolve();
}
}
protected async takeScreenShot(page: Page, opts?: Parameters<typeof page.screenshot>[0]): Promise<Buffer | undefined> {
const r = await page.screenshot(opts).catch((err) => {
this.logger.warn(`Failed to take screenshot`, { err });
});
if (r) {
return Buffer.from(r);
}
return undefined;
}
async snapshotChildFrames(page: Page): Promise<PageSnapshot[]> {
const childFrames = page.mainFrame().childFrames();
const r = await Promise.all(childFrames.map(async (x) => {
const thisUrl = x.url();
if (!thisUrl || thisUrl === 'about:blank') {
return undefined;
}
try {
await x.evaluate(SCRIPT_TO_INJECT_INTO_FRAME);
return await x.evaluate(`giveSnapshot()`);
} catch (err) {
this.logger.warn(`Failed to snapshot child frame ${thisUrl}`, { err });
return undefined;
}
})) as PageSnapshot[];
return r.filter(Boolean);
}
}
const puppeteerControl = container.resolve(PuppeteerControl);
export default puppeteerControl;
|