@skrillex1224/playwright-toolkit 3.0.25 → 3.0.26

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/dist/index.cjs CHANGED
@@ -256,7 +256,6 @@ var ActorInfo = {
256
256
  name: "\u6587\u5FC3\u4E00\u8A00",
257
257
  domain: "wenxin.baidu.com",
258
258
  path: "/",
259
- device: Device.Mobile,
260
259
  share: {
261
260
  mode: "custom",
262
261
  prefix: "",
@@ -495,6 +494,7 @@ function createInternalLogger(moduleName, explicitLogger) {
495
494
 
496
495
  // src/internals/screenshot.js
497
496
  var import_delay = __toESM(require("delay"), 1);
497
+ var import_jimp = require("jimp");
498
498
 
499
499
  // src/internals/constants.js
500
500
  var PageRuntimeStateKey = "__playwright_toolkit_runtime_state__";
@@ -533,9 +533,23 @@ var FORCED_FULLPAGE_TYPE = "jpeg";
533
533
  var FORCED_FULLPAGE_QUALITY = 50;
534
534
  var SUPPORTED_TYPES = /* @__PURE__ */ new Set(["png", "jpeg", "webp"]);
535
535
  var EXPANDED_SCROLLABLE_CLASS = "__pk_expanded__";
536
+ var STITCH_SCROLL_TARGET_ATTR = "data-pk-stitch-scroll-target";
536
537
  var DEFAULT_MAX_HEIGHT = 8e3;
537
538
  var DEFAULT_SETTLE_MS = 1e3;
538
539
  var DEFAULT_MOBILE_SETTLE_MS = 50;
540
+ var DEFAULT_STITCH_SETTLE_MS = 120;
541
+ var DEFAULT_STITCH_OVERLAP_PX = 24;
542
+ var MIN_VIRTUALIZED_SCROLL_RATIO = 2.2;
543
+ var MIN_SPARSE_SCROLL_RATIO = 4;
544
+ var MIN_STITCH_VISIBLE_HEIGHT_PX = 120;
545
+ var MIN_STITCH_VISIBLE_HEIGHT_RATIO = 0.22;
546
+ var MIN_STITCH_OUTPUT_HEIGHT_RATIO = 0.35;
547
+ var MIN_STITCH_OUTPUT_VIEWPORT_RATIO = 1.15;
548
+ var MOBILE_VIEWPORT_WIDTH_THRESHOLD = 520;
549
+ var DEFAULT_QUALITY_RETRY_ATTEMPTS = 2;
550
+ var DEFAULT_QUALITY_RETRY_DELAY_MS = 2500;
551
+ var MIN_TRAILING_BLANK_GAP_PX = 320;
552
+ var MIN_TRAILING_BLANK_GAP_RATIO = 0.12;
539
553
  var toPositiveNumber = (value, fallback = 0) => {
540
554
  const n = Number(value);
541
555
  if (!Number.isFinite(n) || n <= 0) return fallback;
@@ -558,7 +572,22 @@ var normalizeQuality = (value, type) => {
558
572
  if (rounded < 0 || rounded > 100) return void 0;
559
573
  return rounded;
560
574
  };
561
- var resolvePageDevice = (page) => normalizeDevice(page?.[PageRuntimeStateKey]?.device);
575
+ var resolvePageDevice = async (page) => {
576
+ const declared = normalizeDevice(page?.[PageRuntimeStateKey]?.device);
577
+ if (declared === Device.Mobile) return Device.Mobile;
578
+ const viewport = await resolveCurrentViewportSize(page).catch(() => null);
579
+ const viewportWidth = Math.round(Number(viewport?.width) || 0);
580
+ if (viewportWidth > 0 && viewportWidth <= MOBILE_VIEWPORT_WIDTH_THRESHOLD) {
581
+ return Device.Mobile;
582
+ }
583
+ return declared;
584
+ };
585
+ var resolveStitchMode = (options = {}) => {
586
+ const raw = options.stitch ?? options.stitching ?? options.strategy;
587
+ if (raw === false || raw === "off" || raw === "none" || raw === "single") return "off";
588
+ if (raw === true || raw === "force" || raw === "stitched") return "force";
589
+ return "auto";
590
+ };
562
591
  var buildFullPageClip = (metrics, viewport, maxClipHeight) => {
563
592
  const contentSize = metrics && typeof metrics === "object" ? metrics.contentSize || null : null;
564
593
  const width = Math.max(1, Math.ceil(viewport.width || contentSize?.width || 1));
@@ -905,10 +934,156 @@ var restoreAffixedElementsForExpandedScreenshot = async (page) => {
905
934
  });
906
935
  }, EXPANDED_SCROLLABLE_CLASS);
907
936
  };
937
+ var measureMeaningfulContentBounds = async (page) => {
938
+ return await page.evaluate(() => {
939
+ const body = document.body;
940
+ if (!body) return null;
941
+ const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || body.clientWidth || 0;
942
+ const viewportHeight = window.innerHeight || document.documentElement?.clientHeight || body.clientHeight || 0;
943
+ const scrollX = window.scrollX || window.pageXOffset || 0;
944
+ const scrollY = window.scrollY || window.pageYOffset || 0;
945
+ const bounds = {
946
+ left: Number.POSITIVE_INFINITY,
947
+ top: Number.POSITIVE_INFINITY,
948
+ right: 0,
949
+ bottom: 0,
950
+ nodes: 0
951
+ };
952
+ const isVisible = (el, style, rect) => {
953
+ if (!el || !style || !rect) return false;
954
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
955
+ if (Number(style.opacity) === 0) return false;
956
+ return rect.width > 1 && rect.height > 1;
957
+ };
958
+ const hasFixedAncestor = (el) => {
959
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
960
+ const position = String(window.getComputedStyle(node).position || "").toLowerCase();
961
+ if (position === "fixed") {
962
+ return true;
963
+ }
964
+ }
965
+ return false;
966
+ };
967
+ const parseRgbColor = (value) => {
968
+ const raw = String(value || "").trim();
969
+ const match = raw.match(/rgba?\(([^)]+)\)/i);
970
+ if (!match) return null;
971
+ const parts = match[1].replace(/\//g, " ").split(/[,\s]+/).map((part) => part.trim()).filter(Boolean);
972
+ if (parts.length < 3) return null;
973
+ const normalizeChannel = (part) => {
974
+ if (part.endsWith("%")) {
975
+ return Math.max(0, Math.min(255, Number.parseFloat(part) * 2.55));
976
+ }
977
+ return Math.max(0, Math.min(255, Number.parseFloat(part)));
978
+ };
979
+ const alpha = parts.length >= 4 ? parts[3].endsWith("%") ? Number.parseFloat(parts[3]) / 100 : Number.parseFloat(parts[3]) : 1;
980
+ return {
981
+ r: normalizeChannel(parts[0]),
982
+ g: normalizeChannel(parts[1]),
983
+ b: normalizeChannel(parts[2]),
984
+ a: Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1
985
+ };
986
+ };
987
+ const colorLuminance = (color) => {
988
+ const channel = (value) => {
989
+ const ratio = Math.max(0, Math.min(255, value)) / 255;
990
+ return ratio <= 0.03928 ? ratio / 12.92 : ((ratio + 0.055) / 1.055) ** 2.4;
991
+ };
992
+ return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
993
+ };
994
+ const contrastRatio = (a, b) => {
995
+ const l1 = colorLuminance(a);
996
+ const l2 = colorLuminance(b);
997
+ const lighter = Math.max(l1, l2);
998
+ const darker = Math.min(l1, l2);
999
+ return (lighter + 0.05) / (darker + 0.05);
1000
+ };
1001
+ const resolveBackgroundColor = (el) => {
1002
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
1003
+ const background = parseRgbColor(window.getComputedStyle(node).backgroundColor);
1004
+ if (background && background.a > 0.2) {
1005
+ return background;
1006
+ }
1007
+ }
1008
+ return { r: 255, g: 255, b: 255, a: 1 };
1009
+ };
1010
+ const isLowInformationTextPaint = (el, style) => {
1011
+ const color = parseRgbColor(style?.color);
1012
+ if (!color) return false;
1013
+ const opacity = Number(style.opacity);
1014
+ if (color.a <= 0.08 || Number.isFinite(opacity) && opacity <= 0.18) {
1015
+ return true;
1016
+ }
1017
+ const max = Math.max(color.r, color.g, color.b);
1018
+ const min = Math.min(color.r, color.g, color.b);
1019
+ if (!(min >= 224 && max - min <= 24 && color.a >= 0.85)) {
1020
+ return false;
1021
+ }
1022
+ const background = resolveBackgroundColor(el);
1023
+ return colorLuminance(background) > 0.76 && contrastRatio(color, background) < 1.35;
1024
+ };
1025
+ const addRect = (rect) => {
1026
+ if (!rect || rect.width <= 1 || rect.height <= 1) return;
1027
+ const left = Math.max(0, Math.floor(rect.left + scrollX));
1028
+ const top = Math.max(0, Math.floor(rect.top + scrollY));
1029
+ const right = Math.ceil(rect.right + scrollX);
1030
+ const bottom = Math.ceil(rect.bottom + scrollY);
1031
+ if (right <= left || bottom <= top) return;
1032
+ bounds.left = Math.min(bounds.left, left);
1033
+ bounds.top = Math.min(bounds.top, top);
1034
+ bounds.right = Math.max(bounds.right, right);
1035
+ bounds.bottom = Math.max(bounds.bottom, bottom);
1036
+ bounds.nodes += 1;
1037
+ };
1038
+ const addElement = (el, { minArea = 12, text = false } = {}) => {
1039
+ if (!el || el.nodeType !== 1 || hasFixedAncestor(el)) return;
1040
+ const style = window.getComputedStyle(el);
1041
+ if (text && isLowInformationTextPaint(el, style)) return;
1042
+ const rects = Array.from(el.getClientRects ? el.getClientRects() : []);
1043
+ rects.forEach((rect) => {
1044
+ if (!isVisible(el, style, rect)) return;
1045
+ if (rect.width * rect.height < minArea) return;
1046
+ addRect(rect);
1047
+ });
1048
+ };
1049
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
1050
+ let visitedTextNodes = 0;
1051
+ while (walker.nextNode() && visitedTextNodes < 6e3) {
1052
+ const node = walker.currentNode;
1053
+ visitedTextNodes += 1;
1054
+ const text = String(node.nodeValue || "").replace(/\s+/g, " ").trim();
1055
+ if (text.length < 2) continue;
1056
+ addElement(node.parentElement, { minArea: 8, text: true });
1057
+ }
1058
+ document.querySelectorAll("img,video,canvas,svg,picture").forEach((el) => {
1059
+ addElement(el, { minArea: 900 });
1060
+ });
1061
+ if (!bounds.nodes || !Number.isFinite(bounds.left)) return null;
1062
+ const paddingX = Math.max(16, Math.min(96, viewportWidth * 0.04));
1063
+ const paddingY = Math.max(24, Math.min(160, viewportHeight * 0.18));
1064
+ return {
1065
+ left: Math.max(0, Math.floor(bounds.left - paddingX)),
1066
+ top: Math.max(0, Math.floor(bounds.top - paddingY)),
1067
+ right: Math.ceil(bounds.right + paddingX),
1068
+ bottom: Math.ceil(bounds.bottom + paddingY),
1069
+ width: Math.max(1, Math.ceil(bounds.right - bounds.left)),
1070
+ height: Math.max(1, Math.ceil(bounds.bottom - bounds.top)),
1071
+ nodes: bounds.nodes,
1072
+ viewport: {
1073
+ width: Math.max(1, Math.ceil(viewportWidth || 1)),
1074
+ height: Math.max(1, Math.ceil(viewportHeight || 1))
1075
+ }
1076
+ };
1077
+ }).catch((error) => {
1078
+ logger.warning(`\u622A\u56FE\u5185\u5BB9\u8FB9\u754C\u6D4B\u91CF\u5931\u8D25: ${error?.message || error}`);
1079
+ return null;
1080
+ });
1081
+ };
908
1082
  var prepareExpandedFullPageScreenshot = async (page, options = {}) => {
909
1083
  const originalViewport = await resolveCurrentViewportSize(page);
910
1084
  const maxHeight = toPositiveInteger(options.maxHeight, DEFAULT_MAX_HEIGHT);
911
- const preserveViewport = options.preserveViewport ?? resolvePageDevice(page) === Device.Mobile;
1085
+ const device = await resolvePageDevice(page);
1086
+ const preserveViewport = options.preserveViewport ?? device === Device.Mobile;
912
1087
  const defaultSettleMs = preserveViewport ? DEFAULT_MOBILE_SETTLE_MS : DEFAULT_SETTLE_MS;
913
1088
  const requestedSettleMs = Math.max(0, Number(options.settleMs ?? defaultSettleMs) || 0);
914
1089
  const settleMs = preserveViewport ? Math.min(requestedSettleMs, DEFAULT_MOBILE_SETTLE_MS) : requestedSettleMs;
@@ -917,7 +1092,21 @@ var prepareExpandedFullPageScreenshot = async (page, options = {}) => {
917
1092
  visibleOnly: options.visibleOnly !== false,
918
1093
  expandDocumentElements: preserveViewport
919
1094
  });
