@hyperframes/producer 0.9.106 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -355,6 +355,7 @@ import {
355
355
  getDrawElementVerificationDetails,
356
356
  augmentProtocolTimeoutError,
357
357
  augmentPageNavigationTimeoutError,
358
+ createCacheLease,
358
359
  displaySize
359
360
  } from "@hyperframes/engine";
360
361
  import {
@@ -391,11 +392,8 @@ import { promisify } from "node:util";
391
392
  import { Readable } from "node:stream";
392
393
  import { join as join2, extname, resolve as resolve2, sep as sep2 } from "node:path";
393
394
  import { injectScriptsAtHeadStart, injectScriptsIntoHtml } from "@hyperframes/core/compiler";
394
- import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
395
- import {
396
- PREVIEW_FOR_ANOTHER_SITE_META,
397
- serviceWorkerScriptFetch
398
- } from "@hyperframes/core/studio-preview-mark";
395
+ import { markForAnotherSite } from "@hyperframes/core/compiler/html-document";
396
+ import { serviceWorkerScriptFetch } from "@hyperframes/core/studio-preview-mark";
399
397
  import { fpsToNumber, terminalText as terminalText2 } from "@hyperframes/core";
400
398
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
401
399
  import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
@@ -1115,7 +1113,6 @@ var HF_BRIDGE_SCRIPT = `(function() {
1115
1113
  if (bridge()) __realClearInterval(iv);
1116
1114
  }, 50);
1117
1115
  })();`;
1118
- var OFFER_NO_FRAMING_SITE_AN_EDITING_PORT = `<meta name="${PREVIEW_FOR_ANOTHER_SITE_META}">`;
1119
1116
  var RENDER_CAPTURE_MODE_SHIM = "globalThis.__HF_RENDER_CAPTURE_MODE = true;";
1120
1117
  function closeFileServerSafely(fileServer, label, log = defaultLogger) {
1121
1118
  try {
@@ -1214,7 +1211,7 @@ function createFileServer(options) {
1214
1211
  html = injectScriptsAtHeadStart(html, preHeadScripts);
1215
1212
  }
1216
1213
  html = isIndex ? injectScriptsIntoHtml(html, headScripts, bodyScripts, stripEmbeddedRuntime) : html;
1217
- html = injectTagsAtHeadStart(html, OFFER_NO_FRAMING_SITE_AN_EDITING_PORT);
1214
+ html = markForAnotherSite(html);
1218
1215
  return c.text(html, 200, { "Content-Type": contentType });
1219
1216
  }
1220
1217
  if (ext === ".png") {
@@ -2092,94 +2089,21 @@ import {
2092
2089
  mkdirSync as mkdirSync2,
2093
2090
  readFileSync as readFileSync2,
2094
2091
  readdirSync,
2095
- readlinkSync as readlinkSync2,
2096
2092
  rmSync as rmSync2,
2097
2093
  writeFileSync as writeFileSync2
2098
2094
  } from "node:fs";
2099
- import { execFileSync } from "node:child_process";
2100
- import { hostname, uptime } from "node:os";
2101
- import { basename as basename4, dirname as dirname3, join as join5, win32 } from "node:path";
2095
+ import { basename as basename4, dirname as dirname3, join as join5 } from "node:path";
2096
+ import { ownerRecordState, processOwnerRecord } from "@hyperframes/engine";
2102
2097
  import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
2103
2098
  import { createStagingDir, toWin32LongPath } from "@hyperframes/core/atomic-file";
2104
2099
  var OWNER_FILE = "owner.json";
2105
2100
  var TRANSACTION_BACKUP = "backup";
2106
2101
  var RENDER_JOB_DIR = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
2107
- var machineIdRead;
2108
- function machineId() {
2109
- const read2 = (file, args, pattern) => {
2110
- try {
2111
- const out = execFileSync(file, args, {
2112
- encoding: "utf-8",
2113
- timeout: 2e3,
2114
- windowsHide: true
2115
- });
2116
- return pattern.exec(out)?.[1];
2117
- } catch {
2118
- return void 0;
2119
- }
2120
- };
2121
- if (machineIdRead?.platform === process.platform) return machineIdRead.id;
2122
- const systemRoot = process.env.SystemRoot;
2123
- machineIdRead = {
2124
- platform: process.platform,
2125
- id: process.platform === "darwin" ? read2(
2126
- "/usr/sbin/ioreg",
2127
- ["-rd1", "-c", "IOPlatformExpertDevice"],
2128
- /"IOPlatformUUID" = "([^"]+)"/
2129
- ) : process.platform === "win32" && systemRoot && /^[A-Za-z]:\\/.test(systemRoot) ? read2(
2130
- win32.join(systemRoot, "System32", "reg.exe"),
2131
- ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"],
2132
- /MachineGuid\s+REG_SZ\s+(\S+)/
2133
- ) : void 0
2134
- };
2135
- return machineIdRead.id;
2136
- }
2137
- function pidScope() {
2138
- const attempt = (read2) => {
2139
- try {
2140
- return read2();
2141
- } catch {
2142
- return void 0;
2143
- }
2144
- };
2145
- const bootId = attempt(() => readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim());
2146
- return {
2147
- host: hostname(),
2148
- // Without /proc (macOS, Windows) the boot time in seconds stands in for the boot id, on this machine's own id.
2149
- boot: bootId ?? attempt(() => `s:${Math.round(Date.now() / 1e3 - uptime())}`),
2150
- pidns: attempt(() => readlinkSync2("/proc/self/ns/pid")),
2151
- machine: bootId === void 0 ? machineId() : void 0
2152
- };
2153
- }
2154
2102
  function createOwnedRenderDir(prefix) {
2155
2103
  const dir = createStagingDir(dirname3(prefix), basename4(prefix));
2156
- const owner = { pid: process.pid, ...pidScope() };
2157
- writeFileSync2(toWin32LongPath(join5(dir, OWNER_FILE)), JSON.stringify(owner));
2104
+ writeFileSync2(toWin32LongPath(join5(dir, OWNER_FILE)), JSON.stringify(processOwnerRecord()));
2158
2105
  return dir;
2159
2106
  }
2160
- function alive(pid) {
2161
- try {
2162
- process.kill(pid, 0);
2163
- return true;
2164
- } catch (error) {
2165
- return error.code === "EPERM";
2166
- }
2167
- }
2168
- function knownPidScope() {
2169
- const scope = pidScope();
2170
- const unknown = scope.boot === void 0 || process.platform === "linux" && scope.pidns === void 0 || scope.boot.startsWith("s:") && scope.machine === void 0;
2171
- return unknown ? void 0 : scope;
2172
- }
2173
- function sameBoot(stamped, current) {
2174
- if (stamped === current) return true;
2175
- const seconds = (boot) => typeof boot === "string" ? /^s:(\d+)$/.exec(boot)?.[1] : void 0;
2176
- const [a, b] = [seconds(stamped), seconds(current)];
2177
- return a !== void 0 && b !== void 0 && Math.abs(Number(a) - Number(b)) <= 2;
2178
- }
2179
- function inThisPidScope(owner) {
2180
- const scope = knownPidScope();
2181
- return scope !== void 0 && owner.host === scope.host && sameBoot(owner.boot, scope.boot) && owner.pidns === scope.pidns && owner.machine === scope.machine;
2182
- }
2183
2107
  function ownerState(dir) {
2184
2108
  let owner;
2185
2109
  try {
@@ -2187,11 +2111,7 @@ function ownerState(dir) {
2187
2111
  } catch (error) {
2188
2112
  return error.code === "ENOENT" ? "none" : "unknown";
2189
2113
  }
2190
- const { pid } = owner;
2191
- if (!inThisPidScope(owner) || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
2192
- return "unknown";
2193
- }
2194
- return alive(pid) ? "live" : "gone";
2114
+ return ownerRecordState(owner);
2195
2115
  }
2196
2116
  function newestWriteMs(path) {
2197
2117
  const stat = lstatSync2(path);
@@ -11757,14 +11677,14 @@ async function runProbeStage(input) {
11757
11677
  probeSession.beginFrameTimeTicks,
11758
11678
  probeSession.beginFrameIntervalMs
11759
11679
  );
11760
- const alive2 = await probeBeginFrameLiveness(
11680
+ const alive = await probeBeginFrameLiveness(
11761
11681
  probeSession.page,
11762
11682
  probeTimeoutMs,
11763
11683
  probeTick,
11764
11684
  probeSession.beginFrameIntervalMs
11765
11685
  );
11766
11686
  assertNotAborted();
11767
- if (alive2) {
11687
+ if (alive) {
11768
11688
  log.info("BeginFrame liveness probe passed", {
11769
11689
  probeMs: Date.now() - livenessStart
11770
11690
  });
@@ -12478,7 +12398,8 @@ async function runExtractVideosStage(input) {
12478
12398
  shownBoxes,
12479
12399
  urlByAbsentLocalPath,
12480
12400
  audioDownloadDir,
12481
- skipFrameExtractionIds = []
12401
+ skipFrameExtractionIds = [],
12402
+ cacheLease
12482
12403
  } = input;
12483
12404
  const stage2Start = Date.now();
12484
12405
  const assetRoots = job.config.allowOutsideProjectAssets ? void 0 : mediaAssetRoots(projectDir, compiledDir);
@@ -12598,6 +12519,7 @@ async function runExtractVideosStage(input) {
12598
12519
  contentKeyedDirs: [join26(compiledDir, REMOTE_MEDIA_SUBDIR)],
12599
12520
  urlByAbsentLocalPath,
12600
12521
  assetRoots,
12522
+ cacheLease,
12601
12523
  onProgress: ({ planned = 0, done = 0 }) => {
12602
12524
  framesPlanned += planned;
12603
12525
  framesDone += done;
@@ -13746,6 +13668,8 @@ async function runCaptureStage(input) {
13746
13668
  pageErrorLines: workerPageErrors,
13747
13669
  openAttempt: input.openAttempt,
13748
13670
  verifyFirstSession: input.verifyFirstSession,
13671
+ prepareSession: input.prepareSession,
13672
+ onSessionUnprepared: input.onSessionUnprepared,
13749
13673
  onProgress: (progress) => {
13750
13674
  if (progress.latestWorkerPhase) {
13751
13675
  if (progress.capturedFrames === 0) reportWorkerStartup(job, progress, onProgress);
@@ -15914,7 +15838,11 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15914
15838
  } : void 0,
15915
15839
  void 0,
15916
15840
  options.cfg,
15917
- { verifyFirstSession: options.verifyFirstSession }
15841
+ {
15842
+ verifyFirstSession: options.verifyFirstSession,
15843
+ prepareSession: options.prepareSession,
15844
+ onSessionUnprepared: options.onSessionUnprepared
15845
+ }
15918
15846
  );
15919
15847
  pushWorkerDedupPerfs(workerResults, options.dedupPerfs);
15920
15848
  if (options.pageErrorLines) pushWorkerPageErrors(workerResults, options.pageErrorLines);
@@ -16957,6 +16885,8 @@ async function executeRenderPipeline(input) {
16957
16885
  reason
16958
16886
  });
16959
16887
  }
16888
+ const cacheLease = createCacheLease();
16889
+ execution.defer("release extraction cache lease", () => cacheLease.release());
16960
16890
  const extractResult = await observeRenderStage(
16961
16891
  observability,
16962
16892
  "video_extract",
@@ -16974,6 +16904,7 @@ async function executeRenderPipeline(input) {
16974
16904
  assertNotAborted,
16975
16905
  // Local staging can use links; distributed plan() alone requires real copies.
16976
16906
  materializeSymlinks: false,
16907
+ cacheLease,
16977
16908
  deferRangeExtraction: windowVideoFrames ? true : void 0,
16978
16909
  shownBoxes,
16979
16910
  onProgress
@@ -21102,7 +21033,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
21102
21033
  const composition = compileResult.composition;
21103
21034
  const { deviceScaleFactor } = compileResult;
21104
21035
  let forceScreenshot = compileResult.forceScreenshot;
21105
- if (cfg.lowMemoryMode) forceScreenshot = true;
21036
+ if (cfg.lowMemoryMode || deviceScaleFactor !== 1) forceScreenshot = true;
21106
21037
  const { width, height } = composition;
21107
21038
  if (config.rejectOnSystemFonts !== false) {
21108
21039
  validateNoSystemFonts(compiled.html);
@@ -21535,6 +21466,8 @@ import {
21535
21466
  getEncoderPreset as getEncoderPreset5,
21536
21467
  initializeSession as initializeSession10,
21537
21468
  measureVideoShownBoxes,
21469
+ measureVideoShownBoxPart,
21470
+ mergeVideoShownBoxParts,
21538
21471
  probeBeginFrameLiveness as probeBeginFrameLiveness2,
21539
21472
  readWebGlVendorInfoFromCanvas,
21540
21473
  resolveConfig as resolveConfig4,
@@ -22548,6 +22481,35 @@ async function beginFrameSessionNeedsScreenshotFallback(session, probe = probeBe
22548
22481
  );
22549
22482
  return !await probe(session.page, timeoutMs, probeTick, session.beginFrameIntervalMs);
22550
22483
  }
22484
+ function createSharedBoxMeasure(onDone) {
22485
+ const started = Date.now();
22486
+ let done = false;
22487
+ let workerCount = 0;
22488
+ const shares = /* @__PURE__ */ new Map();
22489
+ return {
22490
+ settled: () => done,
22491
+ fullSize: () => {
22492
+ if (done) return;
22493
+ done = true;
22494
+ onDone(void 0);
22495
+ },
22496
+ add: (worker, part, cost) => {
22497
+ if (done) return;
22498
+ if (worker.workerCount !== workerCount) shares.clear();
22499
+ workerCount = worker.workerCount;
22500
+ shares.set(worker.workerId, { part, ...cost });
22501
+ if (shares.size < workerCount) return;
22502
+ done = true;
22503
+ const all = [...shares.values()];
22504
+ onDone(mergeVideoShownBoxParts(all.map((share) => share.part)), {
22505
+ workers: workerCount,
22506
+ frames: all.reduce((sum2, share) => sum2 + share.frames, 0),
22507
+ durationMs: Date.now() - started,
22508
+ slowestShareMs: Math.max(...all.map((share) => share.durationMs))
22509
+ });
22510
+ }
22511
+ };
22512
+ }
22551
22513
  function hashChunkOutput(outputPath, kind) {
22552
22514
  if (kind === "file") return sha256Hex(readFileSync15(outputPath));
22553
22515
  const entries = readdirSync11(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
@@ -22753,14 +22715,26 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22753
22715
  });
22754
22716
  boxesReady.catch(() => {
22755
22717
  });
22718
+ const shownVideoIds = [...shownFrames.keys()];
22719
+ const chunkFrameTimes = chunkFrameNumbers.map(
22720
+ (frame) => frame * chunkFps.den / chunkFps.num
22721
+ );
22756
22722
  const measureBoxes = async (page) => {
22757
- shownBoxes = await measureVideoShownBoxes(
22758
- page,
22759
- [...shownFrames.keys()],
22760
- chunkFrameNumbers.map((frame) => frame * chunkFps.den / chunkFps.num)
22761
- );
22723
+ shownBoxes = await measureVideoShownBoxes(page, shownVideoIds, chunkFrameTimes);
22762
22724
  boxesMeasured();
22763
22725
  };
22726
+ const sharedBoxes = createSharedBoxMeasure((boxes2, pass) => {
22727
+ shownBoxes = boxes2;
22728
+ boxesMeasured();
22729
+ if (pass) log.info("[renderChunk] video boxes measured", { chunkIndex, ...pass });
22730
+ });
22731
+ const measureShare = async (session2, worker) => {
22732
+ if (sharedBoxes.settled()) return;
22733
+ const started = Date.now();
22734
+ const times = chunkFrameTimes.filter((_, i) => i % worker.workerCount === worker.workerId);
22735
+ const part = await measureVideoShownBoxPart(session2.page, shownVideoIds, times);
22736
+ sharedBoxes.add(worker, part, { frames: times.length, durationMs: Date.now() - started });
22737
+ };
22764
22738
  if (chunkWorkerCount === 1) {
22765
22739
  const bootStarted = Date.now();
22766
22740
  session = await createVerifiedDistributedCaptureSession(
@@ -22802,14 +22776,13 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22802
22776
  );
22803
22777
  sessionBootMs += Date.now() - screenshotBootStarted;
22804
22778
  }
22805
- } else if (!verifyInWorker) {
22806
- boxesMeasured();
22779
+ } else if (!verifyInWorker || shownVideoIds.length === 0) {
22780
+ sharedBoxes.fullSize();
22807
22781
  }
22808
22782
  let verification;
22809
22783
  const verifyFirstWorker = (first) => verification ??= (async () => {
22810
22784
  sessionBootMs = Date.now() - verifyStarted;
22811
22785
  try {
22812
- await measureBoxes(first.page);
22813
22786
  const selectedScreenshot = first.launchCaptureMode === "screenshot";
22814
22787
  if (selectedScreenshot || await beginFrameSessionNeedsScreenshotFallback(first)) {
22815
22788
  forceScreenshotForChunk = true;
@@ -22994,7 +22967,9 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22994
22967
  onFrameLanded: (frame) => overlap.current?.onFrameLanded(frame),
22995
22968
  interleaveFrames: interleavesCapture(overlap.current !== null, options),
22996
22969
  openAttempt,
22997
- verifyFirstSession: forceScreenshot || !verifyInWorker ? void 0 : verifyFirstWorker
22970
+ verifyFirstSession: forceScreenshot || !verifyInWorker ? void 0 : verifyFirstWorker,
22971
+ prepareSession: forceScreenshot || !verifyInWorker ? void 0 : measureShare,
22972
+ onSessionUnprepared: () => sharedBoxes.fullSize()
22998
22973
  }),
22999
22974
  { stall: frameStallRule(job, framesInChunk, void 0) }
23000
22975
  ).catch(async (captureError) => {
@@ -23006,7 +22981,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
23006
22981
  },
23007
22982
  resetForScreenshotRetry: () => {
23008
22983
  rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
23009
- boxesMeasured();
22984
+ sharedBoxes.fullSize();
23010
22985
  mkdirSync22(framesDir, { recursive: true });
23011
22986
  capturePerfs.length = 0;
23012
22987
  captureAttempts.length = 0;
@@ -24974,18 +24949,18 @@ function hostnameOf(host) {
24974
24949
  return null;
24975
24950
  }
24976
24951
  }
24977
- function isAllowedBrowserHostname(hostname2, allowed) {
24978
- if (!hostname2) return false;
24979
- if (hostname2 === "localhost" || hostname2.endsWith(".localhost")) return true;
24980
- if (isIP(hostname2.replace(/^\[|\]$/g, "")) !== 0) return true;
24981
- return allowed.has(hostname2);
24952
+ function isAllowedBrowserHostname(hostname, allowed) {
24953
+ if (!hostname) return false;
24954
+ if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
24955
+ if (isIP(hostname.replace(/^\[|\]$/g, "")) !== 0) return true;
24956
+ return allowed.has(hostname);
24982
24957
  }
24983
24958
  function allowedHostnames(options) {
24984
24959
  const fromEnv = (process.env.PRODUCER_ALLOWED_HOSTS ?? "").split(",");
24985
24960
  const names = /* @__PURE__ */ new Set();
24986
24961
  for (const entry of [...options.allowedHosts ?? [], ...fromEnv]) {
24987
- const hostname2 = entry.trim() ? hostnameOf(entry.trim()) : null;
24988
- if (hostname2) names.add(hostname2);
24962
+ const hostname = entry.trim() ? hostnameOf(entry.trim()) : null;
24963
+ if (hostname) names.add(hostname);
24989
24964
  }
24990
24965
  return names;
24991
24966
  }
@@ -24999,8 +24974,8 @@ function hasBearerToken(c, token) {
24999
24974
  digest(`Bearer ${token}`)
25000
24975
  );
25001
24976
  }
25002
- function isLoopbackHostname(hostname2) {
25003
- const host = hostname2.replace(/^\[|\]$/g, "").toLowerCase();
24977
+ function isLoopbackHostname(hostname) {
24978
+ const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
25004
24979
  return host === "localhost" || host === "::1" || isIP(host) === 4 && host.startsWith("127.");
25005
24980
  }
25006
24981
  function isDisallowedBrowserHost(c, allowed) {
@@ -25069,12 +25044,12 @@ function onEscapedRejection(reason, log) {
25069
25044
  });
25070
25045
  scope?.fail(err);
25071
25046
  }
25072
- function serverAuth(options, hostname2, port) {
25047
+ function serverAuth(options, hostname, port) {
25073
25048
  const configured = resolveAuthToken(options);
25074
25049
  if (configured) return { token: configured };
25075
- if (!isLoopbackHostname(hostname2)) {
25050
+ if (!isLoopbackHostname(hostname)) {
25076
25051
  throw new Error(
25077
- `Refusing to listen on ${hostname2} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`
25052
+ `Refusing to listen on ${hostname} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`
25078
25053
  );
25079
25054
  }
25080
25055
  const file = resolve14(
@@ -25089,11 +25064,11 @@ function serverAuth(options, hostname2, port) {
25089
25064
  }
25090
25065
  function startServer(options = {}) {
25091
25066
  const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
25092
- const hostname2 = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
25067
+ const hostname = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
25093
25068
  const log = options.logger ?? defaultLogger;
25094
- const auth = serverAuth(options, hostname2, port);
25069
+ const auth = serverAuth(options, hostname, port);
25095
25070
  const app = createProducerApp({ ...options, authToken: auth.token });
25096
- const server = serve2({ fetch: app.fetch, port, hostname: hostname2 }, (info) => {
25071
+ const server = serve2({ fetch: app.fetch, port, hostname }, (info) => {
25097
25072
  const address = info.family === "IPv6" ? `[${info.address}]` : info.address;
25098
25073
  log.info(`Listening on http://${address}:${info.port}`);
25099
25074
  if (auth.generatedFile) {