@hyperframes/producer 0.9.31 → 0.9.33

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
@@ -9,7 +9,7 @@ import {
9
9
  // src/services/renderOrchestrator.ts
10
10
  import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
11
11
  import {
12
- existsSync as existsSync22,
12
+ existsSync as existsSync21,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync12,
@@ -206,7 +206,9 @@ function createConsoleLogger(level = "info") {
206
206
  }
207
207
  };
208
208
  }
209
- var defaultLogger = createConsoleLogger("info");
209
+ var defaultLogger = createConsoleLogger(
210
+ process.env.HF_DEBUG_RENDER === "1" ? "debug" : "info"
211
+ );
210
212
 
211
213
  // src/services/fileServer.ts
212
214
  var readFileAsync = promisify(readFile);
@@ -980,11 +982,38 @@ function resolveDeliveryEncoderOptions(config) {
980
982
  return { maxBitrate, bufferSize, ...gop };
981
983
  }
982
984
 
985
+ // src/services/render/chromaSubsampling.ts
986
+ function validateChromaSubsamplingConfig(config) {
987
+ if (config.chromaSubsampling !== "444") return;
988
+ const format = config.format ?? "mp4";
989
+ if (format !== "mp4") {
990
+ throw new Error(
991
+ `[Render] chromaSubsampling "444" supports format "mp4" only (got "${format}"). WebM, MOV and GIF use their own pixel formats, and HLS targets broad playback. Use --format mp4, or drop --chroma-subsampling 444.`
992
+ );
993
+ }
994
+ if (config.hdrMode === "force-hdr") {
995
+ throw new Error(
996
+ `[Render] chromaSubsampling "444" is SDR only; HDR output stays 10-bit 4:2:0 H.265. Drop --hdr, or drop --chroma-subsampling 444.`
997
+ );
998
+ }
999
+ if (config.useGpu === true) {
1000
+ throw new Error(
1001
+ `[Render] chromaSubsampling "444" requires the software encoder (libx264); GPU encoders do not reliably support 4:4:4. Re-run without --gpu.`
1002
+ );
1003
+ }
1004
+ }
1005
+ function assertChromaSubsamplingSdr(config, hasHdrContent) {
1006
+ if (config.chromaSubsampling !== "444" || !hasHdrContent) return;
1007
+ throw new Error(
1008
+ `[Render] chromaSubsampling "444" is SDR only, but this composition has HDR sources. Re-run with --sdr (hdrMode "force-sdr"), or drop --chroma-subsampling 444.`
1009
+ );
1010
+ }
1011
+
983
1012
  // src/services/render/shared.ts
