@hyperframes/producer 0.9.92 → 0.9.94

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
@@ -10,11 +10,11 @@ import {
10
10
  import { audioFailureDiagnostics as audioFailureDiagnostics2, cpuBudget } from "@hyperframes/engine";
11
11
  import {
12
12
  existsSync as existsSync22,
13
- mkdirSync as mkdirSync12,
13
+ mkdirSync as mkdirSync13,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync13,
16
16
  statSync as statSync10,
17
- writeFileSync as writeFileSync6,
17
+ writeFileSync as writeFileSync7,
18
18
  copyFileSync as copyFileSync5,
19
19
  appendFileSync
20
20
  } from "fs";
@@ -339,6 +339,7 @@ import {
339
339
  LOW_MEMORY_TOTAL_MB_THRESHOLD,
340
340
  assertConfiguredFfmpegBinariesExist,
341
341
  resolveBrowserGpuMode,
342
+ probedHardwareGpu,
342
343
  resolveHeadlessShellPath,
343
344
  compositionRequiresWebGpu as compositionRequiresWebGpu2,
344
345
  applyConcreteGpuScreenshotClamp,
@@ -360,7 +361,7 @@ import {
360
361
  referenceBackgroundResult,
361
362
  createReferenceBackgroundRecorder
362
363
  } from "@hyperframes/engine";
363
- import { join as join35, dirname as dirname15, resolve as resolve9 } from "path";
364
+ import { join as join35, dirname as dirname16, resolve as resolve9 } from "path";
364
365
  import { totalmem as totalmem2 } from "node:os";
365
366
  import { randomUUID as randomUUID3 } from "crypto";
366
367
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -390,7 +391,7 @@ import {
390
391
  serviceWorkerScriptFetch
391
392
  } from "@hyperframes/core/studio-preview-mark";
392
393
  import { fpsToNumber, terminalText as terminalText2 } from "@hyperframes/core";
393
- import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
394
+ import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
394
395
  import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
395
396
  import { openRangeEnd } from "@hyperframes/studio-server/media-range";
396
397
 
@@ -532,7 +533,7 @@ import {
532
533
  } from "node:path";
533
534
  import { statSync } from "node:fs";
534
535
  import { fileURLToPath as fileURLToPath2 } from "node:url";
535
- import { isSafePath } from "@hyperframes/core/safe-path";
536
+ import { isPrivateFileUnder, isSafePath, isStudioPrivatePath } from "@hyperframes/core/safe-path";
536
537
  import {
537
538
  isCopiedOutsideFileType,
538
539
  isPrivateOutsideFile,
@@ -559,7 +560,10 @@ function escapesAssetRoot(path, assetRoot) {
559
560
  return assetRoot !== void 0 && !isSafePath(assetRoot, path);
560
561
  }
561
562
  function outsideAssetRefusal(projectDir, path, policy = {}) {
562
- if (!linksOutside(projectDir, path)) return null;
563
+ if (!linksOutside(projectDir, path)) {
564
+ const privateByAnotherSpelling = !isPathInside(path, projectDir) && isPrivateFileUnder(projectDir, path, isStudioPrivatePath);
565
+ return privateByAnotherSpelling ? "blocklisted" : null;
566
+ }
563
567
  if (isPrivateOutsideFile(projectDir, path)) return "blocklisted";
564
568
  const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
565
569
  if (folder || isUploadedOutsideFileType(path)) return null;
@@ -1185,7 +1189,7 @@ function createFileServer(options) {
1185
1189
  const candidate = join2(root, relativePath);
1186
1190
  const resolveSymlinks = !allowOutsideProjectAssets && root !== compiledDir;
1187
1191
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
1188
- if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
1192
+ if (isPrivateFileUnder2(root, candidate, isStudioPrivatePath2)) continue;
1189
1193
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
1190
1194
  if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut, outsidePolicy)) continue;
1191
1195
  file = openRegularFile(candidate);
@@ -4129,12 +4133,12 @@ function distributeLayeredHybridFrameRanges(totalFrames, workerCount) {
4129
4133
  }
4130
4134
  return ranges;
4131
4135
  }
4132
- function partitionTransitionFrames(transitionRanges, totalFrames) {
4136
+ function partitionTransitionFrames(transitionRanges, totalFrames, firstFrame = 0) {
4133
4137
  const frames = /* @__PURE__ */ new Set();
4134
4138
  if (totalFrames <= 0) return frames;
4135
4139
  for (const range of transitionRanges) {
4136
- const start = Math.max(0, range.startFrame);
4137
- const end = Math.min(totalFrames - 1, range.endFrame);
4140
+ const start = Math.max(firstFrame, range.startFrame);
4141
+ const end = Math.min(firstFrame + totalFrames - 1, range.endFrame);
4138
4142
  for (let i = start; i <= end; i++) frames.add(i);
4139
4143
  }
4140
4144
  return frames;
@@ -4344,6 +4348,18 @@ function cleanupEndedHdrVideos(args) {
4344
4348
  }
4345
4349
  }
4346
4350
  }
4351
+ function transitionAtFrame(transitionRanges, frame) {
4352
+ return transitionRanges.find((t) => frame >= t.startFrame && frame <= t.endFrame);
4353
+ }
4354
+ function cleanupHdrVideosEndedBefore(firstFrame, fps, transitionRanges, state) {
4355
+ for (let frame = 0; frame < firstFrame; frame++) {
4356
+ cleanupEndedHdrVideos({
4357
+ ...state,
4358
+ time: frame * fps.den / fps.num,
4359
+ activeTransition: transitionAtFrame(transitionRanges, frame)
4360
+ });
4361
+ }
4362
+ }
4347
4363
 
4348
4364
  // src/services/render/segmentPlan.ts
4349
4365
  import { join as join9 } from "node:path";
@@ -5998,6 +6014,18 @@ function estimateMeasuredCaptureCostMultiplier(samples) {
5998
6014
  medianMs
5999
6015
  };
6000
6016
  }
6017
+ function shouldCalibrateSoftwareGpu(requestedMode, resolvedMode, hardware) {
6018
+ return requestedMode === "auto" && resolvedMode === "hardware" && hardware !== void 0 && hardware.multiplier > 1 && hardware.p95Ms !== void 0;
6019
+ }
6020
+ function settleAutoGpuChoice(hardware, software) {
6021
+ if (hardware?.p95Ms === void 0) return void 0;
6022
+ if (hardware.multiplier <= 1) return "hardware";
6023
+ if (software?.p95Ms === void 0) return void 0;
6024
+ return software.p95Ms < hardware.p95Ms ? "software" : "hardware";
6025
+ }
6026
+ function pickAutoGpuModeFromCalibration(hardware, software) {
6027
+ return settleAutoGpuChoice(hardware, software) ?? "hardware";
6028
+ }
6001
6029
  function selectCaptureCalibrationFrames(totalFrames) {
6002
6030
  if (totalFrames <= 0) return [];
6003
6031
  const lastFrame = totalFrames - 1;
@@ -6012,8 +6040,8 @@ function selectCaptureCalibrationFrames(totalFrames) {
6012
6040
  new Set(candidates.map((frame) => Math.max(0, Math.min(lastFrame, frame))))
6013
6041
  ).sort((a, b) => a - b);
6014
6042
  }
6015
- async function measureCaptureCostFromSession(session, totalFrames, fps, log) {
6016
- const sampledFrames = selectCaptureCalibrationFrames(totalFrames);
6043
+ async function measureCaptureCostFromSession(session, totalFrames, fps, log, firstFrame = 0) {
6044
+ const sampledFrames = selectCaptureCalibrationFrames(totalFrames).map((i) => firstFrame + i);
6017
6045
  const samples = [];
6018
6046
  const totalSamples = sampledFrames.length;
6019
6047
  const savedStaticFrames = session.staticFrames;
@@ -6109,7 +6137,13 @@ async function runCaptureCalibration(input) {
6109
6137
  }
6110
6138
  assertNotAborted();
6111
6139
  log.info("Calibration session ready, capturing test frames...");
6112
- const result = await measureCaptureCostFromSession(session, totalFrames, fps, log);
6140
+ const result = await measureCaptureCostFromSession(
6141
+ session,
6142
+ totalFrames,
6143
+ fps,
6144
+ log,
6145
+ job.frameWindow?.startFrame
6146
+ );
6113
6147
  logCaptureCalibrationResult(result, log);
6114
6148
  return result;
6115
6149
  };
@@ -6670,6 +6704,57 @@ function resolveVideoCaptureBeyondViewport(videoCount) {
6670
6704
  return true;
6671
6705
  }
6672
6706
 
6707
+ // src/services/render/gpuChoice.ts
6708
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
6709
+ import { dirname as dirname6 } from "node:path";
6710
+ function gpuChoiceStore(cfg, gpu) {
6711
+ if (!cfg.gpuChoiceFile || !cfg.hyperframesVersion || !gpu) return void 0;
6712
+ return { file: cfg.gpuChoiceFile, key: `${cfg.hyperframesVersion} | ${gpu}` };
6713
+ }
6714
+ function readGpuChoice(store) {
6715
+ let record;
6716
+ try {
6717
+ record = JSON.parse(readFileSync5(store.file, "utf8"));
6718
+ } catch {
6719
+ return void 0;
6720
+ }
6721
+ if (record?.key !== store.key) return void 0;
6722
+ return record.mode === "software" || record.mode === "hardware" ? record.mode : void 0;
6723
+ }
6724
+ function writeGpuChoice(store, mode, measured) {
6725
+ mkdirSync7(dirname6(store.file), { recursive: true });
6726
+ const temp = `${store.file}.${process.pid}.tmp`;
6727
+ const record = { key: store.key, mode, ...measured, measuredAt: (/* @__PURE__ */ new Date()).toISOString() };
6728
+ writeFileSync3(temp, `${JSON.stringify(record, null, 2)}
6729
+ `);
6730
+ renameSync(temp, store.file);
6731
+ }
6732
+
6733
+ // src/services/render/frameWindow.ts
6734
+ function resolveFrameWindow(range, fps, filmFrames) {
6735
+ const frameAt = (seconds) => Math.round(seconds * fps.num / fps.den);
6736
+ const startFrame = frameAt(range.startSeconds);
6737
+ const endFrame = Math.min(
6738
+ range.endSeconds === void 0 ? filmFrames : frameAt(range.endSeconds),
6739
+ filmFrames
6740
+ );
6741
+ if (!(endFrame > startFrame)) {
6742
+ throw new Error(
6743
+ `The range ${range.startSeconds}s to ${range.endSeconds ?? "the end"}s holds no frame: the film has ${filmFrames} frames at ${fps.num}/${fps.den} fps.`
6744
+ );
6745
+ }
6746
+ return { startFrame, endFrame };
6747
+ }
6748
+ function windowStartFrame(frameWindow) {
6749
+ return frameWindow?.startFrame ?? 0;
6750
+ }
6751
+ function assertRangeSupported(frameWindow, route) {
6752
+ if (!frameWindow || route === "sdr_disk" || route === "hdr_layered") return;
6753
+ throw new Error(
6754
+ `This composition renders on the "${route}" capture route, which renders the whole film only; render it without a start or end.`
6755
+ );
6756
+ }
6757
+
6673
6758
  // src/services/render/observability.ts
6674
6759
  import { createHash as createHash3 } from "node:crypto";
6675
6760
  import { redactTelemetryString } from "@hyperframes/core";
@@ -7041,7 +7126,7 @@ function emitFallbackCaptureProfile(recorder, perfSummaries, env = process.env)
7041
7126
  }
7042
7127
 
7043
7128
  // src/services/render/videoFrameCoverage.ts
7044
- import { parseHTML } from "linkedom";
7129
+ import { parseHTML } from "@hyperframes/parsers/linkedom";
7045
7130
  import {
7046
7131
  fpsToNumber as fpsToNumber5,
7047
7132
  normalizeRateSpec,
@@ -7056,7 +7141,6 @@ var SHORT_CLIP_ONE_FRAME_TOLERANCE_MIN_EXPECTED_FRAMES = 14;
7056
7141
  var SHORT_CLIP_ONE_FRAME_TOLERANCE_MAX_EXPECTED_FRAMES = 20;
7057
7142
  var VideoFrameCoverageError = class extends Error {
7058
7143
  // Read structurally by isVideoFrameCoverageError and cross-module callers.
7059
- // fallow-ignore-next-line unused-class-member
7060
7144
  hyperframesVideoFrameCoverageError = true;
7061
7145
  threshold;
7062
7146
  worst;
@@ -7159,7 +7243,7 @@ function requireOutputDimensions(expected, width, height) {
7159
7243
  }
7160
7244
 
7161
7245
  // src/services/render/stages/compileStage.ts
7162
- import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7246
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
7163
7247
  import { join as join23, relative as relative5 } from "node:path";
7164
7248
  import { privateCacheRoot } from "@hyperframes/engine";
7165
7249
  import { suggestMatchingPreset } from "@hyperframes/core";
@@ -7169,7 +7253,7 @@ import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperf
7169
7253
 
7170
7254
  // src/services/compileInWorker.ts
7171
7255
  import { existsSync as existsSync12, rmSync as rmSync11 } from "node:fs";
7172
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7256
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7173
7257
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7174
7258
  import { Worker } from "node:worker_threads";
7175
7259
 
@@ -7189,17 +7273,17 @@ import {
7189
7273
  stylesheetLinkMatches
7190
7274
  } from "@hyperframes/parsers/css-url-scans";
7191
7275
  import { createHash as createHash6 } from "node:crypto";
7192
- import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8, statSync as statSync8 } from "fs";
7193
- import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7194
- import { parseHTML as parseHTML5 } from "linkedom";
7276
+ import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync10, readFileSync as readFileSync9, statSync as statSync8 } from "fs";
7277
+ import { join as join21, dirname as dirname10, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7278
+ import { parseHTML as parseHTML5 } from "@hyperframes/parsers/linkedom";
7195
7279
 
7196
7280
  // src/services/bundledScripts.ts
7197
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7281
+ import { existsSync as existsSync8, readFileSync as readFileSync6 } from "node:fs";
7198
7282
  import { join as join17 } from "node:path";
7199
7283
  import { GSAP_CDN_VERSION } from "@hyperframes/core/gsap-cdn";
7200
7284
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
7201
7285
  var DEFAULT_CDN_GSAP_3 = /^https:\/\/cdn\.jsdelivr\.net\/npm\/gsap@(3\.\d+\.\d+)\/dist\/([A-Za-z]+\.min\.js)$/;
7202
- var read = (file) => existsSync8(file) ? readFileSync5(file) : null;
7286
+ var read = (file) => existsSync8(file) ? readFileSync6(file) : null;
7203
7287
  function bundledScript(url) {
7204
7288
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
7205
7289
  const [, version, file] = DEFAULT_CDN_GSAP_3.exec(url) ?? [];
@@ -7273,7 +7357,7 @@ import {
7273
7357
  readTextFile,
7274
7358
  resolveCompositionSrc
7275
7359
  } from "@hyperframes/parsers/asset-resolution";
7276
- import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7360
+ import { isPrivateFileUnder as isPrivateFileUnder3, isStudioPrivatePath as isStudioPrivatePath3 } from "@hyperframes/core/safe-path";
7277
7361
  import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
7278
7362
  import {
7279
7363
  assertCompositionFileSize,
@@ -7284,7 +7368,7 @@ import {
7284
7368
  } from "@hyperframes/core/compiler";
7285
7369
 
7286
7370
  // src/services/renderMediaCollector.ts
7287
- import { parseHTML as parseHTML2 } from "linkedom";
7371
+ import { parseHTML as parseHTML2 } from "@hyperframes/parsers/linkedom";
7288
7372
  import {
7289
7373
  MEDIA_RENDER_ID_ATTR,
7290
7374
  normalizeRateSpec as normalizeRateSpec2,
@@ -7476,9 +7560,9 @@ import {
7476
7560
 
7477
7561
  // src/services/animatedGifPrep.ts
7478
7562
  import { createHash as createHash4, randomUUID } from "node:crypto";
7479
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7480
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7481
- import { parseHTML as parseHTML3 } from "linkedom";
7563
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync8, readFileSync as readFileSync7, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7564
+ import { dirname as dirname7, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7565
+ import { parseHTML as parseHTML3 } from "@hyperframes/parsers/linkedom";
7482
7566
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
7483
7567
  import {
7484
7568
  DEFAULT_VP9_CPU_USED,
@@ -7530,7 +7614,11 @@ function resolveLocalImageSourcePath(src, options) {
7530
7614
  resolve6(options.downloadDir, normalizedBase)
7531
7615
  ];
7532
7616
  const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7533
- const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7617
+ const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(
7618
+ candidate,
7619
+ [options.projectDir, options.downloadDir],
7620
+ options.allowOutsideFiles
7621
+ ) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7534
7622
  return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7535
7623
  }
7536
7624
  function isUsableFile(path) {
@@ -7659,11 +7747,11 @@ async function runAnimatedGifTranscode(request) {
7659
7747
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
7660
7748
  }
7661
7749
  async function ensurePreparedWebm(input) {
7662
- if (!existsSync9(dirname6(input.cachePath))) {
7663
- mkdirSync7(dirname6(input.cachePath), { recursive: true });
7750
+ if (!existsSync9(dirname7(input.cachePath))) {
7751
+ mkdirSync8(dirname7(input.cachePath), { recursive: true });
7664
7752
  }
7665
- if (!existsSync9(dirname6(input.outputPath))) {
7666
- mkdirSync7(dirname6(input.outputPath), { recursive: true });
7753
+ if (!existsSync9(dirname7(input.outputPath))) {
7754
+ mkdirSync8(dirname7(input.outputPath), { recursive: true });
7667
7755
  }
7668
7756
  if (!isUsableFile(input.cachePath)) {
7669
7757
  const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
@@ -7764,7 +7852,7 @@ async function prepareAnimatedGifInputs(html, options) {
7764
7852
  if (!hasGifExtension(src)) continue;
7765
7853
  const sourcePath = resolveLocalImageSourcePath(src, options);
7766
7854
  if (!sourcePath) continue;
7767
- const bytes = readFileSync6(sourcePath);
7855
+ const bytes = readFileSync7(sourcePath);
7768
7856
  const metadata = parseAnimatedGifMetadata(bytes);
7769
7857
  if (!metadata?.animated) continue;
7770
7858
  const loopOverride = readLoopOverride(img);
@@ -7816,16 +7904,16 @@ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypt
7816
7904
  import {
7817
7905
  closeSync as closeSync5,
7818
7906
  copyFileSync as copyFileSync3,
7819
- mkdirSync as mkdirSync8,
7907
+ mkdirSync as mkdirSync9,
7820
7908
  openSync as openSync5,
7821
- readFileSync as readFileSync7,
7909
+ readFileSync as readFileSync8,
7822
7910
  readSync as readSync3,
7823
7911
  rmSync as rmSync10,
7824
7912
  statSync as statSync7,
7825
- writeFileSync as writeFileSync3
7913
+ writeFileSync as writeFileSync4
7826
7914
  } from "node:fs";
7827
- import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
7828
- import { parseHTML as parseHTML4 } from "linkedom";
7915
+ import { dirname as dirname8, join as join19, resolve as resolve7 } from "node:path";
7916
+ import { parseHTML as parseHTML4 } from "@hyperframes/parsers/linkedom";
7829
7917
  import { renameWithRetry as renameWithRetry3, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7830
7918
 
7831
7919
  // src/services/heifRotation.ts
@@ -8009,7 +8097,7 @@ function primaryGrid(probed) {
8009
8097
  async function convertHeifToJpeg(request) {
8010
8098
  const probed = await probeJson(request.inputPath, true);
8011
8099
  const grid = primaryGrid(probed);
8012
- const rotation = readHeifPrimaryRotation(readFileSync7(request.inputPath));
8100
+ const rotation = readHeifPrimaryRotation(readFileSync8(request.inputPath));
8013
8101
  const filters = [];
8014
8102
  let inputs = [];
8015
8103
  let size = probed.streams?.[0];
@@ -8073,7 +8161,7 @@ function resolveImageSource(src, options) {
8073
8161
  const path = resolveLocalImageSourcePath(src, options);
8074
8162
  const head = path ? readHead(path) : null;
8075
8163
  if (!path || !head || !isHeifBytes(head)) return null;
8076
- return { path, bytes: readFileSync7(path), label: `"${splitUrlSuffix(src).basePath}"` };
8164
+ return { path, bytes: readFileSync8(path), label: `"${splitUrlSuffix(src).basePath}"` };
8077
8165
  }
8078
8166
  function isUsableFile2(path) {
8079
8167
  try {
@@ -8083,14 +8171,14 @@ function isUsableFile2(path) {
8083
8171
  }
8084
8172
  }
8085
8173
  async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8086
- mkdirSync8(dirname7(cachePath), { recursive: true });
8087
- mkdirSync8(dirname7(outputPath), { recursive: true });
8174
+ mkdirSync9(dirname8(cachePath), { recursive: true });
8175
+ mkdirSync9(dirname8(outputPath), { recursive: true });
8088
8176
  if (!isUsableFile2(cachePath)) {
8089
8177
  const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8090
8178
  const inlinePath = `${tmpPath}.heic`;
8091
8179
  const inputPath = source.path ?? inlinePath;
8092
8180
  try {
8093
- if (!source.path) writeFileSync3(inlinePath, source.bytes);
8181
+ if (!source.path) writeFileSync4(inlinePath, source.bytes);
8094
8182
  await (options.transcode ?? convertHeifToJpeg)({
8095
8183
  inputPath,
8096
8184
  outputPath: tmpPath,
@@ -8163,7 +8251,7 @@ import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position
8163
8251
 
8164
8252
  // src/services/assetMediaType.ts
8165
8253
  import { existsSync as existsSync10 } from "node:fs";
8166
- import { dirname as dirname8, join as join20 } from "node:path";
8254
+ import { dirname as dirname9, join as join20 } from "node:path";
8167
8255
  import {
8168
8256
  fingerprintElementId,
8169
8257
  isHttpUrl as isHttpUrl2,
@@ -8217,7 +8305,7 @@ function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
8217
8305
  ]);
8218
8306
  }
8219
8307
  function mediaAssetRoots(projectDir, compiledDir) {
8220
- return [projectDir, compiledDir, join20(dirname8(compiledDir), "downloads")];
8308
+ return [projectDir, compiledDir, join20(dirname9(compiledDir), "downloads")];
8221
8309
  }
8222
8310
  function dropMediaOutsideProject(input) {
8223
8311
  const { projectDir, workDir, composition, log } = input;
@@ -8226,7 +8314,7 @@ function dropMediaOutsideProject(input) {
8226
8314
  const staysInside = ({ id, src }) => {
8227
8315
  if (!src || isHttpUrl2(src)) return true;
8228
8316
  const path = resolveProjectRelativeSrc3(src, projectDir, compiledDir);
8229
- if (isPrivateUnderAssetRoots2(path, roots)) {
8317
+ if (isPrivateUnderAssetRoots2(path, roots, input.allowOutsideProjectAssets)) {
8230
8318
  log.warn(`[Render] Media "${id}" source is missing: it is a private project file`, { src });
8231
8319
  return false;
8232
8320
  }
@@ -8396,7 +8484,7 @@ function assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outs
8396
8484
  throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
8397
8485
  }
8398
8486
  }
8399
- var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
8487
+ var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder3(projectDir, filePath, isStudioPrivatePath3);
8400
8488
  function compositionSrcsIn(html) {
8401
8489
  const { document: document2 } = parseHTML5(html);
8402
8490
  const mounts = [];
@@ -8722,7 +8810,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8722
8810
  let filePath = src;
8723
8811
  if (isHttpUrl(src)) {
8724
8812
  const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8725
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8813
+ if (!existsSync11(remoteDir)) mkdirSync10(remoteDir, { recursive: true });
8726
8814
  run?.assets.reserve([src]);
8727
8815
  try {
8728
8816
  filePath = await downloadAsset(src, remoteDir, run?.assets);
@@ -8733,7 +8821,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8733
8821
  } else {
8734
8822
  filePath = decodedUrlPath(src);
8735
8823
  if (!filePath.startsWith("/")) filePath = join21(baseDir, filePath);
8736
- if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir, downloadDir])) {
8824
+ if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir, downloadDir], assetRoot === void 0)) {
8737
8825
  return { duration: null, resolvedPath: filePath };
8738
8826
  }
8739
8827
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
@@ -8916,7 +9004,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8916
9004
  const { html: compiledSub } = await compileHtmlFile(
8917
9005
  rewriteUnresolvableGsapToCdn(item.rawSubHtml, projectDir, item.srcPath),
8918
9006
  projectDir,
8919
- dirname9(item.filePath),
9007
+ dirname10(item.filePath),
8920
9008
  downloadDir,
8921
9009
  void 0,
8922
9010
  urlByAbsentLocalPath,
@@ -9489,7 +9577,7 @@ var REMOTE_MEDIA_SUBDIR = "_remote_media";
9489
9577
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, assets, extraRewrite) {
9490
9578
  assets?.reserve(urlSet);
9491
9579
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9492
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9580
+ if (!existsSync11(remoteDir)) mkdirSync10(remoteDir, { recursive: true });
9493
9581
  const urlToLocal = /* @__PURE__ */ new Map();
9494
9582
  await Promise.all(
9495
9583
  [...urlSet].map(async (url) => {
@@ -9686,11 +9774,11 @@ function projectStylesheetFontFamilies(html, projectDir) {
9686
9774
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
9687
9775
  const sheet = resolve8(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9688
9776
  if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
9689
- for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
9777
+ for (const face of extractFontFaceBlocks(readFileSync9(sheet, "utf8"))) {
9690
9778
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
9691
9779
  const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
9692
9780
  const path = decodedUrlPath(url);
9693
- const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname9(sheet), path);
9781
+ const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname10(sheet), path);
9694
9782
  return isPathInside(file, projectDir) && existsSync11(file);
9695
9783
  });
9696
9784
  if (family && shipsFile) families.push(family);
@@ -10136,7 +10224,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10136
10224
  for (const video of videos) {
10137
10225
  if (isHttpUrl(video.src)) continue;
10138
10226
  const videoPath = resolve8(projectDir, video.src);
10139
- if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
10227
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir], assetRoot === void 0))
10140
10228
  continue;
10141
10229
  advised.add(videoPath);
10142
10230
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
@@ -10602,7 +10690,7 @@ function resolveCompileWorkerEntry(explicit, log) {
10602
10690
  }
10603
10691
  return void 0;
10604
10692
  }
10605
- const sibling = join22(dirname10(fileURLToPath3(import.meta.url)), "compileWorker.js");
10693
+ const sibling = join22(dirname11(fileURLToPath3(import.meta.url)), "compileWorker.js");
10606
10694
  return existsSync12(sibling) ? sibling : void 0;
10607
10695
  }
10608
10696
  function rebuildError({ name, message, stack, props }) {
@@ -10754,7 +10842,7 @@ function resolveEntryHtmlPath(input) {
10754
10842
  );
10755
10843
  }
10756
10844
  const wrapperPath = join23(workDir, "standalone-entry.html");
10757
- writeFileSync4(wrapperPath, standaloneHtml, "utf-8");
10845
+ writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
10758
10846
  log.info("Extracted standalone entry from index.html host context", { entryFile });
10759
10847
  return wrapperPath;
10760
10848
  }
@@ -10912,7 +11000,7 @@ async function runCompileStage(input) {
10912
11000
  // src/services/render/stages/probeStage.ts
10913
11001
  import { createHash as createHash7 } from "node:crypto";
10914
11002
  import { basename as basename7, join as join24 } from "node:path";
10915
- import { parseHTML as parseHTML6 } from "linkedom";
11003
+ import { parseHTML as parseHTML6 } from "@hyperframes/parsers/linkedom";
10916
11004
  import {
10917
11005
  closeCaptureSession as closeCaptureSession4,
10918
11006
  compositionRequiresWebGpu,
@@ -12419,7 +12507,7 @@ import {
12419
12507
 
12420
12508
  // src/services/render/audioDeliveryLimit.ts
12421
12509
  import { existsSync as existsSync16 } from "node:fs";
12422
- import { dirname as dirname12, join as join27 } from "node:path";
12510
+ import { dirname as dirname13, join as join27 } from "node:path";
12423
12511
  import {
12424
12512
  applyAudioFxChain,
12425
12513
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -12430,7 +12518,7 @@ import {
12430
12518
  // src/services/render/audioPadTrim.ts
12431
12519
  import { localContainerInputArgs } from "@hyperframes/parsers/ff-binaries";
12432
12520
  import { spawn } from "node:child_process";
12433
- import { dirname as dirname11, join as join26 } from "node:path";
12521
+ import { dirname as dirname12, join as join26 } from "node:path";
12434
12522
  import {
12435
12523
  DEFAULT_CONFIG,
12436
12524
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -12725,7 +12813,7 @@ async function cutSource(input, scratchDir, attenuationDb) {
12725
12813
  async function enforceAacTruePeak(input) {
12726
12814
  let scratchDir;
12727
12815
  try {
12728
- scratchDir = createStagingDir3(dirname11(input.audioPath), ".true-peak-");
12816
+ scratchDir = createStagingDir3(dirname12(input.audioPath), ".true-peak-");
12729
12817
  const correctedPath = join26(scratchDir, "audio.m4a");
12730
12818
  const measurements = [];
12731
12819
  let attenuationDb = 0;
@@ -12949,7 +13037,7 @@ async function limitDeliveryPeaks(input, deps = {
12949
13037
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
12950
13038
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
12951
13039
  const alternating = ["a", "b"].map(
12952
- (k) => join27(dirname12(sourcePath), `audio-source-limited-${k}.wav`)
13040
+ (k) => join27(dirname13(sourcePath), `audio-source-limited-${k}.wav`)
12953
13041
  );
12954
13042
  let encodedFrom;
12955
13043
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -13023,10 +13111,15 @@ function runAudioStage(input) {
13023
13111
  async function runAudioStageScoped(input) {
13024
13112
  const stageStart = Date.now();
13025
13113
  const pcmSourcePath = join28(input.workDir, "audio-source.wav");
13026
- const duration = input.totalFrames * input.fps.den / input.fps.num;
13114
+ const seconds = (frames) => frames * input.fps.den / input.fps.num;
13115
+ const duration = seconds(input.totalFrames);
13116
+ const window2 = input.frameWindow && {
13117
+ startSeconds: seconds(input.frameWindow.startFrame),
13118
+ durationSeconds: seconds(input.frameWindow.endFrame - input.frameWindow.startFrame)
13119
+ };
13027
13120
  let deliverySourcePath;
13028
13121
  try {
13029
- const result = await mixAudioForDelivery(input, duration, pcmSourcePath);
13122
+ const result = await mixAudioForDelivery(input, duration, pcmSourcePath, window2);
13030
13123
  let audioLoweredDb;
13031
13124
  if (result.hasAudio) {
13032
13125
  const guardStart = Date.now();
@@ -13034,7 +13127,7 @@ async function runAudioStageScoped(input) {
13034
13127
  input,
13035
13128
  result.audioOutputPath,
13036
13129
  pcmSourcePath,
13037
- duration
13130
+ window2?.durationSeconds ?? duration
13038
13131
  );
13039
13132
  audioLoweredDb = guard.loweredDb;
13040
13133
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
@@ -13072,7 +13165,7 @@ async function guardDeliveryPeaks(input, audioPath, sourcePath, duration) {
13072
13165
  if (!peak.success) throw encoderFailureError("Audio true-peak check failed", peak);
13073
13166
  return { loweredDb: peak.loweredDb, sourceStale: peak.sourceStale };
13074
13167
  }
13075
- async function mixAudioForDelivery(input, duration, pcmSourcePath) {
13168
+ async function mixAudioForDelivery(input, duration, pcmSourcePath, window2) {
13076
13169
  const {
13077
13170
  projectDir,
13078
13171
  workDir,
@@ -13109,6 +13202,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
13109
13202
  urlByAbsentLocalPath,
13110
13203
  audioSidecarUrlByLocalPath,
13111
13204
  keepEncoderInputAt: pcmSourcePath,
13205
+ window: window2,
13112
13206
  assetRoots: input.allowOutsideProjectAssets ? void 0 : mediaAssetRoots(projectDir, compiledDir)
13113
13207
  },
13114
13208
  compiledDir
@@ -13516,7 +13610,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
13516
13610
  assertNotAborted();
13517
13611
  const absoluteIdx = rangeStart + i;
13518
13612
  const time = absoluteIdx * job.config.fps.den / job.config.fps.num;
13519
- const { encodeResult } = await captureFrameToBufferPipelined2(session, i, time);
13613
+ const { encodeResult } = await captureFrameToBufferPipelined2(session, absoluteIdx, time);
13520
13614
  await drainPrev();
13521
13615
  prev = { fileIndex: i, encodeResult };
13522
13616
  }
@@ -13526,7 +13620,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
13526
13620
  assertNotAborted();
13527
13621
  const absoluteIdx = rangeStart + i;
13528
13622
  const time = absoluteIdx * job.config.fps.den / job.config.fps.num;
13529
- await captureFrame(session, i, time);
13623
+ await captureFrame(session, absoluteIdx, time, i);
13530
13624
  reportFrame(i);
13531
13625
  }
13532
13626
  }
@@ -13545,7 +13639,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
13545
13639
  }
13546
13640
 
13547
13641
  // src/services/render/stages/captureHdrStage.ts
13548
- import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
13642
+ import { existsSync as existsSync20, mkdirSync as mkdirSync11 } from "node:fs";
13549
13643
  import { join as join33 } from "node:path";
13550
13644
  import {
13551
13645
  closeCaptureSession as closeCaptureSession7,
@@ -13657,9 +13751,18 @@ async function runSequentialLayeredFrameLoop(input) {
13657
13751
  output: Buffer.alloc(bufSize)
13658
13752
  } : null;
13659
13753
  const normalCanvas = Buffer.alloc(bufSize);
13754
+ const firstFrame = windowStartFrame(job.frameWindow);
13755
+ cleanupHdrVideosEndedBefore(firstFrame, job.config.fps, transitionRanges, {
13756
+ hdrVideoEndTimes,
13757
+ cleanedUpVideos,
13758
+ hdrVideoFrameSources,
13759
+ sceneElements,
13760
+ log
13761
+ });
13660
13762
  for (let i = 0; i < totalFrames; i++) {
13661
13763
  assertNotAborted();
13662
- const time = i * job.config.fps.den / job.config.fps.num;
13764
+ const frame = firstFrame + i;
13765
+ const time = frame * job.config.fps.den / job.config.fps.num;
13663
13766
  if (hdrPerf) hdrPerf.frames += 1;
13664
13767
  const stackingInfo = await seekInjectAndQueryStacking(
13665
13768
  domSession.page,
@@ -13671,11 +13774,11 @@ async function runSequentialLayeredFrameLoop(input) {
13671
13774
  "frameInjectMs",
13672
13775
  "stackingQueryMs"
13673
13776
  );
13674
- const activeTransition = transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame);
13777
+ const activeTransition = transitionAtFrame(transitionRanges, frame);
13675
13778
  if (i % 30 === 0 && (log.isLevelEnabled?.("debug") ?? true)) {
13676
13779
  const hdrEl = stackingInfo.find((e) => e.isHdr);
13677
13780
  log.debug("[Render] HDR layer composite frame", {
13678
- frame: i,
13781
+ frame,
13679
13782
  time: time.toFixed(2),
13680
13783
  hdrElement: hdrEl ? { z: hdrEl.zIndex, visible: hdrEl.visible, width: hdrEl.width } : null,
13681
13784
  stackingCount: stackingInfo.length,
@@ -13685,7 +13788,7 @@ async function runSequentialLayeredFrameLoop(input) {
13685
13788
  if (activeTransition && transitionBuffers) {
13686
13789
  if (hdrPerf) hdrPerf.transitionFrames += 1;
13687
13790
  const transitionTimingStart = Date.now();
13688
- const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (i - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
13791
+ const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (frame - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
13689
13792
  const sceneAIds = new Set(sceneElements[activeTransition.fromScene] ?? []);
13690
13793
  const sceneBIds = new Set(sceneElements[activeTransition.toScene] ?? []);
13691
13794
  timeHdrPhase(hdrPerf, "canvasClearMs", () => {
@@ -13714,7 +13817,7 @@ async function runSequentialLayeredFrameLoop(input) {
13714
13817
  hdrTargetTransfer,
13715
13818
  hdrPerf,
13716
13819
  log,
13717
- frameIdx: i
13820
+ frameIdx: frame
13718
13821
  });
13719
13822
  }
13720
13823
  const shaderName = activeTransition.shader;
@@ -13739,7 +13842,7 @@ async function runSequentialLayeredFrameLoop(input) {
13739
13842
  await timeHdrPhaseAsync(
13740
13843
  hdrPerf,
13741
13844
  "normalCompositeMs",
13742
- () => compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, void 0, i)
13845
+ () => compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, void 0, frame)
13743
13846
  );
13744
13847
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
13745
13848
  writeFileExclusiveSync(
@@ -13789,7 +13892,7 @@ import {
13789
13892
  // src/services/shaderTransitionWorkerPool.ts
13790
13893
  import { Worker as Worker2 } from "node:worker_threads";
13791
13894
  import { fileURLToPath as fileURLToPath4, pathToFileURL } from "node:url";
13792
- import { dirname as dirname13, join as join31 } from "node:path";
13895
+ import { dirname as dirname14, join as join31 } from "node:path";
13793
13896
  import { createRequire } from "node:module";
13794
13897
  import { usableCpuCount } from "@hyperframes/engine";
13795
13898
  import { existsSync as existsSync19 } from "node:fs";
@@ -13802,7 +13905,7 @@ function resolveWorkerEntry(explicit) {
13802
13905
  const isTs = override.endsWith(".ts");
13803
13906
  return { path: override, isTs };
13804
13907
  }
13805
- const moduleDir = dirname13(fileURLToPath4(import.meta.url));
13908
+ const moduleDir = dirname14(fileURLToPath4(import.meta.url));
13806
13909
  const jsPath = join31(moduleDir, "shaderTransitionWorker.js");
13807
13910
  if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
13808
13911
  const tsPath = join31(moduleDir, "shaderTransitionWorker.ts");
@@ -14010,7 +14113,8 @@ async function runHybridLayeredFrameLoop(input) {
14010
14113
  assertNotAborted,
14011
14114
  onProgress
14012
14115
  } = input;
14013
- const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames);
14116
+ const firstFrame = windowStartFrame(job.frameWindow);
14117
+ const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames, firstFrame);
14014
14118
  const hasTransitions = transitionRanges.length > 0;
14015
14119
  const bufSize = width * height * 6;
14016
14120
  const workerSessions = [];
@@ -14101,8 +14205,9 @@ async function runHybridLayeredFrameLoop(input) {
14101
14205
  for (let i = range.start; i < range.end; i++) {
14102
14206
  throwIfFailed();
14103
14207
  assertNotAborted();
14104
- const time = i * job.config.fps.den / job.config.fps.num;
14105
- const activeTransition = transitionFramesSet.has(i) ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) : void 0;
14208
+ const frame = firstFrame + i;
14209
+ const time = frame * job.config.fps.den / job.config.fps.num;
14210
+ const activeTransition = transitionFramesSet.has(frame) ? transitionAtFrame(transitionRanges, frame) : void 0;
14106
14211
  if (activeTransition && ring) {
14107
14212
  const slot = nextRingIdx;
14108
14213
  nextRingIdx = (nextRingIdx + 1) % TRANSITION_RING_DEPTH;
@@ -14113,7 +14218,7 @@ async function runHybridLayeredFrameLoop(input) {
14113
14218
  if (!buffers) continue;
14114
14219
  await captureTransitionFrameOnWorker({
14115
14220
  session,
14116
- frameIdx: i,
14221
+ frameIdx: frame,
14117
14222
  time,
14118
14223
  transition: activeTransition,
14119
14224
  buffers,
@@ -14128,7 +14233,7 @@ async function runHybridLayeredFrameLoop(input) {
14128
14233
  hdrPerf,
14129
14234
  log
14130
14235
  });
14131
- const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (i - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
14236
+ const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 : (frame - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame);
14132
14237
  const frameIdx = i;
14133
14238
  const shaderName = activeTransition.shader;
14134
14239
  const dispatch = (async () => {
@@ -14179,7 +14284,7 @@ async function runHybridLayeredFrameLoop(input) {
14179
14284
  await timeHdrPhaseAsync(
14180
14285
  hdrPerf,
14181
14286
  "normalCompositeMs",
14182
- () => compositeHdrFrame(wctx, canvas, time, stackingInfo, void 0, i)
14287
+ () => compositeHdrFrame(wctx, canvas, time, stackingInfo, void 0, frame)
14183
14288
  );
14184
14289
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
14185
14290
  writeFileExclusiveSync(
@@ -14389,7 +14494,7 @@ async function runCaptureHdrStage(input) {
14389
14494
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
14390
14495
  const debugDumpDir = debugDumpEnabled ? join33(framesDir, "debug-composite") : null;
14391
14496
  if (debugDumpDir && !existsSync20(debugDumpDir)) {
14392
- mkdirSync10(debugDumpDir, { recursive: true });
14497
+ mkdirSync11(debugDumpDir, { recursive: true });
14393
14498
  }
14394
14499
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
14395
14500
  const hdrTargetTransfer = compositeTransfer === "srgb" ? void 0 : compositeTransfer;
@@ -14417,7 +14522,11 @@ async function runCaptureHdrStage(input) {
14417
14522
  hdrPerf
14418
14523
  };
14419
14524
  const effectiveWorkerCount = Math.max(1, workerCount);
14420
- const transitionFrameCount = partitionTransitionFrames(transitionRanges, totalFrames).size;
14525
+ const transitionFrameCount = partitionTransitionFrames(
14526
+ transitionRanges,
14527
+ totalFrames,
14528
+ windowStartFrame(job.frameWindow)
14529
+ ).size;
14421
14530
  const useHybrid = shouldUseHybridLayeredPath({
14422
14531
  hasHdrContent,
14423
14532
  transitionFramesCount: transitionFrameCount,
@@ -14548,15 +14657,15 @@ async function runCaptureHdrStage(input) {
14548
14657
  import {
14549
14658
  copyFileSync as copyFileSync4,
14550
14659
  existsSync as existsSync21,
14551
- mkdirSync as mkdirSync11,
14660
+ mkdirSync as mkdirSync12,
14552
14661
  readdirSync as readdirSync5,
14553
- readFileSync as readFileSync9,
14662
+ readFileSync as readFileSync10,
14554
14663
  rmSync as rmSync12,
14555
14664
  statSync as statSync9,
14556
- writeFileSync as writeFileSync5
14665
+ writeFileSync as writeFileSync6
14557
14666
  } from "node:fs";
14558
14667
  import { readFile as readFile2 } from "node:fs/promises";
14559
- import { dirname as dirname14, join as join34 } from "node:path";
14668
+ import { dirname as dirname15, join as join34 } from "node:path";
14560
14669
  import {
14561
14670
  encodeFramesChunkedConcat,
14562
14671
  encodeFramesFromDir,
@@ -14644,12 +14753,12 @@ async function reencodeWithClearedWholeFrames(argsInput, run, startTime) {
14644
14753
  const error = formatFfmpegError(result.exitCode, result.stderr);
14645
14754
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
14646
14755
  }
14647
- const gif = readFileSync9(outputPath);
14756
+ const gif = readFileSync10(outputPath);
14648
14757
  if (!clearGifFramesBeforeNext(gif)) {
14649
14758
  const error = "[FFmpeg] GIF output could not be parsed to clear its frames";
14650
14759
  return gifEncodeFailure(startTime, outputPath, error);
14651
14760
  }
14652
- writeFileSync5(outputPath, gif);
14761
+ writeFileSync6(outputPath, gif);
14653
14762
  return null;
14654
14763
  }
14655
14764
  async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
@@ -14677,7 +14786,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14677
14786
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
14678
14787
  }
14679
14788
  }
14680
- if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync9(outputPath)) !== false) {
14789
+ if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync10(outputPath)) !== false) {
14681
14790
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
14682
14791
  if (failure) return failure;
14683
14792
  }
@@ -14850,7 +14959,7 @@ async function runEncodeStage(input) {
14850
14959
  const stage5Start = Date.now();
14851
14960
  if (isPngSequence) {
14852
14961
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
14853
- if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
14962
+ if (!existsSync21(outputPath)) mkdirSync12(outputPath, { recursive: true });
14854
14963
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
14855
14964
  if (captured.length === 0) {
14856
14965
  throw new Error(
@@ -14882,7 +14991,7 @@ async function runEncodeStage(input) {
14882
14991
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
14883
14992
  fps: job.config.fps,
14884
14993
  loop,
14885
- palettePath: join34(dirname14(videoOnlyPath), "gif-palette.png"),
14994
+ palettePath: join34(dirname15(videoOnlyPath), "gif-palette.png"),
14886
14995
  preserveAlpha: needsAlpha,
14887
14996
  signal: abortSignal,
14888
14997
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -15336,7 +15445,7 @@ function getNextRetryWorkerCount(currentWorkers) {
15336
15445
  }
15337
15446
  function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir3()) {
15338
15447
  if (platform2 === "win32" || platform2 === "darwin") return join35(systemTempDir, "hf-render-");
15339
- return join35(dirname15(outputPath), `work-${jobId}-`);
15448
+ return join35(dirname16(outputPath), `work-${jobId}-`);
15340
15449
  }
15341
15450
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
15342
15451
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -16064,7 +16173,7 @@ function deVerifyFallbackTelemetry(err) {
16064
16173
  };
16065
16174
  }
16066
16175
  function resolveRenderDebugDir() {
16067
- const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve9(process.env.PRODUCER_RENDERS_DIR, "..") : resolve9(dirname15(fileURLToPath5(import.meta.url)), "../..");
16176
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve9(process.env.PRODUCER_RENDERS_DIR, "..") : resolve9(dirname16(fileURLToPath5(import.meta.url)), "../..");
16068
16177
  return join35(producerRoot, ".debug");
16069
16178
  }
16070
16179
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
@@ -16072,8 +16181,8 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
16072
16181
  validateDeliveryEncoderConfig(job.config);
16073
16182
  validateChromaSubsamplingConfig(job.config);
16074
16183
  const debugDir = resolveRenderDebugDir();
16075
- const outputDir = dirname15(outputPath);
16076
- if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
16184
+ const outputDir = dirname16(outputPath);
16185
+ if (!existsSync22(outputDir)) mkdirSync13(outputDir, { recursive: true });
16077
16186
  const workDir = job.config.debug ? join35(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
16078
16187
  const pipelineStart = Date.now();
16079
16188
  const baseLog = job.config.logger ?? defaultLogger;
@@ -16230,7 +16339,7 @@ async function executeRenderPipeline(input) {
16230
16339
  job.startedAt = /* @__PURE__ */ new Date();
16231
16340
  assertNotAborted();
16232
16341
  assertConfiguredFfmpegBinariesExist();
16233
- if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
16342
+ if (!existsSync22(workDir)) mkdirSync13(workDir, { recursive: true });
16234
16343
  if (job.config.debug) {
16235
16344
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
16236
16345
  }
@@ -16399,15 +16508,18 @@ async function executeRenderPipeline(input) {
16399
16508
  if (resolvedCaptureBeyondViewport !== void 0) {
16400
16509
  updateCaptureObservability({ captureBeyondViewport: resolvedCaptureBeyondViewport });
16401
16510
  }
16402
- job.duration = probeResult.duration;
16403
- job.totalFrames = probeResult.totalFrames;
16404
- const totalFrames = probeResult.totalFrames;
16405
- captureTotalFrames = totalFrames;
16406
16511
  validateRenderDuration({
16407
16512
  duration: probeResult.duration,
16408
- totalFrames,
16513
+ totalFrames: probeResult.totalFrames,
16409
16514
  fps: fpsToNumber8(job.config.fps)
16410
16515
  });
16516
+ const frameWindow = job.config.range ? resolveFrameWindow(job.config.range, job.config.fps, probeResult.totalFrames) : void 0;
16517
+ job.frameWindow = frameWindow;
16518
+ if (frameWindow) cfg.enableStreamingEncode = false;
16519
+ const totalFrames = frameWindow ? frameWindow.endFrame - frameWindow.startFrame : probeResult.totalFrames;
16520
+ job.totalFrames = totalFrames;
16521
+ job.duration = frameWindow ? totalFrames * job.config.fps.den / job.config.fps.num : probeResult.duration;
16522
+ captureTotalFrames = totalFrames;
16411
16523
  const shownBoxes = largerThanCanvas.length > 0 && probeSession?.isInitialized ? await measureLocalShownBoxes(
16412
16524
  probeSession.page,
16413
16525
  largerThanCanvas,
@@ -16588,6 +16700,7 @@ async function executeRenderPipeline(input) {
16588
16700
  workDir,
16589
16701
  compiledDir,
16590
16702
  totalFrames: probeResult.totalFrames,
16703
+ ...frameWindow && { frameWindow },
16591
16704
  fps: job.config.fps,
16592
16705
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
16593
16706
  audioGain: cfg.audioGain,
@@ -16634,14 +16747,31 @@ async function executeRenderPipeline(input) {
16634
16747
  throw new Error("File server failed to initialize before frame capture");
16635
16748
  }
16636
16749
  const framesDir = join35(workDir, "captured-frames");
16637
- if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
16750
+ if (!existsSync22(framesDir)) mkdirSync13(framesDir, { recursive: true });
16638
16751
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
16639
16752
  code: "start_browsers"
16640
16753
  });
16641
- const resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
16754
+ let resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
16642
16755
  chromePath: resolveHeadlessShellPath(cfg),
16643
16756
  browserTimeout: cfg.browserTimeout
16644
16757
  });
16758
+ const closeProbeSession = async () => {
16759
+ if (!probeSession) return;
16760
+ lastBrowserConsole = probeSession.browserConsoleBuffer;
16761
+ await closeCaptureSession8(probeSession).catch(() => {
16762
+ });
16763
+ probeSession = null;
16764
+ };
16765
+ const gpuStore = cfg.browserGpuMode === "auto" && resolvedBrowserGpuMode === "hardware" ? gpuChoiceStore(cfg, await probedHardwareGpu()) : void 0;
16766
+ const storedGpuChoice = gpuStore && readGpuChoice(gpuStore);
16767
+ if (gpuStore && storedGpuChoice === "software") {
16768
+ log.info("[Render] Auto GPU mode: rendering in software, as measured on this machine.", {
16769
+ file: gpuStore.file
16770
+ });
16771
+ cfg.browserGpuMode = "software";
16772
+ resolvedBrowserGpuMode = "software";
16773
+ await closeProbeSession();
16774
+ }
16645
16775
  startingFrameCapture();
16646
16776
  captureForceScreenshot = applyConcreteGpuScreenshotClamp(
16647
16777
  captureForceScreenshot,
@@ -16878,6 +17008,10 @@ async function executeRenderPipeline(input) {
16878
17008
  totalMemoryMb: Math.round(totalmem2() / (1024 * 1024)),
16879
17009
  minMemoryMb: deParallelMinMemoryMb
16880
17010
  });
17011
+ if (frameWindow) {
17012
+ deInversionEligible = false;
17013
+ deParallelRouterEligible = false;
17014
+ }
16881
17015
  if (probeSession === null && (deInversionEligible || deParallelRouterEligible)) {
16882
17016
  try {
16883
17017
  probeSession = await createCaptureSession8(
@@ -16942,7 +17076,9 @@ async function executeRenderPipeline(input) {
16942
17076
  return "beginFrame";
16943
17077
  }
16944
17078
  });
16945
- if (job.config.workers === void 0 && totalFrames >= 60 && !htmlInCanvasDetected && !cfg.lowMemoryMode && !deInversionEligible && !deParallelRouterEligible) {
17079
+ const sizeByCalibration = job.config.workers === void 0 && totalFrames >= 60 && !htmlInCanvasDetected && !cfg.lowMemoryMode && !deInversionEligible && !deParallelRouterEligible;
17080
+ const measureGpuChoice = gpuStore !== void 0 && storedGpuChoice === void 0;
17081
+ if (sizeByCalibration || measureGpuChoice) {
16946
17082
  updateJobStatus(job, "rendering", "Measuring capture speed", 25, onProgress, {
16947
17083
  code: "start_browsers"
16948
17084
  });
@@ -16951,6 +17087,16 @@ async function executeRenderPipeline(input) {
16951
17087
  "calibration"
16952
17088
  ) : void 0;
16953
17089
  let outcome;
17090
+ let softwareOutcome;
17091
+ const calibrationInput = {
17092
+ fileServer: activeFileServer,
17093
+ log,
17094
+ job,
17095
+ totalFrames,
17096
+ buildCaptureOptions: buildPrepCaptureOptions,
17097
+ createRenderVideoFrameInjector: calibrationFrames ? calibrationFrames.injector : createRenderVideoFrameInjector,
17098
+ assertNotAborted
17099
+ };
16954
17100
  try {
16955
17101
  outcome = await observeRenderStage(
16956
17102
  observability,
@@ -16963,38 +17109,91 @@ async function executeRenderPipeline(input) {
16963
17109
  // ts=1784019503.
16964
17110
  stagePhase: "calibrating"
16965
17111
  }),
16966
- () => runCaptureCalibration({
16967
- cfg: calibrationCaptureConfig(cfg),
16968
- fileServer: activeFileServer,
16969
- workDir,
16970
- log,
16971
- job,
16972
- totalFrames,
16973
- forceScreenshot: captureForceScreenshot,
16974
- probeSession,
16975
- buildCaptureOptions: buildPrepCaptureOptions,
16976
- createRenderVideoFrameInjector: calibrationFrames ? calibrationFrames.injector : createRenderVideoFrameInjector,
16977
- assertNotAborted
16978
- }),
17112
+ async () => {
17113
+ const result = await runCaptureCalibration({
17114
+ ...calibrationInput,
17115
+ cfg: calibrationCaptureConfig(cfg),
17116
+ workDir,
17117
+ forceScreenshot: captureForceScreenshot,
17118
+ probeSession
17119
+ });
17120
+ probeSession = result.probeSession;
17121
+ if (storedGpuChoice === void 0 && shouldCalibrateSoftwareGpu(
17122
+ cfg.browserGpuMode,
17123
+ resolvedBrowserGpuMode,
17124
+ result.calibration?.estimate
17125
+ )) {
17126
+ softwareOutcome = await runCaptureCalibration({
17127
+ ...calibrationInput,
17128
+ cfg: calibrationCaptureConfig({ ...cfg, browserGpuMode: "software" }),
17129
+ workDir: join35(workDir, "software-gpu"),
17130
+ forceScreenshot: applyConcreteGpuScreenshotClamp(
17131
+ captureForceScreenshot,
17132
+ "software",
17133
+ cfg
17134
+ ),
17135
+ probeSession: null
17136
+ });
17137
+ }
17138
+ return result;
17139
+ },
16979
17140
  { heartbeatMessage: "browser calibrating (frames not started)" }
16980
17141
  );
16981
17142
  } finally {
16982
17143
  calibrationFrames?.release();
16983
17144
  }
16984
17145
  startingFrameCapture();
16985
- captureCalibration = outcome.calibration;
17146
+ if (sizeByCalibration) captureCalibration = outcome.calibration;
16986
17147
  calibrationEvaluateTimedOut = outcome.calibrationEvaluateTimedOut;
16987
17148
  captureForceScreenshot = outcome.forceScreenshot;
16988
17149
  updateCaptureObservability({ forceScreenshot: captureForceScreenshot });
16989
- probeSession = outcome.probeSession;
16990
17150
  if (outcome.lastBrowserConsole.length > 0) {
16991
17151
  lastBrowserConsole = outcome.lastBrowserConsole;
16992
17152
  }
17153
+ if (softwareOutcome && outcome.calibration && pickAutoGpuModeFromCalibration(
17154
+ outcome.calibration.estimate,
17155
+ softwareOutcome.calibration?.estimate
17156
+ ) === "software") {
17157
+ log.warn(
17158
+ "[Render] Auto GPU mode: software capture measured faster than the hardware GPU, rendering in software.",
17159
+ {
17160
+ hardwareP95Ms: outcome.calibration.estimate.p95Ms,
17161
+ softwareP95Ms: softwareOutcome.calibration?.estimate.p95Ms
17162
+ }
17163
+ );
17164
+ cfg.browserGpuMode = "software";
17165
+ resolvedBrowserGpuMode = "software";
17166
+ if (sizeByCalibration) captureCalibration = softwareOutcome.calibration;
17167
+ captureForceScreenshot = softwareOutcome.forceScreenshot;
17168
+ await closeProbeSession();
17169
+ updateCaptureObservability({
17170
+ browserGpuMode: resolvedBrowserGpuMode,
17171
+ forceScreenshot: captureForceScreenshot
17172
+ });
17173
+ }
17174
+ const settledGpuChoice = measureGpuChoice ? settleAutoGpuChoice(outcome.calibration?.estimate, softwareOutcome?.calibration?.estimate) : void 0;
17175
+ if (gpuStore && settledGpuChoice) {
17176
+ try {
17177
+ writeGpuChoice(gpuStore, settledGpuChoice, {
17178
+ hardwareP95Ms: outcome.calibration?.estimate.p95Ms,
17179
+ softwareP95Ms: softwareOutcome?.calibration?.estimate.p95Ms
17180
+ });
17181
+ } catch (error) {
17182
+ log.warn(
17183
+ "[Render] Could not save the measured GPU choice; the next render measures again.",
17184
+ {
17185
+ file: gpuStore.file,
17186
+ error: error instanceof Error ? error.message : String(error)
17187
+ }
17188
+ );
17189
+ }
17190
+ }
16993
17191
  observability.checkpoint("capture_calibration", "resolved", {
16994
17192
  forceScreenshot: captureForceScreenshot,
16995
- multiplier: outcome.calibration?.estimate.multiplier ?? null,
16996
- p95Ms: outcome.calibration?.estimate.p95Ms ?? null,
16997
- medianMs: outcome.calibration?.estimate.medianMs ?? null
17193
+ browserGpuMode: resolvedBrowserGpuMode,
17194
+ multiplier: captureCalibration?.estimate.multiplier ?? null,
17195
+ p95Ms: captureCalibration?.estimate.p95Ms ?? null,
17196
+ medianMs: captureCalibration?.estimate.medianMs ?? null
16998
17197
  });
16999
17198
  } else {
17000
17199
  observability.checkpoint("capture_calibration", "skipped", {
@@ -17344,6 +17543,7 @@ async function executeRenderPipeline(input) {
17344
17543
  });
17345
17544
  const syncCapturePlan = () => {
17346
17545
  assertMotionBlurSupported(job.config.motionBlur, capturePlan.kind);
17546
+ assertRangeSupported(job.frameWindow, capturePlan.kind);
17347
17547
  assertOutputScaleSupported(deviceScaleFactor, capturePlan.kind);
17348
17548
  workerCount = capturePlan.workerCount;
17349
17549
  captureForceScreenshot = capturePlan.forceScreenshot;
@@ -17929,6 +18129,7 @@ async function executeRenderPipeline(input) {
17929
18129
  framesDir,
17930
18130
  job,
17931
18131
  totalFrames,
18132
+ ...job.frameWindow && { frameRange: job.frameWindow },
17932
18133
  cfg,
17933
18134
  plan: diskPlan,
17934
18135
  log,
@@ -17969,7 +18170,7 @@ async function executeRenderPipeline(input) {
17969
18170
  "drawElement capture failed; retrying with a fresh screenshot session"
17970
18171
  );
17971
18172
  rmSync13(framesDir, { recursive: true, force: true });
17972
- mkdirSync12(framesDir, { recursive: true });
18173
+ mkdirSync13(framesDir, { recursive: true });
17973
18174
  resetCaptureAttemptProgress(job);
17974
18175
  dedupPerfs.length = 0;
17975
18176
  cfg.useDrawElement = false;
@@ -18148,7 +18349,7 @@ async function executeRenderPipeline(input) {
18148
18349
  job.perfSummary = perfSummary;
18149
18350
  if (job.config.debug) {
18150
18351
  try {
18151
- writeFileSync6(perfOutputPath, JSON.stringify(perfSummary, null, 2), "utf-8");
18352
+ writeFileSync7(perfOutputPath, JSON.stringify(perfSummary, null, 2), "utf-8");
18152
18353
  } catch (err) {
18153
18354
  log.debug("Failed to write perf summary", {
18154
18355
  perfOutputPath,
@@ -18277,15 +18478,15 @@ import {
18277
18478
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD4,
18278
18479
  referenceBackgroundResult as referenceBackgroundResult6
18279
18480
  } from "@hyperframes/engine";
18280
- import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync19 } from "node:fs";
18481
+ import { mkdirSync as mkdirSync21, mkdtempSync, readFileSync as readFileSync16, rmSync as rmSync19 } from "node:fs";
18281
18482
  import { join as join49 } from "node:path";
18282
18483
  import { tmpdir as tmpdir5 } from "node:os";
18283
18484
 
18284
18485
  // src/services/distributed/mp4Stitch.ts
18285
- import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync14 } from "node:fs";
18486
+ import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync14, rmSync as rmSync14 } from "node:fs";
18286
18487
  import { open } from "node:fs/promises";
18287
18488
  import { renameWithRetry as renameWithRetry6 } from "@hyperframes/engine";
18288
- import { basename as basename8, dirname as dirname16, join as join36 } from "node:path";
18489
+ import { basename as basename8, dirname as dirname17, join as join36 } from "node:path";
18289
18490
  import { finished, pipeline } from "node:stream/promises";
18290
18491
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
18291
18492
  function boxAt(src, off, at, limit) {
@@ -18650,8 +18851,8 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
18650
18851
  const sourcePaths = audioPath ? [audioPath, ...chunkPaths] : chunkPaths;
18651
18852
  const layouts = await Promise.all(sourcePaths.map((path) => readMp4Layout(fileRange(path))));
18652
18853
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
18653
- mkdirSync13(dirname16(outputPath), { recursive: true });
18654
- const workDir = createStagingDir4(dirname16(outputPath), `${basename8(outputPath)}.stitch-`);
18854
+ mkdirSync14(dirname17(outputPath), { recursive: true });
18855
+ const workDir = createStagingDir4(dirname17(outputPath), `${basename8(outputPath)}.stitch-`);
18655
18856
  const out = createWriteStream(join36(workDir, "out.mp4"));
18656
18857
  try {
18657
18858
  out.write(header);
@@ -18677,9 +18878,9 @@ import {
18677
18878
  cpSync as cpSync2,
18678
18879
  existsSync as existsSync27,
18679
18880
  linkSync,
18680
- mkdirSync as mkdirSync16,
18881
+ mkdirSync as mkdirSync17,
18681
18882
  rmSync as rmSync15,
18682
- writeFileSync as writeFileSync9
18883
+ writeFileSync as writeFileSync10
18683
18884
  } from "node:fs";
18684
18885
  import { extname as extname6, isAbsolute as isAbsolute5, join as join44, relative as relative8, sep as sep5 } from "node:path";
18685
18886
  import {
@@ -18717,8 +18918,8 @@ import {
18717
18918
 
18718
18919
  // src/services/distributed/shared.ts
18719
18920
  import { execFile as execFileCallback } from "node:child_process";
18720
- import { dirname as dirname17, join as join37 } from "node:path";
18721
- import { existsSync as existsSync23, readFileSync as readFileSync10 } from "node:fs";
18921
+ import { dirname as dirname18, join as join37 } from "node:path";
18922
+ import { existsSync as existsSync23, readFileSync as readFileSync11 } from "node:fs";
18722
18923
  import { fileURLToPath as fileURLToPath6 } from "node:url";
18723
18924
  import { promisify as promisify2 } from "node:util";
18724
18925
  import {
@@ -18995,13 +19196,13 @@ function buildSyntheticRenderJob(input) {
18995
19196
  var cachedProducerVersion = null;
18996
19197
  function readProducerVersion() {
18997
19198
  if (cachedProducerVersion !== null) return cachedProducerVersion;
18998
- const startDir = dirname17(fileURLToPath6(import.meta.url));
19199
+ const startDir = dirname18(fileURLToPath6(import.meta.url));
18999
19200
  let current = startDir;
19000
19201
  for (let i = 0; i < 10; i++) {
19001
19202
  const candidate = join37(current, "package.json");
19002
19203
  if (existsSync23(candidate)) {
19003
19204
  try {
19004
- const pkg = JSON.parse(readFileSync10(candidate, "utf-8"));
19205
+ const pkg = JSON.parse(readFileSync11(candidate, "utf-8"));
19005
19206
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
19006
19207
  cachedProducerVersion = pkg.version;
19007
19208
  return pkg.version;
@@ -19009,7 +19210,7 @@ function readProducerVersion() {
19009
19210
  } catch {
19010
19211
  }
19011
19212
  }
19012
- const parent = dirname17(current);
19213
+ const parent = dirname18(current);
19013
19214
  if (parent === current) break;
19014
19215
  current = parent;
19015
19216
  }
@@ -19354,7 +19555,7 @@ async function readPlanReferenceBackground(input) {
19354
19555
  }
19355
19556
 
19356
19557
  // src/services/render/stages/freezePlan.ts
19357
- import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
19558
+ import { existsSync as existsSync25, mkdirSync as mkdirSync15, readFileSync as readFileSync12, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
19358
19559
  import { join as join41, relative as relative6, resolve as resolve10 } from "node:path";
19359
19560
  import {
19360
19561
  REFERENCE_BACKGROUND_FIELD,
@@ -19594,7 +19795,7 @@ function collectPlanAssetShas(planDir, digests) {
19594
19795
  const assets = [];
19595
19796
  for (const file of files) {
19596
19797
  if (file.planRelativePath === COMPILED_INDEX_RELATIVE_PATH) {
19597
- compositionHtml = readFileSync11(file.absolutePath);
19798
+ compositionHtml = readFileSync12(file.absolutePath);
19598
19799
  continue;
19599
19800
  }
19600
19801
  if (HASH_EXCLUDED_PLAN_FILES.has(file.planRelativePath)) continue;
@@ -19614,11 +19815,11 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
19614
19815
  function writePlanRemoteFiles(planDir, files) {
19615
19816
  if (files.length === 0) return;
19616
19817
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
19617
- writeFileSync7(join41(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
19818
+ writeFileSync8(join41(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
19618
19819
  }
19619
19820
  function readPlanRemoteFiles(planDir) {
19620
19821
  const path = join41(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
19621
- return existsSync25(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
19822
+ return existsSync25(path) ? JSON.parse(readFileSync12(path, "utf-8")) : [];
19622
19823
  }
19623
19824
  function recomputePlanHashFromPlanDir(planDir, digests) {
19624
19825
  const planJsonPath = join41(planDir, "plan.json");
@@ -19629,8 +19830,8 @@ function recomputePlanHashFromPlanDir(planDir, digests) {
19629
19830
  if (!existsSync25(encoderJsonPath)) {
19630
19831
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
19631
19832
  }
19632
- const planJson = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
19633
- const encoderConfigCanonicalJson = readFileSync11(encoderJsonPath, "utf-8");
19833
+ const planJson = JSON.parse(readFileSync12(planJsonPath, "utf-8"));
19834
+ const encoderConfigCanonicalJson = readFileSync12(encoderJsonPath, "utf-8");
19634
19835
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
19635
19836
  return computePlanHash({
19636
19837
  compositionHtml,
@@ -19660,8 +19861,8 @@ async function freezePlan(input) {
19660
19861
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
19661
19862
  }
19662
19863
  const metaDir = join41(planDir, "meta");
19663
- if (!existsSync25(metaDir)) mkdirSync14(metaDir, { recursive: true });
19664
- writeFileSync7(
19864
+ if (!existsSync25(metaDir)) mkdirSync15(metaDir, { recursive: true });
19865
+ writeFileSync8(
19665
19866
  join41(metaDir, "composition.json"),
19666
19867
  `${JSON.stringify(composition, null, 2)}
19667
19868
  `,
@@ -19669,8 +19870,8 @@ async function freezePlan(input) {
19669
19870
  );
19670
19871
  const encoderForCanonical = stripUndefined(encoder);
19671
19872
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
19672
- writeFileSync7(join41(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
19673
- writeFileSync7(join41(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
19873
+ writeFileSync8(join41(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
19874
+ writeFileSync8(join41(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
19674
19875
  `, "utf-8");
19675
19876
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
19676
19877
  const planHash = computePlanHash({
@@ -19696,7 +19897,7 @@ async function freezePlan(input) {
19696
19897
  hasAudio
19697
19898
  };
19698
19899
  const planJsonPath = join41(planDir, "plan.json");
19699
- writeFileSync7(planJsonPath, `${JSON.stringify(planJson, null, 2)}
19900
+ writeFileSync8(planJsonPath, `${JSON.stringify(planJson, null, 2)}
19700
19901
  `, "utf-8");
19701
19902
  return { planJsonPath, planHash };
19702
19903
  }
@@ -19737,8 +19938,8 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
19737
19938
  }
19738
19939
 
19739
19940
  // src/services/distributed/chunkAudio.ts
19740
- import { closeSync as closeSync7, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync7, readFileSync as readFileSync12 } from "node:fs";
19741
- import { writeFileSync as writeFileSync8, writeSync } from "node:fs";
19941
+ import { closeSync as closeSync7, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync16, openSync as openSync7, readFileSync as readFileSync13 } from "node:fs";
19942
+ import { writeFileSync as writeFileSync9, writeSync } from "node:fs";
19742
19943
  import { join as join42 } from "node:path";
19743
19944
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
19744
19945
  function audioCutForChunk(grid, chunks, index, fps) {
@@ -19825,9 +20026,9 @@ async function writeChunkAudioSlices(input) {
19825
20026
  offset += track.sizes[offsets.length - 1];
19826
20027
  }
19827
20028
  });
19828
- const bytes = readFileSync12(input.audioPath);
20029
+ const bytes = readFileSync13(input.audioPath);
19829
20030
  const layout = { sizeBytes: bytes.length, payloadStart, payloadEnd, partStarts: {} };
19830
- mkdirSync15(join42(input.planDir, SLICE_DIR), { recursive: true });
20031
+ mkdirSync16(join42(input.planDir, SLICE_DIR), { recursive: true });
19831
20032
  input.chunks.forEach((_, index) => {
19832
20033
  const cut = audioCutForChunk(grid, input.chunks, index, input.fps);
19833
20034
  if (!cut) return;
@@ -19835,17 +20036,17 @@ async function writeChunkAudioSlices(input) {
19835
20036
  const start = offsets[cut.firstPacket];
19836
20037
  layout.partStarts[index] = start;
19837
20038
  const end = offsets[last] + track.sizes[last];
19838
- writeFileSync8(join42(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
20039
+ writeFileSync9(join42(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
19839
20040
  });
19840
20041
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
19841
- writeFileSync8(join42(input.planDir, SLICE_FRAME), Buffer.concat(frame));
19842
- writeFileSync8(join42(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
20042
+ writeFileSync9(join42(input.planDir, SLICE_FRAME), Buffer.concat(frame));
20043
+ writeFileSync9(join42(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
19843
20044
  }
19844
20045
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19845
20046
  const layoutPath = join42(planDir, SLICE_LAYOUT);
19846
20047
  if (!existsSync26(layoutPath)) return resolvePlanAudioPath(planDir);
19847
- const layout = JSON.parse(readFileSync12(layoutPath, "utf-8"));
19848
- const frame = readFileSync12(join42(planDir, SLICE_FRAME));
20048
+ const layout = JSON.parse(readFileSync13(layoutPath, "utf-8"));
20049
+ const frame = readFileSync13(join42(planDir, SLICE_FRAME));
19849
20050
  const fd = openSync7(scratchPath, "w");
19850
20051
  try {
19851
20052
  writeSync(fd, frame, 0, layout.payloadStart, 0);
@@ -19858,7 +20059,7 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19858
20059
  );
19859
20060
  const start = layout.partStarts[chunkIndex];
19860
20061
  if (start !== void 0) {
19861
- const part = readFileSync12(join42(planDir, chunkAudioSlicePath(chunkIndex)));
20062
+ const part = readFileSync13(join42(planDir, chunkAudioSlicePath(chunkIndex)));
19862
20063
  writeSync(fd, part, 0, part.length, start);
19863
20064
  }
19864
20065
  ftruncateSync(fd, layout.sizeBytes);
@@ -20418,7 +20619,7 @@ function createVideoSourceShipper(input) {
20418
20619
  if (result === null) {
20419
20620
  result = `video-sources/${shipped.size}${extname6(current)}`;
20420
20621
  const destination = join44(input.planDir, ...result.split("/"));
20421
- mkdirSync16(join44(input.planDir, "video-sources"), { recursive: true });
20622
+ mkdirSync17(join44(input.planDir, "video-sources"), { recursive: true });
20422
20623
  try {
20423
20624
  linkSync(current, destination);
20424
20625
  } catch {
@@ -20438,7 +20639,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20438
20639
  useGpu: false,
20439
20640
  browserGpuMode: "software"
20440
20641
  });
20441
- if (!existsSync27(planDir)) mkdirSync16(planDir, { recursive: true });
20642
+ if (!existsSync27(planDir)) mkdirSync17(planDir, { recursive: true });
20442
20643
  const log = config.logger ?? defaultLogger;
20443
20644
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
20444
20645
  const abortSignal = config.abortSignal;
@@ -20478,9 +20679,9 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20478
20679
  }
20479
20680
  const workDir = join44(planDir, ".plan-work");
20480
20681
  rmSync15(workDir, { recursive: true, force: true });
20481
- mkdirSync16(workDir, { recursive: true });
20682
+ mkdirSync17(workDir, { recursive: true });
20482
20683
  const compiledDir = join44(workDir, "compiled");
20483
- mkdirSync16(compiledDir, { recursive: true });
20684
+ mkdirSync17(compiledDir, { recursive: true });
20484
20685
  let stageStarted = Date.now();
20485
20686
  cpSync2(projectDir, compiledDir, {
20486
20687
  recursive: true,
@@ -20715,7 +20916,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20715
20916
  if (existsSync27(stagedVideoFrames)) {
20716
20917
  renameWithRetry7(stagedVideoFrames, videoFramesDst);
20717
20918
  } else {
20718
- mkdirSync16(videoFramesDst, { recursive: true });
20919
+ mkdirSync17(videoFramesDst, { recursive: true });
20719
20920
  }
20720
20921
  if (existsSync27(finalCompiledDir)) rmSync15(finalCompiledDir, { recursive: true, force: true });
20721
20922
  renameWithRetry7(compiledDir, finalCompiledDir);
@@ -20747,7 +20948,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20747
20948
  };
20748
20949
  })
20749
20950
  });
20750
- mkdirSync16(join44(planDir, "meta"), { recursive: true });
20951
+ mkdirSync17(join44(planDir, "meta"), { recursive: true });
20751
20952
  writePlanRemoteFiles(
20752
20953
  planDir,
20753
20954
  remoteFiles.map(([rel, { sha256, sizeBytes }]) => ({
@@ -20756,7 +20957,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20756
20957
  sizeBytes
20757
20958
  }))
20758
20959
  );
20759
- writeFileSync9(
20960
+ writeFileSync10(
20760
20961
  join44(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
20761
20962
  JSON.stringify(planVideosJson, null, 2),
20762
20963
  "utf-8"
@@ -20963,7 +21164,7 @@ async function plan(projectDir, config, planDir, options = {}) {
20963
21164
 
20964
21165
  // src/services/distributed/renderChunk.ts
20965
21166
  import { randomBytes } from "node:crypto";
20966
- import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync18, writeFileSync as writeFileSync12 } from "node:fs";
21167
+ import { existsSync as existsSync30, mkdirSync as mkdirSync20, readFileSync as readFileSync15, readdirSync as readdirSync11, rmSync as rmSync18, writeFileSync as writeFileSync13 } from "node:fs";
20967
21168
  import { join as join48 } from "node:path";
20968
21169
  import {
20969
21170
  assertSwiftShader,
@@ -20992,15 +21193,15 @@ import {
20992
21193
  copyFileSync as copyFileSync8,
20993
21194
  existsSync as existsSync29,
20994
21195
  lstatSync as lstatSync5,
20995
- mkdirSync as mkdirSync18,
20996
- readFileSync as readFileSync13,
21196
+ mkdirSync as mkdirSync19,
21197
+ readFileSync as readFileSync14,
20997
21198
  readdirSync as readdirSync10,
20998
21199
  rmSync as rmSync17,
20999
21200
  statSync as statSync12,
21000
- writeFileSync as writeFileSync11
21201
+ writeFileSync as writeFileSync12
21001
21202
  } from "node:fs";
21002
21203
  import { tmpdir as tmpdir4 } from "node:os";
21003
- import { dirname as dirname19, isAbsolute as isAbsolute6, join as join47, relative as relative9, resolve as resolve11, sep as sep6 } from "node:path";
21204
+ import { dirname as dirname20, isAbsolute as isAbsolute6, join as join47, relative as relative9, resolve as resolve11, sep as sep6 } from "node:path";
21004
21205
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
21005
21206
  import {
21006
21207
  createFrameLookupTable as createFrameLookupTable5,
@@ -21013,13 +21214,13 @@ import {
21013
21214
  copyFileSync as copyFileSync7,
21014
21215
  existsSync as existsSync28,
21015
21216
  linkSync as linkSync2,
21016
- mkdirSync as mkdirSync17,
21217
+ mkdirSync as mkdirSync18,
21017
21218
  rmSync as rmSync16,
21018
21219
  statSync as statSync11,
21019
- writeFileSync as writeFileSync10
21220
+ writeFileSync as writeFileSync11
21020
21221
  } from "node:fs";
21021
21222
  import { renameWithRetry as renameWithRetry8 } from "@hyperframes/engine";
21022
- import { dirname as dirname18, join as join46 } from "node:path";
21223
+ import { dirname as dirname19, join as join46 } from "node:path";
21023
21224
 
21024
21225
  // src/services/distributed/planV2Errors.ts
21025
21226
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -21080,8 +21281,8 @@ var LocalPlanV2ArtifactPublisher = class {
21080
21281
  }
21081
21282
  this.destinationDir = destinationDir;
21082
21283
  this.#linkFile = options.linkFile ?? linkSync2;
21083
- mkdirSync17(dirname18(destinationDir), { recursive: true });
21084
- this.temporaryDir = createStagingDir5(dirname18(destinationDir), ".plan-v2-publish-");
21284
+ mkdirSync18(dirname19(destinationDir), { recursive: true });
21285
+ this.temporaryDir = createStagingDir5(dirname19(destinationDir), ".plan-v2-publish-");
21085
21286
  }
21086
21287
  async putBlob(blob) {
21087
21288
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
@@ -21093,8 +21294,8 @@ var LocalPlanV2ArtifactPublisher = class {
21093
21294
  }
21094
21295
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
21095
21296
  if (existsSync28(destinationPath)) return;
21096
- mkdirSync17(dirname18(destinationPath), { recursive: true });
21097
- const stagingDir = createStagingDir5(dirname18(destinationPath), ".plan-v2-blob-");
21297
+ mkdirSync18(dirname19(destinationPath), { recursive: true });
21298
+ const stagingDir = createStagingDir5(dirname19(destinationPath), ".plan-v2-blob-");
21098
21299
  const temporaryPath = join46(stagingDir, "blob");
21099
21300
  try {
21100
21301
  try {
@@ -21116,7 +21317,7 @@ var LocalPlanV2ArtifactPublisher = class {
21116
21317
  );
21117
21318
  }
21118
21319
  }
21119
- writeFileSync10(join46(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
21320
+ writeFileSync11(join46(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
21120
21321
  renameWithRetry8(this.temporaryDir, this.destinationDir);
21121
21322
  this.#committed = true;
21122
21323
  }
@@ -21142,7 +21343,7 @@ function isNonNegativeIntegerArray(value) {
21142
21343
  return Array.isArray(value) && value.every((item) => typeof item === "number" && Number.isInteger(item) && item >= 0);
21143
21344
  }
21144
21345
  function readJsonFile(path, label) {
21145
- const contents = readFileSync13(path, "utf-8");
21346
+ const contents = readFileSync14(path, "utf-8");
21146
21347
  try {
21147
21348
  const parsed = JSON.parse(contents);
21148
21349
  return parsed;
@@ -21294,7 +21495,7 @@ function materializeExtractedVideoDirectories(planDir) {
21294
21495
  if (!existsSync29(videosPath)) return;
21295
21496
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
21296
21497
  for (const video of videos.extracted) {
21297
- mkdirSync18(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
21498
+ mkdirSync19(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
21298
21499
  }
21299
21500
  }
21300
21501
  function parseChunkSlices(value) {
@@ -21385,8 +21586,8 @@ function computeManifestHash(manifest) {
21385
21586
  }
21386
21587
  function writeBlob(sourcePath, destinationPath) {
21387
21588
  if (existsSync29(destinationPath)) return;
21388
- mkdirSync18(dirname19(destinationPath), { recursive: true });
21389
- const temporaryDir = createStagingDir6(dirname19(destinationPath), ".plan-v2-blob-");
21589
+ mkdirSync19(dirname20(destinationPath), { recursive: true });
21590
+ const temporaryDir = createStagingDir6(dirname20(destinationPath), ".plan-v2-blob-");
21390
21591
  const temporaryPath = join47(temporaryDir, "blob");
21391
21592
  try {
21392
21593
  copyFileSync8(sourcePath, temporaryPath);
@@ -21511,13 +21712,13 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
21511
21712
  if (publication.storedBlobs.length > 0) {
21512
21713
  throw new PlanV2IntegrityError("a local plan v2 directory cannot reference remote files");
21513
21714
  }
21514
- mkdirSync18(dirname19(planV2Dir), { recursive: true });
21515
- const tempDir = createStagingDir6(dirname19(planV2Dir), ".plan-v2-build-");
21715
+ mkdirSync19(dirname20(planV2Dir), { recursive: true });
21716
+ const tempDir = createStagingDir6(dirname20(planV2Dir), ".plan-v2-build-");
21516
21717
  try {
21517
21718
  for (const blob of publication.blobs) {
21518
21719
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
21519
21720
  }
21520
- writeFileSync11(
21721
+ writeFileSync12(
21521
21722
  join47(tempDir, "plan.json"),
21522
21723
  canonicalJsonStringify(publication.manifest),
21523
21724
  "utf-8"
@@ -21599,7 +21800,7 @@ async function planV2(projectDir, config, planV2Dir) {
21599
21800
  }
21600
21801
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
21601
21802
  const manifest = await planV2WithPublisher(projectDir, config, publisher, {
21602
- stagingParentDir: dirname19(planV2Dir)
21803
+ stagingParentDir: dirname20(planV2Dir)
21603
21804
  });
21604
21805
  return resultFromManifest(planV2Dir, manifest);
21605
21806
  }
@@ -21792,16 +21993,16 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21792
21993
  artifact,
21793
21994
  sourcePath: verifyBlob(planV2Dir, artifact)
21794
21995
  }));
21795
- mkdirSync18(dirname19(destinationDir), { recursive: true });
21796
- const tempDir = createStagingDir6(dirname19(destinationDir), ".plan-v2-materialize-");
21996
+ mkdirSync19(dirname20(destinationDir), { recursive: true });
21997
+ const tempDir = createStagingDir6(dirname20(destinationDir), ".plan-v2-materialize-");
21797
21998
  try {
21798
21999
  for (const { artifact, sourcePath } of verified) {
21799
22000
  const destinationPath = join47(tempDir, ...artifact.path.split("/"));
21800
- mkdirSync18(dirname19(destinationPath), { recursive: true });
22001
+ mkdirSync19(dirname20(destinationPath), { recursive: true });
21801
22002
  copyFileSync8(sourcePath, destinationPath);
21802
22003
  }
21803
22004
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
21804
- writeFileSync11(
22005
+ writeFileSync12(
21805
22006
  join47(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
21806
22007
  canonicalJsonStringify({
21807
22008
  manifest,
@@ -21991,10 +22192,10 @@ async function beginFrameSessionNeedsScreenshotFallback(session, probe = probeBe
21991
22192
  return !await probe(session.page, timeoutMs, probeTick, session.beginFrameIntervalMs);
21992
22193
  }
21993
22194
  function hashChunkOutput(outputPath, kind) {
21994
- if (kind === "file") return sha256Hex(readFileSync14(outputPath));
22195
+ if (kind === "file") return sha256Hex(readFileSync15(outputPath));
21995
22196
  const entries = readdirSync11(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
21996
22197
  const lines = entries.map(
21997
- (name) => `${name}\0${sha256Hex(readFileSync14(join48(outputPath, name)))}`
22198
+ (name) => `${name}\0${sha256Hex(readFileSync15(join48(outputPath, name)))}`
21998
22199
  );
21999
22200
  return sha256Hex(lines.join("\0"));
22000
22201
  }
@@ -22020,7 +22221,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22020
22221
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
22021
22222
  );
22022
22223
  }
22023
- const plan2 = JSON.parse(readFileSync14(planJsonPath, "utf-8"));
22224
+ const plan2 = JSON.parse(readFileSync15(planJsonPath, "utf-8"));
22024
22225
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.chunk);
22025
22226
  const planHashStarted = Date.now();
22026
22227
  const v2Materialization = readValidatedPlanV2Materialization(planDir, {
@@ -22037,13 +22238,13 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22037
22238
  );
22038
22239
  }
22039
22240
  }
22040
- const encoder = JSON.parse(readFileSync14(encoderJsonPath, "utf-8"));
22041
- const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
22241
+ const encoder = JSON.parse(readFileSync15(encoderJsonPath, "utf-8"));
22242
+ const chunks = JSON.parse(readFileSync15(chunksJsonPath, "utf-8"));
22042
22243
  const videosJsonPath = join48(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
22043
22244
  let planVideos = null;
22044
22245
  if (existsSync30(videosJsonPath)) {
22045
22246
  try {
22046
- planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync14(videosJsonPath, "utf-8")));
22247
+ planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync15(videosJsonPath, "utf-8")));
22047
22248
  } catch (err) {
22048
22249
  if (err instanceof RenderChunkValidationError) throw err;
22049
22250
  throw new RenderChunkValidationError(
@@ -22129,9 +22330,9 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22129
22330
  forceScreenshotExplicitlyOptedOut: !encoder.forceScreenshot
22130
22331
  };
22131
22332
  const workDir = `${outputChunkPath}.work.${process.pid}.${randomBytes(4).toString("hex")}`;
22132
- mkdirSync19(workDir, { recursive: true });
22333
+ mkdirSync20(workDir, { recursive: true });
22133
22334
  const framesDir = join48(workDir, "captured-frames");
22134
- mkdirSync19(framesDir, { recursive: true });
22335
+ mkdirSync20(framesDir, { recursive: true });
22135
22336
  const videoFramesDir = `${workDir}.video-frames`;
22136
22337
  const chunkFrameNumbers = Array.from({ length: framesInChunk }, (_, i) => range.startFrame + i);
22137
22338
  const chunkFps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
@@ -22155,7 +22356,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22155
22356
  dimensions: plan2.dimensions,
22156
22357
  encoder,
22157
22358
  videoCount: planVideos?.videos.length ?? 0,
22158
- html: readFileSync14(join48(compiledDir, "index.html"), "utf-8"),
22359
+ html: readFileSync15(join48(compiledDir, "index.html"), "utf-8"),
22159
22360
  // The plan ships a deferred source only to chunks that show it; don't wait on the rest.
22160
22361
  skipReadinessVideoIds: deferredVideos.filter(
22161
22362
  (video) => !shownFrames.get(video.videoId)?.size || remoteVideoIds.has(video.videoId)
@@ -22325,10 +22526,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22325
22526
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
22326
22527
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
22327
22528
  if (isPngSequence) {
22328
- if (!existsSync30(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
22529
+ if (!existsSync30(outputChunkPath)) mkdirSync20(outputChunkPath, { recursive: true });
22329
22530
  } else {
22330
22531
  const outDir = join48(outputChunkPath, "..");
22331
- if (!existsSync30(outDir)) mkdirSync19(outDir, { recursive: true });
22532
+ if (!existsSync30(outDir)) mkdirSync20(outDir, { recursive: true });
22332
22533
  }
22333
22534
  const encodeInput = {
22334
22535
  job,
@@ -22449,7 +22650,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22449
22650
  resetForScreenshotRetry: () => {
22450
22651
  rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22451
22652
  boxesMeasured();
22452
- mkdirSync19(framesDir, { recursive: true });
22653
+ mkdirSync20(framesDir, { recursive: true });
22453
22654
  capturePerfs.length = 0;
22454
22655
  captureAttempts.length = 0;
22455
22656
  job.framesRendered = 0;
@@ -22541,7 +22742,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22541
22742
  producerVersion: plan2.producerVersion,
22542
22743
  ffmpegVersion
22543
22744
  };
22544
- writeFileSync12(perfPath, `${JSON.stringify(perfPayload, null, 2)}
22745
+ writeFileSync13(perfPath, `${JSON.stringify(perfPayload, null, 2)}
22545
22746
  `, "utf-8");
22546
22747
  try {
22547
22748
  rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
@@ -22608,7 +22809,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
22608
22809
  try {
22609
22810
  const planDir = join49(workDir, "plan");
22610
22811
  const partsDir = join49(workDir, "parts");
22611
- mkdirSync20(partsDir, { recursive: true });
22812
+ mkdirSync21(partsDir, { recursive: true });
22612
22813
  const planned = await plan(
22613
22814
  projectDir,
22614
22815
  { ...config, rejectOnSystemFonts: false, failClosedFontFetch: false },
@@ -22626,7 +22827,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
22626
22827
  planned.totalFrames
22627
22828
  );
22628
22829
  const slices = JSON.parse(
22629
- readFileSync15(join49(planDir, "meta", "chunks.json"), "utf-8")
22830
+ readFileSync16(join49(planDir, "meta", "chunks.json"), "utf-8")
22630
22831
  );
22631
22832
  const parts = [];
22632
22833
  for (const slice of slices) {
@@ -23298,16 +23499,16 @@ import {
23298
23499
  existsSync as existsSync33,
23299
23500
  fstatSync as fstatSync5,
23300
23501
  lstatSync as lstatSync6,
23301
- mkdirSync as mkdirSync21,
23502
+ mkdirSync as mkdirSync22,
23302
23503
  openSync as openSync9,
23303
23504
  statSync as statSync14,
23304
23505
  mkdtempSync as mkdtempSync2,
23305
- writeFileSync as writeFileSync13,
23506
+ writeFileSync as writeFileSync14,
23306
23507
  rmSync as rmSync20,
23307
23508
  createReadStream as createReadStream6
23308
23509
  } from "node:fs";
23309
23510
  import { AsyncLocalStorage } from "node:async_hooks";
23310
- import { basename as basename9, resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23511
+ import { basename as basename9, resolve as resolve13, dirname as dirname23, join as join52 } from "node:path";
23311
23512
  import { homedir, tmpdir as tmpdir6 } from "node:os";
23312
23513
  import { parseArgs } from "node:util";
23313
23514
  import { isIP } from "node:net";
@@ -23326,14 +23527,14 @@ import { foreignWritablePath } from "@hyperframes/core/cache-dir";
23326
23527
  // src/services/hyperframeLint.ts
23327
23528
  import {
23328
23529
  existsSync as existsSync31,
23329
- readFileSync as readFileSync16,
23530
+ readFileSync as readFileSync17,
23330
23531
  statSync as statSync13,
23331
23532
  openSync as openSync8,
23332
23533
  fstatSync as fstatSync4,
23333
23534
  closeSync as closeSync8,
23334
23535
  constants as constants4
23335
23536
  } from "node:fs";
23336
- import { resolve as resolve12, join as join50, relative as relative10, isAbsolute as isAbsolute7, sep as sep7, dirname as dirname20 } from "node:path";
23537
+ import { resolve as resolve12, join as join50, relative as relative10, isAbsolute as isAbsolute7, sep as sep7, dirname as dirname21 } from "node:path";
23337
23538
  import { fileURLToPath as fileURLToPath7 } from "node:url";
23338
23539
  import { Worker as Worker3 } from "node:worker_threads";
23339
23540
  function isStringRecord(value) {
@@ -23373,7 +23574,7 @@ function readEntryHtml(filePath) {
23373
23574
  }
23374
23575
  try {
23375
23576
  if (!fstatSync4(fd).isFile()) return null;
23376
- return readFileSync16(fd, "utf-8");
23577
+ return readFileSync17(fd, "utf-8");
23377
23578
  } finally {
23378
23579
  closeSync8(fd);
23379
23580
  }
@@ -23472,7 +23673,7 @@ function freeLintSlot() {
23472
23673
  waiting.shift()?.();
23473
23674
  }
23474
23675
  function resolveLintWorkerEntry() {
23475
- const here = dirname20(fileURLToPath7(import.meta.url));
23676
+ const here = dirname21(fileURLToPath7(import.meta.url));
23476
23677
  for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
23477
23678
  const candidate = join50(here, name);
23478
23679
  if (existsSync31(candidate)) return candidate;
@@ -23545,7 +23746,7 @@ async function runHyperframeLint(prepared, options = {}) {
23545
23746
  // src/services/healthWorker.ts
23546
23747
  import { Worker as Worker4 } from "node:worker_threads";
23547
23748
  import { fileURLToPath as fileURLToPath8 } from "node:url";
23548
- import { dirname as dirname21, join as join51 } from "node:path";
23749
+ import { dirname as dirname22, join as join51 } from "node:path";
23549
23750
  import { existsSync as existsSync32 } from "node:fs";
23550
23751
  var DEFAULT_HEALTH_PORT = 9848;
23551
23752
  async function startHealthWorker(options = {}) {
@@ -23620,7 +23821,7 @@ function defaultLogger2() {
23620
23821
  };
23621
23822
  }
23622
23823
  function resolveWorkerEntry2() {
23623
- const here = dirname21(fileURLToPath8(import.meta.url));
23824
+ const here = dirname22(fileURLToPath8(import.meta.url));
23624
23825
  const candidates = [join51(here, "healthWorkerThread.js"), join51(here, "healthWorkerThread.ts")];
23625
23826
  for (const candidate of candidates) {
23626
23827
  if (existsSync32(candidate)) return candidate;
@@ -23788,9 +23989,9 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
23788
23989
  const serverNamed = input.outputPath == null;
23789
23990
  const outputCandidate = input.outputPath ?? join52(rendersDir, `${basename9(resolve13(input.projectDir))}-${crypto.randomUUID()}.mp4`);
23790
23991
  const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
23791
- const outputDir = dirname22(absoluteOutputPath);
23992
+ const outputDir = dirname23(absoluteOutputPath);
23792
23993
  if (confineOutput) {
23793
- mkdirSync21(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23994
+ mkdirSync22(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23794
23995
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
23795
23996
  throw new Error("outputPath must be inside the renders directory");
23796
23997
  }
@@ -23801,7 +24002,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
23801
24002
  );
23802
24003
  }
23803
24004
  }
23804
- if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
24005
+ if (!existsSync33(outputDir)) mkdirSync22(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23805
24006
  return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
23806
24007
  }
23807
24008
  var STICKY_BIT = 512;
@@ -23913,7 +24114,7 @@ async function resolveInlineRenderHtml(body) {
23913
24114
  function materializeInlineProject(html, options) {
23914
24115
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir6();
23915
24116
  const tempProjectDir = mkdtempSync2(join52(tempRoot, "producer-project-"));
23916
- writeFileSync13(join52(tempProjectDir, "index.html"), html, "utf-8");
24117
+ writeFileSync14(join52(tempProjectDir, "index.html"), html, "utf-8");
23917
24118
  return {
23918
24119
  prepared: {
23919
24120
  input: { projectDir: tempProjectDir, ...options },
@@ -24506,9 +24707,9 @@ function serverAuth(options, hostname2, port) {
24506
24707
  options.authTokenFile?.trim() || process.env.PRODUCER_AUTH_TOKEN_FILE?.trim() || join52(homedir(), ".hyperframes", "producer", `${port}.token`)
24507
24708
  );
24508
24709
  const token = crypto.randomBytes(32).toString("base64url");
24509
- mkdirSync21(dirname22(file), { recursive: true, mode: 448 });
24710
+ mkdirSync22(dirname23(file), { recursive: true, mode: 448 });
24510
24711
  rmSync20(file, { force: true });
24511
- writeFileSync13(file, `${token}
24712
+ writeFileSync14(file, `${token}
24512
24713
  `, { flag: "wx", mode: 384 });
24513
24714
  return { token, generatedFile: file };
24514
24715
  }
@@ -24598,14 +24799,14 @@ import {
24598
24799
  import {
24599
24800
  cpSync as cpSync3,
24600
24801
  existsSync as existsSync34,
24601
- mkdirSync as mkdirSync22,
24602
- readFileSync as readFileSync17,
24802
+ mkdirSync as mkdirSync23,
24803
+ readFileSync as readFileSync18,
24603
24804
  readdirSync as readdirSync12,
24604
24805
  rmSync as rmSync21,
24605
24806
  statSync as statSync15
24606
24807
  } from "node:fs";
24607
24808
  import { localContainerInputArgs as localContainerInputArgs2 } from "@hyperframes/parsers/ff-binaries";
24608
- import { basename as basename10, dirname as dirname23, join as join53 } from "node:path";
24809
+ import { basename as basename10, dirname as dirname24, join as join53 } from "node:path";
24609
24810
  import {
24610
24811
  appendRateCapArgs as appendRateCapArgs2,
24611
24812
  writeVideoConcatList,
@@ -24654,10 +24855,10 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
24654
24855
  }
24655
24856
  const format = plan2.dimensions.format;
24656
24857
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
24657
- if (!existsSync34(dirname23(outputPath))) {
24658
- mkdirSync22(dirname23(outputPath), { recursive: true });
24858
+ if (!existsSync34(dirname24(outputPath))) {
24859
+ mkdirSync23(dirname24(outputPath), { recursive: true });
24659
24860
  }
24660
- const workDir = createStagingDir7(dirname23(outputPath), `${basename10(outputPath)}.assemble-work-`);
24861
+ const workDir = createStagingDir7(dirname24(outputPath), `${basename10(outputPath)}.assemble-work-`);
24661
24862
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
24662
24863
  const stageMs = {};
24663
24864
  const ctx = {
@@ -24711,13 +24912,13 @@ function readAssemblePlan(planDir, chunkPaths) {
24711
24912
  if (!existsSync34(planJsonPath)) {
24712
24913
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
24713
24914
  }
24714
- const plan2 = JSON.parse(readFileSync17(planJsonPath, "utf-8"));
24915
+ const plan2 = JSON.parse(readFileSync18(planJsonPath, "utf-8"));
24715
24916
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
24716
24917
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
24717
24918
  if (!existsSync34(chunksJsonPath)) {
24718
24919
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
24719
24920
  }
24720
- const chunks = JSON.parse(readFileSync17(chunksJsonPath, "utf-8"));
24921
+ const chunks = JSON.parse(readFileSync18(chunksJsonPath, "utf-8"));
24721
24922
  if (chunkPaths.length !== chunks.length) {
24722
24923
  throw new Error(
24723
24924
  `[assemble] chunkPaths length (${chunkPaths.length}) does not match chunks.json length (${chunks.length}). Adapters must pass one path per chunk, ordered by index.`
@@ -24864,13 +25065,13 @@ function stitchesSeparateAudio(planDir) {
24864
25065
  return lockedAudio(planDir).separateAudio === true;
24865
25066
  }
24866
25067
  function planFormat(planDir) {
24867
- const plan2 = JSON.parse(readFileSync17(join53(planDir, "plan.json"), "utf-8"));
25068
+ const plan2 = JSON.parse(readFileSync18(join53(planDir, "plan.json"), "utf-8"));
24868
25069
  return plan2.dimensions.format;
24869
25070
  }
24870
25071
  function lockedAudio(planDir) {
24871
25072
  const encoderJsonPath = join53(planDir, "meta", "encoder.json");
24872
25073
  if (!existsSync34(encoderJsonPath)) return {};
24873
- return JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
25074
+ return JSON.parse(readFileSync18(encoderJsonPath, "utf-8"));
24874
25075
  }
24875
25076
  function readCfrEncoder(planDir, format) {
24876
25077
  if (format !== "mp4") {
@@ -24882,7 +25083,7 @@ function readCfrEncoder(planDir, format) {
24882
25083
  if (!existsSync34(encoderJsonPath)) {
24883
25084
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
24884
25085
  }
24885
- const encoderJson = JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
25086
+ const encoderJson = JSON.parse(readFileSync18(encoderJsonPath, "utf-8"));
24886
25087
  if (encoderJson.encoder === "libx265-software") {
24887
25088
  throw new Error(
24888
25089
  `[assemble] cfr=true is not yet supported with codec: "h265". The cfr re-encode pass uses libx264 and would silently transcode the h265 chunks. Either disable cfr or render with codec: "h264".`
@@ -24892,7 +25093,7 @@ function readCfrEncoder(planDir, format) {
24892
25093
  }
24893
25094
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
24894
25095
  if (existsSync34(outputPath)) rmSync21(outputPath, { recursive: true, force: true });
24895
- mkdirSync22(outputPath, { recursive: true });
25096
+ mkdirSync23(outputPath, { recursive: true });
24896
25097
  let globalIdx = 0;
24897
25098
  for (const chunkDir of chunkPaths) {
24898
25099
  if (!statSync15(chunkDir).isDirectory()) {
@@ -24967,7 +25168,7 @@ async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
24967
25168
  }
24968
25169
 
24969
25170
  // src/services/distributed/projectHash.ts
24970
- import { isPrivateFileUnder as isPrivateFileUnder3, isStudioPrivatePath as isStudioPrivatePath3 } from "@hyperframes/core/safe-path";
25171
+ import { isPrivateFileUnder as isPrivateFileUnder4, isStudioPrivatePath as isStudioPrivatePath4 } from "@hyperframes/core/safe-path";
24971
25172
  var READ_CHUNK_BYTES = 256 * 1024;
24972
25173
 
24973
25174
  // src/services/distributed/audioSidecar.ts