920
- const targetHeight = Math.min(maxScrollHeight, maxHeight);
1095
+ const contentBounds = await measureMeaningfulContentBounds(page);
1096
+ let targetHeight = Math.min(maxScrollHeight, maxHeight);
1097
+ if (contentBounds?.bottom > 0) {
1098
+ const contentBottom = Math.min(Math.ceil(contentBounds.bottom), maxHeight);
1099
+ const trailingGap = targetHeight - contentBottom;
1100
+ const minTrailingGap = Math.max(
1101
+ MIN_TRAILING_BLANK_GAP_PX,
1102
+ Math.floor(targetHeight * MIN_TRAILING_BLANK_GAP_RATIO),
1103
+ Math.floor(originalViewport.height * 0.45)
1104
+ );
1105
+ if (trailingGap >= minTrailingGap && contentBottom >= originalViewport.height * 0.65) {
1106
+ targetHeight = Math.max(1, contentBottom);
1107
+ logger.info(`\u957F\u622A\u56FE\u88C1\u6389\u4F4E\u4FE1\u606F\u5C3E\u90E8: contentBottom=${contentBottom}, originalHeight=${Math.min(maxScrollHeight, maxHeight)}`);
1108
+ }
1109
+ }
921
1110
  let viewportResized = false;
922
1111
  if (!preserveViewport) {
923
1112
  await page.setViewportSize({
@@ -937,6 +1126,7 @@ var prepareExpandedFullPageScreenshot = async (page, options = {}) => {
937
1126
  originalViewport,
938
1127
  maxScrollHeight,
939
1128
  targetHeight,
1129
+ contentBounds,
940
1130
  preserveViewport,
941
1131
  viewportResized
942
1132
  };
@@ -969,6 +1159,436 @@ var restoreExpandedFullPageScreenshot = async (page, state2 = {}) => {
969
1159
  await page.setViewportSize(state2.originalViewport);
970
1160
  }
971
1161
  };
1162
+ var resolveVirtualizedScrollTarget = async (page, options = {}) => {
1163
+ const stitchMode = resolveStitchMode(options);
1164
+ if (stitchMode === "off") return null;
1165
+ const device = await resolvePageDevice(page);
1166
+ if (stitchMode !== "force" && device !== Device.Mobile) {
1167
+ return null;
1168
+ }
1169
+ return await page.evaluate((config) => {
1170
+ const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || document.body?.clientWidth || 0;
1171
+ const viewportHeight = window.innerHeight || document.documentElement?.clientHeight || document.body?.clientHeight || 0;
1172
+ const root = document.documentElement;
1173
+ const body = document.body;
1174
+ const scrollingElement = document.scrollingElement;
1175
+ const candidates = [];
1176
+ const seen = /* @__PURE__ */ new Set();
1177
+ const scrollableOverflow = /* @__PURE__ */ new Set(["auto", "scroll", "overlay"]);
1178
+ const clippingOverflow = /* @__PURE__ */ new Set(["hidden", "clip"]);
1179
+ const pushCandidate = (el2) => {
1180
+ if (!el2 || seen.has(el2)) return;
1181
+ seen.add(el2);
1182
+ candidates.push(el2);
1183
+ };
1184
+ pushCandidate(scrollingElement);
1185
+ pushCandidate(root);
1186
+ pushCandidate(body);
1187
+ document.querySelectorAll("*").forEach(pushCandidate);
1188
+ const isDocumentElement = (el2) => el2 === root || el2 === body || el2 === scrollingElement;
1189
+ const isVisible = (el2, style, rect) => {
1190
+ if (!el2 || !style || !rect) return false;
1191
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
1192
+ if (Number(style.opacity) === 0) return false;
1193
+ return rect.width > 0 && rect.height > 0;
1194
+ };
1195
+ const hasOverflowValue = (style, values) => {
1196
+ const overflowY = String(style?.overflowY || "").toLowerCase();
1197
+ const overflow = String(style?.overflow || "").toLowerCase();
1198
+ return values.has(overflowY) || values.has(overflow);
1199
+ };
1200
+ const looksScrollable = (el2, style) => {
1201
+ if (!el2 || el2.scrollHeight <= el2.clientHeight + 1) return false;
1202
+ if (isDocumentElement(el2)) return true;
1203
+ return hasOverflowValue(style, scrollableOverflow) || hasOverflowValue(style, clippingOverflow);
1204
+ };
1205
+ const textHeightFor = (el2) => {
1206
+ const nodes = isDocumentElement(el2) ? document.querySelectorAll("body *") : el2.querySelectorAll("*");
1207
+ let textHeight = 0;
1208
+ let textNodes = 0;
1209
+ const maxNodes = 3500;
1210
+ for (const node of nodes) {
1211
+ if (textNodes >= maxNodes) break;
1212
+ const text = String(node.textContent || "").replace(/\s+/g, " ").trim();
1213
+ if (text.length < 2) continue;
1214
+ let childHasText = false;
1215
+ for (const child of node.children || []) {
1216
+ if (String(child.textContent || "").replace(/\s+/g, " ").trim().length >= 2) {
1217
+ childHasText = true;
1218
+ break;
1219
+ }
1220
+ }
1221
+ if (childHasText) continue;
1222
+ const style = window.getComputedStyle(node);
1223
+ const rect = node.getBoundingClientRect();
1224
+ if (!isVisible(node, style, rect)) continue;
1225
+ textNodes += 1;
1226
+ textHeight += Math.min(Math.ceil(rect.height || 0), 900);
1227
+ }
1228
+ return { textHeight, textNodes };
1229
+ };
1230
+ const resolveEdgeOcclusion = () => {
1231
+ let top = 0;
1232
+ let bottom = 0;
1233
+ const maxHeight = Math.max(48, viewportHeight * 0.45);
1234
+ document.querySelectorAll("*").forEach((el2) => {
1235
+ const style = window.getComputedStyle(el2);
1236
+ const position = String(style.position || "").toLowerCase();
1237
+ if (position !== "fixed" && position !== "sticky") return;
1238
+ const rect = el2.getBoundingClientRect();
1239
+ if (!isVisible(el2, style, rect)) return;
1240
+ if (rect.height <= 0 || rect.height > maxHeight) return;
1241
+ if (rect.width < viewportWidth * 0.35) return;
1242
+ if (rect.top <= Math.max(16, viewportHeight * 0.08)) {
1243
+ top = Math.max(top, Math.ceil(rect.bottom));
1244
+ }
1245
+ if (rect.bottom >= viewportHeight - Math.max(16, viewportHeight * 0.08)) {
1246
+ bottom = Math.max(bottom, Math.ceil(viewportHeight - rect.top));
1247
+ }
1248
+ });
1249
+ return {
1250
+ top: Math.max(0, Math.min(Math.ceil(top), Math.floor(viewportHeight * 0.45))),
1251
+ bottom: Math.max(0, Math.min(Math.ceil(bottom), Math.floor(viewportHeight * 0.45)))
1252
+ };
1253
+ };
1254
+ let best = null;
1255
+ candidates.forEach((el2) => {
1256
+ const style = window.getComputedStyle(el2);
1257
+ const rect = isDocumentElement(el2) ? {
1258
+ top: 0,
1259
+ bottom: viewportHeight,
1260
+ left: 0,
1261
+ right: viewportWidth,
1262
+ width: viewportWidth,
1263
+ height: viewportHeight
1264
+ } : el2.getBoundingClientRect();
1265
+ if (!isDocumentElement(el2) && !isVisible(el2, style, rect)) return;
1266
+ if (!looksScrollable(el2, style)) return;
1267
+ const scrollHeight = Math.ceil(el2.scrollHeight || 0);
1268
+ const clientHeight = Math.ceil(el2.clientHeight || viewportHeight || 0);
1269
+ if (scrollHeight < Math.max(900, clientHeight * config.minScrollRatio)) return;
1270
+ const visibleTop = Math.max(0, Math.round(rect.top || 0));
1271
+ const visibleBottom = Math.min(viewportHeight, Math.round(rect.bottom || viewportHeight));
1272
+ const visibleHeight = Math.max(0, visibleBottom - visibleTop);
1273
+ const minVisibleHeight = Math.max(
1274
+ config.minVisibleHeightPx,
1275
+ Math.floor(viewportHeight * config.minVisibleHeightRatio)
1276
+ );
1277
+ if (!config.force && !isDocumentElement(el2) && visibleHeight < minVisibleHeight) return;
1278
+ const { textHeight, textNodes } = textHeightFor(el2);
1279
+ const sparseRatio = scrollHeight / Math.max(1, textHeight);
1280
+ const sparse = config.force || textNodes > 0 && sparseRatio >= config.minSparseRatio && scrollHeight - textHeight > clientHeight;
1281
+ if (!sparse) return;
1282
+ const visibleWidth = Math.max(1, Math.ceil(rect.width || viewportWidth || 1));
1283
+ const score2 = scrollHeight * Math.min(visibleWidth, viewportWidth || visibleWidth) * Math.min(1, visibleHeight / Math.max(1, viewportHeight));
1284
+ if (!best || score2 > best.score) {
1285
+ best = {
1286
+ el: el2,
1287
+ score: score2,
1288
+ kind: isDocumentElement(el2) ? "document" : "element",
1289
+ scrollHeight,
1290
+ clientHeight,
1291
+ scrollTop: Math.max(0, Math.round(el2.scrollTop || 0)),
1292
+ rect: {
1293
+ top: Math.max(0, Math.round(rect.top || 0)),
1294
+ bottom: Math.min(viewportHeight, Math.round(rect.bottom || viewportHeight)),
1295
+ left: Math.max(0, Math.round(rect.left || 0)),
1296
+ width: Math.max(1, Math.round(rect.width || viewportWidth || 1)),
1297
+ height: Math.max(1, Math.round(rect.height || viewportHeight || 1))
1298
+ },
1299
+ visibleHeight,
1300
+ textHeight,
1301
+ textNodes,
1302
+ sparseRatio
1303
+ };
1304
+ }
1305
+ });
1306
+ if (!best) return null;
1307
+ document.querySelectorAll(`[${config.attrName}="1"]`).forEach((node) => {
1308
+ node.removeAttribute(config.attrName);
1309
+ });
1310
+ if (best.kind === "element") {
1311
+ best.el.setAttribute(config.attrName, "1");
1312
+ }
1313
+ const { el, score, ...target } = best;
1314
+ return {
1315
+ ...target,
1316
+ viewport: {
1317
+ width: Math.max(1, Math.ceil(viewportWidth || best.rect.width || 1)),
1318
+ height: Math.max(1, Math.ceil(viewportHeight || best.rect.height || 1))
1319
+ },
1320
+ edgeOcclusion: resolveEdgeOcclusion()
1321
+ };
1322
+ }, {
1323
+ attrName: STITCH_SCROLL_TARGET_ATTR,
1324
+ force: stitchMode === "force",
1325
+ minScrollRatio: MIN_VIRTUALIZED_SCROLL_RATIO,
1326
+ minSparseRatio: MIN_SPARSE_SCROLL_RATIO,
1327
+ minVisibleHeightPx: MIN_STITCH_VISIBLE_HEIGHT_PX,
1328
+ minVisibleHeightRatio: MIN_STITCH_VISIBLE_HEIGHT_RATIO
1329
+ }).catch((error) => {
1330
+ logger.warning(`\u865A\u62DF\u6EDA\u52A8\u622A\u56FE\u63A2\u6D4B\u5931\u8D25: ${error?.message || error}`);
1331
+ return null;
1332
+ });
1333
+ };
1334
+ var setStitchScrollTop = async (page, target, scrollTop) => {
1335
+ await page.evaluate(({ attrName, kind, top }) => {
1336
+ const el = kind === "document" ? document.scrollingElement || document.documentElement || document.body : document.querySelector(`[${attrName}="1"]`);
1337
+ if (!el) return;
1338
+ el.scrollTop = Math.max(0, Math.round(Number(top) || 0));
1339
+ el.dispatchEvent(new Event("scroll", { bubbles: true }));
1340
+ window.dispatchEvent(new Event("scroll"));
1341
+ }, {
1342
+ attrName: STITCH_SCROLL_TARGET_ATTR,
1343
+ kind: target.kind,
1344
+ top: scrollTop
1345
+ });
1346
+ };
1347
+ var cleanupStitchTarget = async (page) => {
1348
+ await page.evaluate((attrName) => {
1349
+ document.querySelectorAll(`[${attrName}="1"]`).forEach((node) => {
1350
+ node.removeAttribute(attrName);
1351
+ });
1352
+ }, STITCH_SCROLL_TARGET_ATTR).catch(() => {
1353
+ });
1354
+ };
1355
+ var cropImage = (image, crop) => image.clone().crop({
1356
+ x: Math.max(0, Math.round(crop.x || 0)),
1357
+ y: Math.max(0, Math.round(crop.y || 0)),
1358
+ w: Math.max(1, Math.round(crop.w || 1)),
1359
+ h: Math.max(1, Math.round(crop.h || 1))
1360
+ });
1361
+ var captureStitchedScrollableScreenshot = async (page, target, options = {}) => {
1362
+ const maxHeight = toPositiveInteger(options.maxHeight, DEFAULT_MAX_HEIGHT);
1363
+ const settleMs = Math.max(0, Number(options.stitchSettleMs ?? DEFAULT_STITCH_SETTLE_MS) || 0);
1364
+ const overlapPx = Math.max(0, Math.round(Number(options.stitchOverlapPx ?? DEFAULT_STITCH_OVERLAP_PX) || 0));
1365
+ const viewport = target.viewport || await resolveCurrentViewportSize(page);
1366
+ const rect = target.rect || {
1367
+ top: 0,
1368
+ bottom: viewport.height,
1369
+ left: 0,
1370
+ width: viewport.width,
1371
+ height: viewport.height
1372
+ };
1373
+ const edge = target.edgeOcclusion || { top: 0, bottom: 0 };
1374
+ const topCrop = Math.max(0, Math.min(rect.top, viewport.height - 1));
1375
+ const topOverlay = Math.max(topCrop, Math.min(edge.top || 0, viewport.height - 1));
1376
+ const bottomOverlay = Math.max(0, Math.min(edge.bottom || 0, viewport.height - topOverlay - 1));
1377
+ const middleCropY = Math.max(topCrop, topOverlay);
1378
+ const middleCropBottom = Math.max(
1379
+ middleCropY + 1,
1380
+ Math.min(rect.bottom || viewport.height, viewport.height - bottomOverlay)
1381
+ );
1382
+ const middleCropHeight = Math.max(1, middleCropBottom - middleCropY);
1383
+ const scrollStep = Math.max(120, middleCropHeight - overlapPx);
1384
+ const maxScrollTop = Math.max(0, Math.ceil(target.scrollHeight - target.clientHeight));
1385
+ const positions = [];
1386
+ for (let top = 0; top < maxScrollTop; top += scrollStep) {
1387
+ positions.push(Math.round(top));
1388
+ }
1389
+ if (!positions.includes(maxScrollTop)) {
1390
+ positions.push(maxScrollTop);
1391
+ }
1392
+ if (positions.length === 0) {
1393
+ positions.push(0);
1394
+ }
1395
+ const segments = [];
1396
+ let totalHeight = 0;
1397
+ let outputWidth = Math.max(1, Math.round(viewport.width || rect.width || 1));
1398
+ try {
1399
+ for (let index = 0; index < positions.length && totalHeight < maxHeight; index += 1) {
1400
+ const isFirst = index === 0;
1401
+ const isLast = index === positions.length - 1;
1402
+ await setStitchScrollTop(page, target, positions[index]);
1403
+ if (settleMs > 0) {
1404
+ await (0, import_delay.default)(settleMs);
1405
+ }
1406
+ const buffer = await capturePageScreenshot(page, {
1407
+ type: options.type || "png",
1408
+ quality: options.quality,
1409
+ timeout: options.timeout
1410
+ });
1411
+ const image = await import_jimp.Jimp.read(buffer);
1412
+ outputWidth = Math.min(outputWidth, image.bitmap.width);
1413
+ const cropY = isFirst ? 0 : middleCropY;
1414
+ const cropBottom = isLast ? image.bitmap.height : middleCropBottom;
1415
+ let cropHeight = Math.max(1, Math.min(image.bitmap.height, cropBottom) - cropY);
1416
+ const remaining = maxHeight - totalHeight;
1417
+ if (cropHeight > remaining) {
1418
+ cropHeight = remaining;
1419
+ }
1420
+ segments.push(cropImage(image, {
1421
+ x: 0,
1422
+ y: cropY,
1423
+ w: outputWidth,
1424
+ h: cropHeight
1425
+ }));
1426
+ totalHeight += cropHeight;
1427
+ }
1428
+ const canvas = new import_jimp.Jimp({
1429
+ width: outputWidth,
1430
+ height: Math.max(1, totalHeight),
1431
+ color: 4294967295
1432
+ });
1433
+ let y = 0;
1434
+ for (const segment of segments) {
1435
+ canvas.composite(segment, 0, y);
1436
+ y += segment.bitmap.height;
1437
+ }
1438
+ logger.info(
1439
+ `\u865A\u62DF\u6EDA\u52A8\u5206\u6BB5\u622A\u56FE: segments=${segments.length}, height=${totalHeight}, scrollHeight=${target.scrollHeight}, textNodes=${target.textNodes}, sparseRatio=${Number(target.sparseRatio || 0).toFixed(2)}`
1440
+ );
1441
+ const expectedHeight = Math.min(maxHeight, Math.max(target.scrollHeight || 0, viewport.height || 0));
1442
+ const minPlausibleHeight = Math.max(
1443
+ Math.floor((viewport.height || rect.height || 0) * MIN_STITCH_OUTPUT_VIEWPORT_RATIO),
1444
+ Math.floor(expectedHeight * MIN_STITCH_OUTPUT_HEIGHT_RATIO)
1445
+ );
1446
+ if (positions.length > 1 && expectedHeight > (viewport.height || rect.height || 0) * 1.3 && totalHeight < minPlausibleHeight) {
1447
+ logger.warning(
1448
+ `\u865A\u62DF\u6EDA\u52A8\u5206\u6BB5\u622A\u56FE\u7ED3\u679C\u8FC7\u77ED\uFF0C\u964D\u7EA7\u666E\u901A\u957F\u622A\u56FE: segments=${segments.length}, height=${totalHeight}, expectedMin=${minPlausibleHeight}, scrollHeight=${target.scrollHeight}, rect=${rect.width}x${rect.height}@${rect.top}`
1449
+ );
1450
+ return null;
1451
+ }
1452
+ return await canvas.getBuffer(import_jimp.JimpMime.png);
1453
+ } finally {
1454
+ await setStitchScrollTop(page, target, target.scrollTop || 0).catch(() => {
1455
+ });
1456
+ await cleanupStitchTarget(page);
1457
+ }
1458
+ };
1459
+ var isLightBlankPixel = ({ r, g, b }) => {
1460
+ const max = Math.max(r, g, b);
1461
+ const min = Math.min(r, g, b);
1462
+ return max >= 238 && max - min <= 18;
1463
+ };
1464
+ var isDarkBlankPixel = ({ r, g, b }) => {
1465
+ const max = Math.max(r, g, b);
1466
+ const min = Math.min(r, g, b);
1467
+ return max <= 34 && max - min <= 10;
1468
+ };
1469
+ var isLowInfoPixel = ({ r, g, b }) => {
1470
+ const max = Math.max(r, g, b);
1471
+ const min = Math.min(r, g, b);
1472
+ return max - min <= 12;
1473
+ };
1474
+ var analyzeScreenshotBuffer = async (buffer) => {
1475
+ const image = await import_jimp.Jimp.read(buffer);
1476
+ const width = image.bitmap.width;
1477
+ const height = image.bitmap.height;
1478
+ const stepY = Math.max(1, Math.floor(height / 900));
1479
+ const stepX = Math.max(1, Math.floor(width / 420));
1480
+ const rows = [];
1481
+ let lightRows = 0;
1482
+ let darkRows = 0;
1483
+ let lowInfoRows = 0;
1484
+ let loadingLikeRows = 0;
1485
+ const rowFlags = [];
1486
+ for (let y = 0; y < height; y += stepY) {
1487
+ let light = 0;
1488
+ let dark = 0;
1489
+ let lowInfo = 0;
1490
+ let edge = 0;
1491
+ let count = 0;
1492
+ let prev = null;
1493
+ for (let x = 0; x < width; x += stepX) {
1494
+ const rgba = (0, import_jimp.intToRGBA)(image.getPixelColor(x, y));
1495
+ count += 1;
1496
+ if (isLightBlankPixel(rgba)) light += 1;
1497
+ if (isDarkBlankPixel(rgba)) dark += 1;
1498
+ if (isLowInfoPixel(rgba)) lowInfo += 1;
1499
+ if (prev) {
1500
+ const diff = Math.abs(rgba.r - prev.r) + Math.abs(rgba.g - prev.g) + Math.abs(rgba.b - prev.b);
1501
+ if (diff > 45) edge += 1;
1502
+ }
1503
+ prev = rgba;
1504
+ }
1505
+ const stat = {
1506
+ y,
1507
+ lightRatio: light / Math.max(1, count),
1508
+ darkRatio: dark / Math.max(1, count),
1509
+ lowInfoRatio: lowInfo / Math.max(1, count),
1510
+ edgeRatio: edge / Math.max(1, count - 1)
1511
+ };
1512
+ rows.push(stat);
1513
+ const lightBlank = stat.lightRatio >= 0.965 && stat.edgeRatio <= 0.015;
1514
+ const darkBlank = stat.darkRatio >= 0.965 && stat.edgeRatio <= 0.012;
1515
+ const lowInfoBlank = stat.lowInfoRatio >= 0.965 && stat.edgeRatio <= 0.012;
1516
+ const loadingLike = stat.darkRatio >= 0.88 && stat.edgeRatio <= 0.025;
1517
+ if (lightBlank) lightRows += 1;
1518
+ if (darkBlank) darkRows += 1;
1519
+ if (lowInfoBlank) lowInfoRows += 1;
1520
+ if (loadingLike) loadingLikeRows += 1;
1521
+ rowFlags.push({ lightBlank, darkBlank, lowInfoBlank, loadingLike });
1522
+ }
1523
+ const sampledRows = Math.max(1, rows.length);
1524
+ return {
1525
+ image,
1526
+ width,
1527
+ height,
1528
+ lightBlankRowsRatio: lightRows / sampledRows,
1529
+ darkBlankRowsRatio: darkRows / sampledRows,
1530
+ lowInfoRowsRatio: lowInfoRows / sampledRows,
1531
+ loadingLikeRowsRatio: loadingLikeRows / sampledRows,
1532
+ rowFlags
1533
+ };
1534
+ };
1535
+ var resolveScreenshotQualityIssue = (analysis) => {
1536
+ if (!analysis) return null;
1537
+ if (analysis.loadingLikeRowsRatio >= 0.92 || analysis.darkBlankRowsRatio >= 0.72) {
1538
+ return "loading-like-dark-screenshot";
1539
+ }
1540
+ return null;
1541
+ };
1542
+ var cropBufferToContentBounds = async (buffer, bounds, options = {}) => {
1543
+ if (!bounds || bounds.nodes <= 0) return buffer;
1544
+ const image = options.image || await import_jimp.Jimp.read(buffer);
1545
+ const width = image.bitmap.width;
1546
+ const height = image.bitmap.height;
1547
+ const safeLeft = Math.max(0, Math.min(width - 1, Math.floor(bounds.left || 0)));
1548
+ const safeRight = Math.max(safeLeft + 1, Math.min(width, Math.ceil(bounds.right || width)));
1549
+ const safeTop = Math.max(0, Math.min(height - 1, Math.floor(bounds.top || 0)));
1550
+ const safeBottom = Math.max(safeTop + 1, Math.min(height, Math.ceil(bounds.bottom || height)));
1551
+ const cropW = safeRight - safeLeft;
1552
+ const cropH = safeBottom - safeTop;
1553
+ const shouldCropX = cropW > 80 && cropW <= width * 0.82 && (safeLeft > width * 0.04 || width - safeRight > width * 0.04);
1554
+ const shouldCropY = cropH > 160 && cropH <= height * 0.88 && height - safeBottom > Math.max(320, height * 0.1);
1555
+ if (!shouldCropX && !shouldCropY) {
1556
+ return buffer;
1557
+ }
1558
+ const x = shouldCropX ? safeLeft : 0;
1559
+ const y = shouldCropY ? safeTop : 0;
1560
+ const w = shouldCropX ? cropW : width;
1561
+ const h = shouldCropY ? cropH : height;
1562
+ logger.info(`\u5185\u5BB9\u611F\u77E5\u88C1\u526A\u622A\u56FE: x=${x}, y=${y}, w=${w}, h=${h}, original=${width}x${height}`);
1563
+ return await cropImage(image, { x, y, w, h }).getBuffer(import_jimp.JimpMime.png);
1564
+ };
1565
+ var captureExpandedFullPageScreenshotOnce = async (page, options = {}) => {
1566
+ const stitchedTarget = await resolveVirtualizedScrollTarget(page, options);
1567
+ if (stitchedTarget) {
1568
+ const buffer = await captureStitchedScrollableScreenshot(page, stitchedTarget, options);
1569
+ if (buffer) {
1570
+ return buffer;
1571
+ }
1572
+ }
1573
+ const state2 = await prepareExpandedFullPageScreenshot(page, options);
1574
+ try {
1575
+ const buffer = await capturePageScreenshot(page, {
1576
+ fullPage: true,
1577
+ type: options.type || "png",
1578
+ quality: options.quality,
1579
+ timeout: options.timeout,
1580
+ maxClipHeight: state2.targetHeight
1581
+ });
1582
+ return await cropBufferToContentBounds(buffer, state2.contentBounds);
1583
+ } finally {
1584
+ await restoreAffixedElementsForExpandedScreenshot(page).catch((error) => {
1585
+ logger.warning(`\u79FB\u52A8\u7AEF\u5438\u9644\u5143\u7D20\u6062\u590D\u5931\u8D25: ${error?.message || error}`);
1586
+ });
1587
+ if (options.restore) {
1588
+ await restoreExpandedFullPageScreenshot(page, state2);
1589
+ }
1590
+ }
1591
+ };
972
1592
  var capturePageScreenshot = async (page, options = {}) => {
973
1593
  const fullPage = Boolean(options.fullPage);
974
1594
  const type = fullPage ? FORCED_FULLPAGE_TYPE : normalizeType(options.type);
@@ -1023,23 +1643,35 @@ var capturePageScreenshot = async (page, options = {}) => {
1023
1643
  }
1024
1644
  };
1025
1645
  var captureExpandedFullPageScreenshot = async (page, options = {}) => {
1026
- const state2 = await prepareExpandedFullPageScreenshot(page, options);
1027
- try {
1028
- return await capturePageScreenshot(page, {
1029
- fullPage: true,
1030
- type: options.type || "png",
1031
- quality: options.quality,
1032
- timeout: options.timeout,
1033
- maxClipHeight: state2.targetHeight
1034
- });
1035
- } finally {
1036
- await restoreAffixedElementsForExpandedScreenshot(page).catch((error) => {
1037
- logger.warning(`\u79FB\u52A8\u7AEF\u5438\u9644\u5143\u7D20\u6062\u590D\u5931\u8D25: ${error?.message || error}`);
1646
+ const attempts = Math.max(1, toPositiveInteger(options.qualityRetryAttempts, DEFAULT_QUALITY_RETRY_ATTEMPTS));
1647
+ const retryDelayMs = Math.max(0, Number(options.qualityRetryDelayMs ?? DEFAULT_QUALITY_RETRY_DELAY_MS) || 0);
1648
+ let lastBuffer = null;
1649
+ let lastAnalysis = null;
1650
+ let lastIssue = null;
1651
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
1652
+ const buffer = await captureExpandedFullPageScreenshotOnce(page, options);
1653
+ const analysis = await analyzeScreenshotBuffer(buffer).catch((error) => {
1654
+ logger.warning(`\u622A\u56FE\u8D28\u91CF\u5206\u6790\u5931\u8D25: ${error?.message || error}`);
1655
+ return null;
1038
1656
  });
1039
- if (options.restore) {
1040
- await restoreExpandedFullPageScreenshot(page, state2);
1657
+ const issue = resolveScreenshotQualityIssue(analysis);
1658
+ lastBuffer = buffer;
1659
+ lastAnalysis = analysis;
1660
+ lastIssue = issue;
1661
+ if (!issue) {
1662
+ return buffer;
1663
+ }
1664
+ if (attempt < attempts && retryDelayMs > 0) {
1665
+ logger.warning(`\u622A\u56FE\u7591\u4F3C\u5F02\u5E38(${issue})\uFF0C\u7B49\u5F85\u540E\u91CD\u8BD5: attempt=${attempt}/${attempts}`);
1666
+ await (0, import_delay.default)(retryDelayMs);
1041
1667
  }
1042
1668
  }
1669
+ if (lastIssue && lastAnalysis) {
1670
+ logger.warning(
1671
+ `\u622A\u56FE\u8D28\u91CF\u4ECD\u5F02\u5E38(${lastIssue})\uFF0C\u8FD4\u56DE\u6700\u4F73\u53EF\u5F97\u7ED3\u679C: light=${lastAnalysis.lightBlankRowsRatio.toFixed(2)}, dark=${lastAnalysis.darkBlankRowsRatio.toFixed(2)}, loading=${lastAnalysis.loadingLikeRowsRatio.toFixed(2)}`
1672
+ );
1673
+ }
1674
+ return lastBuffer;
1043
1675
  };
1044
1676
 
1045
1677
  // src/errors.js
@@ -9724,7 +10356,7 @@ var watermarkifyScreenshotBuffer = async (buffer, meta, page = null, options = {
9724
10356
  };
9725
10357
 
9726
10358
  // src/internals/compression.js
9727
- var import_jimp = require("jimp");
10359
+ var import_jimp2 = require("jimp");
9728
10360
  var logger15 = createInternalLogger("Compression");
9729
10361
  var DEFAULT_SCREENSHOT_MAX_BYTES = 5 * 1024 * 1024;
9730
10362
  var DEFAULT_SCREENSHOT_OUTPUT_TYPE = "jpeg";
@@ -9791,10 +10423,10 @@ var encodeJpeg = async (sourceImage, compression, scale, quality) => {
9791
10423
  image.resize({
9792
10424
  w: width,
9793
10425
  h: height,
9794
- mode: import_jimp.ResizeStrategy.BILINEAR
10426
+ mode: import_jimp2.ResizeStrategy.BILINEAR
9795
10427
  });
9796
10428
  }
9797
- const buffer = await image.getBuffer(import_jimp.JimpMime.jpeg, { quality });
10429
+ const buffer = await image.getBuffer(import_jimp2.JimpMime.jpeg, { quality });
9798
10430
  return {
9799
10431
  buffer,
9800
10432
  bytes: getBase64BytesFromBuffer(buffer),
@@ -9806,7 +10438,7 @@ var encodeJpeg = async (sourceImage, compression, scale, quality) => {
9806
10438
  };
9807
10439
  };
9808
10440
  var compressImageBuffer = async (buffer, compression) => {
9809
- const sourceImage = await import_jimp.Jimp.read(buffer);
10441
+ const sourceImage = await import_jimp2.Jimp.read(buffer);
9810
10442
  const maxQuality = toJpegQuality(compression.quality);
9811
10443
  const minQuality = Math.min(maxQuality, toJpegQuality(compression.minQuality));
9812
10444
  let quality = maxQuality;