984
1013
  import {
985
1014
  copyFileSync,
986
1015
  cpSync,
987
- existsSync as existsSync4,
1016
+ existsSync as existsSync3,
988
1017
  mkdirSync,
989
1018
  rmSync,
990
1019
  symlinkSync,
@@ -995,6 +1024,9 @@ import {
995
1024
  CANVAS_DIMENSIONS,
996
1025
  checkOutputResolutionCompatibility
997
1026
  } from "@hyperframes/core";
1027
+ import {
1028
+ mediaIdPathSegment
1029
+ } from "@hyperframes/engine";
998
1030
 
999
1031
  // src/utils/paths.ts
1000
1032
  import {
@@ -1004,9 +1036,7 @@ import {
1004
1036
  relative as nodeRelative,
1005
1037
  isAbsolute as nodeIsAbsolute
1006
1038
  } from "node:path";
1007
- import { existsSync as existsSync3 } from "node:fs";
1008
1039
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1009
- import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
1010
1040
  var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (not URL.pathname): on Windows .pathname is "/D:/..." which
1011
1041
  // resolves to a bogus renders dir.
1012
1042
  nodeResolve(fileURLToPath2(import.meta.url), "../../..", "renders");
@@ -1044,13 +1074,6 @@ function resolveRenderPaths(projectDir, outputPath, rendersDir = DEFAULT_RENDERS
1044
1074
  const absoluteOutputPath = nodeResolve(resolvedOutputPath);
1045
1075
  return { absoluteProjectDir, absoluteOutputPath };
1046
1076
  }
1047
- function resolveCompositionSrc(projectDir, src) {
1048
- const rooted = (value) => nodeResolve(projectDir, value.replace(/^(?:\.?[\\/])+/, ""));
1049
- const decoded = rooted(decodedUrlPath(src));
1050
- if (!isPathInside2(decoded, projectDir)) return null;
1051
- const raw = rooted(src);
1052
- return !existsSync3(decoded) && isPathInside2(raw, projectDir) && existsSync3(raw) ? raw : decoded;
1053
- }
1054
1077
 
1055
1078
  // src/services/render/shared.ts
1056
1079
  var BROWSER_MEDIA_EPSILON = 1e-4;
@@ -1089,6 +1112,10 @@ function writeCompiledArtifacts(compiled, workDir, includeSummary) {
1089
1112
  writeFileSync(join3(compileDir, "index.html"), compiled.html, "utf-8");
1090
1113
  for (const [srcPath, html] of compiled.subCompositions) {
1091
1114
  const outPath = join3(compileDir, srcPath);
1115
+ if (!isPathInside2(outPath, compileDir)) {
1116
+ console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
1117
+ continue;
1118
+ }
1092
1119
  mkdirSync(dirname2(outPath), { recursive: true });
1093
1120
  writeFileSync(outPath, html, "utf-8");
1094
1121
  }
@@ -1221,6 +1248,13 @@ var workerPhasesByJob = /* @__PURE__ */ new WeakMap();
1221
1248
  function forgetWorkerPhases(job) {
1222
1249
  workerPhasesByJob.delete(job);
1223
1250
  }
1251
+ var staticDedupActivityByJob = /* @__PURE__ */ new WeakMap();
1252
+ function noteStaticDedupActivity(job) {
1253
+ staticDedupActivityByJob.set(job, (staticDedupActivityByJob.get(job) ?? 0) + 1);
1254
+ }
1255
+ function staticDedupActivity(job) {
1256
+ return staticDedupActivityByJob.get(job) ?? 0;
1257
+ }
1224
1258
  function describeWorkerPhases(job) {
1225
1259
  const phases = workerPhasesByJob.get(job);
1226
1260
  if (!phases?.size) return void 0;
@@ -1254,7 +1288,7 @@ var materializePathModule = {
1254
1288
  isAbsolute
1255
1289
  };
1256
1290
  var materializeFileSystem = {
1257
- existsSync: existsSync4,
1291
+ existsSync: existsSync3,
1258
1292
  mkdirSync,
1259
1293
  symlinkSync,
1260
1294
  cpSync,
@@ -1350,7 +1384,7 @@ function materializeExtractedFramesForCompiledDir(extracted, compiledDir, option
1350
1384
  for (const ext of extracted) {
1351
1385
  const resolvedOut = pathModule.resolve(ext.outputDir);
1352
1386
  if (isPathInside2(resolvedOut, resolvedCompiledDir, { pathModule })) continue;
1353
- const linkPath = pathModule.join(compiledFrameRoot, ext.videoId);
1387
+ const linkPath = pathModule.join(compiledFrameRoot, mediaIdPathSegment(ext.videoId));
1354
1388
  if (!fileSystem.existsSync(linkPath)) {
1355
1389
  fileSystem.mkdirSync(pathModule.dirname(linkPath), { recursive: true });
1356
1390
  stageExtractedFrameDir(
@@ -1556,7 +1590,7 @@ var RenderExecutionContext = class {
1556
1590
  };
1557
1591
 
1558
1592
  // src/services/render/artifactTransaction.ts
1559
- import { closeSync as closeSync2, existsSync as existsSync6, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
1593
+ import { closeSync as closeSync2, existsSync as existsSync5, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
1560
1594
  import { basename as basename4, dirname as dirname4, extname as extname2, join as join5, resolve as resolve4 } from "node:path";
1561
1595
  import { HLS_MASTER_PLAYLIST, HLS_VIDEO_PLAYLIST, renameWithRetry } from "@hyperframes/engine";
1562
1596
 
@@ -1569,7 +1603,7 @@ import {
1569
1603
 
1570
1604
  // src/services/render/renderDirOwner.ts
1571
1605
  import {
1572
- existsSync as existsSync5,
1606
+ existsSync as existsSync4,
1573
1607
  lstatSync,
1574
1608
  readFileSync as readFileSync2,
1575
1609
  readdirSync,
@@ -1645,7 +1679,7 @@ function newestWriteMs(path) {
1645
1679
  }
1646
1680
  function isAbandoned(dir, ownerlessIdleMs, now) {
1647
1681
  try {
1648
- if (!lstatSync(dir).isDirectory() || existsSync5(join4(dir, TRANSACTION_BACKUP))) return false;
1682
+ if (!lstatSync(dir).isDirectory() || existsSync4(join4(dir, TRANSACTION_BACKUP))) return false;
1649
1683
  const owner = ownerState(dir);
1650
1684
  if (owner === "gone") return true;
1651
1685
  return owner === "none" && ownerlessIdleMs !== void 0 && now - newestWriteMs(dir) >= ownerlessIdleMs;
@@ -1677,7 +1711,7 @@ function createRenderWorkDir(prefix, outputDir) {
1677
1711
 
1678
1712
  // src/services/render/artifactTransaction.ts
1679
1713
  var defaultFileSystem = {
1680
- existsSync: existsSync6,
1714
+ existsSync: existsSync5,
1681
1715
  renameSync: (source, destination) => renameWithRetry(source, destination),
1682
1716
  rmSync: rmSync3
1683
1717
  };
@@ -1831,7 +1865,7 @@ var ArtifactTransaction = class {
1831
1865
  async assertDirectoryExpectation(expected, files) {
1832
1866
  for (const required of expected.requiredFiles ?? []) {
1833
1867
  const path = join5(this.stagingPath, required);
1834
- if (!existsSync6(path)) {
1868
+ if (!existsSync5(path)) {
1835
1869
  throw new Error(`Render artifact directory is missing ${required}: ${this.stagingPath}`);
1836
1870
  }
1837
1871
  assertReadableNonEmptyFile(path);
@@ -2080,7 +2114,7 @@ function replanAfterFailure(plan2, failure) {
2080
2114
  }
2081
2115
 
2082
2116
  // src/services/render/stages/captureSegmentedStage.ts
2083
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync3 } from "node:fs";
2117
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync3 } from "node:fs";
2084
2118
  import { join as join9 } from "node:path";
2085
2119
  import {
2086
2120
  captureFrameToBuffer as captureFrameToBuffer2,
@@ -4426,7 +4460,7 @@ async function runCaptureStreamingStage(input) {
4426
4460
  const session = probeSession ?? await openSession();
4427
4461
  captureBeyondViewport = session.options.captureBeyondViewport;
4428
4462
  if (probeSession) {
4429
- prepareCaptureSessionForReuse(session, framesDir, videoInjector);
4463
+ await prepareCaptureSessionForReuse(session, framesDir, videoInjector);
4430
4464
  probeSession = null;
4431
4465
  }
4432
4466
  let riskSession = null;
@@ -4684,7 +4718,7 @@ async function captureSegmentToEncoder(ctx, segment) {
4684
4718
  path: segmentPath,
4685
4719
  // Recorded so resume can prove the file on disk is the one that
4686
4720
  // finished; absent only in unit tests, whose fake encoder writes none.
4687
- bytes: existsSync7(segmentPath) ? statSync3(segmentPath).size : 0
4721
+ bytes: existsSync6(segmentPath) ? statSync3(segmentPath).size : 0
4688
4722
  });
4689
4723
  return encodeResult;
4690
4724
  } finally {
@@ -4731,8 +4765,13 @@ function defaultSessionFactory(input) {
4731
4765
  };
4732
4766
  const session = probeSession ?? await openSession();
4733
4767
  if (probeSession) {
4734
- openSegmentedSessionReuse(input, probeSession, injector);
4768
+ const reused = probeSession;
4735
4769
  probeSession = null;
4770
+ await openSegmentedSessionReuse(input, reused, injector).catch(async (error) => {
4771
+ await closeCaptureSession2(reused).catch(() => {
4772
+ });
4773
+ throw error;
4774
+ });
4736
4775
  }
4737
4776
  try {
4738
4777
  if (!session.isInitialized) await withinInitBudget(initializeSession2(session), session);
@@ -4746,8 +4785,8 @@ function defaultSessionFactory(input) {
4746
4785
  }
4747
4786
  };
4748
4787
  }
4749
- function openSegmentedSessionReuse(input, session, injector) {
4750
- prepareCaptureSessionForReuse2(session, input.framesDir, injector());
4788
+ async function openSegmentedSessionReuse(input, session, injector) {
4789
+ await prepareCaptureSessionForReuse2(session, input.framesDir, injector());
4751
4790
  }
4752
4791
  async function openSegmentedSession(input, injector) {
4753
4792
  const captureCfg = input.cfg.forceScreenshot === input.plan.forceScreenshot ? input.cfg : { ...input.cfg, forceScreenshot: input.plan.forceScreenshot };
@@ -5425,6 +5464,7 @@ import { dirname as dirname5, join as join11 } from "node:path";
5425
5464
  import {
5426
5465
  createFrameLookupTable,
5427
5466
  extractVideoFramesRange,
5467
+ mediaIdPathSegment as mediaIdPathSegment2,
5428
5468
  runVideoExtractionWithRetry
5429
5469
  } from "@hyperframes/engine";
5430
5470
  function contiguousRuns(sortedIndexes) {
@@ -5465,7 +5505,7 @@ async function extractDeferredFrames(input) {
5465
5505
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5466
5506
  return Promise.all(
5467
5507
  deferred.map(async (video) => {
5468
- const outputDir = join11(input.outputRoot, video.videoId);
5508
+ const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
5469
5509
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5470
5510
  if (indexes.length === 0) {
5471
5511
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -5684,7 +5724,7 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
5684
5724
 
5685
5725
  // src/services/render/segmentManifest.ts
5686
5726
  import { createHash as createHash2 } from "node:crypto";
5687
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync4, statSync as statSync5, writeFileSync as writeFileSync3 } from "node:fs";
5727
+ import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync4, statSync as statSync5, writeFileSync as writeFileSync3 } from "node:fs";
5688
5728
  import { join as join14 } from "node:path";
5689
5729
  import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
5690
5730
  var MANIFEST_FILENAME = "segments.json";
@@ -5732,7 +5772,7 @@ function isManifest(value) {
5732
5772
  }
5733
5773
  function readSegmentManifest(segmentDir) {
5734
5774
  const path = join14(segmentDir, MANIFEST_FILENAME);
5735
- if (!existsSync8(path)) return null;
5775
+ if (!existsSync7(path)) return null;
5736
5776
  try {
5737
5777
  const parsed = JSON.parse(readFileSync4(path, "utf-8"));
5738
5778
  return isManifest(parsed) ? parsed : null;
@@ -5761,7 +5801,7 @@ async function validateCompletedSegments(manifest, expectedHash, probeFrames) {
5761
5801
  const ok = /* @__PURE__ */ new Set();
5762
5802
  if (manifest.planHash !== expectedHash) return ok;
5763
5803
  for (const entry of manifest.completed) {
5764
- if (!existsSync8(entry.path)) continue;
5804
+ if (!existsSync7(entry.path)) continue;
5765
5805
  const size = statSync5(entry.path).size;
5766
5806
  if (size <= 0 || size !== entry.bytes) continue;
5767
5807
  const frames = await probeFrames(entry.path);
@@ -6129,26 +6169,26 @@ var STALL_POLL_MS = 5e3;
6129
6169
  function watchStall(phase, rule) {
6130
6170
  const detail = rule.detail ?? (() => void 0);
6131
6171
  let last = rule.progress();
6172
+ let lastActivity = rule.activity?.();
6132
6173
  let budgetMs = rule.firstProgressMs;
6133
6174
  const silence = createStallClock();
6134
6175
  const pollMs = Math.min(STALL_POLL_MS, rule.noProgressMs, rule.firstProgressMs);
6135
6176
  let attempt;
6136
6177
  let timer;
6137
6178
  let inTail = false;
6179
+ const activityMoved = () => {
6180
+ const activity = rule.activity?.();
6181
+ if (activity === lastActivity) return false;
6182
+ lastActivity = activity;
6183
+ return true;
6184
+ };
6138
6185
  const restartWindow = (ms) => {
6139
6186
  last = rule.progress();
6140
6187
  budgetMs = ms;
6141
6188
  silence.reset();
6142
6189
  };
6143
6190
  const tripped = new Promise((_, reject) => {
6144
- timer = setInterval(() => {
6145
- const current = rule.progress();
6146
- if (rule.complete?.() && !inTail) {
6147
- inTail = true;
6148
- return restartWindow(rule.tailMs ?? rule.noProgressMs);
6149
- }
6150
- if (current !== last) return restartWindow(rule.noProgressMs);
6151
- if (silence.idle(pollMs) < budgetMs) return;
6191
+ const trip = (current) => {
6152
6192
  const error = new RenderStageStalledError(phase, budgetMs, current, detail());
6153
6193
  if (attempt && !attempt.signal.aborted) {
6154
6194
  attempt.abort(error);
@@ -6156,6 +6196,16 @@ function watchStall(phase, rule) {
6156
6196
  }
6157
6197
  clearInterval(timer);
6158
6198
  reject(error);
6199
+ };
6200
+ timer = setInterval(() => {
6201
+ const current = rule.progress();
6202
+ if (rule.complete?.() && !inTail) {
6203
+ inTail = true;
6204
+ return restartWindow(rule.tailMs ?? rule.noProgressMs);
6205
+ }
6206
+ if (current !== last) return restartWindow(rule.noProgressMs);
6207
+ if (activityMoved()) return silence.reset();
6208
+ if (silence.idle(pollMs) >= budgetMs) trip(current);
6159
6209
  }, pollMs);
6160
6210
  });
6161
6211
  const openAttempt = (parent) => {
@@ -6340,21 +6390,21 @@ function countAuthoredTimedClips(html) {
6340
6390
  }
6341
6391
 
6342
6392
  // src/services/render/stages/compileStage.ts
6343
- import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
6393
+ import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6344
6394
  import { join as join19 } from "node:path";
6345
6395
  import { suggestMatchingPreset } from "@hyperframes/core";
6346
6396
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6347
6397
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6348
6398
 
6349
6399
  // src/services/htmlCompiler.ts
6350
- import { decodedUrlPath as decodedUrlPath2 } from "@hyperframes/parsers/asset-paths";
6400
+ import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6351
6401
  import { createHash as createHash6 } from "node:crypto";
6352
- import { createReadStream as createReadStream2, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6402
+ import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6353
6403
  import { join as join18, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep2 } from "path";
6354
6404
  import { parseHTML as parseHTML5 } from "linkedom";
6355
6405
 
6356
6406
  // src/services/bundledScripts.ts
6357
- import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
6407
+ import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
6358
6408
  import { join as join15 } from "node:path";
6359
6409
  import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
6360
6410
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
@@ -6362,7 +6412,7 @@ function bundledScript(url) {
6362
6412
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
6363
6413
  if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
6364
6414
  const file = join15(dir, "gsap.min.js");
6365
- return existsSync9(file) ? readFileSync5(file) : null;
6415
+ return existsSync8(file) ? readFileSync5(file) : null;
6366
6416
  }
6367
6417
 
6368
6418
  // src/services/htmlCompiler.ts
@@ -6402,6 +6452,7 @@ import {
6402
6452
  emitRootCompositionVariableStyles,
6403
6453
  readDeclaredDefaults,
6404
6454
  parseHostVariableValues,
6455
+ boundMediaSrc,
6405
6456
  headStyleRuns,
6406
6457
  isAlwaysAppliedStyle,
6407
6458
  dedupeFontFaceRules,
@@ -6416,8 +6467,10 @@ import {
6416
6467
  } from "@hyperframes/parsers/sub-composition-validity";
6417
6468
  import {
6418
6469
  isUnresolvedAssetPlaceholder,
6470
+ namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
6419
6471
  readProjectFile,
6420
- readTextFile
6472
+ readTextFile,
6473
+ resolveCompositionSrc
6421
6474
  } from "@hyperframes/parsers/asset-resolution";
6422
6475
 
6423
6476
  // src/services/renderMediaCollector.ts
@@ -6610,11 +6663,12 @@ import {
6610
6663
 
6611
6664
  // src/services/animatedGifPrep.ts
6612
6665
  import { createHash as createHash4 } from "node:crypto";
6613
- import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6666
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6614
6667
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
6615
6668
  import { parseHTML as parseHTML3 } from "linkedom";
6616
6669
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
6617
6670
  import { DEFAULT_VP9_CPU_USED, runFfmpeg as runFfmpeg2, renameWithRetry as renameWithRetry3 } from "@hyperframes/engine";
6671
+ import { namesAnotherNetworkRoot } from "@hyperframes/parsers/asset-resolution";
6618
6672
  var PREPARED_GIF_SUBDIR = "_animated_gif";
6619
6673
  var CACHE_SCHEMA = "hfgif-v1";
6620
6674
  function splitUrlSuffix(src) {
@@ -6649,14 +6703,15 @@ function resolveLocalImageSourcePath(src, options) {
6649
6703
  const { basePath } = splitUrlSuffix(trimmed);
6650
6704
  const normalizedBase = normalizeRelPath(basePath);
6651
6705
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
6652
- if (mapped && existsSync10(mapped)) return mapped;
6706
+ if (mapped && existsSync9(mapped)) return mapped;
6653
6707
  if (isHttpUrl(trimmed)) return null;
6708
+ const protocolRelativeUrlOnShare = basePath.startsWith("/") && namesAnotherNetworkRoot(options.projectDir, basePath);
6654
6709
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
6655
6710
  const candidates = [
6656
- isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
6711
+ ...protocolRelativeUrlOnShare ? [] : [isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative)],
6657
6712
  resolve5(options.downloadDir, normalizedBase)
6658
6713
  ];
6659
- return candidates.find((candidate) => existsSync10(candidate)) ?? null;
6714
+ return candidates.find((candidate) => existsSync9(candidate)) ?? null;
6660
6715
  }
6661
6716
  function isUsableFile(path) {
6662
6717
  try {
@@ -6767,10 +6822,10 @@ async function runAnimatedGifTranscode(request) {
6767
6822
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
6768
6823
  }
6769
6824
  async function ensurePreparedWebm(input) {
6770
- if (!existsSync10(dirname6(input.cachePath))) {
6825
+ if (!existsSync9(dirname6(input.cachePath))) {
6771
6826
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
6772
6827
  }
6773
- if (!existsSync10(dirname6(input.outputPath))) {
6828
+ if (!existsSync9(dirname6(input.outputPath))) {
6774
6829
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
6775
6830
  }
6776
6831
  if (!isUsableFile(input.cachePath)) {
@@ -7245,7 +7300,7 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7245
7300
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7246
7301
 
7247
7302
  // src/services/assetMediaType.ts
7248
- import { existsSync as existsSync11 } from "node:fs";
7303
+ import { existsSync as existsSync10 } from "node:fs";
7249
7304
  import {
7250
7305
  fingerprintElementId,
7251
7306
  isNotMediaPayload,
@@ -7318,7 +7373,7 @@ async function preflightCompositionAssetMediaTypes(input) {
7318
7373
  input.projectDir,
7319
7374
  input.compiledDir
7320
7375
  );
7321
- if (!existsSync11(resolvedPath)) continue;
7376
+ if (!existsSync10(resolvedPath)) continue;
7322
7377
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
7323
7378
  }
7324
7379
  const mismatches = [];
@@ -7358,7 +7413,7 @@ async function preflightCompositionAssetMediaTypes(input) {
7358
7413
 
7359
7414
  // src/services/htmlCompiler.ts
7360
7415
  function logRemoteDownloadTelemetry(event) {
7361
- defaultLogger.info("[Compiler] Remote asset download integrity", { ...event });
7416
+ defaultLogger.debug("[Compiler] Remote asset download integrity", { ...event });
7362
7417
  }
7363
7418
  var INFERRED_MEDIA_DURATION_ATTR = "data-hf-inferred-duration";
7364
7419
  function parseSubCompHtmlForValidity(html) {
@@ -7572,7 +7627,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
7572
7627
  let filePath = src;
7573
7628
  if (isHttpUrl(src)) {
7574
7629
  const remoteDir = join18(downloadDir, REMOTE_MEDIA_SUBDIR);
7575
- if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7630
+ if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7576
7631
  try {
7577
7632
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
7578
7633
  onTelemetry: logRemoteDownloadTelemetry
@@ -7581,11 +7636,14 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
7581
7636
  return { duration: null, resolvedPath: src };
7582
7637
  }
7583
7638
  } else {
7584
- filePath = decodedUrlPath2(src);
7639
+ filePath = decodedUrlPath(src);
7585
7640
  if (!filePath.startsWith("/")) filePath = join18(baseDir, filePath);
7586
7641
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
7642
+ if (!isHttpUrl(filePath) && namesAnotherNetworkRoot2(baseDir, filePath)) {
7643
+ return { duration: null, resolvedPath: filePath };
7644
+ }
7587
7645
  }
7588
- if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
7646
+ if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
7589
7647
  return { duration: null, resolvedPath: filePath };
7590
7648
  }
7591
7649
  const withSrcContext = (error) => {
@@ -7934,7 +7992,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
7934
7992
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
7935
7993
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
7936
7994
  // against its own directory, project-root refs stay as authored.
7937
- assetExists: (path) => existsSync12(resolve7(projectDir, path)),
7995
+ assetExists: (path) => existsSync11(resolve7(projectDir, path)),
7938
7996
  // Preserve the authored root wrapper as a child of the host, matching
7939
7997
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
7940
7998
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8110,7 +8168,7 @@ ${safeText}
8110
8168
  //# sourceURL=${new URL(src).href}
8111
8169
  `;
8112
8170
  el.replaceWith(inlineScript);
8113
- defaultLogger.info(`[Compiler] Inlined CDN script: ${src}`);
8171
+ defaultLogger.debug(`[Compiler] Inlined CDN script: ${src}`);
8114
8172
  } else {
8115
8173
  if (download.reason instanceof ScriptIntegrityError) throw download.reason;
8116
8174
  defaultLogger.warn(
@@ -8130,7 +8188,7 @@ function collectExternalAssets(html, projectDir) {
8130
8188
  if (isPathInside2(absPath, absProjectDir)) {
8131
8189
  return null;
8132
8190
  }
8133
- if (!existsSync12(absPath)) return null;
8191
+ if (!existsSync11(absPath)) return null;
8134
8192
  const safeKey = toExternalAssetKey(absPath);
8135
8193
  externalAssets.set(safeKey, absPath);
8136
8194
  return safeKey;
@@ -8165,7 +8223,7 @@ function collectExternalAssets(html, projectDir) {
8165
8223
  if (rewritten !== style) el.setAttribute("style", rewritten);
8166
8224
  }
8167
8225
  if (externalAssets.size > 0) {
8168
- defaultLogger.info(
8226
+ defaultLogger.debug(
8169
8227
  `[Compiler] Found ${externalAssets.size} asset(s) outside project directory, will copy to render output`
8170
8228
  );
8171
8229
  }
@@ -8180,7 +8238,7 @@ var REMOTE_SOURCE_TAG_RE = /<source\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+)["
8180
8238
  var REMOTE_IMG_TAG_RE = /<img\b[^>]*?(?<![\w-])src\s*=\s*["'](https?:\/\/[^"']+)["'][^>]*>/gi;
8181
8239
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
8182
8240
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
8183
- if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8241
+ if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8184
8242
  const urlToLocal = /* @__PURE__ */ new Map();
8185
8243
  await Promise.all(
8186
8244
  [...urlSet].map(async (url) => {
@@ -8212,7 +8270,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
8212
8270
  result = result.replaceAll(`"${url}"`, `"${relPath}"`).replaceAll(`'${url}'`, `'${relPath}'`);
8213
8271
  if (extraRewrite) result = extraRewrite(result, url, relPath);
8214
8272
  }
8215
- defaultLogger.info(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
8273
+ defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
8216
8274
  return { html: result, remoteMediaAssets };
8217
8275
  }
8218
8276
  async function localizeRemoteMediaSources(html, downloadDir) {
@@ -8349,7 +8407,7 @@ async function inlineExternalFontStylesheets(html) {
8349
8407
  ${fontFaceBlocks.join("\n")}
8350
8408
  </style>`;
8351
8409
  result = result.replace(fullMatch, inlineStyle);
8352
- defaultLogger.info("[Compiler] Inlined external @font-face rule(s)", {
8410
+ defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
8353
8411
  count: fontFaceBlocks.length,
8354
8412
  urlFingerprint: identity.urlFingerprint,
8355
8413
  host: identity.host
@@ -8362,14 +8420,14 @@ function projectStylesheetFontFamilies(html, projectDir) {
8362
8420
  for (const [tag] of html.matchAll(/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi)) {
8363
8421
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
8364
8422
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
8365
- const sheet = resolve7(projectDir, decodedUrlPath2(href).replace(/^(?:\.?\/)+/, ""));
8366
- if (!isPathInside2(sheet, projectDir) || !existsSync12(sheet)) continue;
8423
+ const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
8424
+ if (!isPathInside2(sheet, projectDir) || !existsSync11(sheet)) continue;
8367
8425
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
8368
8426
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
8369
8427
  const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
8370
- const path = decodedUrlPath2(url);
8428
+ const path = decodedUrlPath(url);
8371
8429
  const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname8(sheet), path);
8372
- return isPathInside2(file, projectDir) && existsSync12(file);
8430
+ return isPathInside2(file, projectDir) && existsSync11(file);
8373
8431
  });
8374
8432
  if (family && shipsFile) families.push(family);
8375
8433
  }
@@ -8471,7 +8529,7 @@ async function embedLocalFontFaces(html, projectDir) {
8471
8529
  const font = await readLocalFont(absPath);
8472
8530
  if (font.kind === "file-backed") {
8473
8531
  fileBackedAbsolutePaths.add(absPath);
8474
- defaultLogger.info(
8532
+ defaultLogger.debug(
8475
8533
  `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
8476
8534
  );
8477
8535
  embeddedPaths.add(localPath);
@@ -8479,7 +8537,7 @@ async function embedLocalFontFaces(html, projectDir) {
8479
8537
  }
8480
8538
  dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
8481
8539
  dataUriByAbsolutePath.set(absPath, dataUri);
8482
- defaultLogger.info(
8540
+ defaultLogger.debug(
8483
8541
  `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
8484
8542
  );
8485
8543
  }
@@ -8507,14 +8565,17 @@ function renderGsapDist() {
8507
8565
  }
8508
8566
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
8509
8567
  let gsapDist;
8510
- const exists = (path) => existsSync12(resolve7(projectDir, path));
8568
+ const exists = (path) => {
8569
+ const file = resolve7(projectDir, path);
8570
+ return !namesAnotherNetworkRoot2(projectDir, file) && existsSync11(file);
8571
+ };
8511
8572
  return html.replace(
8512
8573
  /(<script\b[^>]*\bsrc=["'])([^"']*gsap[^"']*\/dist\/([^"']+))(["'][^>]*>)/gi,
8513
8574
  (full, prefix, src, file, suffix) => {
8514
8575
  if (/^https?:\/\//i.test(src)) return full;
8515
8576
  if (exists(compSrcPath ? rewriteAssetPath(compSrcPath, src, exists) : src)) return full;
8516
8577
  gsapDist ??= renderGsapDist();
8517
- defaultLogger.info(`[Compiler] Rewriting missing gsap script: ${src} \u2192 ${gsapDist}${file}`);
8578
+ defaultLogger.debug(`[Compiler] Rewriting missing gsap script: ${src} \u2192 ${gsapDist}${file}`);
8518
8579
  return `${prefix}${gsapDist}${file}${suffix}`;
8519
8580
  }
8520
8581
  );
@@ -8524,7 +8585,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
8524
8585
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
8525
8586
  if (!entryPath.includes("/")) return html;
8526
8587
  const { document: document2 } = parseHTML5(html);
8527
- const assetExists = (path) => existsSync12(resolve7(projectDir, path));
8588
+ const assetExists = (path) => existsSync11(resolve7(projectDir, path));
8528
8589
  rewriteAssetPaths(
8529
8590
  document2.querySelectorAll("[src], [href], [srcset]"),
8530
8591
  entryPath,
@@ -8544,11 +8605,29 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
8544
8605
  }
8545
8606
  return document2.toString();
8546
8607
  }
8608
+ function bindVariableMediaSources(html, variables) {
8609
+ if (!html.includes("data-var-src")) return html;
8610
+ const { document: document2 } = parseHTML5(html);
8611
+ const declared = {};
8612
+ for (const el of document2.querySelectorAll("[data-composition-variables]")) {
8613
+ Object.assign(declared, readDeclaredDefaults(el));
8614
+ }
8615
+ const values = { ...declared, ...variables };
8616
+ let changed = false;
8617
+ for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
8618
+ if (el.closest("[data-variable-values]")) continue;
8619
+ const src = boundMediaSrc(el, values);
8620
+ if (src === null || el.getAttribute("src") === src) continue;
8621
+ el.setAttribute("src", src);
8622
+ changed = true;
8623
+ }
8624
+ return changed ? document2.toString() : html;
8625
+ }
8547
8626
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
8548
8627
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
8549
- const rawHtml = normalizeCompositionSrcs(
8550
- rewriteUnresolvableGsapToCdn(entryHtml, projectDir),
8551
- projectDir
8628
+ const rawHtml = bindVariableMediaSources(
8629
+ normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
8630
+ options.variables ?? {}
8552
8631
  );
8553
8632
  assertSubCompositionsUsable(rawHtml, projectDir);
8554
8633
  const probes = /* @__PURE__ */ new Map();
@@ -8632,7 +8711,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
8632
8711
  timeoutMs: options.ffmpegProcessTimeout
8633
8712
  });
8634
8713
  if (preparedHeifImages.length > 0) {
8635
- defaultLogger.info(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
8714
+ defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
8636
8715
  }
8637
8716
  const gifSourceAssets = new Map(remoteImageAssets);
8638
8717
  const {
@@ -8647,7 +8726,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
8647
8726
  timeoutMs: options.ffmpegProcessTimeout
8648
8727
  });
8649
8728
  if (preparedGifs.length > 0) {
8650
- defaultLogger.info(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
8729
+ defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
8651
8730
  }
8652
8731
  const embeddedHtml = await embedLocalFontFaces(htmlWithPreparedGifs, projectDir);
8653
8732
  const { html, externalAssets } = collectExternalAssets(embeddedHtml, projectDir);
@@ -8675,7 +8754,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
8675
8754
  for (const video of videos) {
8676
8755
  if (isHttpUrl(video.src)) continue;
8677
8756
  const videoPath = resolve7(projectDir, video.src);
8678
- if (advised.has(videoPath)) continue;
8757
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath)) continue;
8679
8758
  advised.add(videoPath);
8680
8759
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
8681
8760
  (async () => {
@@ -9094,7 +9173,7 @@ function resolveEntryHtmlPath(input) {
9094
9173
  const rawEntry = readTextFile2(htmlPath);
9095
9174
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
9096
9175
  const projectIndexPath = join19(projectDir, "index.html");
9097
- if (!existsSync13(projectIndexPath)) {
9176
+ if (!existsSync12(projectIndexPath)) {
9098
9177
  throw new Error(
9099
9178
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
9100
9179
  );
@@ -9114,6 +9193,14 @@ function resolveEntryHtmlPath(input) {
9114
9193
  log.info("Extracted standalone entry from index.html host context", { entryFile });
9115
9194
  return wrapperPath;
9116
9195
  }
9196
+ function applyChroma444Gate(cfg, chromaSubsampling, gate, log) {
9197
+ if (!cfg.useDrawElement || chromaSubsampling !== "444") return gate;
9198
+ cfg.useDrawElement = false;
9199
+ log.info(
9200
+ "[Render] Fast capture: chromaSubsampling 444 captures lossless PNG frames, so disabling drawElementImage for this render. Capture uses the platform's baseline route."
9201
+ );
9202
+ return "chroma_444";
9203
+ }
9117
9204
  async function runCompileStage(input) {
9118
9205
  const {
9119
9206
  projectDir,
@@ -9165,6 +9252,7 @@ async function runCompileStage(input) {
9165
9252
  "[Render] Fast capture: composition uses shader transitions, so disabling drawElementImage so page-side compositing stays available."
9166
9253
  );
9167
9254
  }
9255
+ deCompileGate = applyChroma444Gate(cfg, job.config.chromaSubsampling, deCompileGate, log);
9168
9256
  if (!cfg.useDrawElement && cfg.pageSideCompositingAutoDisabled) {
9169
9257
  cfg.enablePageSideCompositing = true;
9170
9258
  cfg.pageSideCompositingAutoDisabled = false;
@@ -9276,11 +9364,19 @@ function isActionableProbeFailure(line) {
9276
9364
 
9277
9365
  // src/services/render/captureImageFormat.ts
9278
9366
  function resolveCaptureImageFormat(input) {
9279
- return input.needsAlpha || input.motionBlur ? "png" : "jpeg";
9367
+ return input.needsAlpha || input.motionBlur || input.chromaSubsampling === "444" ? "png" : "jpeg";
9280
9368
  }
9281
9369
  function resolveCaptureJpegQuality(quality) {
9282
9370
  return quality === "draft" ? 80 : 100;
9283
9371
  }
9372
+ function resolveCaptureSurface(input, quality) {
9373
+ const format = resolveCaptureImageFormat(input);
9374
+ return {
9375
+ format,
9376
+ quality: format === "png" ? void 0 : resolveCaptureJpegQuality(quality),
9377
+ transparent: input.needsAlpha
9378
+ };
9379
+ }
9284
9380
 
9285
9381
  // src/services/render/stages/probeStage.ts
9286
9382
  var FRAME_BOUNDARY_EPSILON = 1e-3;
@@ -9410,7 +9506,8 @@ async function runProbeStage(input) {
9410
9506
  height,
9411
9507
  needsAlpha,
9412
9508
  deviceScaleFactor,
9413
- subTimelineWaitMemo
9509
+ subTimelineWaitMemo,
9510
+ staticDedupMemo
9414
9511
  } = input;
9415
9512
  let { compiled } = input;
9416
9513
  const probeCfg = cfg.forceScreenshot === forceScreenshot ? cfg : { ...cfg, forceScreenshot };
@@ -9457,21 +9554,25 @@ async function runProbeStage(input) {
9457
9554
  });
9458
9555
  assertNotAborted();
9459
9556
  const motionBlur = job.config.motionBlur;
9460
- const captureFormat = resolveCaptureImageFormat({ needsAlpha, motionBlur });
9461
9557
  const captureOpts = {
9462
9558
  recordReferenceBackground: input.recordReferenceBackground,
9463
9559
  width,
9464
9560
  height,
9465
9561
  fps: job.config.fps,
9466
- format: captureFormat,
9467
- transparent: needsAlpha,
9468
- quality: captureFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
9562
+ ...resolveCaptureSurface(
9563
+ { needsAlpha, motionBlur, chromaSubsampling: job.config.chromaSubsampling },
9564
+ job.config.quality
9565
+ ),
9469
9566
  variables: job.config.variables,
9470
9567
  deviceScaleFactor,
9471
9568
  motionBlur,
9472
9569
  pageMotionBlur: job.config.pageMotionBlur,
9473
9570
  requiresWebGpu: compositionRequiresWebGpu(compiled.html),
9474
- subTimelineWaitMemo
9571
+ subTimelineWaitMemo,
9572
+ staticDedupMemo,
9573
+ compositionHash: computeCompositionObservabilityHash(compiled.html),
9574
+ deferStaticDedup: true,
9575
+ onStaticDedupActivity: () => noteStaticDedupActivity(job)
9475
9576
  };
9476
9577
  const PROBE_MAX_ATTEMPTS = 2;
9477
9578
  for (let attempt = 1; attempt <= PROBE_MAX_ATTEMPTS; attempt++) {
@@ -9960,7 +10061,7 @@ function validateDistributedDuration(input) {
9960
10061
  }
9961
10062
 
9962
10063
  // src/services/render/stages/extractVideosStage.ts
9963
- import { existsSync as existsSync14 } from "node:fs";
10064
+ import { existsSync as existsSync13 } from "node:fs";
9964
10065
  import { join as join21 } from "node:path";
9965
10066
  import {
9966
10067
  classifyVideoExtractionError,
@@ -10235,7 +10336,7 @@ async function runExtractVideosStage(input) {
10235
10336
  const probeFailures = await Promise.all(
10236
10337
  composition.videos.map(async (v) => {
10237
10338
  const videoPath = resolveProjectRelativeSrc3(v.src, projectDir, compiledDir);
10238
- if (!existsSync14(videoPath)) return null;
10339
+ if (!existsSync13(videoPath)) return null;
10239
10340
  try {
10240
10341
  const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata3(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata3(videoPath), {
10241
10342
  signal: abortSignal,
@@ -10273,7 +10374,7 @@ async function runExtractVideosStage(input) {
10273
10374
  const probed = await Promise.all(
10274
10375
  composition.images.map(async (img) => {
10275
10376
  const imgPath = resolveProjectRelativeSrc3(img.src, projectDir, compiledDir);
10276
- if (!existsSync14(imgPath)) return null;
10377
+ if (!existsSync13(imgPath)) return null;
10277
10378
  const colorSpace = await probeColorSpaceSafely(imgPath, log);
10278
10379
  if (isHdrColorSpace2(colorSpace)) {
10279
10380
  nativeHdrImageIds.add(img.id);
@@ -10393,7 +10494,7 @@ async function appendVideoAudioFromProbe(input) {
10393
10494
  videos.map(async (video) => {
10394
10495
  const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc3(video.src, projectDir, compiledDir);
10395
10496
  const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
10396
- if (!isHttpUrl2(readFrom) && !existsSync14(readFrom)) return null;
10497
+ if (!isHttpUrl2(readFrom) && !existsSync13(readFrom)) return null;
10397
10498
  const metadata = await extractMediaMetadata3(readFrom);
10398
10499
  const window2 = await resolveFinalFrameExtractionWindow2(
10399
10500
  readFrom,
@@ -10413,7 +10514,7 @@ async function appendVideoAudioFromProbe(input) {
10413
10514
  }
10414
10515
 
10415
10516
  // src/services/render/videoLayerPassthroughPlan.ts
10416
- import { existsSync as existsSync15 } from "node:fs";
10517
+ import { existsSync as existsSync14 } from "node:fs";
10417
10518
  import {
10418
10519
  buildVideoLayerInput,
10419
10520
  isHttpUrl as isHttpUrl3,
@@ -10481,7 +10582,7 @@ async function planVideoLayerPassthrough(input) {
10481
10582
  const { video } = q;
10482
10583
  if (isHttpUrl3(video.src)) return { reason: "remote_source" };
10483
10584
  const path = resolveProjectRelativeSrc4(video.src, input.projectDir, input.compiledDir);
10484
- if (!existsSync15(path)) return { reason: "source_missing" };
10585
+ if (!existsSync14(path)) return { reason: "source_missing" };
10485
10586
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
10486
10587
  if ("reason" in layout) return layout;
10487
10588
  const layer = await buildVideoLayerInput(
@@ -10496,7 +10597,7 @@ async function planVideoLayerPassthrough(input) {
10496
10597
  }
10497
10598
 
10498
10599
  // src/services/render/stages/audioStage.ts
10499
- import { existsSync as existsSync17 } from "node:fs";
10600
+ import { existsSync as existsSync16 } from "node:fs";
10500
10601
  import { join as join24 } from "node:path";
10501
10602
  import {
10502
10603
  MIXED_AUDIO_FILENAME,
@@ -10507,7 +10608,7 @@ import {
10507
10608
  } from "@hyperframes/engine";
10508
10609
 
10509
10610
  // src/services/render/audioDeliveryLimit.ts
10510
- import { existsSync as existsSync16 } from "node:fs";
10611
+ import { existsSync as existsSync15 } from "node:fs";
10511
10612
  import { dirname as dirname10, join as join23 } from "node:path";
10512
10613
  import {
10513
10614
  applyAudioFxChain,
@@ -11016,7 +11117,7 @@ async function limitDeliveryPeaks(input, deps = {
11016
11117
  applyChain: applyAudioFxChain,
11017
11118
  encode: encodeAac2,
11018
11119
  rename: renameWithRetry6,
11019
- sourceExists: existsSync16
11120
+ sourceExists: existsSync15
11020
11121
  }) {
11021
11122
  const { audioPath, sourcePath, signal, timeoutMs } = input;
11022
11123
  if (!deps.sourceExists(sourcePath)) return { success: true };
@@ -11111,7 +11212,7 @@ async function runAudioStageScoped(input) {
11111
11212
  );
11112
11213
  audioLoweredDb = guard.loweredDb;
11113
11214
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
11114
- if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
11215
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
11115
11216
  deliverySourcePath = pcmSourcePath;
11116
11217
  }
11117
11218
  }
@@ -11239,7 +11340,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11239
11340
  }
11240
11341
 
11241
11342
  // src/services/render/stages/captureStage.ts
11242
- import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11343
+ import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11243
11344
  import { join as join25 } from "node:path";
11244
11345
  import {
11245
11346
  classifyCaptureFailure as classifyCaptureFailure2,
@@ -11310,7 +11411,7 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
11310
11411
  }
11311
11412
  function measureCaptureFrameBytes(workDir, framesDir) {
11312
11413
  let total = sampleDirectoryBytes(framesDir);
11313
- if (!existsSync18(workDir)) return total;
11414
+ if (!existsSync17(workDir)) return total;
11314
11415
  for (const attempt of readdirSync4(workDir)) {
11315
11416
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
11316
11417
  total += sampleDirectoryBytes(join25(workDir, attempt));
@@ -11492,7 +11593,7 @@ async function runSequentialDiskCapture(input, captureOptions, captureCfg, check
11492
11593
  captureBeyondViewport = session.options.captureBeyondViewport;
11493
11594
  try {
11494
11595
  if (probeSession) {
11495
- prepareCaptureSessionForReuse3(session, framesDir, videoInjector);
11596
+ await prepareCaptureSessionForReuse3(session, framesDir, videoInjector);
11496
11597
  probeSession = null;
11497
11598
  }
11498
11599
  await ensureSessionReady(session, {
@@ -11617,7 +11718,7 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
11617
11718
  }
11618
11719
 
11619
11720
  // src/services/render/stages/captureHdrStage.ts
11620
- import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
11721
+ import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
11621
11722
  import { join as join29 } from "node:path";
11622
11723
  import {
11623
11724
  closeCaptureSession as closeCaptureSession7,
@@ -11863,7 +11964,7 @@ import { Worker } from "node:worker_threads";
11863
11964
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
11864
11965
  import { dirname as dirname11, join as join27 } from "node:path";
11865
11966
  import { createRequire } from "node:module";
11866
- import { existsSync as existsSync19 } from "node:fs";
11967
+ import { existsSync as existsSync18 } from "node:fs";
11867
11968
  import { cpus as cpus2 } from "node:os";
11868
11969
  function resolveWorkerEntry(explicit) {
11869
11970
  if (explicit && explicit.length > 0) {
@@ -11876,7 +11977,7 @@ function resolveWorkerEntry(explicit) {
11876
11977
  }
11877
11978
  const moduleDir = dirname11(fileURLToPath3(import.meta.url));
11878
11979
  const jsPath = join27(moduleDir, "shaderTransitionWorker.js");
11879
- if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
11980
+ if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
11880
11981
  const tsPath = join27(moduleDir, "shaderTransitionWorker.ts");
11881
11982
  return { path: tsPath, isTs: true };
11882
11983
  }
@@ -12437,7 +12538,7 @@ async function runCaptureHdrStage(input) {
12437
12538
  }
12438
12539
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
12439
12540
  const debugDumpDir = debugDumpEnabled ? join29(framesDir, "debug-composite") : null;
12440
- if (debugDumpDir && !existsSync20(debugDumpDir)) {
12541
+ if (debugDumpDir && !existsSync19(debugDumpDir)) {
12441
12542
  mkdirSync10(debugDumpDir, { recursive: true });
12442
12543
  }
12443
12544
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -12594,7 +12695,7 @@ async function runCaptureHdrStage(input) {
12594
12695
  // src/services/render/stages/encodeStage.ts
12595
12696
  import {
12596
12697
  copyFileSync as copyFileSync4,
12597
- existsSync as existsSync21,
12698
+ existsSync as existsSync20,
12598
12699
  mkdirSync as mkdirSync11,
12599
12700
  readdirSync as readdirSync5,
12600
12701
  readFileSync as readFileSync9,
@@ -12728,7 +12829,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
12728
12829
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
12729
12830
  if (failure) return failure;
12730
12831
  }
12731
- const fileSize = existsSync21(outputPath) ? statSync8(outputPath).size : 0;
12832
+ const fileSize = existsSync20(outputPath) ? statSync8(outputPath).size : 0;
12732
12833
  return {
12733
12834
  success: true,
12734
12835
  outputPath,
@@ -12889,7 +12990,7 @@ async function runEncodeStage(input) {
12889
12990
  const stage5Start = Date.now();
12890
12991
  if (isPngSequence) {
12891
12992
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
12892
- if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
12993
+ if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
12893
12994
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
12894
12995
  if (captured.length === 0) {
12895
12996
  throw new Error(
@@ -12900,7 +13001,7 @@ async function runEncodeStage(input) {
12900
13001
  const dst = join30(outputPath, formatExportFrameName(i, "png"));
12901
13002
  copyFileSync4(join30(framesDir, name), dst);
12902
13003
  });
12903
- if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
13004
+ if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
12904
13005
  copyFileSync4(audioOutputPath, join30(outputPath, MIXED_AUDIO_FILENAME2));
12905
13006
  log.info(
12906
13007
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
@@ -13289,7 +13390,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
13289
13390
  let rangeStart = null;
13290
13391
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13291
13392
  const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13292
- const missing = !existsSync22(framePath) || statSync9(framePath).size <= 8;
13393
+ const missing = !existsSync21(framePath) || statSync9(framePath).size <= 8;
13293
13394
  if (missing && rangeStart === null) {
13294
13395
  rangeStart = frameIndex;
13295
13396
  } else if (!missing && rangeStart !== null) {
@@ -13379,17 +13480,25 @@ function resetCaptureAttemptProgress(job) {
13379
13480
  job.framesRendered = 0;
13380
13481
  }
13381
13482
  var FIRST_FRAME_STALL_MS = 3e5;
13483
+ var FIRST_FRAME_STARTUP_FACTOR = 2;
13484
+ var FIRST_FRAME_STALL_CEILING_MS = 9e5;
13382
13485
  var TAIL_STALL_MS = FIRST_FRAME_STALL_MS;
13383
- function frameStallRule(job, totalFrames) {
13486
+ function firstFrameWindowMs(probeStartupMs) {
13487
+ const fromStartup = (probeStartupMs ?? 0) * FIRST_FRAME_STARTUP_FACTOR;
13488
+ if (!Number.isFinite(fromStartup)) return FIRST_FRAME_STALL_MS;
13489
+ return Math.max(FIRST_FRAME_STALL_MS, Math.min(FIRST_FRAME_STALL_CEILING_MS, fromStartup));
13490
+ }
13491
+ function frameStallRule(job, totalFrames, probeStartupMs) {
13384
13492
  const noProgressMs = resolveCaptureStallTimeoutMs();
13385
13493
  return {
13386
13494
  progress: () => job.framesRendered ?? 0,
13387
13495
  noProgressMs,
13388
- firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
13496
+ firstProgressMs: Math.max(firstFrameWindowMs(probeStartupMs), noProgressMs),
13389
13497
  complete: () => (job.framesRendered ?? 0) >= totalFrames,
13390
13498
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
13391
13499
  detail: () => describeWorkerPhases(job),
13392
- attemptOpened: () => forgetWorkerPhases(job)
13500
+ attemptOpened: () => forgetWorkerPhases(job),
13501
+ activity: () => staticDedupActivity(job)
13393
13502
  };
13394
13503
  }
13395
13504
  function isRecoverableParallelCaptureError(error) {
@@ -13414,7 +13523,7 @@ function countCapturedFrames(totalFrames, framesDir, frameExt) {
13414
13523
  let captured = 0;
13415
13524
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13416
13525
  const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13417
- if (existsSync22(framePath)) captured++;
13526
+ if (existsSync21(framePath)) captured++;
13418
13527
  }
13419
13528
  return captured;
13420
13529
  }
@@ -14077,9 +14186,10 @@ function resolveRenderDebugDir() {
14077
14186
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
14078
14187
  validateHlsRenderConfig(job.config);
14079
14188
  validateDeliveryEncoderConfig(job.config);
14189
+ validateChromaSubsamplingConfig(job.config);
14080
14190
  const debugDir = resolveRenderDebugDir();
14081
14191
  const outputDir = dirname13(outputPath);
14082
- if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
14192
+ if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
14083
14193
  const workDir = job.config.debug ? join31(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14084
14194
  const pipelineStart = Date.now();
14085
14195
  const baseLog = job.config.logger ?? defaultLogger;
@@ -14221,7 +14331,7 @@ async function executeRenderPipeline(input) {
14221
14331
  job.startedAt = /* @__PURE__ */ new Date();
14222
14332
  assertNotAborted();
14223
14333
  assertConfiguredFfmpegBinariesExist();
14224
- if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
14334
+ if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
14225
14335
  if (job.config.debug) {
14226
14336
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
14227
14337
  }
@@ -14251,7 +14361,7 @@ async function executeRenderPipeline(input) {
14251
14361
  });
14252
14362
  const entryFile = job.config.entryFile || "index.html";
14253
14363
  const htmlPath = join31(projectDir, entryFile);
14254
- if (!existsSync22(htmlPath)) {
14364
+ if (!existsSync21(htmlPath)) {
14255
14365
  throw new Error(`Entry file not found: ${htmlPath}`);
14256
14366
  }
14257
14367
  assertNotAborted();
@@ -14343,6 +14453,7 @@ async function executeRenderPipeline(input) {
14343
14453
  (result) => Object.assign(job, result)
14344
14454
  );
14345
14455
  const subTimelineWaitMemo = {};
14456
+ const staticDedupMemo = {};
14346
14457
  const probeResult = await observeRenderStage(
14347
14458
  observability,
14348
14459
  "browser_probe",
@@ -14363,6 +14474,7 @@ async function executeRenderPipeline(input) {
14363
14474
  needsAlpha,
14364
14475
  deviceScaleFactor,
14365
14476
  subTimelineWaitMemo,
14477
+ staticDedupMemo,
14366
14478
  recordReferenceBackground
14367
14479
  }),
14368
14480
  // Browser probe is pre-capture; report `browser calibrating` so a
@@ -14595,7 +14707,7 @@ async function executeRenderPipeline(input) {
14595
14707
  throw new Error("File server failed to initialize before frame capture");
14596
14708
  }
14597
14709
  const framesDir = join31(workDir, "captured-frames");
14598
- if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
14710
+ if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
14599
14711
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
14600
14712
  code: "start_browsers"
14601
14713
  });
@@ -14614,18 +14726,28 @@ async function executeRenderPipeline(input) {
14614
14726
  forceScreenshot: captureForceScreenshot
14615
14727
  });
14616
14728
  const videoCaptureBeyondViewport = resolveVideoCaptureBeyondViewport(composition.videos.length);
14617
- const captureImageFormat = resolveCaptureImageFormat({
14618
- needsAlpha,
14619
- motionBlur: job.config.motionBlur
14620
- });
14729
+ const captureSurface = resolveCaptureSurface(
14730
+ {
14731
+ needsAlpha,
14732
+ motionBlur: job.config.motionBlur,
14733
+ chromaSubsampling: job.config.chromaSubsampling
14734
+ },
14735
+ job.config.quality
14736
+ );
14737
+ if (job.config.chromaSubsampling === "444") {
14738
+ log.info("[Render] Capture: png (chromaSubsampling 444, lossless)");
14739
+ }
14621
14740
  const captureOptions = {
14622
14741
  width,
14623
14742
  height,
14624
14743
  fps: job.config.fps,
14625
- format: videoLayer ? "png" : captureImageFormat,
14626
- transparent: needsAlpha || videoLayer !== void 0,
14627
- ...videoLayer ? { hiddenElementIds: [videoLayer.videoId] } : {},
14628
- quality: captureImageFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
14744
+ ...captureSurface,
14745
+ ...videoLayer ? {
14746
+ format: "png",
14747
+ quality: void 0,
14748
+ transparent: true,
14749
+ hiddenElementIds: [videoLayer.videoId]
14750
+ } : {},
14629
14751
  variables: job.config.variables,
14630
14752
  deviceScaleFactor,
14631
14753
  motionBlur: job.config.motionBlur,
@@ -14644,6 +14766,9 @@ async function executeRenderPipeline(input) {
14644
14766
  videoMetadataHints,
14645
14767
  skipReadinessVideoIds: videoReadinessSkipIds,
14646
14768
  subTimelineWaitMemo,
14769
+ staticDedupMemo,
14770
+ compositionHash,
14771
+ onStaticDedupActivity: () => noteStaticDedupActivity(job),
14647
14772
  // Probe-resolved duration: drawElement self-verification derives its
14648
14773
  // sample frame indices from this so they land inside the drained range.
14649
14774
  compositionDurationSeconds: job.duration,
@@ -14732,6 +14857,7 @@ async function executeRenderPipeline(input) {
14732
14857
  );
14733
14858
  const nativeHdrIds = /* @__PURE__ */ new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
14734
14859
  const hasHdrContent = Boolean(effectiveHdr && nativeHdrIds.size > 0);
14860
+ assertChromaSubsamplingSdr(job.config, hasHdrContent);
14735
14861
  if (hasHdrContent) assertOutputScaleSupported(deviceScaleFactor, "hdr_layered");
14736
14862
  routePageMotionBlur = pageMotionBlurForRoute({ hasHdrContent, useLayeredComposite: false });
14737
14863
  const deSingleMinFrames = resolveDeSingleMinFrames(process.env);
@@ -15314,7 +15440,9 @@ async function executeRenderPipeline(input) {
15314
15440
  usePageSideCompositing: capturePlan.usePageSideCompositing,
15315
15441
  hasHdrContent: capturePlan.hasHdrContent,
15316
15442
  hasShaderTransitions: compiled.hasShaderTransitions,
15317
- isPngSequence
15443
+ isPngSequence,
15444
+ captureImageFormat: captureOptions.format ?? "jpeg",
15445
+ chromaSubsampling: job.config.chromaSubsampling ?? "420"
15318
15446
  });
15319
15447
  const encoderHdr = hasHdrContent ? effectiveHdr : void 0;
15320
15448
  const presetFormat = outputFormat === "webm" || outputFormat === "mov" ? outputFormat : "mp4";
@@ -15322,7 +15450,8 @@ async function executeRenderPipeline(input) {
15322
15450
  job.config.quality,
15323
15451
  presetFormat,
15324
15452
  encoderHdr,
15325
- job.config.proresProfile
15453
+ job.config.proresProfile,
15454
+ job.config.chromaSubsampling
15326
15455
  );
15327
15456
  if (job.config.crf != null && job.config.videoBitrate) {
15328
15457
  log.warn(
@@ -15404,7 +15533,7 @@ async function executeRenderPipeline(input) {
15404
15533
  onProgress
15405
15534
  });
15406
15535
  },
15407
- { stall: frameStallRule(job, totalFrames) }
15536
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15408
15537
  );
15409
15538
  lastBrowserConsole = hdrRes.lastBrowserConsole;
15410
15539
  layeredCaptureWarnings.push(...hdrRes.warnings);
@@ -15856,7 +15985,7 @@ async function executeRenderPipeline(input) {
15856
15985
  interleaveFrames: overlap !== null,
15857
15986
  openAttempt
15858
15987
  }),
15859
- { stall: frameStallRule(job, totalFrames) }
15988
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15860
15989
  );
15861
15990
  let captureRes;
15862
15991
  try {
@@ -15986,7 +16115,7 @@ async function executeRenderPipeline(input) {
15986
16115
  })
15987
16116
  );
15988
16117
  const totalElapsed = Date.now() - pipelineStart;
15989
- const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
16118
+ const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
15990
16119
  recordTransientRetryObservability();
15991
16120
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
15992
16121
  const observabilitySummary = observability.summary({
@@ -16067,7 +16196,7 @@ async function executeRenderPipeline(input) {
16067
16196
  }
16068
16197
  }
16069
16198
  if (job.config.debug) {
16070
- if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
16199
+ if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
16071
16200
  const debugOutput = join31(workDir, `output${videoExt}`);
16072
16201
  copyFileSync5(stagedOutputPath, debugOutput);
16073
16202
  }
@@ -16580,7 +16709,7 @@ import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframe
16580
16709
  import {
16581
16710
  copyFileSync as copyFileSync6,
16582
16711
  cpSync as cpSync2,
16583
- existsSync as existsSync27,
16712
+ existsSync as existsSync26,
16584
16713
  linkSync,
16585
16714
  mkdirSync as mkdirSync16,
16586
16715
  rmSync as rmSync14,
@@ -16611,17 +16740,18 @@ import {
16611
16740
  } from "@hyperframes/engine";
16612
16741
 
16613
16742
  // src/services/distributed/chunkFrames.ts
16614
- import { existsSync as existsSync24, readdirSync as readdirSync7 } from "node:fs";
16743
+ import { existsSync as existsSync23, readdirSync as readdirSync7 } from "node:fs";
16615
16744
  import { extname as extname4, join as join34 } from "node:path";
16616
16745
  import {
16617
16746
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
16618
- createVideoFrameInjector as createVideoFrameInjector3
16747
+ createVideoFrameInjector as createVideoFrameInjector3,
16748
+ mediaIdPathSegment as mediaIdPathSegment3
16619
16749
  } from "@hyperframes/engine";
16620
16750
 
16621
16751
  // src/services/distributed/shared.ts
16622
16752
  import { execFile as execFileCallback } from "node:child_process";
16623
16753
  import { dirname as dirname15, join as join33 } from "node:path";
16624
- import { existsSync as existsSync23, readFileSync as readFileSync10 } from "node:fs";
16754
+ import { existsSync as existsSync22, readFileSync as readFileSync10 } from "node:fs";
16625
16755
  import { fileURLToPath as fileURLToPath5 } from "node:url";
16626
16756
  import { promisify as promisify2 } from "node:util";
16627
16757
  import {
@@ -16637,7 +16767,7 @@ function isPlanAudioArtifactPath(path) {
16637
16767
  function resolvePlanAudioPath(planDir) {
16638
16768
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
16639
16769
  const candidate = join33(planDir, name);
16640
- if (existsSync23(candidate)) return candidate;
16770
+ if (existsSync22(candidate)) return candidate;
16641
16771
  }
16642
16772
  return null;
16643
16773
  }
@@ -16898,7 +17028,7 @@ function readProducerVersion() {
16898
17028
  let current = startDir;
16899
17029
  for (let i = 0; i < 10; i++) {
16900
17030
  const candidate = join33(current, "package.json");
16901
- if (existsSync23(candidate)) {
17031
+ if (existsSync22(candidate)) {
16902
17032
  try {
16903
17033
  const pkg = JSON.parse(readFileSync10(candidate, "utf-8"));
16904
17034
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
@@ -16952,8 +17082,8 @@ function frameNumberFromFileName(name) {
16952
17082
  function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v1") {
16953
17083
  const result = [];
16954
17084
  for (const v of videos) {
16955
- const outputDir = join34(planDir, "video-frames", v.videoId);
16956
- if (!existsSync24(outputDir)) {
17085
+ const outputDir = join34(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
17086
+ if (!existsSync23(outputDir)) {
16957
17087
  throw new Error(
16958
17088
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
16959
17089
  );
@@ -17052,7 +17182,7 @@ async function extractDeferredVideoFramesForChunk(input) {
17052
17182
  const range = planned.get(video.videoId).deferredRange;
17053
17183
  const remoteUrl = remoteSources[range.sourcePath];
17054
17184
  const sourcePath = remoteUrl ?? join34(input.planDir, ...range.sourcePath.split("/"));
17055
- if (remoteUrl === void 0 && !existsSync24(sourcePath)) {
17185
+ if (remoteUrl === void 0 && !existsSync23(sourcePath)) {
17056
17186
  throw new RenderChunkValidationError(
17057
17187
  MISSING_PLAN_ARTIFACT,
17058
17188
  `[renderChunk] planDir is missing the source for video ${JSON.stringify(video.videoId)}: ${range.sourcePath}`
@@ -17252,7 +17382,7 @@ async function readPlanReferenceBackground(input) {
17252
17382
  }
17253
17383
 
17254
17384
  // src/services/render/stages/freezePlan.ts
17255
- import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
17385
+ import { existsSync as existsSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
17256
17386
  import { join as join37, relative as relative3, resolve as resolve9 } from "node:path";
17257
17387
  import {
17258
17388
  REFERENCE_BACKGROUND_FIELD,
@@ -17446,7 +17576,7 @@ function planFileSha256(absolutePath, digests) {
17446
17576
  return sha256;
17447
17577
  }
17448
17578
  async function prehashPlanFiles(dir, digests) {
17449
- if (!existsSync25(dir)) return;
17579
+ if (!existsSync24(dir)) return;
17450
17580
  for (const { absolutePath } of listPlanFiles(dir)) {
17451
17581
  if (!digests.has(absolutePath)) digests.set(absolutePath, await sha256FileAsync(absolutePath));
17452
17582
  }
@@ -17516,15 +17646,15 @@ function writePlanRemoteFiles(planDir, files) {
17516
17646
  }
17517
17647
  function readPlanRemoteFiles(planDir) {
17518
17648
  const path = join37(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
17519
- return existsSync25(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
17649
+ return existsSync24(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
17520
17650
  }
17521
17651
  function recomputePlanHashFromPlanDir(planDir, digests) {
17522
17652
  const planJsonPath = join37(planDir, "plan.json");
17523
17653
  const encoderJsonPath = join37(planDir, "meta", "encoder.json");
17524
- if (!existsSync25(planJsonPath)) {
17654
+ if (!existsSync24(planJsonPath)) {
17525
17655
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
17526
17656
  }
17527
- if (!existsSync25(encoderJsonPath)) {
17657
+ if (!existsSync24(encoderJsonPath)) {
17528
17658
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
17529
17659
  }
17530
17660
  const planJson = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
@@ -17554,11 +17684,11 @@ async function freezePlan(input) {
17554
17684
  hasAudio,
17555
17685
  digests
17556
17686
  } = input;
17557
- if (!existsSync25(planDir)) {
17687
+ if (!existsSync24(planDir)) {
17558
17688
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
17559
17689
  }
17560
17690
  const metaDir = join37(planDir, "meta");
17561
- if (!existsSync25(metaDir)) mkdirSync14(metaDir, { recursive: true });
17691
+ if (!existsSync24(metaDir)) mkdirSync14(metaDir, { recursive: true });
17562
17692
  writeFileSync8(
17563
17693
  join37(metaDir, "composition.json"),
17564
17694
  `${JSON.stringify(composition, null, 2)}
@@ -17635,7 +17765,7 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
17635
17765
  }
17636
17766
 
17637
17767
  // src/services/distributed/chunkAudio.ts
17638
- import { closeSync as closeSync6, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
17768
+ import { closeSync as closeSync6, existsSync as existsSync25, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
17639
17769
  import { writeFileSync as writeFileSync9, writeSync } from "node:fs";
17640
17770
  import { join as join38 } from "node:path";
17641
17771
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
@@ -17741,7 +17871,7 @@ async function writeChunkAudioSlices(input) {
17741
17871
  }
17742
17872
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
17743
17873
  const layoutPath = join38(planDir, SLICE_LAYOUT);
17744
- if (!existsSync26(layoutPath)) return resolvePlanAudioPath(planDir);
17874
+ if (!existsSync25(layoutPath)) return resolvePlanAudioPath(planDir);
17745
17875
  const layout = JSON.parse(readFileSync12(layoutPath, "utf-8"));
17746
17876
  const frame = readFileSync12(join38(planDir, SLICE_FRAME));
17747
17877
  const fd = openSync6(scratchPath, "w");
@@ -18305,7 +18435,7 @@ function createVideoSourceShipper(input) {
18305
18435
  let result = null;
18306
18436
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
18307
18437
  const rel = pathInside(root, srcPath);
18308
- if (rel !== null && (existsSync27(join40(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
18438
+ if (rel !== null && (existsSync26(join40(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
18309
18439
  result = ["compiled", ...rel.split(sep3)].join("/");
18310
18440
  break;
18311
18441
  }
@@ -18333,7 +18463,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
18333
18463
  useGpu: false,
18334
18464
  browserGpuMode: "software"
18335
18465
  });
18336
- if (!existsSync27(planDir)) mkdirSync16(planDir, { recursive: true });
18466
+ if (!existsSync26(planDir)) mkdirSync16(planDir, { recursive: true });
18337
18467
  const log = config.logger ?? defaultLogger;
18338
18468
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
18339
18469
  const abortSignal = config.abortSignal;
@@ -18364,7 +18494,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
18364
18494
  });
18365
18495
  const entryFile = config.entryFile ?? "index.html";
18366
18496
  const htmlPath = join40(projectDir, entryFile);
18367
- if (!existsSync27(htmlPath)) {
18497
+ if (!existsSync26(htmlPath)) {
18368
18498
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
18369
18499
  }
18370
18500
  const workDir = join40(planDir, ".plan-work");
@@ -18592,15 +18722,15 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18592
18722
  logPlanStage(log, "extract", stageStarted);
18593
18723
  const stagedVideoFrames = join40(compiledDir, "__hyperframes_video_frames");
18594
18724
  const videoFramesDst = join40(planDir, "video-frames");
18595
- if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
18725
+ if (existsSync26(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
18596
18726
  const videoSourcesDir = join40(planDir, "video-sources");
18597
18727
  rmSync14(videoSourcesDir, { recursive: true, force: true });
18598
- if (existsSync27(stagedVideoFrames)) {
18728
+ if (existsSync26(stagedVideoFrames)) {
18599
18729
  renameWithRetry8(stagedVideoFrames, videoFramesDst);
18600
18730
  } else {
18601
18731
  mkdirSync16(videoFramesDst, { recursive: true });
18602
18732
  }
18603
- if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
18733
+ if (existsSync26(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
18604
18734
  renameWithRetry8(compiledDir, finalCompiledDir);
18605
18735
  const shipVideoSource = createVideoSourceShipper({
18606
18736
  planDir,
@@ -18721,10 +18851,10 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
18721
18851
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
18722
18852
  }
18723
18853
  const planAudioPath = join40(planDir, PLAN_AUDIO_RELATIVE_PATH);
18724
- if (audioResult?.hasAudio && existsSync27(audioResult.audioOutputPath)) {
18854
+ if (audioResult?.hasAudio && existsSync26(audioResult.audioOutputPath)) {
18725
18855
  renameWithRetry8(audioResult.audioOutputPath, planAudioPath);
18726
18856
  }
18727
- if (chunksCarryAudio && existsSync27(planAudioPath)) {
18857
+ if (chunksCarryAudio && existsSync26(planAudioPath)) {
18728
18858
  if (options.sliceChunkAudio) {
18729
18859
  stageStarted = Date.now();
18730
18860
  await writeChunkAudioSlices({
@@ -18842,7 +18972,7 @@ async function plan(projectDir, config, planDir, options = {}) {
18842
18972
 
18843
18973
  // src/services/distributed/renderChunk.ts
18844
18974
  import { randomBytes } from "node:crypto";
18845
- import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
18975
+ import { existsSync as existsSync29, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
18846
18976
  import { cpus as cpus3 } from "node:os";
18847
18977
  import { join as join44 } from "node:path";
18848
18978
  import {
@@ -18869,7 +18999,7 @@ import {
18869
18999
  } from "@hyperframes/engine";
18870
19000
  import {
18871
19001
  copyFileSync as copyFileSync8,
18872
- existsSync as existsSync29,
19002
+ existsSync as existsSync28,
18873
19003
  lstatSync as lstatSync3,
18874
19004
  mkdirSync as mkdirSync18,
18875
19005
  readFileSync as readFileSync13,
@@ -18881,12 +19011,16 @@ import {
18881
19011
  import { tmpdir as tmpdir3 } from "node:os";
18882
19012
  import { dirname as dirname17, isAbsolute as isAbsolute4, join as join43, relative as relative6, resolve as resolve10, sep as sep4 } from "node:path";
18883
19013
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
18884
- import { createFrameLookupTable as createFrameLookupTable5, renameWithRetry as renameWithRetry10 } from "@hyperframes/engine";
19014
+ import {
19015
+ createFrameLookupTable as createFrameLookupTable5,
19016
+ mediaIdPathSegment as mediaIdPathSegment4,
19017
+ renameWithRetry as renameWithRetry10
19018
+ } from "@hyperframes/engine";
18885
19019
 
18886
19020
  // src/services/distributed/planV2Publisher.ts
18887
19021
  import {
18888
19022
  copyFileSync as copyFileSync7,
18889
- existsSync as existsSync28,
19023
+ existsSync as existsSync27,
18890
19024
  linkSync as linkSync2,
18891
19025
  mkdirSync as mkdirSync17,
18892
19026
  rmSync as rmSync15,
@@ -18955,7 +19089,7 @@ var LocalPlanV2ArtifactPublisher = class {
18955
19089
  #linkFile;
18956
19090
  #committed = false;
18957
19091
  constructor(destinationDir, options = {}) {
18958
- if (existsSync28(destinationDir)) {
19092
+ if (existsSync27(destinationDir)) {
18959
19093
  throw new PlanV2IntegrityError(`output directory already exists: ${destinationDir}`);
18960
19094
  }
18961
19095
  this.destinationDir = destinationDir;
@@ -18972,7 +19106,7 @@ var LocalPlanV2ArtifactPublisher = class {
18972
19106
  );
18973
19107
  }
18974
19108
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
18975
- if (existsSync28(destinationPath)) return;
19109
+ if (existsSync27(destinationPath)) return;
18976
19110
  mkdirSync17(dirname16(destinationPath), { recursive: true });
18977
19111
  const stagingDir = createStagingDir5(dirname16(destinationPath), ".plan-v2-blob-");
18978
19112
  const temporaryPath = join42(stagingDir, "blob");
@@ -18990,7 +19124,7 @@ var LocalPlanV2ArtifactPublisher = class {
18990
19124
  }
18991
19125
  async commitManifest(manifestBytes) {
18992
19126
  for (const digest of new Set(manifestDigests(manifestBytes))) {
18993
- if (!existsSync28(planV2BlobPath(this.temporaryDir, digest))) {
19127
+ if (!existsSync27(planV2BlobPath(this.temporaryDir, digest))) {
18994
19128
  throw new PlanV2IntegrityError(
18995
19129
  `cannot commit manifest before referenced blob is durable: ${digest}`
18996
19130
  );
@@ -19070,7 +19204,7 @@ function assertValidExtractionCacheCompleteSentinel(path) {
19070
19204
  }
19071
19205
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
19072
19206
  const videoRoot = join43(executionPlanDir, "video-frames");
19073
- if (!existsSync29(videoRoot)) return;
19207
+ if (!existsSync28(videoRoot)) return;
19074
19208
  for (const videoEntry of readdirSync10(videoRoot, { withFileTypes: true })) {
19075
19209
  if (!videoEntry.isDirectory()) continue;
19076
19210
  const videoDir = join43(videoRoot, videoEntry.name);
@@ -19086,7 +19220,7 @@ function isExtractionCacheCompleteSentinelPath(path) {
19086
19220
  }
19087
19221
  function resolveExtractedVideoOutputDir(planDir, videoId) {
19088
19222
  const videoRoot = resolve10(planDir, "video-frames");
19089
- const outputDir = resolve10(videoRoot, videoId);
19223
+ const outputDir = resolve10(videoRoot, mediaIdPathSegment4(videoId));
19090
19224
  if (outputDir === videoRoot || !outputDir.startsWith(`${videoRoot}${sep4}`)) {
19091
19225
  throw new PlanV2IntegrityError(`unsafe extracted video id: ${JSON.stringify(videoId)}`);
19092
19226
  }
@@ -19171,7 +19305,7 @@ function parsePlanVideosJson2(value) {
19171
19305
  }
19172
19306
  function materializeExtractedVideoDirectories(planDir) {
19173
19307
  const videosPath = join43(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19174
- if (!existsSync29(videosPath)) return;
19308
+ if (!existsSync28(videosPath)) return;
19175
19309
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
19176
19310
  for (const video of videos.extracted) {
19177
19311
  mkdirSync18(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
@@ -19205,9 +19339,9 @@ function parseChunkSlices(value) {
19205
19339
  }
19206
19340
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
19207
19341
  const videoRoot = join43(executionPlanDir, "video-frames");
19208
- const hasExtractedFrames = existsSync29(videoRoot) && listFiles(videoRoot).length > 0;
19342
+ const hasExtractedFrames = existsSync28(videoRoot) && listFiles(videoRoot).length > 0;
19209
19343
  const videosPath = join43(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19210
- if (!existsSync29(videosPath)) {
19344
+ if (!existsSync28(videosPath)) {
19211
19345
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
19212
19346
  }
19213
19347
  const chunksPath = join43(executionPlanDir, "meta", "chunks.json");
@@ -19264,7 +19398,7 @@ function computeManifestHash(manifest) {
19264
19398
  return sha256Hex(`${PLAN_V2_HASH_PREFIX}${canonicalJsonStringify(manifestPayload(manifest))}`);
19265
19399
  }
19266
19400
  function writeBlob(sourcePath, destinationPath) {
19267
- if (existsSync29(destinationPath)) return;
19401
+ if (existsSync28(destinationPath)) return;
19268
19402
  mkdirSync18(dirname17(destinationPath), { recursive: true });
19269
19403
  const temporaryDir = createStagingDir6(dirname17(destinationPath), ".plan-v2-blob-");
19270
19404
  const temporaryPath = join43(temporaryDir, "blob");
@@ -19304,7 +19438,7 @@ async function putTasks(tasks) {
19304
19438
  }
19305
19439
  function buildPlanV2Publication(executionPlanDir, digests) {
19306
19440
  const executionPlanPath = join43(executionPlanDir, "plan.json");
19307
- if (!existsSync29(executionPlanPath)) {
19441
+ if (!existsSync28(executionPlanPath)) {
19308
19442
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
19309
19443
  }
19310
19444
  const executionPlanValue = readJsonFile(executionPlanPath, "execution plan.json");
@@ -19384,7 +19518,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
19384
19518
  };
19385
19519
  }
19386
19520
  function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
19387
- if (existsSync29(planV2Dir)) {
19521
+ if (existsSync28(planV2Dir)) {
19388
19522
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
19389
19523
  }
19390
19524
  const publication = buildPlanV2Publication(executionPlanDir);
@@ -19470,7 +19604,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
19470
19604
  }
19471
19605
  }
19472
19606
  async function planV2(projectDir, config, planV2Dir) {
19473
- if (existsSync29(planV2Dir)) {
19607
+ if (existsSync28(planV2Dir)) {
19474
19608
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
19475
19609
  }
19476
19610
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
@@ -19624,7 +19758,7 @@ function parsePlanV2Manifest(value) {
19624
19758
  }
19625
19759
  function readPlanV2Manifest(planV2Dir) {
19626
19760
  const manifestPath = join43(planV2Dir, "plan.json");
19627
- if (!existsSync29(manifestPath)) {
19761
+ if (!existsSync28(manifestPath)) {
19628
19762
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
19629
19763
  }
19630
19764
  const value = readJsonFile(manifestPath, "v2 manifest");
@@ -19643,7 +19777,7 @@ function listPlanV2ArtifactsForTarget(manifest, target) {
19643
19777
  }
19644
19778
  function verifyBlob(planV2Dir, artifact) {
19645
19779
  const sourcePath = planV2BlobPath(planV2Dir, artifact.sha256);
19646
- if (!existsSync29(sourcePath)) {
19780
+ if (!existsSync28(sourcePath)) {
19647
19781
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
19648
19782
  }
19649
19783
  const stats = statSync11(sourcePath);
@@ -19656,7 +19790,7 @@ function verifyBlob(planV2Dir, artifact) {
19656
19790
  return sourcePath;
19657
19791
  }
19658
19792
  function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}) {
19659
- if (existsSync29(destinationDir)) {
19793
+ if (existsSync28(destinationDir)) {
19660
19794
  throw new PlanV2IntegrityError(`materialization destination already exists: ${destinationDir}`);
19661
19795
  }
19662
19796
  const manifest = readPlanV2Manifest(planV2Dir);
@@ -19721,7 +19855,7 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
19721
19855
  }
19722
19856
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
19723
19857
  const markerPath = join43(planDir, PLAN_V2_MATERIALIZATION_MARKER);
19724
- if (!existsSync29(markerPath)) return null;
19858
+ if (!existsSync28(markerPath)) return null;
19725
19859
  const marker = readJsonFile(markerPath, "materialization marker");
19726
19860
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
19727
19861
  throw new PlanV2IntegrityError("malformed materialization marker");
@@ -19739,7 +19873,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
19739
19873
  for (const artifact of required) {
19740
19874
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
19741
19875
  const path = join43(planDir, ...artifact.path.split("/"));
19742
- if (!existsSync29(path) || statSync11(path).size !== artifact.sizeBytes) {
19876
+ if (!existsSync28(path) || statSync11(path).size !== artifact.sizeBytes) {
19743
19877
  throw new PlanV2IntegrityError(
19744
19878
  `materialized artifact missing or truncated: ${artifact.path}`
19745
19879
  );
@@ -19890,7 +20024,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19890
20024
  const planJsonPath = join44(planDir, "plan.json");
19891
20025
  const encoderJsonPath = join44(planDir, "meta", "encoder.json");
19892
20026
  const chunksJsonPath = join44(planDir, "meta", "chunks.json");
19893
- if (!existsSync30(planJsonPath)) {
20027
+ if (!existsSync29(planJsonPath)) {
19894
20028
  throw new RenderChunkValidationError(
19895
20029
  MISSING_PLAN_ARTIFACT,
19896
20030
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
@@ -19906,7 +20040,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19906
20040
  const v2Manifest = v2Materialization?.manifest ?? null;
19907
20041
  const remoteSources = v2Materialization?.remoteSources ?? {};
19908
20042
  for (const required of [encoderJsonPath, chunksJsonPath]) {
19909
- if (!existsSync30(required)) {
20043
+ if (!existsSync29(required)) {
19910
20044
  throw new RenderChunkValidationError(
19911
20045
  MISSING_PLAN_ARTIFACT,
19912
20046
  `[renderChunk] planDir is missing required artifact: ${required}`
@@ -19917,7 +20051,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19917
20051
  const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
19918
20052
  const videosJsonPath = join44(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
19919
20053
  let planVideos = null;
19920
- if (existsSync30(videosJsonPath)) {
20054
+ if (existsSync29(videosJsonPath)) {
19921
20055
  try {
19922
20056
  planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync14(videosJsonPath, "utf-8")));
19923
20057
  } catch (err) {
@@ -19948,7 +20082,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
19948
20082
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
19949
20083
  const framesInChunk = range.endFrame - range.startFrame;
19950
20084
  const compiledDir = join44(planDir, "compiled");
19951
- if (!existsSync30(compiledDir)) {
20085
+ if (!existsSync29(compiledDir)) {
19952
20086
  throw new RenderChunkValidationError(
19953
20087
  MISSING_PLAN_ARTIFACT,
19954
20088
  `[renderChunk] planDir missing compiled/ directory: ${compiledDir}`
@@ -20040,6 +20174,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20040
20174
  deferredVideos.filter((video) => remoteVideoIds.has(video.videoId))
20041
20175
  )
20042
20176
  });
20177
+ captureOptions.onStaticDedupActivity = () => noteStaticDedupActivity(job);
20043
20178
  const captureFrames = effectiveChunkFrames(framesInChunk, slice.captureCost);
20044
20179
  const chunkWorkerCount = resolveChunkCaptureWorkers(
20045
20180
  captureFrames,
@@ -20199,10 +20334,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20199
20334
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
20200
20335
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
20201
20336
  if (isPngSequence) {
20202
- if (!existsSync30(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
20337
+ if (!existsSync29(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
20203
20338
  } else {
20204
20339
  const outDir = join44(outputChunkPath, "..");
20205
- if (!existsSync30(outDir)) mkdirSync19(outDir, { recursive: true });
20340
+ if (!existsSync29(outDir)) mkdirSync19(outDir, { recursive: true });
20206
20341
  }
20207
20342
  const encodeInput = {
20208
20343
  job,
@@ -20309,7 +20444,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
20309
20444
  openAttempt,
20310
20445
  verifyFirstSession: forceScreenshot || !verifyInWorker ? void 0 : verifyFirstWorker
20311
20446
  }),
20312
- { stall: frameStallRule(job, framesInChunk) }
20447
+ { stall: frameStallRule(job, framesInChunk, void 0) }
20313
20448
  ).catch(async (captureError) => {
20314
20449
  await overlap.current?.abort();
20315
20450
  overlap.current = null;
@@ -20741,6 +20876,13 @@ function validateDistributedRenderConfig(config) {
20741
20876
  `distributed mode supports only ${ALLOWED_HDR_MODES.join(", ")}; got ${String(config.hdrMode)}`
20742
20877
  );
20743
20878
  }
20879
+ const chromaSubsampling = config.chromaSubsampling;
20880
+ if (chromaSubsampling !== void 0 && chromaSubsampling !== "420") {
20881
+ throw new InvalidConfigError(
20882
+ "config.chromaSubsampling",
20883
+ `distributed mode encodes 4:2:0 only; got ${String(chromaSubsampling)}`
20884
+ );
20885
+ }
20744
20886
  if (config.variables !== void 0) {
20745
20887
  validateVariablesPayload(config.variables);
20746
20888
  }
@@ -20924,6 +21066,7 @@ function assertRequestOptionScalars(options) {
20924
21066
  assertOptionalEnum(options, "proresProfile", PRORES_PROFILE_NAMES2);
20925
21067
  assertOptionalEnum(options, "strictness", ["strict", "best-effort"]);
20926
21068
  assertOptionalEnum(options, "hdrMode", ["auto", "force-hdr", "force-sdr"]);
21069
+ assertOptionalEnum(options, "chromaSubsampling", ["420", "444"]);
20927
21070
  assertOptionalEnum(options, "pageMotionBlur", ["off"]);
20928
21071
  if (options.videoFrameFormat !== void 0 && !isVideoFrameFormat2(options.videoFrameFormat)) {
20929
21072
  throw new Error("Render request videoFrameFormat is invalid");
@@ -21012,6 +21155,11 @@ function distributedConfigFromRequest(request, runtime = {}) {
21012
21155
  if (options.hdrMode === "force-hdr") {
21013
21156
  throw new Error("Distributed render does not support force-hdr");
21014
21157
  }
21158
+ if (options.chromaSubsampling === "444") {
21159
+ throw new Error(
21160
+ "Distributed render does not support chromaSubsampling 444: chunk workers and the assemble encode 4:2:0"
21161
+ );
21162
+ }
21015
21163
  return {
21016
21164
  fps: distributedFps(options.fps),
21017
21165
  width: distributed.width,
@@ -21119,7 +21267,7 @@ import {
21119
21267
 
21120
21268
  // src/server.ts
21121
21269
  import {
21122
- existsSync as existsSync33,
21270
+ existsSync as existsSync32,
21123
21271
  mkdirSync as mkdirSync21,
21124
21272
  statSync as statSync13,
21125
21273
  mkdtempSync as mkdtempSync2,
@@ -21142,7 +21290,7 @@ import {
21142
21290
 
21143
21291
  // src/services/hyperframeLint.ts
21144
21292
  import {
21145
- existsSync as existsSync31,
21293
+ existsSync as existsSync30,
21146
21294
  readFileSync as readFileSync16,
21147
21295
  statSync as statSync12,
21148
21296
  openSync as openSync7,
@@ -21196,7 +21344,7 @@ function readEntryHtml(filePath) {
21196
21344
  }
21197
21345
  function readProjectEntryFile(projectDir, preferredEntryFile) {
21198
21346
  const absProjectDir = resolve11(projectDir);
21199
- if (!existsSync31(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
21347
+ if (!existsSync30(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
21200
21348
  return { error: `Project directory not found: ${absProjectDir}` };
21201
21349
  }
21202
21350
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -21265,7 +21413,7 @@ async function runHyperframeLint(prepared) {
21265
21413
  import { Worker as Worker2 } from "node:worker_threads";
21266
21414
  import { fileURLToPath as fileURLToPath6 } from "node:url";
21267
21415
  import { dirname as dirname18, join as join47 } from "node:path";
21268
- import { existsSync as existsSync32 } from "node:fs";
21416
+ import { existsSync as existsSync31 } from "node:fs";
21269
21417
  var DEFAULT_HEALTH_PORT = 9848;
21270
21418
  async function startHealthWorker(options = {}) {
21271
21419
  const log = options.logger ?? defaultLogger2();
@@ -21342,7 +21490,7 @@ function resolveWorkerEntry2() {
21342
21490
  const here = dirname18(fileURLToPath6(import.meta.url));
21343
21491
  const candidates = [join47(here, "healthWorkerThread.js"), join47(here, "healthWorkerThread.ts")];
21344
21492
  for (const candidate of candidates) {
21345
- if (existsSync32(candidate)) return candidate;
21493
+ if (existsSync31(candidate)) return candidate;
21346
21494
  }
21347
21495
  return void 0;
21348
21496
  }
@@ -21418,7 +21566,15 @@ function parseRenderOptions(body) {
21418
21566
  const format = parseServerFormat(body.format);
21419
21567
  const outputDynamicRange = parseServerOutputDynamicRange(body.outputDynamicRange) ?? fromRenderHdrMode(parseLegacyServerHdrMode(body.hdrMode));
21420
21568
  const encoder = parseEncoderOptions(body, format ?? "mp4");
21421
- const { crf, videoBitrate, videoFrameFormat, keyframeIntervalSeconds, maxBitrate, bufferSize } = encoder.ok ? encoder.options : {};
21569
+ const {
21570
+ crf,
21571
+ videoBitrate,
21572
+ videoFrameFormat,
21573
+ keyframeIntervalSeconds,
21574
+ maxBitrate,
21575
+ bufferSize,
21576
+ chromaSubsampling
21577
+ } = encoder.ok ? encoder.options : {};
21422
21578
  const { variables, outputResolution, outputResolutionAspectAgnostic } = parseRenderOverrides(body);
21423
21579
  return {
21424
21580
  outputPath,
@@ -21431,6 +21587,7 @@ function parseRenderOptions(body) {
21431
21587
  keyframeIntervalSeconds,
21432
21588
  maxBitrate,
21433
21589
  bufferSize,
21590
+ chromaSubsampling,
21434
21591
  useGpu,
21435
21592
  debug,
21436
21593
  forceScreenshot,
@@ -21470,6 +21627,7 @@ function buildRenderJobConfig(input, outputPath, log) {
21470
21627
  keyframeIntervalSeconds: input.keyframeIntervalSeconds,
21471
21628
  maxBitrate: input.maxBitrate,
21472
21629
  bufferSize: input.bufferSize,
21630
+ chromaSubsampling: input.chromaSubsampling,
21473
21631
  useGpu: input.useGpu,
21474
21632
  debug: input.debug,
21475
21633
  strictness: input.strictness,
@@ -21488,15 +21646,28 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log) {
21488
21646
  const { input, cleanupProjectDir } = prepared;
21489
21647
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
21490
21648
  const outputDir = dirname19(absoluteOutputPath);
21491
- if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
21649
+ if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
21492
21650
  return { input, cleanupProjectDir, absoluteOutputPath };
21493
21651
  }
21652
+ function prepareRenderJob(prepared, rendersDir, log) {
21653
+ try {
21654
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
21655
+ const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
21656
+ return { ...output, job };
21657
+ } catch (error) {
21658
+ cleanupTempDir(prepared.cleanupProjectDir, log);
21659
+ return { error: error instanceof Error ? error.message : String(error) };
21660
+ }
21661
+ }
21494
21662
  function validateRenderOverrides(body) {
21495
21663
  const encoder = parseEncoderOptions(body, parseServerFormat(body.format) ?? "mp4");
21496
21664
  if (!encoder.ok) return encoder.error;
21497
21665
  if (body.maxRenderMs !== void 0 && (typeof body.maxRenderMs !== "number" || !Number.isInteger(body.maxRenderMs) || body.maxRenderMs < 0)) {
21498
21666
  return "maxRenderMs must be a non-negative integer number of milliseconds";
21499
21667
  }
21668
+ if (typeof body.workers === "number" && (!Number.isInteger(body.workers) || body.workers < 1)) {
21669
+ return "workers must be a positive integer";
21670
+ }
21500
21671
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
21501
21672
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
21502
21673
  }
@@ -21511,6 +21682,9 @@ function validateRenderOverrides(body) {
21511
21682
  if (outputDynamicRange !== void 0 && legacyHdrMode !== void 0 && outputDynamicRange !== fromRenderHdrMode(legacyHdrMode)) {
21512
21683
  return "outputDynamicRange and legacy hdrMode must describe the same output policy";
21513
21684
  }
21685
+ if (body.chromaSubsampling === "444" && outputDynamicRange === "hdr") {
21686
+ return 'chromaSubsampling "444" is SDR only, not outputDynamicRange "hdr"';
21687
+ }
21514
21688
  return validateOutputResolutionOverride(body);
21515
21689
  }
21516
21690
  function validateOutputResolutionOverride(body) {
@@ -21529,11 +21703,11 @@ function prepareProjectDirectory(projectDir, options) {
21529
21703
  const candidate = nonEmptyString(projectDir);
21530
21704
  if (!candidate) return null;
21531
21705
  const absProjectDir = resolve12(candidate);
21532
- if (!existsSync33(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
21706
+ if (!existsSync32(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
21533
21707
  return { error: `Project directory not found: ${absProjectDir}` };
21534
21708
  }
21535
21709
  const entry = options.entryFile || "index.html";
21536
- if (!existsSync33(resolve12(absProjectDir, entry))) {
21710
+ if (!existsSync32(resolve12(absProjectDir, entry))) {
21537
21711
  return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
21538
21712
  }
21539
21713
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -21625,7 +21799,7 @@ function cleanupTempDir(dir, log) {
21625
21799
  }
21626
21800
  }
21627
21801
  function outputFileSize(path) {
21628
- return existsSync33(path) ? statSync13(path).size : 0;
21802
+ return existsSync32(path) ? statSync13(path).size : 0;
21629
21803
  }
21630
21804
  function createBlockingProgressReporter(log, requestId) {
21631
21805
  let lastLoggedPct = -10;
@@ -21774,11 +21948,11 @@ function createRenderHandlers(options = {}) {
21774
21948
  if ("error" in preparedResult) {
21775
21949
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
21776
21950
  }
21777
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
21778
- preparedResult.prepared,
21779
- rendersDir,
21780
- log
21781
- );
21951
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
21952
+ if ("error" in preparedJob) {
21953
+ return c.json({ success: false, requestId, error: preparedJob.error }, 400);
21954
+ }
21955
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
21782
21956
  const release = await renderSemaphore.acquire();
21783
21957
  log.info("render started", {
21784
21958
  requestId,
@@ -21786,7 +21960,6 @@ function createRenderHandlers(options = {}) {
21786
21960
  fps: input.fps,
21787
21961
  quality: input.quality
21788
21962
  });
21789
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
21790
21963
  try {
21791
21964
  await executeRenderJob(
21792
21965
  job,
@@ -21854,13 +22027,20 @@ function createRenderHandlers(options = {}) {
21854
22027
  const t0 = Date.now();
21855
22028
  const prepared = await prepareSseRenderRequest(c, stream, requestId);
21856
22029
  if (!prepared) return;
21857
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
21858
- prepared,
21859
- rendersDir,
21860
- log
21861
- );
22030
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log);
22031
+ if ("error" in preparedJob) {
22032
+ await stream.writeSSE({
22033
+ data: JSON.stringify({
22034
+ type: "error",
22035
+ requestId,
22036
+ error: preparedJob.error,
22037
+ stage: "validation"
22038
+ })
22039
+ });
22040
+ return;
22041
+ }
22042
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
21862
22043
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
21863
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
21864
22044
  const abortController = new AbortController();
21865
22045
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
21866
22046
  c.req.raw.signal.addEventListener("abort", onRequestAbort, { once: true });
@@ -21904,7 +22084,8 @@ function createRenderHandlers(options = {}) {
21904
22084
  videoDurationSeconds: job.duration ?? null,
21905
22085
  outcome: job.outcome ?? "completed",
21906
22086
  warnings: job.warnings,
21907
- perf: job.perfSummary ?? null
22087
+ perf: job.perfSummary ?? null,
22088
+ producerVersion: readProducerVersion()
21908
22089
  })
21909
22090
  });
21910
22091
  } catch (error) {
@@ -21929,7 +22110,7 @@ function createRenderHandlers(options = {}) {
21929
22110
  if (!artifact) {
21930
22111
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
21931
22112
  }
21932
- if (!existsSync33(artifact.path)) {
22113
+ if (!existsSync32(artifact.path)) {
21933
22114
  store.delete(token);
21934
22115
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
21935
22116
  }
@@ -21949,9 +22130,26 @@ function createRenderHandlers(options = {}) {
21949
22130
  });
21950
22131
  return { render, renderStream, lint, health, outputs, queue };
21951
22132
  }
22133
+ function isCrossOriginBrowserRequest(c) {
22134
+ const fetchSite = c.req.header("sec-fetch-site");
22135
+ if (fetchSite) return fetchSite !== "same-origin" && fetchSite !== "none";
22136
+ const origin = c.req.header("origin");
22137
+ if (!origin) return false;
22138
+ try {
22139
+ return new URL(origin).host !== c.req.header("host");
22140
+ } catch {
22141
+ return true;
22142
+ }
22143
+ }
21952
22144
  function createProducerApp(options = {}) {
21953
22145
  const app = new Hono2();
21954
22146
  const handlers = createRenderHandlers(options);
22147
+ app.post("*", async (c, next) => {
22148
+ if (isCrossOriginBrowserRequest(c)) {
22149
+ return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
22150
+ }
22151
+ await next();
22152
+ });
21955
22153
  app.get("/health", handlers.health);
21956
22154
  app.post("/render", handlers.render);
21957
22155
  app.post("/render/stream", handlers.renderStream);
@@ -22035,7 +22233,7 @@ import {
22035
22233
  } from "@hyperframes/engine";
22036
22234
  import {
22037
22235
  cpSync as cpSync3,
22038
- existsSync as existsSync34,
22236
+ existsSync as existsSync33,
22039
22237
  mkdirSync as mkdirSync22,
22040
22238
  readFileSync as readFileSync17,
22041
22239
  readdirSync as readdirSync12,
@@ -22090,7 +22288,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22090
22288
  }
22091
22289
  const format = plan2.dimensions.format;
22092
22290
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
22093
- if (!existsSync34(dirname20(outputPath))) {
22291
+ if (!existsSync33(dirname20(outputPath))) {
22094
22292
  mkdirSync22(dirname20(outputPath), { recursive: true });
22095
22293
  }
22096
22294
  const workDir = createStagingDir7(dirname20(outputPath), `${basename8(outputPath)}.assemble-work-`);
@@ -22114,7 +22312,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22114
22312
  try {
22115
22313
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
22116
22314
  const finalPath = join49(workDir, `output.${format}`);
22117
- const audio = audioPath !== null && existsSync34(audioPath) ? audioPath : null;
22315
+ const audio = audioPath !== null && existsSync33(audioPath) ? audioPath : null;
22118
22316
  await writeJoined(ctx, videoSources, audio, finalPath);
22119
22317
  renameWithRetry11(finalPath, outputPath);
22120
22318
  log.info("[assemble] stage timings", {
@@ -22132,7 +22330,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22132
22330
  });
22133
22331
  }
22134
22332
  }
22135
- const fileSize = existsSync34(outputPath) ? statSync14(outputPath).size : 0;
22333
+ const fileSize = existsSync33(outputPath) ? statSync14(outputPath).size : 0;
22136
22334
  return {
22137
22335
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
22138
22336
  outputPath,
@@ -22144,13 +22342,13 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22144
22342
  function readAssemblePlan(planDir, chunkPaths) {
22145
22343
  const planJsonPath = join49(planDir, "plan.json");
22146
22344
  const chunksJsonPath = join49(planDir, "meta", "chunks.json");
22147
- if (!existsSync34(planJsonPath)) {
22345
+ if (!existsSync33(planJsonPath)) {
22148
22346
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
22149
22347
  }
22150
22348
  const plan2 = JSON.parse(readFileSync17(planJsonPath, "utf-8"));
22151
22349
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
22152
22350
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
22153
- if (!existsSync34(chunksJsonPath)) {
22351
+ if (!existsSync33(chunksJsonPath)) {
22154
22352
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
22155
22353
  }
22156
22354
  const chunks = JSON.parse(readFileSync17(chunksJsonPath, "utf-8"));
@@ -22165,7 +22363,7 @@ function readAssemblePlan(planDir, chunkPaths) {
22165
22363
  }
22166
22364
  }
22167
22365
  for (const path of chunkPaths.flat()) {
22168
- if (!existsSync34(path)) {
22366
+ if (!existsSync33(path)) {
22169
22367
  throw new Error(`[assemble] chunk path does not exist: ${path}`);
22170
22368
  }
22171
22369
  }
@@ -22304,7 +22502,7 @@ function planFormat(planDir) {
22304
22502
  }
22305
22503
  function lockedAudio(planDir) {
22306
22504
  const encoderJsonPath = join49(planDir, "meta", "encoder.json");
22307
- if (!existsSync34(encoderJsonPath)) return {};
22505
+ if (!existsSync33(encoderJsonPath)) return {};
22308
22506
  return JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
22309
22507
  }
22310
22508
  function readCfrEncoder(planDir, format) {
@@ -22314,7 +22512,7 @@ function readCfrEncoder(planDir, format) {
22314
22512
  );
22315
22513
  }
22316
22514
  const encoderJsonPath = join49(planDir, "meta", "encoder.json");
22317
- if (!existsSync34(encoderJsonPath)) {
22515
+ if (!existsSync33(encoderJsonPath)) {
22318
22516
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
22319
22517
  }
22320
22518
  const encoderJson = JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
@@ -22326,7 +22524,7 @@ function readCfrEncoder(planDir, format) {
22326
22524
  return encoderJson;
22327
22525
  }
22328
22526
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
22329
- if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
22527
+ if (existsSync33(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
22330
22528
  mkdirSync22(outputPath, { recursive: true });
22331
22529
  let globalIdx = 0;
22332
22530
  for (const chunkDir of chunkPaths) {
@@ -22350,7 +22548,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
22350
22548
  `[assemble] png-sequence frame count mismatch: merged ${globalIdx} frames vs plan.totalFrames=${totalFrames}. Using on-disk count.`
22351
22549
  );
22352
22550
  }
22353
- if (audioPath !== null && existsSync34(audioPath)) {
22551
+ if (audioPath !== null && existsSync33(audioPath)) {
22354
22552
  const sidecar = join49(outputPath, MIXED_AUDIO_FILENAME4);
22355
22553
  cpSync3(audioPath, sidecar);
22356
22554
  }