@howells/fieldwork-sdk 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +72 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +66 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +8 -8
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +176 -171
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +351 -33
  42. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  43. package/package.json +6 -1
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
@@ -0,0 +1,1436 @@
1
+ import { r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
2
+ import { n as checkCallSettings } from "./util-LvME_uOj.js";
3
+ import { z } from "zod/mini";
4
+ import { createDocument } from "@mixmark-io/domino";
5
+ // src/image/blocked.ts
6
+ /**
7
+ * What the page is instead of the page, such as "a Cloudflare challenge", or
8
+ * undefined when nothing marks it. The markers are conservative, and
9
+ * `bestImages` asks only when a page has no images, so a page with content
10
+ * never counts as blocked.
11
+ *
12
+ * Self-contained so it can be serialised into a page script.
13
+ */
14
+ const blockedBy = (document, url) => {
15
+ const text = (selector) => (document.querySelector(selector)?.textContent ?? "").trim();
16
+ const title = text("title");
17
+ const heading = text("h1");
18
+ const has = (selectors) => document.querySelectorAll(selectors).length > 0;
19
+ let host = "";
20
+ try {
21
+ host = new URL(url).hostname;
22
+ } catch {}
23
+ return [
24
+ [/^just a moment|^attention required!? \| cloudflare/iu.test(title) || has("#challenge-form, #challenge-stage, #cf-challenge-running, .cf-browser-verification, script[src*=\"challenges.cloudflare.com\"]"), "a Cloudflare challenge"],
25
+ [has("#px-captcha, iframe[src*=\"captcha-delivery.com\"]") || /captcha|robot|human|verif|security check/iu.test(title) && has(".g-recaptcha, .h-captcha, iframe[src*=\"recaptcha\"], iframe[src*=\"hcaptcha\"]"), "a captcha"],
26
+ [/^access denied/iu.test(title) || /^access denied/iu.test(heading), "an Access Denied page"],
27
+ [/^(?:consent|guce)\./iu.test(host) || has(".sp_veil, .fc-dialog-overlay, #consent-wall"), "a consent wall"]
28
+ ].find(([matched]) => matched)?.[1];
29
+ };
30
+ // src/image/collect/markup.ts
31
+ /** The nodes as an array. */
32
+ const nodeList = (nodes) => Array.from(nodes);
33
+ /** A positive pixel count written as "640" or "640px", or undefined. */
34
+ const pixels = (value) => {
35
+ const match = /^\s*(?<count>\d+(?:\.\d+)?)\s*(?:px)?\s*$/iu.exec(value ?? "");
36
+ const count = Number(match?.groups?.count ?? NaN);
37
+ return count > 0 ? count : void 0;
38
+ };
39
+ /** srcset entries as written: a URL is a run of non-space; a trailing comma ends it with no descriptor. */
40
+ const parseSrcset = (srcset) => {
41
+ const entries = [];
42
+ let index = 0;
43
+ while (index < srcset.length) {
44
+ while (index < srcset.length && /[\s,]/u.test(srcset.charAt(index))) index += 1;
45
+ let url = "";
46
+ while (index < srcset.length && !/\s/u.test(srcset.charAt(index))) {
47
+ url += srcset.charAt(index);
48
+ index += 1;
49
+ }
50
+ if (url === "") break;
51
+ let descriptor = "";
52
+ if (url.endsWith(",")) url = url.replace(/,+$/u, "");
53
+ else while (index < srcset.length && srcset.charAt(index) !== ",") {
54
+ descriptor += srcset.charAt(index);
55
+ index += 1;
56
+ }
57
+ entries.push({
58
+ descriptor: descriptor.trim(),
59
+ url
60
+ });
61
+ }
62
+ return entries;
63
+ };
64
+ /** Whether `node` has an ancestor with the tag name `tag`, lowercase. */
65
+ const isInside = (node, tag) => {
66
+ let parent = node.parentNode;
67
+ while (parent !== null) {
68
+ if (parent.nodeName.toLowerCase() === tag) return true;
69
+ parent = parent.parentNode;
70
+ }
71
+ return false;
72
+ };
73
+ /** The attributes lazy-loading scripts keep an image's real URL in: as a src, and as a srcset. */
74
+ const lazyAttributes = () => ({
75
+ src: [
76
+ "data-src",
77
+ "data-lazy-src",
78
+ "data-original",
79
+ "data-lazy",
80
+ "data-hi-res-src",
81
+ "data-full-src",
82
+ "data-large-src",
83
+ "data-zoom-src",
84
+ "data-zoom-image",
85
+ "data-large_image"
86
+ ],
87
+ srcset: ["data-srcset", "data-lazy-srcset"]
88
+ });
89
+ // src/image/collect/elements.ts
90
+ /** Where `node` sits, read from its ancestors from `from` up, with `alt` from the image itself. */
91
+ const contextOf = (node, from) => {
92
+ const chromeTags = /* @__PURE__ */ new Set([
93
+ "header",
94
+ "nav",
95
+ "footer",
96
+ "dialog"
97
+ ]);
98
+ const chromeRoles = /* @__PURE__ */ new Set([
99
+ "banner",
100
+ "navigation",
101
+ "contentinfo",
102
+ "dialog",
103
+ "alertdialog"
104
+ ]);
105
+ const context = {
106
+ alt: (node.getAttribute("alt") ?? "").trim(),
107
+ chrome: false,
108
+ figure: false
109
+ };
110
+ for (let parent = from; parent !== null; parent = parent.parentNode) {
111
+ const tag = parent.nodeName.toLowerCase();
112
+ context.figure ||= tag === "figure";
113
+ if (tag === "main" || tag === "article") context.chrome = false;
114
+ else if (chromeTags.has(tag) || tag !== "#document" && chromeRoles.has(parent.getAttribute("role") ?? "")) context.chrome = true;
115
+ }
116
+ return context;
117
+ };
118
+ /** Adds each srcset entry, sized from its descriptor and the element's declared aspect ratio. */
119
+ const addSrcset = (sink, srcset, source, element, { height, width }, context) => {
120
+ if (srcset === null) return;
121
+ for (const entry of parseSrcset(srcset)) {
122
+ const descriptor = /^(?<value>\d+(?:\.\d+)?)(?<unit>[wx])$/iu.exec(entry.descriptor)?.groups ?? {};
123
+ const value = Number(descriptor.value);
124
+ let entryWidth;
125
+ if (descriptor.unit?.toLowerCase() === "w" && value > 0) entryWidth = value;
126
+ else if (descriptor.unit !== void 0 && value > 0 && width !== void 0) entryWidth = Math.round(width * value);
127
+ else if (entry.descriptor === "") entryWidth = width;
128
+ const entryHeight = entryWidth !== void 0 && width !== void 0 && height !== void 0 ? Math.round(entryWidth * height / width) : void 0;
129
+ sink.add(entry.url, source, element, entryWidth, entryHeight, context);
130
+ }
131
+ };
132
+ /** An img's src, srcset and lazy attributes, all as one element. */
133
+ const addImg = (sink, img, element, context, noscript) => {
134
+ const declared = {
135
+ height: pixels(img.getAttribute("height")),
136
+ width: pixels(img.getAttribute("width"))
137
+ };
138
+ sink.add(img.getAttribute("src"), noscript ? "noscript" : "img", element, declared.width, declared.height, context);
139
+ addSrcset(sink, img.getAttribute("srcset"), noscript ? "noscript" : "srcset", element, declared, context);
140
+ const lazy = noscript ? "noscript" : "data-attribute";
141
+ const attributes = lazyAttributes();
142
+ for (const name of attributes.src) sink.add(img.getAttribute(name), lazy, element, declared.width, declared.height, context);
143
+ for (const name of attributes.srcset) addSrcset(sink, img.getAttribute(name), lazy, element, declared, context);
144
+ };
145
+ /**
146
+ * img elements, with a picture's sources as the same element. An img inside
147
+ * noscript is read with the noscript fallbacks, because a browser exposes
148
+ * noscript content as text and domino as elements.
149
+ */
150
+ const collectImgs = (document, sink) => {
151
+ const pictures = /* @__PURE__ */ new Map();
152
+ for (const img of nodeList(document.querySelectorAll("img"))) {
153
+ if (isInside(img, "noscript")) continue;
154
+ const element = sink.next();
155
+ const context = sink.placed(img, img.parentNode);
156
+ const picture = img.parentNode;
157
+ if (picture !== null && picture.nodeName.toLowerCase() === "picture") pictures.set(picture, {
158
+ context,
159
+ declared: {
160
+ height: pixels(img.getAttribute("height")),
161
+ width: pixels(img.getAttribute("width"))
162
+ },
163
+ element
164
+ });
165
+ addImg(sink, img, element, context, false);
166
+ }
167
+ for (const [picture, { context, declared: fallback, element }] of pictures) for (const source of nodeList(picture.querySelectorAll("source"))) {
168
+ const declared = {
169
+ height: pixels(source.getAttribute("height")) ?? fallback.height,
170
+ width: pixels(source.getAttribute("width")) ?? fallback.width
171
+ };
172
+ for (const name of ["srcset", ...lazyAttributes().srcset]) addSrcset(sink, source.getAttribute(name), "picture", element, declared, context);
173
+ }
174
+ };
175
+ /**
176
+ * noscript fallbacks: the same markup in a browser (text) and on domino
177
+ * (elements), parsed again in an inert document so nothing loads.
178
+ */
179
+ const collectNoscript = (document, sink) => {
180
+ for (const noscript of nodeList(document.querySelectorAll("noscript"))) {
181
+ const inert = document.implementation.createHTMLDocument("");
182
+ if (inert.body === null) continue;
183
+ inert.body.innerHTML = noscript.innerHTML;
184
+ for (const img of nodeList(inert.body.querySelectorAll("img"))) addImg(sink, img, sink.next(), contextOf(img, noscript.parentNode), true);
185
+ }
186
+ };
187
+ /** Inline background images. */
188
+ const collectBackgrounds = (document, sink) => {
189
+ for (const styled of nodeList(document.querySelectorAll("[style]"))) {
190
+ const style = styled.getAttribute("style") ?? "";
191
+ for (const declaration of style.matchAll(/background(?:-image)?\s*:(?<value>[^;]*)/giu)) {
192
+ const value = declaration.groups?.value ?? "";
193
+ for (const match of value.matchAll(/url\(\s*(?<quote>['"]?)(?<url>.*?)\k<quote>\s*\)/giu)) sink.add(match.groups?.url, "css-background", sink.next(), void 0, void 0, sink.placed(styled, styled));
194
+ }
195
+ }
196
+ };
197
+ // src/image/collect/metadata.ts
198
+ /**
199
+ * og:image and twitter:image, with og:image's width and height, which
200
+ * belong to the og:image before them.
201
+ */
202
+ const collectSharing = (document, sink) => {
203
+ const og = [];
204
+ const ogUrlKeys = /* @__PURE__ */ new Set([
205
+ "og:image",
206
+ "og:image:url",
207
+ "og:image:secure_url"
208
+ ]);
209
+ const twitterKeys = /* @__PURE__ */ new Set(["twitter:image", "twitter:image:src"]);
210
+ const addOg = (key, content) => {
211
+ const url = sink.absolute(content);
212
+ const last = og.at(-1);
213
+ if (url === void 0 || last?.url === url) return;
214
+ if (key !== "og:image" && last !== void 0) {
215
+ og.push({
216
+ element: last.element,
217
+ height: last.height,
218
+ url,
219
+ width: last.width
220
+ });
221
+ return;
222
+ }
223
+ og.push({
224
+ element: sink.next(),
225
+ url
226
+ });
227
+ };
228
+ const setDimension = (field, content) => {
229
+ const last = og.at(-1);
230
+ const value = pixels(content);
231
+ if (last === void 0) return;
232
+ for (const entry of og) if (entry.element === last.element) entry[field] = value;
233
+ };
234
+ for (const meta of nodeList(document.querySelectorAll("meta"))) {
235
+ const key = (meta.getAttribute("property") ?? meta.getAttribute("name") ?? "").toLowerCase();
236
+ const content = meta.getAttribute("content");
237
+ if (ogUrlKeys.has(key)) addOg(key, content);
238
+ else if (key === "og:image:width" || key === "og:image:height") setDimension(key === "og:image:width" ? "width" : "height", content);
239
+ else if (twitterKeys.has(key)) sink.add(content, "twitter:image", sink.next());
240
+ }
241
+ for (const entry of og) sink.add(entry.url, "og:image", entry.element, entry.width, entry.height);
242
+ };
243
+ /** A JSON-LD width or height, written as a number or a string, in pixels. */
244
+ const jsonPixels = (value) => typeof value === "number" || typeof value === "string" ? pixels(String(value)) : void 0;
245
+ /**
246
+ * Every `image` and `thumbnailUrl` in the page's JSON-LD, as a URL, a list or
247
+ * an ImageObject, anywhere in the graph. There is no schema library in a page
248
+ * script, so the parsed JSON is narrowed by hand.
249
+ */
250
+ const collectJsonLd = (document, sink) => {
251
+ const visitImage = (value) => {
252
+ if (typeof value === "string") sink.add(value, "json-ld", sink.next());
253
+ else if (Array.isArray(value)) for (const item of value) visitImage(item);
254
+ else if (typeof value === "object" && value !== null) {
255
+ const fields = new Map(Object.entries(value));
256
+ const url = fields.get("contentUrl") ?? fields.get("url");
257
+ if (typeof url === "string") sink.add(url, "json-ld", sink.next(), jsonPixels(fields.get("width")), jsonPixels(fields.get("height")));
258
+ }
259
+ };
260
+ const walk = (value) => {
261
+ if (Array.isArray(value)) for (const item of value) walk(item);
262
+ else if (typeof value === "object" && value !== null) for (const [key, child] of Object.entries(value)) if (key === "image" || key === "thumbnailUrl") visitImage(child);
263
+ else walk(child);
264
+ };
265
+ for (const script of nodeList(document.querySelectorAll("script[type]"))) {
266
+ if ((script.getAttribute("type") ?? "").split(";")[0]?.trim().toLowerCase() !== "application/ld+json") continue;
267
+ try {
268
+ walk(JSON.parse(script.textContent ?? ""));
269
+ } catch {}
270
+ }
271
+ };
272
+ // src/image/collect.ts
273
+ /**
274
+ * Every image candidate in `document`, with URLs resolved against `baseUrl`
275
+ * (or the document's `<base href>`). Reads og:image and twitter:image,
276
+ * JSON-LD image fields, `img` (src, srcset and lazy-loading attributes),
277
+ * `picture` sources, `noscript` fallbacks and inline background images.
278
+ * Only http and https URLs are kept.
279
+ *
280
+ * `probe`, in a rendered page, lays out each img and background element.
281
+ *
282
+ * To run it in a page, use `collectImagesSource`, which brings the functions
283
+ * it calls; see the file comment.
284
+ */
285
+ const collectImages = (document, baseUrl, probe) => {
286
+ const candidates = [];
287
+ let elements = 0;
288
+ let base = baseUrl;
289
+ const baseHref = document.querySelector("base[href]")?.getAttribute("href");
290
+ if (baseHref !== null && baseHref !== void 0) try {
291
+ base = new URL(baseHref, baseUrl).href;
292
+ } catch {}
293
+ const absolute = (value) => {
294
+ const trimmed = value?.trim();
295
+ if (trimmed === void 0 || trimmed === "") return;
296
+ try {
297
+ const url = new URL(trimmed, base);
298
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : void 0;
299
+ } catch {
300
+ return;
301
+ }
302
+ };
303
+ const sink = {
304
+ absolute,
305
+ add: (value, source, element, width, height, context) => {
306
+ const url = absolute(value);
307
+ if (url === void 0) return;
308
+ candidates.push({
309
+ element,
310
+ source,
311
+ url,
312
+ ...width !== void 0 && { width },
313
+ ...height !== void 0 && { height },
314
+ ...context !== void 0 && { context }
315
+ });
316
+ },
317
+ next: () => {
318
+ elements += 1;
319
+ return elements;
320
+ },
321
+ placed: (node, from) => {
322
+ const context = contextOf(node, from);
323
+ if (probe !== void 0) context.layout = probe(node);
324
+ return context;
325
+ }
326
+ };
327
+ collectSharing(document, sink);
328
+ collectJsonLd(document, sink);
329
+ collectImgs(document, sink);
330
+ collectNoscript(document, sink);
331
+ collectBackgrounds(document, sink);
332
+ return candidates;
333
+ };
334
+ /**
335
+ * `collectImages` as the source of an expression, for a page script: it
336
+ * evaluates to the collector, with every function it calls defined beside it
337
+ * in a closed scope, so it runs with nothing in scope but standard globals.
338
+ * Each is defined under the name the build gave it, which is the name the
339
+ * others call it by.
340
+ */
341
+ const collectImagesSource = `(() => {
342
+ ${[
343
+ nodeList,
344
+ pixels,
345
+ parseSrcset,
346
+ isInside,
347
+ lazyAttributes,
348
+ jsonPixels,
349
+ collectSharing,
350
+ collectJsonLd,
351
+ contextOf,
352
+ addSrcset,
353
+ addImg,
354
+ collectImgs,
355
+ collectNoscript,
356
+ collectBackgrounds
357
+ ].map((helper) => `const ${helper.name} = ${helper.toString()};`).join("\n")}
358
+ return ${collectImages.toString()};
359
+ })()`;
360
+ // src/image/resolve.ts
361
+ /**
362
+ * The largest original of the image at `url`, from the URL alone: the first
363
+ * CDN pattern that changes it strips resize parameters and size suffixes, or
364
+ * rewrites it to the master or original path. Unwraps Next.js's and
365
+ * Vercel's image optimizers first. Covers Condé Nast, Cloudinary,
366
+ * Cloudflare Images, Fastly IO, Shopify, Sanity, imgix, WordPress,
367
+ * Squarespace, Contentful, Prismic, Bunny, ImageKit, Storyblok, Builder and
368
+ * SpeedSize, then common resize parameters on any host. Never fetches.
369
+ *
370
+ * Self-contained so it can be serialised into a page script; see the file
371
+ * comment.
372
+ */
373
+ const resolveOriginal = (url) => {
374
+ /** The CDNs, in srcfull's order; the first whose rules change a URL wins. */
375
+ const PATTERNS = [
376
+ {
377
+ extract: {
378
+ pattern: /^(?<photo>https?:\/\/media\.[^/]+\/photos\/[a-f0-9]{24})(?:\/.*)?$/u,
379
+ replacement: "$<photo>/master/w_2560,c_limit/image.jpg"
380
+ },
381
+ where: ["media."]
382
+ },
383
+ {
384
+ extract: {
385
+ pattern: /^(?<upload>https?:\/\/res\.cloudinary\.com\/[^/]+\/image\/upload)\/(?:[a-z]{1,3}_[^/]*\/)+(?<file>.+)$/u,
386
+ replacement: "$<upload>/$<file>"
387
+ },
388
+ where: ["res.cloudinary.com"]
389
+ },
390
+ {
391
+ extract: {
392
+ pattern: /^https?:\/\/[^/]+\/cdn-cgi\/image\/[^/]+\/(?<source>.+)$/u,
393
+ replacement: "$<source>"
394
+ },
395
+ where: ["/cdn-cgi/image/"]
396
+ },
397
+ {
398
+ strip: [
399
+ /[?&]width=\d+/gu,
400
+ /[?&]height=\d+/gu,
401
+ /[?&]quality=\d+/gu,
402
+ /[?&]fit=[^&#]+/gu,
403
+ /[?&]crop=[^&#]+/gu,
404
+ /[?&]dpr=[\d.]+/gu,
405
+ /[?&]format=[^&#]+/gu,
406
+ /[?&]bg-color=[^&#]+/gu
407
+ ],
408
+ where: ["fastly.io"]
409
+ },
410
+ {
411
+ strip: [
412
+ /[?&]v=[^&#]+/gu,
413
+ /[?&]width=\d+/gu,
414
+ /[?&]height=\d+/gu,
415
+ /[?&]crop=[^&#]+/gu,
416
+ /[?&]originalWidth=\d+/gu,
417
+ /[?&]originalHeight=\d+/gu
418
+ ],
419
+ suffixes: [
420
+ "_small",
421
+ "_medium",
422
+ "_large",
423
+ "_grande",
424
+ "_master",
425
+ String.raw`_\d+x\d*`,
426
+ String.raw`_\d*x\d+`
427
+ ],
428
+ where: ["cdn.shopify.com", "/cdn/shop/"]
429
+ },
430
+ {
431
+ size: /-(?<width>\d+)x(?<height>\d+)\.\w+$/u,
432
+ strip: [/\?.*/gu],
433
+ where: ["cdn.sanity.io"]
434
+ },
435
+ {
436
+ strip: [
437
+ /[?&]w=\d+/gu,
438
+ /[?&]h=\d+/gu,
439
+ /[?&]fit=\w+/gu,
440
+ /[?&]auto=[\w,]+/gu,
441
+ /[?&]q=\d+/gu,
442
+ /[?&]fm=\w+/gu,
443
+ /[?&]dpr=[\d.]+/gu,
444
+ /[?&]crop=[\w,]+/gu
445
+ ],
446
+ where: [".imgix.net"]
447
+ },
448
+ {
449
+ suffixes: [String.raw`-\d+x\d+`, "-scaled"],
450
+ where: ["wp-content/uploads"]
451
+ },
452
+ {
453
+ strip: [/[?&]format=\w+/gu, /[?&]content-type=[^&#]+/gu],
454
+ where: ["images.squarespace-cdn.com/content/", "squarespace.com/static/"]
455
+ },
456
+ {
457
+ strip: [
458
+ /[?&]w=\d+/gu,
459
+ /[?&]h=\d+/gu,
460
+ /[?&]q=\d+/gu,
461
+ /[?&]fm=\w+/gu,
462
+ /[?&]fit=\w+/gu
463
+ ],
464
+ where: ["images.ctfassets.net", "images-www.contentful.com"]
465
+ },
466
+ {
467
+ strip: [
468
+ /[?&]w=\d+/gu,
469
+ /[?&]h=\d+/gu,
470
+ /[?&]q=\d+/gu,
471
+ /[?&]auto=[\w,]+/gu
472
+ ],
473
+ where: ["images.prismic.io"]
474
+ },
475
+ {
476
+ strip: [
477
+ /[?&]width=\d+/gu,
478
+ /[?&]height=\d+/gu,
479
+ /[?&]quality=\d+/gu
480
+ ],
481
+ where: ["b-cdn.net"]
482
+ },
483
+ {
484
+ extract: {
485
+ pattern: /^(?<account>https?:\/\/ik\.imagekit\.io\/[^/]+)\/tr:[^/]+\/(?<file>.+)$/u,
486
+ replacement: "$<account>/$<file>"
487
+ },
488
+ where: ["ik.imagekit.io"]
489
+ },
490
+ {
491
+ extract: {
492
+ pattern: /^(?<file>https?:\/\/a\.storyblok\.com\/f\/\d+\/\d+x\d+\/[^/]+\/[^/?]+)(?:\/m\/[^?]+)?(?:\?.*)?$/u,
493
+ replacement: "$<file>"
494
+ },
495
+ size: /\/f\/\d+\/(?<width>\d+)x(?<height>\d+)\//u,
496
+ where: ["a.storyblok.com"]
497
+ },
498
+ {
499
+ strip: [
500
+ /[?&]width=\d+/gu,
501
+ /[?&]height=\d+/gu,
502
+ /[?&]quality=\d+/gu,
503
+ /[?&]fit=[^&#]+/gu,
504
+ /[?&]position=[^&#]+/gu,
505
+ /[?&]format=[^&#]+/gu
506
+ ],
507
+ where: ["cdn.builder.io/api/v1/image/", "builder.io/api/v1/image/"]
508
+ },
509
+ {
510
+ extract: {
511
+ pattern: /^https?:\/\/(?:aicdn|sfycdn)\.speedsize\.com\/[^/]+\/(?:https?:\/\/)?(?<source>(?:www\.)?[^/?#]+\/.+)$/u,
512
+ replacement: "https://$<source>"
513
+ },
514
+ strip: [
515
+ /[?&]w=\d+/gu,
516
+ /[?&]h=\d+/gu,
517
+ /[?&]width=\d+/gu,
518
+ /[?&]height=\d+/gu,
519
+ /[?&]quality=\d+/gu,
520
+ /[?&]q=\d+/gu,
521
+ /[?&]format=[^&#]+/gu,
522
+ /[?&]fmt=[^&#]+/gu,
523
+ /[?&]fit=[^&#]+/gu,
524
+ /[?&]resize=[^&#]+/gu
525
+ ],
526
+ where: ["aicdn.speedsize.com", "sfycdn.speedsize.com"]
527
+ }
528
+ ];
529
+ /** Any other host: the usual resize parameters, tried when no CDN's rules apply. */
530
+ const GENERIC = {
531
+ strip: [
532
+ /[?&]w=\d+/gu,
533
+ /[?&]h=\d+/gu,
534
+ /[?&]width=\d+/gu,
535
+ /[?&]height=\d+/gu,
536
+ /[?&]resize=\d+(?:,\d+)?/gu,
537
+ /[?&]size=\d+/gu,
538
+ /[?&]quality=\d+/gu,
539
+ /[?&]q=\d+/gu,
540
+ /[?&]\d+=[^&#]*/gu
541
+ ],
542
+ where: []
543
+ };
544
+ const protocols = /* @__PURE__ */ new Set(["http:", "https:"]);
545
+ /** Parses `value` against `base` and returns it only when it is http or https. */
546
+ const httpUrl = (value, base) => {
547
+ try {
548
+ const candidate = new URL(value, base);
549
+ return protocols.has(candidate.protocol) ? candidate : void 0;
550
+ } catch {
551
+ return;
552
+ }
553
+ };
554
+ /** Rewrites `input` with one CDN pattern, keeping only a valid http or https URL. */
555
+ const rewrite = (pattern, input, origin) => {
556
+ let current = input;
557
+ const { extract, strip, suffixes } = pattern;
558
+ if (extract !== void 0 && extract.pattern.test(current)) {
559
+ const extracted = httpUrl(current.replace(extract.pattern, extract.replacement), `${origin}/`);
560
+ if (extracted !== void 0) current = extracted.href;
561
+ }
562
+ if (strip !== void 0) {
563
+ for (const rule of strip) current = current.replaceAll(rule, (match) => match.startsWith("?") ? "?" : "");
564
+ current = current.replace(/\?&+/u, "?").replace(/[?&]+(?=#|$)/u, "");
565
+ }
566
+ if (suffixes !== void 0) {
567
+ const rewritten = httpUrl(current);
568
+ if (rewritten !== void 0) {
569
+ for (const suffix of suffixes) rewritten.pathname = rewritten.pathname.replace(new RegExp(`${suffix}(?<extension>\\.\\w+)$`, "u"), "$<extension>");
570
+ current = rewritten.href;
571
+ }
572
+ }
573
+ return current;
574
+ };
575
+ const page = httpUrl(url);
576
+ if (page === void 0) return {
577
+ url,
578
+ verified: true
579
+ };
580
+ const wrapped = /\/_(?:next|vercel)\/image$/u.test(page.pathname) ? page.searchParams.get("url")?.trim() : void 0;
581
+ const unwrapped = wrapped !== void 0 && wrapped !== "" ? httpUrl(wrapped, page.origin) : void 0;
582
+ if (wrapped !== void 0 && unwrapped === void 0) return {
583
+ url,
584
+ verified: true
585
+ };
586
+ const source = unwrapped === void 0 ? url : unwrapped.href;
587
+ const parsed = unwrapped ?? page;
588
+ const host = parsed.hostname.toLowerCase();
589
+ const href = parsed.href.toLowerCase();
590
+ /** Whether a `where` token names this URL. */
591
+ const applies = (token) => {
592
+ if (token.includes("/")) return href.includes(token);
593
+ if (token.startsWith(".")) return host.endsWith(token);
594
+ if (token.endsWith(".")) return host.startsWith(token);
595
+ return host === token || host.endsWith(`.${token}`);
596
+ };
597
+ /** Resolves one pattern against `source`, returning a result when it rewrites or names dimensions. */
598
+ const resolveWith = (pattern) => {
599
+ const current = rewrite(pattern, source, parsed.origin);
600
+ const named = pattern.size?.exec(current)?.groups;
601
+ const hasSize = named?.width !== void 0 && named.height !== void 0;
602
+ if (current === source && !hasSize) return;
603
+ return {
604
+ url: current,
605
+ verified: current === url,
606
+ ...hasSize && {
607
+ height: Number(named.height),
608
+ width: Number(named.width)
609
+ }
610
+ };
611
+ };
612
+ for (const pattern of [...PATTERNS, GENERIC]) {
613
+ if (pattern !== GENERIC && !pattern.where.some(applies)) continue;
614
+ const resolved = resolveWith(pattern);
615
+ if (resolved !== void 0) return resolved;
616
+ }
617
+ return {
618
+ url: source,
619
+ verified: source === url
620
+ };
621
+ };
622
+ // src/image/rules.ts
623
+ /** The sources that name an image for sharing the page. */
624
+ const SHARING = /* @__PURE__ */ new Set(["og:image", "twitter:image"]);
625
+ /** Words in a URL that name a site-wide sharing card rather than the page's own image. */
626
+ const SITE_CARD = /(?:^|[^a-z])(?:branded|social)(?:[^a-z]|$)/iu;
627
+ /** The area assumed for a sharing image named without a size: a usual og:image. */
628
+ const SHARING_AREA = 756e3;
629
+ /** The area assumed for any other image named without a size: a small content image. */
630
+ const UNSIZED_AREA = 76800;
631
+ /** The shortest side, in pixels, of an image that can be content rather than an icon, logo or badge. */
632
+ const MIN_SIDE = 100;
633
+ /** A URL path to an SVG: drawn decoration (icons, logos, patterns), not a photograph. */
634
+ const SVG_PATH = /\.svgz?$/iu;
635
+ /** How much being the page's largest contentful paint raises an image. */
636
+ const LCP_WEIGHT = 2;
637
+ /** The bottom of a rendered page's first viewport, in CSS pixels from the top. */
638
+ const FOLD = 800;
639
+ /** How far an image's bottom edge runs below the first viewport, in CSS pixels, when its weight halves. */
640
+ const DEPTH = 500;
641
+ /**
642
+ * The box area, in CSS pixels, assumed on a rendered page for an image the
643
+ * page names but does not show, such as a sharing image: a small content image.
644
+ */
645
+ const UNSHOWN_BOX = 1e5;
646
+ /** The pathname of `url`, or empty when `url` cannot parse. */
647
+ const pathnameOf = (url) => URL.parse(url)?.pathname ?? "";
648
+ /**
649
+ * The area of the largest non-chrome box the page shows the image at, weighted
650
+ * by how far its bottom edge runs below the first viewport, so a tall image
651
+ * that only starts in the first viewport gives way to the one shown whole
652
+ * there; `UNSHOWN_BOX` when no content element of it is laid out (or it is
653
+ * also named in metadata), such as a sharing image. Undefined when its content
654
+ * elements are laid out, every box is empty, and no metadata names it: the
655
+ * page holds the image without showing it, as with a tracking pixel or a
656
+ * hidden slide.
657
+ */
658
+ const shownArea = (candidates, content) => {
659
+ const boxes = content.flatMap(({ context }) => context?.layout === void 0 ? [] : [context.layout]);
660
+ if (boxes.length === 0) return UNSHOWN_BOX;
661
+ const best = Math.max(...boxes.map((layout) => layout.width * layout.height / (1 + Math.max(0, layout.top + layout.height - FOLD) / DEPTH)));
662
+ if (best > 0) return best;
663
+ return candidates.some((candidate) => candidate.context === void 0) ? UNSHOWN_BOX : void 0;
664
+ };
665
+ /** The declared pixel area, or the area assumed for an image named without one. */
666
+ const areaOf$1 = (candidates, top) => {
667
+ if (top.width !== void 0 && top.height !== void 0) return top.width * top.height;
668
+ return candidates.every((candidate) => SHARING.has(candidate.source)) ? SHARING_AREA : UNSIZED_AREA;
669
+ };
670
+ /** How much a figure and alt text raise an image, across its non-chrome placements. */
671
+ const contentWeight = (content) => {
672
+ const figure = content.some((candidate) => candidate.context?.figure === true);
673
+ const alt = content.some((candidate) => candidate.context !== void 0 && candidate.context.alt !== "");
674
+ return (figure ? 1.5 : 1) * (alt ? 1.2 : 1);
675
+ };
676
+ /**
677
+ * How much naming the image for sharing raises it: most when the page also
678
+ * shows it, as a product page does its main photograph, since a larger
679
+ * image beside it is then a recommendation or a later view. A sharing image
680
+ * that looks like a site-wide card is held below any content image.
681
+ */
682
+ const sharingWeight = (candidates, top) => {
683
+ if (!candidates.some((candidate) => SHARING.has(candidate.source))) return 1;
684
+ if (SITE_CARD.test(pathnameOf(top.url))) return .01;
685
+ return candidates.some((candidate) => !SHARING.has(candidate.source) && candidate.source !== "json-ld") ? 4 : 1.5;
686
+ };
687
+ /**
688
+ * The score of an image, from its candidates and `top`, the largest of them:
689
+ * its area, weighted by the rules. `rendered` says whether the page was
690
+ * rendered, and so whether its boxes rank it. Undefined when the image is
691
+ * left out: every DOM placement sits in the site's header, nav, footer or
692
+ * pop-up dialog, it is an SVG, its known size is too small for content (which
693
+ * leaves out 1×1 tracking pixels and spacers), or a rendered page holds it
694
+ * without showing it.
695
+ */
696
+ const judge = (candidates, top, rendered) => {
697
+ const dom = candidates.filter((candidate) => candidate.context !== void 0);
698
+ const content = dom.filter((candidate) => candidate.context?.chrome !== true);
699
+ if (dom.length > 0 && content.length === 0 || SVG_PATH.test(pathnameOf(top.url)) || (top.width ?? MIN_SIDE) < MIN_SIDE || (top.height ?? MIN_SIDE) < MIN_SIDE) return;
700
+ const area = rendered ? shownArea(candidates, content) : areaOf$1(candidates, top);
701
+ if (area === void 0) return;
702
+ const lcp = content.some((candidate) => candidate.context?.layout?.lcp === true);
703
+ return area * contentWeight(content) * sharingWeight(candidates, top) * (lcp ? LCP_WEIGHT : 1);
704
+ };
705
+ // src/image/shown.ts
706
+ /**
707
+ * The candidate that stands for an image: the largest declared, then the
708
+ * widest, then a lazy or responsive URL over the plain src, which is often a
709
+ * placeholder, then https over http. Undefined for no candidates.
710
+ *
711
+ * Self-contained so it can be serialised into a page script.
712
+ */
713
+ const shownCandidate = (candidates) => {
714
+ const PREFERENCE = [
715
+ "data-attribute",
716
+ "srcset",
717
+ "picture",
718
+ "noscript",
719
+ "img",
720
+ "json-ld",
721
+ "og:image",
722
+ "twitter:image",
723
+ "css-background"
724
+ ];
725
+ let shown;
726
+ let best = {
727
+ area: -1,
728
+ preference: 0,
729
+ secure: 0,
730
+ width: 0
731
+ };
732
+ for (const candidate of candidates) {
733
+ const { height, source, width } = candidate;
734
+ const rank = {
735
+ area: width === void 0 || height === void 0 ? 0 : width * height,
736
+ preference: PREFERENCE.indexOf(source),
737
+ secure: candidate.url.startsWith("https:") ? 1 : 0,
738
+ width: width ?? 0
739
+ };
740
+ const wins = rank.area - best.area || rank.width - best.width || best.preference - rank.preference || rank.secure - best.secure;
741
+ if (shown === void 0 || wins > 0) {
742
+ shown = candidate;
743
+ best = rank;
744
+ }
745
+ }
746
+ return shown;
747
+ };
748
+ // src/image/rank.ts
749
+ /** The URL that names an image whatever its size or scheme: its original's, over https. */
750
+ const imageKey = (url) => resolveOriginal(url).url.replace(/^http:/u, "https:");
751
+ /** Candidates in groups: one per element, merged where two elements name the same image. */
752
+ const group = (candidates) => {
753
+ const parent = /* @__PURE__ */ new Map();
754
+ const find = (element) => {
755
+ const up = parent.get(element) ?? element;
756
+ if (up === element) return element;
757
+ const root = find(up);
758
+ parent.set(element, root);
759
+ return root;
760
+ };
761
+ const byUrl = /* @__PURE__ */ new Map();
762
+ for (const { element, url } of candidates) {
763
+ const key = imageKey(url);
764
+ const earlier = byUrl.get(key);
765
+ if (earlier === void 0) byUrl.set(key, element);
766
+ else {
767
+ const [a, b] = [find(earlier), find(element)];
768
+ if (a !== b) parent.set(Math.max(a, b), Math.min(a, b));
769
+ }
770
+ }
771
+ const groups = /* @__PURE__ */ new Map();
772
+ for (const candidate of candidates) {
773
+ const root = find(candidate.element);
774
+ const existing = groups.get(root);
775
+ if (existing === void 0) groups.set(root, [candidate]);
776
+ else existing.push(candidate);
777
+ }
778
+ return [...groups.values()];
779
+ };
780
+ const areaOf = (size) => (size.width ?? 0) * (size.height ?? 0);
781
+ /** The width and height that are known. */
782
+ const sized = (size) => ({
783
+ ...size.width !== void 0 && { width: size.width },
784
+ ...size.height !== void 0 && { height: size.height }
785
+ });
786
+ /**
787
+ * Where an image is after a render: at the CDN original when it loaded at
788
+ * least as large as the page's own URL, else at the page's own URL, since a
789
+ * pattern URL that did not load, or loaded smaller (a CDN's placeholder),
790
+ * is not the original. Null when a verified original was not tried;
791
+ * "failed" when the browser could not load the image at any of its URLs.
792
+ */
793
+ const renderedPlace = (shown, original, measured) => {
794
+ const loaded = measured.get(original.url);
795
+ const own = measured.get(shown.url);
796
+ if (loaded === null && (original.verified || own === null)) return "failed";
797
+ if (loaded !== void 0 && loaded !== null && areaOf(loaded) >= areaOf(own ?? shown)) return {
798
+ measured: true,
799
+ url: original.url,
800
+ verified: true,
801
+ ...loaded
802
+ };
803
+ if (loaded === void 0 && original.verified) return null;
804
+ return {
805
+ measured: own !== void 0 && own !== null,
806
+ url: shown.url,
807
+ verified: true,
808
+ ...sized(own ?? shown)
809
+ };
810
+ };
811
+ /** The size to report on the cheap path: the CDN original's embedded size, else the candidate's declared size. */
812
+ const cheapSize = (original, shown) => {
813
+ if (original.width !== void 0 && original.height !== void 0) return original;
814
+ return shown.width === void 0 || shown.height === void 0 ? original : shown;
815
+ };
816
+ /**
817
+ * The URL an image is returned at and its size: measured, else the CDN
818
+ * original's embedded size when the CDN's URL names it, else declared. See
819
+ * `renderedPlace` for a rendered page.
820
+ */
821
+ const placeOf = (shown, measured) => {
822
+ const original = resolveOriginal(shown.url);
823
+ const rendered = measured === void 0 ? null : renderedPlace(shown, original, measured);
824
+ if (rendered !== null) return rendered;
825
+ return {
826
+ measured: false,
827
+ url: original.url,
828
+ verified: original.verified,
829
+ ...sized(cheapSize(original, shown))
830
+ };
831
+ };
832
+ /**
833
+ * The best candidate in `candidates` that did not fail to load in the browser,
834
+ * paired with its resolved place, or null when every candidate failed.
835
+ */
836
+ const pickPlace = (candidates, measured) => {
837
+ const remaining = [...candidates];
838
+ while (remaining.length > 0) {
839
+ const shown = shownCandidate(remaining);
840
+ if (shown === void 0) break;
841
+ const place = placeOf(shown, measured);
842
+ if (place !== "failed") return {
843
+ place,
844
+ shown
845
+ };
846
+ remaining.splice(remaining.indexOf(shown), 1);
847
+ }
848
+ return null;
849
+ };
850
+ /**
851
+ * One image per group, at the group's best candidate, or undefined when the
852
+ * rules leave it out or the browser could not load any of its URLs.
853
+ */
854
+ const toImage = (candidates, measured) => {
855
+ if (candidates.length === 0) throw new Error("an image group has no candidates");
856
+ const picked = pickPlace(candidates, measured);
857
+ if (picked === null) return;
858
+ const { place, shown } = picked;
859
+ const score = judge(candidates, {
860
+ ...shown,
861
+ height: place.height,
862
+ width: place.width
863
+ }, measured !== void 0);
864
+ if (score === void 0) return;
865
+ return {
866
+ ...place,
867
+ score,
868
+ sources: [...new Set(candidates.map((candidate) => candidate.source)), ...candidates.some((candidate) => candidate.context?.chrome !== true && candidate.context?.layout?.lcp === true) ? ["lcp"] : []],
869
+ variants: [...new Set([shown, ...candidates].map((candidate) => candidate.url).filter((url) => url !== place.url))]
870
+ };
871
+ };
872
+ /**
873
+ * The candidates as images, best first. Images with equal scores keep
874
+ * document order. `measured` holds the sizes the render script measured.
875
+ */
876
+ const rankImages = (candidates, measured) => group(candidates).map((images) => toImage(images, measured)).filter((image) => image !== void 0).toSorted((a, b) => b.score - a.score);
877
+ // src/image/render.ts
878
+ /** The time caps, in milliseconds, and how many images the script measures. */
879
+ const RENDER_CAPS = {
880
+ /** Loading the page's document, to its DOMContentLoaded event. */
881
+ document: 3e4,
882
+ /**
883
+ * How many images the script measures: this many of the largest shown,
884
+ * and this many of those the page names without showing (sharing images
885
+ * and JSON-LD).
886
+ */
887
+ images: 12,
888
+ /** Waiting for the page's load event, after its document has loaded. */
889
+ load: 1e4,
890
+ /** Loading the originals to measure them, all at once. */
891
+ measure: 5e3,
892
+ /** Waiting for the largest contentful paint to be reported. */
893
+ paint: 1e3,
894
+ /**
895
+ * How long past its own cap a call into the page may take before the page
896
+ * counts as not responding.
897
+ */
898
+ respond: 1e4,
899
+ /** Scrolling the page, in steps of one viewport. */
900
+ scroll: 8e3,
901
+ /** Waiting for the network to settle after the load event. */
902
+ settle: 3e3,
903
+ /** The pause after each scroll step, for lazy images to start loading. */
904
+ step: 250
905
+ };
906
+ /** The script's error when a call into the page outlives its cap. */
907
+ const PAGE_STOPPED = "the page stopped responding";
908
+ /** The whole script's limit: the caps above, with room for the browser's own work. */
909
+ const RENDER_TIMEOUT = 9e4;
910
+ /**
911
+ * Stops the page loading scripts from other sites: the ad, tracking and chat
912
+ * scripts that keep some pages too busy to answer. A script's site is its
913
+ * host's last two labels, or three under a country's second level such as
914
+ * co.uk. Off by default, since some sites serve their own code from another
915
+ * domain (Kvadrat from azureedge.net) and render nothing without it.
916
+ */
917
+ const BLOCK_OTHER_SITES_SCRIPTS = `
918
+ const siteOf = (host) => {
919
+ const labels = host.split(".");
920
+ const secondLevel = labels.length > 2 && labels.at(-1).length === 2 && ["ac", "co", "com", "edu", "gov", "net", "org"].includes(labels.at(-2));
921
+ return labels.slice(secondLevel ? -3 : -2).join(".");
922
+ };
923
+ const pageSite = () => {
924
+ const current = typeof page.url === "function" ? page.url() : url;
925
+ try {
926
+ const target = current.startsWith("http://") || current.startsWith("https://") ? current : url;
927
+ return siteOf(new URL(target).hostname);
928
+ } catch {
929
+ return "";
930
+ }
931
+ };
932
+ await page.route("**/*", (route) => {
933
+ const request = route.request();
934
+ if (request.resourceType() !== "script") return route.continue();
935
+ let scriptUrl;
936
+ try {
937
+ scriptUrl = new URL(request.url());
938
+ } catch {
939
+ return route.continue();
940
+ }
941
+ if (scriptUrl.protocol !== "http:" && scriptUrl.protocol !== "https:") return route.continue();
942
+ const ownSite = pageSite();
943
+ return ownSite !== "" && siteOf(scriptUrl.hostname) !== ownSite ? route.abort() : route.continue();
944
+ });
945
+ `;
946
+ /** Records the LCP element before any scroll, disconnects the observer, then scrolls to wake lazy images. */
947
+ const LCP_AND_SCROLL = `
948
+ await responding(page.evaluate((wait) => new Promise((resolve) => {
949
+ let observer;
950
+ const done = () => {
951
+ clearTimeout(timer);
952
+ observer?.disconnect?.();
953
+ resolve();
954
+ };
955
+ const timer = setTimeout(done, wait);
956
+ observer = new PerformanceObserver((list) => {
957
+ const last = list.getEntries().at(-1);
958
+ if (last !== undefined) window.__fieldworkLcp = last.element;
959
+ done();
960
+ });
961
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
962
+ }), caps.paint), caps.paint);
963
+ await responding(page.evaluate(async ({ scroll, step }) => {
964
+ const end = Date.now() + scroll;
965
+ for (let y = innerHeight; y < document.documentElement.scrollHeight && Date.now() < end; y += innerHeight) {
966
+ scrollTo(0, y);
967
+ await new Promise((resolve) => setTimeout(resolve, step));
968
+ }
969
+ scrollTo(0, 0);
970
+ }, caps), caps.scroll);`;
971
+ /** Collects candidates with layout boxes, harvests loaded DOM img sizes, and measures the likeliest originals. */
972
+ const COLLECT_AND_MEASURE = `
973
+ const found = await responding(page.evaluate(async ({ images, measure }) => {
974
+ const collectImages = ${collectImagesSource};
975
+ const blockedBy = ${blockedBy.toString()};
976
+ const resolveOriginal = ${resolveOriginal.toString()};
977
+ const shownCandidate = ${shownCandidate.toString()};
978
+ const probe = (element) => {
979
+ const box = element.getBoundingClientRect();
980
+ return {
981
+ height: Math.round(box.height),
982
+ lcp: element === window.__fieldworkLcp,
983
+ top: Math.round(box.top + scrollY),
984
+ width: Math.round(box.width),
985
+ };
986
+ };
987
+ const known = new Map();
988
+ for (const img of Array.from(document.querySelectorAll("img"))) {
989
+ const src = img.currentSrc || img.getAttribute("src");
990
+ if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0 && typeof src === "string" && src !== "") {
991
+ try {
992
+ const abs = new URL(src, location.href).href;
993
+ if (abs.startsWith("http://") || abs.startsWith("https://")) {
994
+ known.set(abs, { height: img.naturalHeight, url: abs, width: img.naturalWidth });
995
+ }
996
+ } catch {}
997
+ }
998
+ }
999
+ const candidates = collectImages(document, location.href, probe);
1000
+ const svgPath = /\\.svgz?$/iu;
1001
+ const isSvg = (src) => {
1002
+ try {
1003
+ return svgPath.test(new URL(src).pathname);
1004
+ } catch {
1005
+ return false;
1006
+ }
1007
+ };
1008
+ const imageKey = (src) => resolveOriginal(src).url.replace(/^http:/u, "https:");
1009
+ const byElement = new Map();
1010
+ for (const candidate of candidates) {
1011
+ if (candidate.context?.chrome === true) continue;
1012
+ const list = byElement.get(candidate.element);
1013
+ if (list === undefined) byElement.set(candidate.element, [candidate]);
1014
+ else list.push(candidate);
1015
+ }
1016
+ const byKey = new Map();
1017
+ for (const group of byElement.values()) {
1018
+ const shown = shownCandidate(group);
1019
+ if (shown === undefined || isSvg(shown.url)) continue;
1020
+ const key = imageKey(shown.url);
1021
+ const merged = byKey.get(key);
1022
+ if (merged === undefined) byKey.set(key, [...group]);
1023
+ else merged.push(...group);
1024
+ }
1025
+ const weightedArea = (layout) => (layout.width * layout.height) / (1 + Math.max(0, layout.top + layout.height - 800) / 500);
1026
+ const placed = [...byKey.values()].map((group) => {
1027
+ const layouts = group.flatMap((candidate) => candidate.context?.layout === undefined ? [] : [candidate.context.layout]);
1028
+ const lcp = layouts.some((layout) => layout.lcp);
1029
+ const weight = layouts.length === 0 ? 0 : Math.max(...layouts.map(weightedArea));
1030
+ return { hasLayout: layouts.length > 0, lcp, shown: shownCandidate(group), weight };
1031
+ });
1032
+ const laidOut = placed
1033
+ .filter(({ hasLayout, weight }) => hasLayout && weight > 0)
1034
+ .sort((a, b) => Number(b.lcp) - Number(a.lcp) || b.weight - a.weight)
1035
+ .slice(0, images);
1036
+ const named = placed.filter(({ hasLayout }) => !hasLayout).slice(0, images);
1037
+ const likeliest = [...laidOut, ...named];
1038
+ const urls = new Set();
1039
+ for (const { shown } of likeliest) {
1040
+ const original = resolveOriginal(shown.url);
1041
+ if (!known.has(original.url)) urls.add(original.url);
1042
+ if (!original.verified && !known.has(shown.url)) urls.add(shown.url);
1043
+ }
1044
+ let timer;
1045
+ const deadline = new Promise((resolve) => {
1046
+ timer = setTimeout(resolve, measure);
1047
+ });
1048
+ let sizes = [];
1049
+ try {
1050
+ sizes = await Promise.all([...urls].map((src) => Promise.race([
1051
+ new Promise((resolve) => {
1052
+ const image = new Image();
1053
+ image.onload = () => resolve(image.naturalWidth > 0 ? { height: image.naturalHeight, url: src, width: image.naturalWidth } : undefined);
1054
+ image.onerror = () => resolve({ failed: src });
1055
+ image.src = src;
1056
+ }),
1057
+ deadline.then(() => undefined),
1058
+ ])));
1059
+ } finally {
1060
+ clearTimeout(timer);
1061
+ }
1062
+ for (const size of sizes) {
1063
+ if (size?.width !== undefined) known.set(size.url, size);
1064
+ }
1065
+ return { blocked: blockedBy(document, location.href) ?? null, candidates, failed: sizes.filter((size) => size?.failed !== undefined).map((size) => size.failed), measured: [...known.values()], url: location.href };
1066
+ }, caps), caps.measure);`;
1067
+ /**
1068
+ * The Playwright script that renders `url` and returns a `Rendered`, with
1069
+ * other sites' scripts blocked when `blockOtherSitesScripts` is set. The
1070
+ * collector, resolver and `shownCandidate` go in as their own source; see
1071
+ * their files.
1072
+ */
1073
+ const renderScript = (url, { blockOtherSitesScripts = false } = {}) => `
1074
+ const url = ${JSON.stringify(url)};
1075
+ const caps = ${JSON.stringify(RENDER_CAPS)};${blockOtherSitesScripts ? BLOCK_OTHER_SITES_SCRIPTS : ""}
1076
+ const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: caps.document });
1077
+ // The load and network-idle waits only give the page time, each up to its cap: a page that never fires them (streaming, polling) is read as it stands, so a timeout there is safe to ignore; any other failure shows at the next call into the page.
1078
+ await page.waitForLoadState("load", { timeout: caps.load }).catch(() => undefined);
1079
+ await page.waitForLoadState("networkidle", { timeout: caps.settle }).catch(() => undefined);
1080
+ const responding = async (call, cap) => {
1081
+ let timer;
1082
+ const stopped = new Promise((_, reject) => {
1083
+ timer = setTimeout(() => reject(new Error(${JSON.stringify(PAGE_STOPPED)})), cap + caps.respond);
1084
+ });
1085
+ try {
1086
+ return await Promise.race([call, stopped]);
1087
+ } finally {
1088
+ clearTimeout(timer);
1089
+ }
1090
+ };${LCP_AND_SCROLL}${COLLECT_AND_MEASURE}
1091
+ return { ...found, status: response?.status() ?? null };
1092
+ `;
1093
+ const Size = z.object({
1094
+ height: z.number(),
1095
+ width: z.number()
1096
+ });
1097
+ const Candidate = z.object({
1098
+ context: z.optional(z.object({
1099
+ alt: z.string(),
1100
+ chrome: z.boolean(),
1101
+ figure: z.boolean(),
1102
+ layout: z.optional(z.object({
1103
+ height: z.number(),
1104
+ lcp: z.boolean(),
1105
+ top: z.number(),
1106
+ width: z.number()
1107
+ }))
1108
+ })),
1109
+ element: z.number(),
1110
+ height: z.optional(z.number()),
1111
+ source: z.enum([
1112
+ "og:image",
1113
+ "twitter:image",
1114
+ "json-ld",
1115
+ "img",
1116
+ "srcset",
1117
+ "picture",
1118
+ "data-attribute",
1119
+ "noscript",
1120
+ "css-background"
1121
+ ]),
1122
+ url: z.string(),
1123
+ width: z.optional(z.number())
1124
+ });
1125
+ /** What the render script returns. */
1126
+ const Rendered = z.object({
1127
+ /** What the page is instead of the page, from `blockedBy`, or null. */
1128
+ blocked: z.nullish(z.string()),
1129
+ candidates: z.array(Candidate),
1130
+ /** The originals and page URLs the browser tried and could not load. */
1131
+ failed: z.array(z.string()),
1132
+ /** The originals and page URLs that loaded, at their natural sizes. */
1133
+ measured: z.array(z.extend(Size, { url: z.string() })),
1134
+ /** The page's status, or null when the browser saw none. */
1135
+ status: z.nullish(z.number()),
1136
+ /** The page's URL after redirects. */
1137
+ url: z.string()
1138
+ });
1139
+ /** Parses the value the render script returned. Throws a ZodError when it is not what the script returns. */
1140
+ const parseRendered = (act) => {
1141
+ const { blocked, candidates, failed, measured, status, url } = z.parse(Rendered, act.result);
1142
+ return {
1143
+ ...blocked !== null && blocked !== void 0 && { blocked },
1144
+ candidates,
1145
+ measured: new Map([...failed.map((src) => [src, null]), ...measured.map((size) => [size.url, {
1146
+ height: size.height,
1147
+ width: size.width
1148
+ }])]),
1149
+ url,
1150
+ ...status !== null && status !== void 0 && { status }
1151
+ };
1152
+ };
1153
+ // src/image/best.ts
1154
+ /** Throws `InvalidRequest` unless `limit` is unset or a positive whole number. */
1155
+ const checkLimit = (provider, limit) => {
1156
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1)) throw invalidRequest(provider, `needs limit as a positive whole number, got ${limit}`);
1157
+ };
1158
+ /** Throws `InvalidRequest` unless `url` parses and is http or https, before any provider call or browser session. */
1159
+ const checkUrl = (provider, url) => {
1160
+ const parsed = URL.parse(url);
1161
+ if (parsed === null) throw invalidRequest(provider, `cannot read ${url}: it is not a URL`);
1162
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw invalidRequest(provider, `reads only http and https URLs, not ${parsed.protocol} (${url})`);
1163
+ };
1164
+ /**
1165
+ * The page's HTML. Throws `ProviderError`, with the read's `meta`, when the
1166
+ * page answered with a status that is not 2xx or came back empty: an empty
1167
+ * list must mean the page has no images.
1168
+ */
1169
+ const htmlOf = (provider, url, page) => {
1170
+ const { meta, statusCode } = page;
1171
+ if (statusCode !== void 0 && (statusCode < 200 || statusCode > 299)) throw new FieldworkError(statusCode === 404 || statusCode === 410 ? "NotFound" : "ProviderError", `${provider} read ${url} but the page answered ${statusCode}`, {
1172
+ cause: page.raw,
1173
+ meta,
1174
+ provider,
1175
+ status: statusCode
1176
+ });
1177
+ const html = page.rawHtml?.trim() ?? "";
1178
+ if (html === "") throw new FieldworkError("ProviderError", `${provider} read ${url} but returned no HTML`, {
1179
+ cause: page.raw,
1180
+ meta,
1181
+ provider
1182
+ });
1183
+ return html;
1184
+ };
1185
+ /** How far the top pick must lead the next for "auto" to trust the read. */
1186
+ const CLEAR_LEAD = 1.2;
1187
+ /** Whether the read settles the ranking for "auto": its top pick is sized and clearly leads the next. */
1188
+ const hasSizedClearLeader = (images) => {
1189
+ const [top, next] = images;
1190
+ return top?.width !== void 0 && top.height !== void 0 && (next === void 0 || top.score >= next.score * CLEAR_LEAD);
1191
+ };
1192
+ /** `a + b`, where either may be missing; undefined only when both are. */
1193
+ const addOptional = (a, b) => a === void 0 ? b : (b ?? 0) + a;
1194
+ /** The calls' usage added up and their warnings together; the request id only when one call ran. */
1195
+ const combined = (metas) => {
1196
+ const present = metas.filter((meta) => meta !== void 0);
1197
+ const [only] = present;
1198
+ if (present.length < 2) return only;
1199
+ const units = {};
1200
+ let credits;
1201
+ let costUsd;
1202
+ for (const { usage } of present) {
1203
+ credits = addOptional(credits, usage?.credits);
1204
+ costUsd = addOptional(costUsd, usage?.costUsd);
1205
+ for (const [name, count] of Object.entries(usage?.units ?? {})) units[name] = (units[name] ?? 0) + count;
1206
+ }
1207
+ const warnings = present.flatMap((meta) => meta.warnings ?? []);
1208
+ return {
1209
+ usage: {
1210
+ ...credits !== void 0 && { credits },
1211
+ ...costUsd !== void 0 && { costUsd },
1212
+ ...Object.keys(units).length > 0 && { units }
1213
+ },
1214
+ ...warnings.length > 0 && { warnings }
1215
+ };
1216
+ };
1217
+ /** The result: at most `limit` of the images, with `meta` and `renderError` only when set. */
1218
+ const resultOf = ({ images, meta, renderError, ...found }, limit) => ({
1219
+ ...found,
1220
+ images: images.slice(0, limit),
1221
+ ...meta && { meta },
1222
+ ...renderError && { renderError }
1223
+ });
1224
+ /** The cheap path: the page's HTML, read and ranked. */
1225
+ const readImages = async (web, provider, url, call) => {
1226
+ const page = await web.read(url, {
1227
+ format: "raw",
1228
+ ...call
1229
+ });
1230
+ const document = createDocument(htmlOf(provider, url, page));
1231
+ const images = rankImages(collectImages(document, page.url));
1232
+ const blocked = images.length === 0 ? blockedBy(document, page.url) : void 0;
1233
+ return {
1234
+ images,
1235
+ page,
1236
+ ...blocked !== void 0 && { blocked }
1237
+ };
1238
+ };
1239
+ /** Providers whose `act` runs the render script: a Playwright script given `page`. */
1240
+ const RENDERERS = ["kernel"];
1241
+ /**
1242
+ * The provider that runs `act`. Throws `Unsupported` when `web` has none, or
1243
+ * one whose `act` does not run a Playwright script, such as Firecrawl's.
1244
+ */
1245
+ const actProvider = (web) => {
1246
+ const provider = web.providerFor("act");
1247
+ if (provider === void 0) throw new FieldworkError("Unsupported", "this Fieldwork does not offer act");
1248
+ if (!RENDERERS.includes(provider)) throw new FieldworkError("Unsupported", `${provider} act does not run the render script; bestImages renders through ${RENDERERS.join(" or ")}`, { provider });
1249
+ return provider;
1250
+ };
1251
+ /** The cheap path's result: the read's images, not rendered. */
1252
+ const readResult = ({ images, page }, limit) => resultOf({
1253
+ images,
1254
+ meta: page.meta,
1255
+ raw: { read: page.raw },
1256
+ rendered: false
1257
+ }, limit);
1258
+ /** Whether `read` found images that can stand in for a failed render. */
1259
+ const canStandIn = (read) => read !== void 0 && read.images.length > 0;
1260
+ /**
1261
+ * Whether a script error is the page failing in the browser (it stopped
1262
+ * responding, did not load in time or crashed the tab), which a second
1263
+ * render or the read can stand in for, rather than the script breaking,
1264
+ * which must throw.
1265
+ */
1266
+ const pageFailed = (error) => error.includes("the page stopped responding") || /\bTimeout \d+ms exceeded\b/u.test(error) || error.includes("Target page, context or browser has been closed");
1267
+ /** The warning on a result whose page was rendered again with other sites' scripts blocked. */
1268
+ const RENDERED_AGAIN = "the page failed in the browser, so it was rendered again with other sites' scripts blocked";
1269
+ /**
1270
+ * The render path's images, from the render script's value. Throws `NotFound`
1271
+ * for 404/410 and `ProviderError` otherwise, with `meta` covering every call
1272
+ * so far, when the script returned something else, the page answered an error
1273
+ * status, or it has no images and is a bot check, captcha or consent wall
1274
+ * instead.
1275
+ */
1276
+ const renderedImages = (provider, url, act, meta) => {
1277
+ const fail = (message, cause, code = "ProviderError", status) => new FieldworkError(code, `${provider} ${message}`, {
1278
+ cause,
1279
+ provider,
1280
+ ...meta && { meta },
1281
+ ...status !== void 0 && { status }
1282
+ });
1283
+ let rendered;
1284
+ try {
1285
+ rendered = parseRendered(act);
1286
+ } catch (error) {
1287
+ throw fail(`rendered ${url} but the script returned something else`, error);
1288
+ }
1289
+ const { status } = rendered;
1290
+ if (status !== void 0 && (status < 200 || status > 299)) throw fail(`rendered ${url} but the page answered ${status}`, act.raw, status === 404 || status === 410 ? "NotFound" : "ProviderError", status);
1291
+ const images = rankImages(rendered.candidates, rendered.measured);
1292
+ if (images.length === 0 && rendered.blocked !== void 0) throw fail(`rendered ${url} but got ${rendered.blocked} instead of the page`, act.raw);
1293
+ return images;
1294
+ };
1295
+ /** Attaches combined `meta` to a rethrown `FieldworkError` when earlier calls already ran. */
1296
+ const withCombinedMeta = (error, meta) => meta === void 0 ? error : new FieldworkError(error.code, error.message, {
1297
+ cause: error.cause,
1298
+ jobId: error.jobId,
1299
+ meta,
1300
+ provider: error.provider,
1301
+ retryAfter: error.retryAfter,
1302
+ retryable: error.retryable,
1303
+ status: error.status
1304
+ });
1305
+ /**
1306
+ * Renders the page through `act` and ranks what it shows. A page that fails
1307
+ * in the browser is rendered once more with other sites' scripts blocked,
1308
+ * since ads, trackers and chat widgets keep some pages too busy to answer;
1309
+ * the result then carries `RENDERED_AGAIN` in `meta.warnings`. When the
1310
+ * provider or the page still fails (a Fieldwork error from `act` other than
1311
+ * `Aborted`, or a page that failed in the browser) after a read that found
1312
+ * images, the read's images come back with the failure as `renderError`.
1313
+ * Anything else throws: a broken script, a value the script never returns,
1314
+ * an error status, and any error in ranking.
1315
+ */
1316
+ const renderWithReadFallback = async (web, actor, url, read, options, call, deadline) => {
1317
+ const acts = [];
1318
+ /** Every call's usage: the read's, each act's, and `thrown`'s, an act that threw. */
1319
+ const metaOf = (thrown) => combined([
1320
+ read?.page.meta,
1321
+ ...acts.map((act) => act.meta),
1322
+ thrown?.meta,
1323
+ acts.length > 1 ? { warnings: [RENDERED_AGAIN] } : void 0
1324
+ ]);
1325
+ const rawOf = () => ({
1326
+ ...read && { read: read.page.raw },
1327
+ ...acts.length > 0 && { act: acts.map((act) => act.raw) }
1328
+ });
1329
+ const fallBack = (stand, renderError, thrown) => resultOf({
1330
+ images: stand.images,
1331
+ meta: metaOf(thrown),
1332
+ raw: rawOf(),
1333
+ renderError,
1334
+ rendered: false
1335
+ }, options.limit);
1336
+ const render = async (blockOtherSitesScripts) => {
1337
+ const remaining = deadline === void 0 ? void 0 : deadline - Date.now();
1338
+ const timeout = remaining === void 0 ? RENDER_TIMEOUT : Math.max(1, Math.min(RENDER_TIMEOUT, remaining));
1339
+ const act = await web.act(renderScript(url, { blockOtherSitesScripts }), {
1340
+ ...call,
1341
+ timeout
1342
+ });
1343
+ acts.push(act);
1344
+ return act;
1345
+ };
1346
+ let act;
1347
+ try {
1348
+ act = await render(false);
1349
+ if (act.error !== void 0 && pageFailed(act.error) && call.signal?.aborted !== true) act = await render(true);
1350
+ } catch (error) {
1351
+ if (error instanceof FieldworkError) {
1352
+ if (canStandIn(read) && error.code !== "Aborted") return fallBack(read, error, error);
1353
+ if (read !== void 0 || acts.length > 0) throw withCombinedMeta(error, metaOf(error));
1354
+ }
1355
+ throw error;
1356
+ }
1357
+ const meta = metaOf();
1358
+ if (act.error !== void 0) {
1359
+ const failure = new FieldworkError("ProviderError", `${actor} could not render ${url}: ${act.error}`, {
1360
+ cause: act.raw,
1361
+ provider: actor,
1362
+ ...meta && { meta }
1363
+ });
1364
+ if (canStandIn(read) && pageFailed(act.error)) return fallBack(read, failure);
1365
+ throw failure;
1366
+ }
1367
+ return resultOf({
1368
+ images: renderedImages(actor, url, act, meta),
1369
+ meta,
1370
+ raw: rawOf(),
1371
+ rendered: true
1372
+ }, options.limit);
1373
+ };
1374
+ /** Combines `signal` with a deadline from `timeout`, when either is set. */
1375
+ const callSignal = (signal, timeout) => {
1376
+ const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((item) => item !== void 0);
1377
+ return signals.length > 1 ? AbortSignal.any(signals) : signals[0];
1378
+ };
1379
+ /** Resolves the providers `render` requires, throwing `Unsupported` when either is missing. */
1380
+ const providersFor = (web, render) => {
1381
+ const reader = render === "always" ? void 0 : web.providerFor("read");
1382
+ if (render !== "always" && reader === void 0) throw new FieldworkError("Unsupported", "this Fieldwork does not offer read");
1383
+ const actor = render === "never" ? void 0 : actProvider(web);
1384
+ return {
1385
+ actor,
1386
+ primary: reader ?? actor ?? "fieldwork",
1387
+ reader
1388
+ };
1389
+ };
1390
+ /**
1391
+ * The best images on a page, largest first: `bestImages(web, url, { limit, render })`.
1392
+ * Reads the page through `web.read`, parses its HTML, gathers every image it
1393
+ * names (og:image, JSON-LD, img, srcset, picture, lazy attributes, noscript
1394
+ * and inline backgrounds), groups the URLs of one image into one entry, and
1395
+ * ranks them by pixel area. With `render`, the page is rendered through
1396
+ * `web.act` instead or as well, and ranked by the boxes it shows its images
1397
+ * at; see `BestImagesOptions`.
1398
+ *
1399
+ * Under "auto", a render that fails after a read that found images does not
1400
+ * throw: the read's images come back, with `rendered: false` and the
1401
+ * failure as `renderError`.
1402
+ *
1403
+ * Throws what the read or act throws, `Unsupported` when `web` cannot read
1404
+ * or act, `NotFound` for a 404 or 410 page, `ProviderError` for another error
1405
+ * status, an empty page, a page with no images that is a bot check, captcha,
1406
+ * access-denied page or consent wall, or a failed render the read cannot stand
1407
+ * in for (with the usage so far), and `InvalidRequest` for an invalid URL,
1408
+ * `timeout`, `retries` or a `limit` that is not a positive whole number.
1409
+ */
1410
+ const bestImages = async (web, url, options = {}) => {
1411
+ const render = options.render ?? "auto";
1412
+ const { actor, primary, reader } = providersFor(web, render);
1413
+ checkLimit(primary, options.limit);
1414
+ checkUrl(primary, url);
1415
+ checkCallSettings({
1416
+ retries: options.retries,
1417
+ timeout: options.timeout
1418
+ });
1419
+ const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
1420
+ const call = {
1421
+ retries: options.retries,
1422
+ signal: callSignal(options.signal, options.timeout)
1423
+ };
1424
+ const read = reader === void 0 ? void 0 : await readImages(web, reader, url, call);
1425
+ if (render === "never" && read !== void 0 && reader !== void 0) {
1426
+ if (read.blocked !== void 0) throw new FieldworkError("ProviderError", `${reader} read ${url} but got ${read.blocked} instead of the page`, {
1427
+ cause: read.page.raw,
1428
+ provider: reader,
1429
+ ...read.page.meta && { meta: read.page.meta }
1430
+ });
1431
+ return readResult(read, options.limit);
1432
+ }
1433
+ if (read !== void 0 && hasSizedClearLeader(read.images)) return readResult(read, options.limit);
1434
+ return await renderWithReadFallback(web, actor ?? actProvider(web), url, read, options, call, deadline);
1435
+ };
1436
+ export { collectImages as a, resolveOriginal as i, bestImages as n, collectImagesSource as o, rankImages as r, RENDERERS as t };