@hyperframes/producer 0.10.6 → 0.10.8

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.js CHANGED
@@ -3448,7 +3448,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
3448
3448
  const domPng = await timeHdrPhaseAsync(
3449
3449
  hdrPerf,
3450
3450
  "domScreenshotMs",
3451
- () => captureAlphaPng(domSession.page, width, height)
3451
+ () => captureAlphaPng(domSession.page, width, height, domSession.options?.onScreenshotRetry)
3452
3452
  );
3453
3453
  await timeHdrPhaseAsync(
3454
3454
  hdrPerf,
@@ -4173,7 +4173,7 @@ async function captureSceneIntoBuffer(a) {
4173
4173
  const domPng = await timeHdrPhaseAsync(
4174
4174
  hdrPerf,
4175
4175
  "domScreenshotMs",
4176
- () => captureAlphaPng2(session.page, width, height)
4176
+ () => captureAlphaPng2(session.page, width, height, session.options?.onScreenshotRetry)
4177
4177
  );
4178
4178
  await timeHdrPhaseAsync(
4179
4179
  hdrPerf,
@@ -4526,6 +4526,7 @@ async function validateCompletedSegments(manifest, check) {
4526
4526
  }
4527
4527
 
4528
4528
  // src/services/render/segmentRecycle.ts
4529
+ import { isTransientScreenshotRefusal } from "@hyperframes/engine";
4529
4530
  var DEFAULT_SEGMENT_BROWSER_RECYCLE = 3;
4530
4531
  function resolveSegmentBrowserRecycle(env) {
4531
4532
  const raw = env.HF_SEGMENT_BROWSER_RECYCLE;
@@ -4536,7 +4537,7 @@ function resolveSegmentBrowserRecycle(env) {
4536
4537
  var TARGET_LOSS_PATTERNS = [/target closed/i, /detached frame/i, /session closed/i];
4537
4538
  function isTargetLossError(error) {
4538
4539
  if (!(error instanceof Error)) return false;
4539
- return TARGET_LOSS_PATTERNS.some((re) => re.test(error.message));
4540
+ return TARGET_LOSS_PATTERNS.some((re) => re.test(error.message)) || isTransientScreenshotRefusal(error);
4540
4541
  }
4541
4542
 
4542
4543
  // src/services/render/stages/captureStreamingStage.ts
@@ -7618,7 +7619,8 @@ import {
7618
7619
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
7619
7620
  NotMediaPayloadError as NotMediaPayloadError2,
7620
7621
  parseMasterFxChain,
7621
- probeMediaProfile as probeMediaProfile2
7622
+ probeMediaProfile as probeMediaProfile2,
7623
+ resolveRestrictPageNetwork
7622
7624
  } from "@hyperframes/engine";
7623
7625
 
7624
7626
  // src/utils/urlDownloader.ts
@@ -9116,7 +9118,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
9116
9118
  }
9117
9119
  return { subCompositions };
9118
9120
  }
9119
- function promoteCssImportsToLinkTags(html) {
9121
+ function promoteCssImportsToLinkTags(html, budget) {
9120
9122
  const { document: document2 } = parseHTML5(html);
9121
9123
  const head = document2.querySelector("head");
9122
9124
  if (!head) return html;
@@ -9125,18 +9127,16 @@ function promoteCssImportsToLinkTags(html) {
9125
9127
  const styleEls = document2.querySelectorAll("style");
9126
9128
  for (const styleEl of styleEls) {
9127
9129
  const original = styleEl.textContent || "";
9128
- let modified = original;
9129
- let match;
9130
- importRe.lastIndex = 0;
9131
- while ((match = importRe.exec(original)) !== null) {
9130
+ const rulesBetweenImports = [];
9131
+ let keptTo = 0;
9132
+ for (const match of original.matchAll(importRe)) {
9132
9133
  const url = match[1] ?? "";
9133
9134
  if (!url.startsWith("http://") && !url.startsWith("https://")) continue;
9134
- if (seenUrls.has(url)) {
9135
- modified = modified.replace(match[0], "");
9136
- continue;
9137
- }
9135
+ rulesBetweenImports.push(original.slice(keptTo, match.index));
9136
+ keptTo = match.index + match[0].length;
9137
+ if (seenUrls.has(url)) continue;
9138
9138
  seenUrls.add(url);
9139
- modified = modified.replace(match[0], "");
9139
+ budget.chargeElements(ENTRY_PAGE, 2);
9140
9140
  const preload = document2.createElement("link");
9141
9141
  preload.setAttribute("rel", "preload");
9142
9142
  preload.setAttribute("href", url);
@@ -9147,8 +9147,8 @@ function promoteCssImportsToLinkTags(html) {
9147
9147
  link.setAttribute("href", url);
9148
9148
  head.appendChild(link);
9149
9149
  }
9150
- if (modified !== original) {
9151
- styleEl.textContent = modified;
9150
+ if (keptTo > 0) {
9151
+ styleEl.textContent = rulesBetweenImports.join("") + original.slice(keptTo);
9152
9152
  }
9153
9153
  }
9154
9154
  return document2.toString();
@@ -9460,16 +9460,61 @@ function operatorGsapMirror() {
9460
9460
  return void 0;
9461
9461
  }
9462
9462
  }
9463
+ var MIRROR_GSAP_FILE = /^gsap@\d+(?:\.\d+)*\/dist\/[A-Za-z0-9][\w-]*(?:\.[\w-]+)*\.js$/;
9464
+ function isOperatorMirrorGsapUrl(src, mirror) {
9465
+ if (!mirror || /[?#%\\]/.test(src) || !URL.canParse(src)) return false;
9466
+ const url = new URL(src);
9467
+ if (url.search || url.hash || !url.href.startsWith(mirror)) return false;
9468
+ return MIRROR_GSAP_FILE.test(url.href.slice(mirror.length));
9469
+ }
9470
+ var warnedRestrictedMirror = false;
9471
+ function mirrorExemptionAllowed() {
9472
+ if (!resolveRestrictPageNetwork()) return true;
9473
+ if (!warnedRestrictedMirror) {
9474
+ warnedRestrictedMirror = true;
9475
+ defaultLogger.warn(
9476
+ "[Compiler] PRODUCER_RESTRICT_PAGE_NETWORK is on, so HYPERFRAMES_GSAP_BASE_URL is fetched only from a public HTTPS address."
9477
+ );
9478
+ }
9479
+ return false;
9480
+ }
9481
+ async function readCappedBody(response, src) {
9482
+ const tooLarge = () => new Error(`Script over 16 MiB: ${src}`);
9483
+ const declared = Number(response.headers.get("content-length"));
9484
+ if (Number.isFinite(declared) && declared > MAX_SCRIPT_BYTES) {
9485
+ await response.body?.cancel().catch(() => {
9486
+ });
9487
+ throw tooLarge();
9488
+ }
9489
+ if (!response.body) return new Uint8Array();
9490
+ const reader = response.body.getReader();
9491
+ const chunks = [];
9492
+ let received = 0;
9493
+ for (; ; ) {
9494
+ const { done, value } = await reader.read();
9495
+ if (done) break;
9496
+ received += value.byteLength;
9497
+ if (received > MAX_SCRIPT_BYTES) {
9498
+ await reader.cancel().catch(() => {
9499
+ });
9500
+ throw tooLarge();
9501
+ }
9502
+ chunks.push(value);
9503
+ }
9504
+ return Buffer.concat(chunks);
9505
+ }
9463
9506
  async function downloadScript(src, mirror, signal) {
9464
- if (mirror && new URL(src).href.startsWith(mirror)) {
9465
- const response = await fetch(src, {
9507
+ if (isOperatorMirrorGsapUrl(src, mirror) && mirrorExemptionAllowed()) {
9508
+ const response = await fetch(new URL(src).href, {
9466
9509
  redirect: "error",
9467
9510
  signal: AbortSignal.any([AbortSignal.timeout(15e3), signal])
9468
9511
  });
9469
- if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
9470
- const bytes = new Uint8Array(await response.arrayBuffer());
9471
- if (bytes.byteLength > MAX_SCRIPT_BYTES) throw new Error(`Script over 16 MiB: ${src}`);
9472
- return bytes;
9512
+ if (!response.ok) {
9513
+ await response.body?.cancel().catch(() => {
9514
+ });
9515
+ throw new Error(`HTTP ${response.status} for ${src}`);
9516
+ }
9517
+ return readCappedBody(response, src);
9473
9518
  }
9474
9519
  return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3, signal });
9475
9520
  }
@@ -9793,15 +9838,22 @@ function matchingBraces(css) {
9793
9838
  }
9794
9839
  return closes;
9795
9840
  }
9796
- function remoteFontStylesheetHref(tag) {
9797
- const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9841
+ var attributeInAnyCase = (el, name) => [...el.attributes].find((attribute) => attribute.name.toLowerCase() === name)?.value;
9842
+ var WHERE_A_BROWSER_LOADS_NO_LINK = "noscript, iframe, noembed, noframes, plaintext, svg, math";
9843
+ function remoteFontStylesheetHref(link) {
9844
+ if (attributeInAnyCase(link, "rel")?.toLowerCase() !== "stylesheet") return void 0;
9845
+ if (link.closest(WHERE_A_BROWSER_LOADS_NO_LINK)) return void 0;
9846
+ const href = attributeInAnyCase(link, "href");
9798
9847
  if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9799
9848
  return href;
9800
9849
  }
9801
9850
  async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget(), signal) {
9851
+ if (!/<link\b/i.test(html)) return html;
9852
+ const { document: document2 } = parseHTML5(html);
9853
+ const linkElements = [...document2.querySelectorAll("link")];
9802
9854
  const hrefs = /* @__PURE__ */ new Set();
9803
- for (const { parts } of stylesheetLinkMatches(html)) {
9804
- const href = remoteFontStylesheetHref(parts[0]);
9855
+ for (const link of linkElements) {
9856
+ const href = remoteFontStylesheetHref(link);
9805
9857
  if (href) hrefs.add(href);
9806
9858
  }
9807
9859
  if (hrefs.size === 0) return html;
@@ -9816,9 +9868,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9816
9868
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9817
9869
  if (fontFaceBlocks.length === 0) return;
9818
9870
  const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9819
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9871
+ const inlineStyle = `/* Inlined external font stylesheet */
9820
9872
  ${fontCssWithLtAsCssEscape}
9821
- </style>`;
9873
+ `;
9822
9874
  try {
9823
9875
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9824
9876
  } catch (error) {
@@ -9836,14 +9888,17 @@ ${fontCssWithLtAsCssEscape}
9836
9888
  await Promise.allSettled([...hrefs].map((href) => limit(() => inlineSheet(href), fetchSignal)));
9837
9889
  if (stop.signal.aborted) throw stop.signal.reason;
9838
9890
  const placed = /* @__PURE__ */ new Set();
9839
- return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9840
- const href = remoteFontStylesheetHref(tag);
9891
+ for (const link of linkElements) {
9892
+ const href = remoteFontStylesheetHref(link);
9841
9893
  const inlineStyle = href ? inlineByHref.get(href) : void 0;
9842
- if (!href || !inlineStyle) return tag;
9894
+ if (!href || !inlineStyle) continue;
9843
9895
  if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9844
9896
  placed.add(href);
9845
- return inlineStyle;
9846
- });
9897
+ const style = document2.createElement("style");
9898
+ style.textContent = inlineStyle;
9899
+ link.replaceWith(style);
9900
+ }
9901
+ return placed.size === 0 ? html : document2.toString();
9847
9902
  }
9848
9903
  function projectStylesheetFontFamilies(html, projectDir) {
9849
9904
  const families = [];
@@ -10198,7 +10253,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10198
10253
  ...options.abortSignal ? [options.abortSignal] : []
10199
10254
  ]);
10200
10255
  const fontSheetHtml = await inlineExternalFontStylesheets(
10201
- promoteCssImportsToLinkTags(sanitizedHtml),
10256
+ promoteCssImportsToLinkTags(sanitizedHtml, budget),
10202
10257
  budget,
10203
10258
  remoteFetches
10204
10259
  );
@@ -12228,7 +12283,7 @@ import {
12228
12283
  assetRootsRefusal,
12229
12284
  assertPublicHttpsUrl,
12230
12285
  downloadToTemp as downloadToTemp2,
12231
- resolveRestrictPageNetwork,
12286
+ resolveRestrictPageNetwork as resolveRestrictPageNetwork2,
12232
12287
  isUrlNotPermittedError,
12233
12288
  writeUrlDownloadTelemetry as writeUrlDownloadTelemetry2,
12234
12289
  resolveProjectRelativeSrc as resolveProjectRelativeSrc5,
@@ -12681,7 +12736,7 @@ function localProbeSource(src, input) {
12681
12736
  }
12682
12737
  async function remoteProbeSource(video, input) {
12683
12738
  if (!isPublicHttpsUrl(video.src)) return null;
12684
- if (!resolveRestrictPageNetwork()) return video.src;
12739
+ if (!resolveRestrictPageNetwork2()) return video.src;
12685
12740
  if (!video.hasAudio || video.hidden) return null;
12686
12741
  const downloadDir = input.downloadDir ?? join26(input.compiledDir, REMOTE_MEDIA_SUBDIR);
12687
12742
  try {
@@ -17196,6 +17251,7 @@ async function executeRenderPipeline(input) {
17196
17251
  updateCaptureObservability({ captureBeyondViewport: resolvedCaptureBeyondViewport });
17197
17252
  }
17198
17253
  let routePageMotionBlur;
17254
+ let screenshotRetries = 0;
17199
17255
  const buildCaptureOptions = () => ({
17200
17256
  ...captureOptions,
17201
17257
  recordReferenceBackground,
@@ -17235,6 +17291,10 @@ async function executeRenderPipeline(input) {
17235
17291
  chromeGpuProcessSeenLastSample: stats.gpuProcessSeenLastSample,
17236
17292
  chromeMemorySamples: stats.samples
17237
17293
  });
17294
+ },
17295
+ onScreenshotRetry: () => {
17296
+ screenshotRetries += 1;
17297
+ updateCaptureObservability({ screenshotRetries });
17238
17298
  }
17239
17299
  });
17240
17300
  const buildPrepCaptureOptions = () => stopPrepSessionOnScriptFailure(buildCaptureOptions());
@@ -24226,7 +24286,11 @@ async function startHealthWorker(options = {}) {
24226
24286
  );
24227
24287
  }
24228
24288
  const worker = new Worker4(entry, {
24229
- workerData: { port },
24289
+ workerData: {
24290
+ port,
24291
+ hostname: options.hostname || "127.0.0.1",
24292
+ closeAfterMs: options.closeAfterMs
24293
+ },
24230
24294
  // Keep stdio inherited so the worker's console logs land in the pod logs
24231
24295
  // alongside the main thread's.
24232
24296
  stdout: false,
@@ -25208,7 +25272,7 @@ function startServer(options = {}) {
25208
25272
  server.setTimeout(0);
25209
25273
  server.requestTimeout = 0;
25210
25274
  server.keepAliveTimeout = 0;
25211
- const healthWorkerPromise = process.env.PRODUCER_DISABLE_HEALTH_WORKER === "1" ? Promise.resolve(null) : startHealthWorker({ logger: log }).catch((err) => {
25275
+ const healthWorkerPromise = process.env.PRODUCER_DISABLE_HEALTH_WORKER === "1" ? Promise.resolve(null) : startHealthWorker({ logger: log, hostname }).catch((err) => {
25212
25276
  log.error(`[server] health worker failed to start: ${err.message}`);
25213
25277
  return null;
25214
25278
  });
@@ -3486,7 +3486,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
3486
3486
  const domPng = await timeHdrPhaseAsync(
3487
3487
  hdrPerf,
3488
3488
  "domScreenshotMs",
3489
- () => captureAlphaPng(domSession.page, width, height)
3489
+ () => captureAlphaPng(domSession.page, width, height, domSession.options?.onScreenshotRetry)
3490
3490
  );
3491
3491
  await timeHdrPhaseAsync(
3492
3492
  hdrPerf,
@@ -4211,7 +4211,7 @@ async function captureSceneIntoBuffer(a) {
4211
4211
  const domPng = await timeHdrPhaseAsync(
4212
4212
  hdrPerf,
4213
4213
  "domScreenshotMs",
4214
- () => captureAlphaPng2(session.page, width, height)
4214
+ () => captureAlphaPng2(session.page, width, height, session.options?.onScreenshotRetry)
4215
4215
  );
4216
4216
  await timeHdrPhaseAsync(
4217
4217
  hdrPerf,
@@ -4564,6 +4564,7 @@ async function validateCompletedSegments(manifest, check) {
4564
4564
  }
4565
4565
 
4566
4566
  // src/services/render/segmentRecycle.ts
4567
+ import { isTransientScreenshotRefusal } from "@hyperframes/engine";
4567
4568
  var DEFAULT_SEGMENT_BROWSER_RECYCLE = 3;
4568
4569
  function resolveSegmentBrowserRecycle(env) {
4569
4570
  const raw = env.HF_SEGMENT_BROWSER_RECYCLE;
@@ -4574,7 +4575,7 @@ function resolveSegmentBrowserRecycle(env) {
4574
4575
  var TARGET_LOSS_PATTERNS = [/target closed/i, /detached frame/i, /session closed/i];
4575
4576
  function isTargetLossError(error) {
4576
4577
  if (!(error instanceof Error)) return false;
4577
- return TARGET_LOSS_PATTERNS.some((re) => re.test(error.message));
4578
+ return TARGET_LOSS_PATTERNS.some((re) => re.test(error.message)) || isTransientScreenshotRefusal(error);
4578
4579
  }
4579
4580
 
4580
4581
  // src/services/render/stages/captureStreamingStage.ts
@@ -7640,7 +7641,8 @@ import {
7640
7641
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
7641
7642
  NotMediaPayloadError as NotMediaPayloadError2,
7642
7643
  parseMasterFxChain,
7643
- probeMediaProfile as probeMediaProfile2
7644
+ probeMediaProfile as probeMediaProfile2,
7645
+ resolveRestrictPageNetwork
7644
7646
  } from "@hyperframes/engine";
7645
7647
 
7646
7648
  // src/utils/urlDownloader.ts
@@ -9138,7 +9140,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
9138
9140
  }
9139
9141
  return { subCompositions };
9140
9142
  }
9141
- function promoteCssImportsToLinkTags(html) {
9143
+ function promoteCssImportsToLinkTags(html, budget) {
9142
9144
  const { document: document2 } = parseHTML5(html);
9143
9145
  const head = document2.querySelector("head");
9144
9146
  if (!head) return html;
@@ -9147,18 +9149,16 @@ function promoteCssImportsToLinkTags(html) {
9147
9149
  const styleEls = document2.querySelectorAll("style");
9148
9150
  for (const styleEl of styleEls) {
9149
9151
  const original = styleEl.textContent || "";
9150
- let modified = original;
9151
- let match;
9152
- importRe.lastIndex = 0;
9153
- while ((match = importRe.exec(original)) !== null) {
9152
+ const rulesBetweenImports = [];
9153
+ let keptTo = 0;
9154
+ for (const match of original.matchAll(importRe)) {
9154
9155
  const url = match[1] ?? "";
9155
9156
  if (!url.startsWith("http://") && !url.startsWith("https://")) continue;
9156
- if (seenUrls.has(url)) {
9157
- modified = modified.replace(match[0], "");
9158
- continue;
9159
- }
9157
+ rulesBetweenImports.push(original.slice(keptTo, match.index));
9158
+ keptTo = match.index + match[0].length;
9159
+ if (seenUrls.has(url)) continue;
9160
9160
  seenUrls.add(url);
9161
- modified = modified.replace(match[0], "");
9161
+ budget.chargeElements(ENTRY_PAGE, 2);
9162
9162
  const preload = document2.createElement("link");
9163
9163
  preload.setAttribute("rel", "preload");
9164
9164
  preload.setAttribute("href", url);
@@ -9169,8 +9169,8 @@ function promoteCssImportsToLinkTags(html) {
9169
9169
  link.setAttribute("href", url);
9170
9170
  head.appendChild(link);
9171
9171
  }
9172
- if (modified !== original) {
9173
- styleEl.textContent = modified;
9172
+ if (keptTo > 0) {
9173
+ styleEl.textContent = rulesBetweenImports.join("") + original.slice(keptTo);
9174
9174
  }
9175
9175
  }
9176
9176
  return document2.toString();
@@ -9482,16 +9482,61 @@ function operatorGsapMirror() {
9482
9482
  return void 0;
9483
9483
  }
9484
9484
  }
9485
+ var MIRROR_GSAP_FILE = /^gsap@\d+(?:\.\d+)*\/dist\/[A-Za-z0-9][\w-]*(?:\.[\w-]+)*\.js$/;
9486
+ function isOperatorMirrorGsapUrl(src, mirror) {
9487
+ if (!mirror || /[?#%\\]/.test(src) || !URL.canParse(src)) return false;
9488
+ const url = new URL(src);
9489
+ if (url.search || url.hash || !url.href.startsWith(mirror)) return false;
9490
+ return MIRROR_GSAP_FILE.test(url.href.slice(mirror.length));
9491
+ }
9492
+ var warnedRestrictedMirror = false;
9493
+ function mirrorExemptionAllowed() {
9494
+ if (!resolveRestrictPageNetwork()) return true;
9495
+ if (!warnedRestrictedMirror) {
9496
+ warnedRestrictedMirror = true;
9497
+ defaultLogger.warn(
9498
+ "[Compiler] PRODUCER_RESTRICT_PAGE_NETWORK is on, so HYPERFRAMES_GSAP_BASE_URL is fetched only from a public HTTPS address."
9499
+ );
9500
+ }
9501
+ return false;
9502
+ }
9503
+ async function readCappedBody(response, src) {
9504
+ const tooLarge = () => new Error(`Script over 16 MiB: ${src}`);
9505
+ const declared = Number(response.headers.get("content-length"));
9506
+ if (Number.isFinite(declared) && declared > MAX_SCRIPT_BYTES) {
9507
+ await response.body?.cancel().catch(() => {
9508
+ });
9509
+ throw tooLarge();
9510
+ }
9511
+ if (!response.body) return new Uint8Array();
9512
+ const reader = response.body.getReader();
9513
+ const chunks = [];
9514
+ let received = 0;
9515
+ for (; ; ) {
9516
+ const { done, value } = await reader.read();
9517
+ if (done) break;
9518
+ received += value.byteLength;
9519
+ if (received > MAX_SCRIPT_BYTES) {
9520
+ await reader.cancel().catch(() => {
9521
+ });
9522
+ throw tooLarge();
9523
+ }
9524
+ chunks.push(value);
9525
+ }
9526
+ return Buffer.concat(chunks);
9527
+ }
9485
9528
  async function downloadScript(src, mirror, signal) {
9486
- if (mirror && new URL(src).href.startsWith(mirror)) {
9487
- const response = await fetch(src, {
9529
+ if (isOperatorMirrorGsapUrl(src, mirror) && mirrorExemptionAllowed()) {
9530
+ const response = await fetch(new URL(src).href, {
9488
9531
  redirect: "error",
9489
9532
  signal: AbortSignal.any([AbortSignal.timeout(15e3), signal])
9490
9533
  });
9491
- if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
9492
- const bytes = new Uint8Array(await response.arrayBuffer());
9493
- if (bytes.byteLength > MAX_SCRIPT_BYTES) throw new Error(`Script over 16 MiB: ${src}`);
9494
- return bytes;
9534
+ if (!response.ok) {
9535
+ await response.body?.cancel().catch(() => {
9536
+ });
9537
+ throw new Error(`HTTP ${response.status} for ${src}`);
9538
+ }
9539
+ return readCappedBody(response, src);
9495
9540
  }
9496
9541
  return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3, signal });
9497
9542
  }
@@ -9815,15 +9860,22 @@ function matchingBraces(css) {
9815
9860
  }
9816
9861
  return closes;
9817
9862
  }
9818
- function remoteFontStylesheetHref(tag) {
9819
- const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9863
+ var attributeInAnyCase = (el, name) => [...el.attributes].find((attribute) => attribute.name.toLowerCase() === name)?.value;
9864
+ var WHERE_A_BROWSER_LOADS_NO_LINK = "noscript, iframe, noembed, noframes, plaintext, svg, math";
9865
+ function remoteFontStylesheetHref(link) {
9866
+ if (attributeInAnyCase(link, "rel")?.toLowerCase() !== "stylesheet") return void 0;
9867
+ if (link.closest(WHERE_A_BROWSER_LOADS_NO_LINK)) return void 0;
9868
+ const href = attributeInAnyCase(link, "href");
9820
9869
  if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9821
9870
  return href;
9822
9871
  }
9823
9872
  async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget(), signal) {
9873
+ if (!/<link\b/i.test(html)) return html;
9874
+ const { document: document2 } = parseHTML5(html);
9875
+ const linkElements = [...document2.querySelectorAll("link")];
9824
9876
  const hrefs = /* @__PURE__ */ new Set();
9825
- for (const { parts } of stylesheetLinkMatches(html)) {
9826
- const href = remoteFontStylesheetHref(parts[0]);
9877
+ for (const link of linkElements) {
9878
+ const href = remoteFontStylesheetHref(link);
9827
9879
  if (href) hrefs.add(href);
9828
9880
  }
9829
9881
  if (hrefs.size === 0) return html;
@@ -9838,9 +9890,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9838
9890
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9839
9891
  if (fontFaceBlocks.length === 0) return;
9840
9892
  const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9841
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9893
+ const inlineStyle = `/* Inlined external font stylesheet */
9842
9894
  ${fontCssWithLtAsCssEscape}
9843
- </style>`;
9895
+ `;
9844
9896
  try {
9845
9897
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9846
9898
  } catch (error) {
@@ -9858,14 +9910,17 @@ ${fontCssWithLtAsCssEscape}
9858
9910
  await Promise.allSettled([...hrefs].map((href) => limit(() => inlineSheet(href), fetchSignal)));
9859
9911
  if (stop.signal.aborted) throw stop.signal.reason;
9860
9912
  const placed = /* @__PURE__ */ new Set();
9861
- return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9862
- const href = remoteFontStylesheetHref(tag);
9913
+ for (const link of linkElements) {
9914
+ const href = remoteFontStylesheetHref(link);
9863
9915
  const inlineStyle = href ? inlineByHref.get(href) : void 0;
9864
- if (!href || !inlineStyle) return tag;
9916
+ if (!href || !inlineStyle) continue;
9865
9917
  if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9866
9918
  placed.add(href);
9867
- return inlineStyle;
9868
- });
9919
+ const style = document2.createElement("style");
9920
+ style.textContent = inlineStyle;
9921
+ link.replaceWith(style);
9922
+ }
9923
+ return placed.size === 0 ? html : document2.toString();
9869
9924
  }
9870
9925
  function projectStylesheetFontFamilies(html, projectDir) {
9871
9926
  const families = [];
@@ -10217,7 +10272,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10217
10272
  ...options.abortSignal ? [options.abortSignal] : []
10218
10273
  ]);
10219
10274
  const fontSheetHtml = await inlineExternalFontStylesheets(
10220
- promoteCssImportsToLinkTags(sanitizedHtml),
10275
+ promoteCssImportsToLinkTags(sanitizedHtml, budget),
10221
10276
  budget,
10222
10277
  remoteFetches
10223
10278
  );
@@ -12215,7 +12270,7 @@ import {
12215
12270
  assetRootsRefusal,
12216
12271
  assertPublicHttpsUrl,
12217
12272
  downloadToTemp as downloadToTemp2,
12218
- resolveRestrictPageNetwork,
12273
+ resolveRestrictPageNetwork as resolveRestrictPageNetwork2,
12219
12274
  isUrlNotPermittedError,
12220
12275
  writeUrlDownloadTelemetry as writeUrlDownloadTelemetry2,
12221
12276
  resolveProjectRelativeSrc as resolveProjectRelativeSrc5,
@@ -12663,7 +12718,7 @@ function localProbeSource(src, input) {
12663
12718
  }
12664
12719
  async function remoteProbeSource(video, input) {
12665
12720
  if (!isPublicHttpsUrl(video.src)) return null;
12666
- if (!resolveRestrictPageNetwork()) return video.src;
12721
+ if (!resolveRestrictPageNetwork2()) return video.src;
12667
12722
  if (!video.hasAudio || video.hidden) return null;
12668
12723
  const downloadDir = input.downloadDir ?? join26(input.compiledDir, REMOTE_MEDIA_SUBDIR);
12669
12724
  try {
@@ -17178,6 +17233,7 @@ async function executeRenderPipeline(input) {
17178
17233
  updateCaptureObservability({ captureBeyondViewport: resolvedCaptureBeyondViewport });
17179
17234
  }
17180
17235
  let routePageMotionBlur;
17236
+ let screenshotRetries = 0;
17181
17237
  const buildCaptureOptions = () => ({
17182
17238
  ...captureOptions,
17183
17239
  recordReferenceBackground,
@@ -17217,6 +17273,10 @@ async function executeRenderPipeline(input) {
17217
17273
  chromeGpuProcessSeenLastSample: stats.gpuProcessSeenLastSample,
17218
17274
  chromeMemorySamples: stats.samples
17219
17275
  });
17276
+ },
17277
+ onScreenshotRetry: () => {
17278
+ screenshotRetries += 1;
17279
+ updateCaptureObservability({ screenshotRetries });
17220
17280
  }
17221
17281
  });
17222
17282
  const buildPrepCaptureOptions = () => stopPrepSessionOnScriptFailure(buildCaptureOptions());
@@ -19068,7 +19128,11 @@ async function startHealthWorker(options = {}) {
19068
19128
  );
19069
19129
  }
19070
19130
  const worker = new Worker4(entry, {
19071
- workerData: { port },
19131
+ workerData: {
19132
+ port,
19133
+ hostname: options.hostname || "127.0.0.1",
19134
+ closeAfterMs: options.closeAfterMs
19135
+ },
19072
19136
  // Keep stdio inherited so the worker's console logs land in the pod logs
19073
19137
  // alongside the main thread's.
19074
19138
  stdout: false,
@@ -20514,7 +20578,7 @@ function startServer(options = {}) {
20514
20578
  server.setTimeout(0);
20515
20579
  server.requestTimeout = 0;
20516
20580
  server.keepAliveTimeout = 0;
20517
- const healthWorkerPromise = process.env.PRODUCER_DISABLE_HEALTH_WORKER === "1" ? Promise.resolve(null) : startHealthWorker({ logger: log }).catch((err) => {
20581
+ const healthWorkerPromise = process.env.PRODUCER_DISABLE_HEALTH_WORKER === "1" ? Promise.resolve(null) : startHealthWorker({ logger: log, hostname }).catch((err) => {
20518
20582
  log.error(`[server] health worker failed to start: ${err.message}`);
20519
20583
  return null;
20520
20584
  });
@@ -17,13 +17,6 @@
17
17
  * the probe `timeoutSeconds` (5s in prod prior to the companion change)
18
18
  * triggers a SIGKILL even when the process is still alive — just busy.
19
19
  *
20
- * Today's incident (2026-06-26): an infinite GSAP timeline caused the
21
- * distributed planner to try to enumerate ~300_000_000_000 frames, and
22
- * the sidecar got killed mid-arithmetic. Miguel's upstream `plan()`
23
- * duration guard kills that input class at the source. This module is
24
- * defense-in-depth: future wedge classes (sync I/O on video-heavy comps,
25
- * runaway loops, GC pauses) shouldn't kill an otherwise-alive pod either.
26
- *
27
20
  * Contract
28
21
  * --------
29
22
  *
@@ -33,10 +26,10 @@
33
26
  * which is a strict subset of process liveness. If the entire Node process
34
27
  * is dead the OS tears down both threads' sockets simultaneously, so the
35
28
  * worker_thread's listener stops answering and k8s correctly kills the pod.
36
- * - Listening on `0.0.0.0` is intentional: this is the probe entry point and
37
- * the sidecar already exposes other ports for in-pod traffic only. The
38
- * endpoint returns the same shape the main-thread `/health` always returned
39
- * so existing observability keeps working.
29
+ * - The listener binds the address it is given (`startServer` passes the main
30
+ * server's own), loopback when given none, and answers in the shape the
31
+ * main-thread `/health` always returned. A connection with no whole request
32
+ * within a few seconds, or idle after one, is closed; connections are capped.
40
33
  *
41
34
  * The main thread still serves `/health` on the main port (9847) for
42
35
  * backwards compatibility; k8s probe config in `heygen-com/app` can migrate
@@ -45,6 +38,10 @@
45
38
  export interface HealthWorkerOptions {
46
39
  /** Port the worker_thread health endpoint listens on. Default 9848 / env. */
47
40
  port?: number;
41
+ /** Address the endpoint listens on. Default `127.0.0.1`. */
42
+ hostname?: string;
43
+ /** How long a connection may go without a whole request, or sit idle. Default 5000 ms. */
44
+ closeAfterMs?: number;
48
45
  /**
49
46
  * Optional logger; falls back to console. Note: the worker thread itself
50
47
  * cannot use the parent's logger directly (separate isolate), so it logs
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Worker-thread entry for the off-main-thread /health endpoint.
3
3
  *
4
- * Runs a minimal `node:http` server bound to `workerData.port` that answers
4
+ * Runs a minimal `node:http` server bound to `workerData.port` on `workerData.hostname` that answers
5
5
  * `GET /health` with `{ status, uptime, timestamp, thread: "worker" }`.
6
6
  *
7
7
  * Lifecycle:
@@ -71,6 +71,8 @@ declare class AssetDownloads {
71
71
  reserve(urls: Iterable<string>): void;
72
72
  download(url: string, destDir: string): Promise<string>;
73
73
  }
74
+ /** Only a GSAP distribution file the compiler would itself name under the operator's mirror skips the address checks. */
75
+ export declare function isOperatorMirrorGsapUrl(src: string, mirror: string | undefined): boolean;
74
76
  /**
75
77
  * Distinct remote addresses one compile downloads, per kind: scripts, and non-Google stylesheets (counted before
76
78
  * their contents are read, so a stylesheet with no font rules counts too).
@@ -182,6 +182,7 @@ export interface RenderCaptureObservability {
182
182
  * out-of-memory exhaustion (`Set maximum size exceeded` and friends).
183
183
  */
184
184
  transientRetries?: number;
185
+ screenshotRetries?: number;
185
186
  memoryExhaustionDetected?: boolean;
186
187
  /**
187
188
  * Chrome process memory from the engine's per-session sampler (Phase −1 of