@hyperframes/producer 0.9.30 → 0.9.32

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/server.ts
4
4
  import {
5
- existsSync as existsSync24,
5
+ existsSync as existsSync26,
6
6
  mkdirSync as mkdirSync13,
7
7
  statSync as statSync11,
8
8
  mkdtempSync,
@@ -10,7 +10,7 @@ import {
10
10
  rmSync as rmSync13,
11
11
  createReadStream as createReadStream3
12
12
  } from "node:fs";
13
- import { resolve as resolve10, dirname as dirname15, join as join34 } from "node:path";
13
+ import { resolve as resolve10, dirname as dirname16, join as join36 } from "node:path";
14
14
  import { tmpdir as tmpdir3 } from "node:os";
15
15
  import { parseArgs } from "node:util";
16
16
  import crypto from "node:crypto";
@@ -26,7 +26,7 @@ import {
26
26
  // src/services/renderOrchestrator.ts
27
27
  import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
28
28
  import {
29
- existsSync as existsSync21,
29
+ existsSync as existsSync22,
30
30
  mkdirSync as mkdirSync12,
31
31
  readdirSync as readdirSync6,
32
32
  rmSync as rmSync12,
@@ -84,7 +84,7 @@ import {
84
84
  referenceBackgroundResult,
85
85
  createReferenceBackgroundRecorder
86
86
  } from "@hyperframes/engine";
87
- import { join as join30, dirname as dirname13, resolve as resolve8 } from "path";
87
+ import { join as join31, dirname as dirname13, resolve as resolve8 } from "path";
88
88
  import { totalmem as totalmem2 } from "node:os";
89
89
  import { randomUUID } from "crypto";
90
90
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -994,6 +994,33 @@ function resolveDeliveryEncoderOptions(config) {
994
994
  return { maxBitrate, bufferSize, ...gop };
995
995
  }
996
996
 
997
+ // src/services/render/chromaSubsampling.ts
998
+ function validateChromaSubsamplingConfig(config) {
999
+ if (config.chromaSubsampling !== "444") return;
1000
+ const format = config.format ?? "mp4";
1001
+ if (format !== "mp4") {
1002
+ throw new Error(
1003
+ `[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.`
1004
+ );
1005
+ }
1006
+ if (config.hdrMode === "force-hdr") {
1007
+ throw new Error(
1008
+ `[Render] chromaSubsampling "444" is SDR only; HDR output stays 10-bit 4:2:0 H.265. Drop --hdr, or drop --chroma-subsampling 444.`
1009
+ );
1010
+ }
1011
+ if (config.useGpu === true) {
1012
+ throw new Error(
1013
+ `[Render] chromaSubsampling "444" requires the software encoder (libx264); GPU encoders do not reliably support 4:4:4. Re-run without --gpu.`
1014
+ );
1015
+ }
1016
+ }
1017
+ function assertChromaSubsamplingSdr(config, hasHdrContent) {
1018
+ if (config.chromaSubsampling !== "444" || !hasHdrContent) return;
1019
+ throw new Error(
1020
+ `[Render] chromaSubsampling "444" is SDR only, but this composition has HDR sources. Re-run with --sdr (hdrMode "force-sdr"), or drop --chroma-subsampling 444.`
1021
+ );
1022
+ }
1023
+
997
1024
  // src/services/render/shared.ts
998
1025
  import {
999
1026
  copyFileSync,
@@ -1009,6 +1036,9 @@ import {
1009
1036
  CANVAS_DIMENSIONS,
1010
1037
  checkOutputResolutionCompatibility
1011
1038
  } from "@hyperframes/core";
1039
+ import {
1040
+ mediaIdPathSegment
1041
+ } from "@hyperframes/engine";
1012
1042
 
1013
1043
  // src/utils/paths.ts
1014
1044
  import {
@@ -1103,6 +1133,10 @@ function writeCompiledArtifacts(compiled, workDir, includeSummary) {
1103
1133
  writeFileSync(join3(compileDir, "index.html"), compiled.html, "utf-8");
1104
1134
  for (const [srcPath, html] of compiled.subCompositions) {
1105
1135
  const outPath = join3(compileDir, srcPath);
1136
+ if (!isPathInside2(outPath, compileDir)) {
1137
+ console.warn(`[Render] Skipping sub-composition with unsafe path: ${srcPath}`);
1138
+ continue;
1139
+ }
1106
1140
  mkdirSync(dirname2(outPath), { recursive: true });
1107
1141
  writeFileSync(outPath, html, "utf-8");
1108
1142
  }
@@ -1364,7 +1398,7 @@ function materializeExtractedFramesForCompiledDir(extracted, compiledDir, option
1364
1398
  for (const ext of extracted) {
1365
1399
  const resolvedOut = pathModule.resolve(ext.outputDir);
1366
1400
  if (isPathInside2(resolvedOut, resolvedCompiledDir, { pathModule })) continue;
1367
- const linkPath = pathModule.join(compiledFrameRoot, ext.videoId);
1401
+ const linkPath = pathModule.join(compiledFrameRoot, mediaIdPathSegment(ext.videoId));
1368
1402
  if (!fileSystem.existsSync(linkPath)) {
1369
1403
  fileSystem.mkdirSync(pathModule.dirname(linkPath), { recursive: true });
1370
1404
  stageExtractedFrameDir(
@@ -5438,6 +5472,7 @@ import { dirname as dirname5, join as join11 } from "node:path";
5438
5472
  import {
5439
5473
  createFrameLookupTable,
5440
5474
  extractVideoFramesRange,
5475
+ mediaIdPathSegment as mediaIdPathSegment2,
5441
5476
  runVideoExtractionWithRetry
5442
5477
  } from "@hyperframes/engine";
5443
5478
  function contiguousRuns(sortedIndexes) {
@@ -5478,7 +5513,7 @@ async function extractDeferredFrames(input) {
5478
5513
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5479
5514
  return Promise.all(
5480
5515
  deferred.map(async (video) => {
5481
- const outputDir = join11(input.outputRoot, video.videoId);
5516
+ const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
5482
5517
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5483
5518
  if (indexes.length === 0) {
5484
5519
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -6353,8 +6388,8 @@ function countAuthoredTimedClips(html) {
6353
6388
  }
6354
6389
 
6355
6390
  // src/services/render/stages/compileStage.ts
6356
- import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6357
- import { join as join18 } from "node:path";
6391
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
6392
+ import { join as join19 } from "node:path";
6358
6393
  import { suggestMatchingPreset } from "@hyperframes/core";
6359
6394
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6360
6395
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
@@ -6362,9 +6397,23 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
6362
6397
  // src/services/htmlCompiler.ts
6363
6398
  import { decodedUrlPath as decodedUrlPath2 } from "@hyperframes/parsers/asset-paths";
6364
6399
  import { createHash as createHash6 } from "node:crypto";
6365
- import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync7 } from "fs";
6366
- import { join as join17, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep2 } from "path";
6400
+ import { createReadStream as createReadStream2, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6401
+ import { join as join18, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep2 } from "path";
6367
6402
  import { parseHTML as parseHTML5 } from "linkedom";
6403
+
6404
+ // src/services/bundledScripts.ts
6405
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
6406
+ import { join as join15 } from "node:path";
6407
+ import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
6408
+ var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
6409
+ function bundledScript(url) {
6410
+ const dir = process.env[GSAP_VENDOR_DIR_ENV];
6411
+ if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
6412
+ const file = join15(dir, "gsap.min.js");
6413
+ return existsSync9(file) ? readFileSync5(file) : null;
6414
+ }
6415
+
6416
+ // src/services/htmlCompiler.ts
6368
6417
  import {
6369
6418
  COMPOSITION_SOURCE_URL,
6370
6419
  compileTimingAttrs,
@@ -6386,7 +6435,7 @@ import {
6386
6435
  import { MAX_AUDIO_GAIN } from "@hyperframes/core/audio-gain";
6387
6436
  import { readPlaybackRate } from "@hyperframes/parsers/media-duration";
6388
6437
  import { resolveRateSpec } from "@hyperframes/core/speed-ramp";
6389
- import { gsapCdnDist, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
6438
+ import { gsapCdnDist as gsapCdnDist2, normalizeGsapBaseUrl } from "@hyperframes/core/gsap-cdn";
6390
6439
  import {
6391
6440
  assignBundledRuntimeCompositionIds,
6392
6441
  assignMediaRenderIds,
@@ -6609,8 +6658,8 @@ import {
6609
6658
 
6610
6659
  // src/services/animatedGifPrep.ts
6611
6660
  import { createHash as createHash4 } from "node:crypto";
6612
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync5, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6613
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join15, resolve as resolve5 } from "node:path";
6661
+ import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
6662
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
6614
6663
  import { parseHTML as parseHTML3 } from "linkedom";
6615
6664
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
6616
6665
  import { DEFAULT_VP9_CPU_USED, runFfmpeg as runFfmpeg2, renameWithRetry as renameWithRetry3 } from "@hyperframes/engine";
@@ -6648,14 +6697,14 @@ function resolveLocalImageSourcePath(src, options) {
6648
6697
  const { basePath } = splitUrlSuffix(trimmed);
6649
6698
  const normalizedBase = normalizeRelPath(basePath);
6650
6699
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
6651
- if (mapped && existsSync9(mapped)) return mapped;
6700
+ if (mapped && existsSync10(mapped)) return mapped;
6652
6701
  if (isHttpUrl(trimmed)) return null;
6653
6702
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
6654
6703
  const candidates = [
6655
6704
  isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
6656
6705
  resolve5(options.downloadDir, normalizedBase)
6657
6706
  ];
6658
- return candidates.find((candidate) => existsSync9(candidate)) ?? null;
6707
+ return candidates.find((candidate) => existsSync10(candidate)) ?? null;
6659
6708
  }
6660
6709
  function isUsableFile(path) {
6661
6710
  try {
@@ -6766,10 +6815,10 @@ async function runAnimatedGifTranscode(request) {
6766
6815
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
6767
6816
  }
6768
6817
  async function ensurePreparedWebm(input) {
6769
- if (!existsSync9(dirname6(input.cachePath))) {
6818
+ if (!existsSync10(dirname6(input.cachePath))) {
6770
6819
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
6771
6820
  }
6772
- if (!existsSync9(dirname6(input.outputPath))) {
6821
+ if (!existsSync10(dirname6(input.outputPath))) {
6773
6822
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
6774
6823
  }
6775
6824
  if (!isUsableFile(input.cachePath)) {
@@ -6853,7 +6902,7 @@ function replaceImageWithVideo(input) {
6853
6902
  return video;
6854
6903
  }
6855
6904
  async function prepareAnimatedGifInputs(html, options) {
6856
- const outputDir = options.outputDir ?? join15(options.downloadDir, PREPARED_GIF_SUBDIR);
6905
+ const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_GIF_SUBDIR);
6857
6906
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
6858
6907
  const cacheDir = options.cacheDir ?? outputDir;
6859
6908
  const { document: document2 } = parseHTML3(html);
@@ -6867,7 +6916,7 @@ async function prepareAnimatedGifInputs(html, options) {
6867
6916
  if (!hasGifExtension(src)) continue;
6868
6917
  const sourcePath = resolveLocalImageSourcePath(src, options);
6869
6918
  if (!sourcePath) continue;
6870
- const bytes = readFileSync5(sourcePath);
6919
+ const bytes = readFileSync6(sourcePath);
6871
6920
  const metadata = parseAnimatedGifMetadata(bytes);
6872
6921
  if (!metadata?.animated) continue;
6873
6922
  const loopOverride = readLoopOverride(img);
@@ -6880,8 +6929,8 @@ async function prepareAnimatedGifInputs(html, options) {
6880
6929
  );
6881
6930
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
6882
6931
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
6883
- const cachePath = join15(cacheDir, filename);
6884
- const outputPath = join15(outputDir, filename);
6932
+ const cachePath = join16(cacheDir, filename);
6933
+ const outputPath = join16(outputDir, filename);
6885
6934
  const outputSrc = `${outputSrcPrefix}/${filename}`;
6886
6935
  await ensurePreparedWebm({
6887
6936
  sourcePath,
@@ -6920,13 +6969,13 @@ import {
6920
6969
  copyFileSync as copyFileSync3,
6921
6970
  mkdirSync as mkdirSync8,
6922
6971
  openSync as openSync4,
6923
- readFileSync as readFileSync6,
6972
+ readFileSync as readFileSync7,
6924
6973
  readSync as readSync3,
6925
6974
  rmSync as rmSync10,
6926
6975
  statSync as statSync7,
6927
6976
  writeFileSync as writeFileSync4
6928
6977
  } from "node:fs";
6929
- import { dirname as dirname7, join as join16, resolve as resolve6 } from "node:path";
6978
+ import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
6930
6979
  import { parseHTML as parseHTML4 } from "linkedom";
6931
6980
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe } from "@hyperframes/engine";
6932
6981
 
@@ -7104,7 +7153,7 @@ function primaryGrid(probed) {
7104
7153
  async function convertHeifToJpeg(request) {
7105
7154
  const probed = await probeJson(request.inputPath, true);
7106
7155
  const grid = primaryGrid(probed);
7107
- const rotation = readHeifPrimaryRotation(readFileSync6(request.inputPath));
7156
+ const rotation = readHeifPrimaryRotation(readFileSync7(request.inputPath));
7108
7157
  const filters = [];
7109
7158
  let inputs = [];
7110
7159
  let size = probed.streams?.[0];
@@ -7162,7 +7211,7 @@ function resolveImageSource(src, options) {
7162
7211
  const path = resolveLocalImageSourcePath(src, options);
7163
7212
  const head = path ? readHead(path) : null;
7164
7213
  if (!path || !head || !isHeifBytes(head)) return null;
7165
- return { path, bytes: readFileSync6(path), label: `"${splitUrlSuffix(src).basePath}"` };
7214
+ return { path, bytes: readFileSync7(path), label: `"${splitUrlSuffix(src).basePath}"` };
7166
7215
  }
7167
7216
  function isUsableFile2(path) {
7168
7217
  try {
@@ -7200,7 +7249,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
7200
7249
  }
7201
7250
  }
7202
7251
  async function prepareHeifImageInputs(html, options) {
7203
- const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_HEIF_SUBDIR);
7252
+ const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_HEIF_SUBDIR);
7204
7253
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
7205
7254
  const cacheDir = options.cacheDir ?? outputDir;
7206
7255
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -7221,7 +7270,7 @@ async function prepareHeifImageInputs(html, options) {
7221
7270
  await Promise.all(
7222
7271
  [...unique].map(
7223
7272
  ([filename, source]) => withMediaProbeSlot(
7224
- () => ensurePreparedJpeg(source, join16(cacheDir, filename), join16(outputDir, filename), options)
7273
+ () => ensurePreparedJpeg(source, join17(cacheDir, filename), join17(outputDir, filename), options)
7225
7274
  ).catch((error) => {
7226
7275
  if (!options.onFailure) throw error;
7227
7276
  failed.add(filename);
@@ -7233,8 +7282,8 @@ async function prepareHeifImageInputs(html, options) {
7233
7282
  if (failed.has(filename)) continue;
7234
7283
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7235
7284
  img.setAttribute("src", outputSrc);
7236
- preparedAssets.set(outputSrc, join16(outputDir, filename));
7237
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join16(outputDir, filename) });
7285
+ preparedAssets.set(outputSrc, join17(outputDir, filename));
7286
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join17(outputDir, filename) });
7238
7287
  }
7239
7288
  return { html: document2.toString(), preparedAssets, preparedImages };
7240
7289
  }
@@ -7244,7 +7293,7 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7244
7293
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7245
7294
 
7246
7295
  // src/services/assetMediaType.ts
7247
- import { existsSync as existsSync10 } from "node:fs";
7296
+ import { existsSync as existsSync11 } from "node:fs";
7248
7297
  import {
7249
7298
  fingerprintElementId,
7250
7299
  isNotMediaPayload,
@@ -7317,7 +7366,7 @@ async function preflightCompositionAssetMediaTypes(input) {
7317
7366
  input.projectDir,
7318
7367
  input.compiledDir
7319
7368
  );
7320
- if (!existsSync10(resolvedPath)) continue;
7369
+ if (!existsSync11(resolvedPath)) continue;
7321
7370
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
7322
7371
  }
7323
7372
  const mismatches = [];
@@ -7570,8 +7619,8 @@ function detectShaderTransitionUsage(html) {
7570
7619
  async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes) {
7571
7620
  let filePath = src;
7572
7621
  if (isHttpUrl(src)) {
7573
- const remoteDir = join17(downloadDir, REMOTE_MEDIA_SUBDIR);
7574
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7622
+ const remoteDir = join18(downloadDir, REMOTE_MEDIA_SUBDIR);
7623
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
7575
7624
  try {
7576
7625
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
7577
7626
  onTelemetry: logRemoteDownloadTelemetry
@@ -7581,10 +7630,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, baseDir, down
7581
7630
  }
7582
7631
  } else {
7583
7632
  filePath = decodedUrlPath2(src);
7584
- if (!filePath.startsWith("/")) filePath = join17(baseDir, filePath);
7633
+ if (!filePath.startsWith("/")) filePath = join18(baseDir, filePath);
7585
7634
  filePath = urlByAbsentLocalPath?.get(filePath) ?? filePath;
7586
7635
  }
7587
- if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
7636
+ if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
7588
7637
  return { duration: null, resolvedPath: filePath };
7589
7638
  }
7590
7639
  const withSrcContext = (error) => {
@@ -7933,7 +7982,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
7933
7982
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
7934
7983
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
7935
7984
  // against its own directory, project-root refs stay as authored.
7936
- assetExists: (path) => existsSync11(resolve7(projectDir, path)),
7985
+ assetExists: (path) => existsSync12(resolve7(projectDir, path)),
7937
7986
  // Preserve the authored root wrapper as a child of the host, matching
7938
7987
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
7939
7988
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8078,12 +8127,17 @@ async function inlineExternalScripts(html) {
8078
8127
  if (externalScripts.length === 0) return html;
8079
8128
  const downloads = await Promise.allSettled(
8080
8129
  externalScripts.map(async ({ el, src }) => {
8130
+ const integrity = el.getAttribute("integrity") || "";
8131
+ const bundled = bundledScript(src);
8132
+ if (bundled && matchesScriptIntegrity(bundled, integrity)) {
8133
+ return { src, text: new TextDecoder().decode(bundled) };
8134
+ }
8081
8135
  const response = await fetch(src, {
8082
8136
  signal: AbortSignal.timeout(15e3)
8083
8137
  });
8084
8138
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
8085
8139
  const bytes = new Uint8Array(await response.arrayBuffer());
8086
- if (!matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "")) {
8140
+ if (!matchesScriptIntegrity(bytes, integrity)) {
8087
8141
  throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
8088
8142
  }
8089
8143
  return { src, text: new TextDecoder().decode(bytes) };
@@ -8124,7 +8178,7 @@ function collectExternalAssets(html, projectDir) {
8124
8178
  if (isPathInside2(absPath, absProjectDir)) {
8125
8179
  return null;
8126
8180
  }
8127
- if (!existsSync11(absPath)) return null;
8181
+ if (!existsSync12(absPath)) return null;
8128
8182
  const safeKey = toExternalAssetKey(absPath);
8129
8183
  externalAssets.set(safeKey, absPath);
8130
8184
  return safeKey;
@@ -8174,7 +8228,7 @@ var REMOTE_SOURCE_TAG_RE = /<source\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+)["
8174
8228
  var REMOTE_IMG_TAG_RE = /<img\b[^>]*?(?<![\w-])src\s*=\s*["'](https?:\/\/[^"']+)["'][^>]*>/gi;
8175
8229
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
8176
8230
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
8177
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8231
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8178
8232
  const urlToLocal = /* @__PURE__ */ new Map();
8179
8233
  await Promise.all(
8180
8234
  [...urlSet].map(async (url) => {
@@ -8221,7 +8275,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
8221
8275
  return downloadAndRewriteUrls(
8222
8276
  urlSet,
8223
8277
  html,
8224
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8278
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8225
8279
  "Remote media download failed",
8226
8280
  "Localized remote media source(s)"
8227
8281
  );
@@ -8236,7 +8290,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
8236
8290
  return downloadAndRewriteUrls(
8237
8291
  urlSet,
8238
8292
  html,
8239
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8293
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8240
8294
  "Remote image download failed",
8241
8295
  "Localized remote image source(s)"
8242
8296
  );
@@ -8252,7 +8306,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
8252
8306
  return downloadAndRewriteUrls(
8253
8307
  urlSet,
8254
8308
  html,
8255
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8309
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8256
8310
  "Remote background-image download failed",
8257
8311
  "Localized remote background-image(s)",
8258
8312
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -8357,13 +8411,13 @@ function projectStylesheetFontFamilies(html, projectDir) {
8357
8411
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
8358
8412
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
8359
8413
  const sheet = resolve7(projectDir, decodedUrlPath2(href).replace(/^(?:\.?\/)+/, ""));
8360
- if (!isPathInside2(sheet, projectDir) || !existsSync11(sheet)) continue;
8361
- for (const face of extractFontFaceBlocks(readFileSync7(sheet, "utf8"))) {
8414
+ if (!isPathInside2(sheet, projectDir) || !existsSync12(sheet)) continue;
8415
+ for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
8362
8416
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
8363
8417
  const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
8364
8418
  const path = decodedUrlPath2(url);
8365
8419
  const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname8(sheet), path);
8366
- return isPathInside2(file, projectDir) && existsSync11(file);
8420
+ return isPathInside2(file, projectDir) && existsSync12(file);
8367
8421
  });
8368
8422
  if (family && shipsFile) families.push(family);
8369
8423
  }
@@ -8404,7 +8458,7 @@ function localizeFontFaceUrls(html, downloadDir) {
8404
8458
  return downloadAndRewriteUrls(
8405
8459
  collectFontFaceUrls(html),
8406
8460
  html,
8407
- join17(downloadDir, REMOTE_MEDIA_SUBDIR),
8461
+ join18(downloadDir, REMOTE_MEDIA_SUBDIR),
8408
8462
  "Remote font download failed",
8409
8463
  "Localized remote font face(s)",
8410
8464
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -8488,7 +8542,7 @@ async function embedLocalFontFaces(html, projectDir) {
8488
8542
  }
8489
8543
  function renderGsapDist() {
8490
8544
  try {
8491
- return gsapCdnDist(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
8545
+ return gsapCdnDist2(void 0, normalizeGsapBaseUrl(process.env.HYPERFRAMES_GSAP_BASE_URL));
8492
8546
  } catch (cause) {
8493
8547
  throw new Error(
8494
8548
  "Invalid HYPERFRAMES_GSAP_BASE_URL: use an absolute HTTPS npm mirror root (plain HTTP only for localhost) without credentials, query, or fragment",
@@ -8498,7 +8552,7 @@ function renderGsapDist() {
8498
8552
  }
8499
8553
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
8500
8554
  let gsapDist;
8501
- const exists = (path) => existsSync11(resolve7(projectDir, path));
8555
+ const exists = (path) => existsSync12(resolve7(projectDir, path));
8502
8556
  return html.replace(
8503
8557
  /(<script\b[^>]*\bsrc=["'])([^"']*gsap[^"']*\/dist\/([^"']+))(["'][^>]*>)/gi,
8504
8558
  (full, prefix, src, file, suffix) => {
@@ -8515,7 +8569,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
8515
8569
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
8516
8570
  if (!entryPath.includes("/")) return html;
8517
8571
  const { document: document2 } = parseHTML5(html);
8518
- const assetExists = (path) => existsSync11(resolve7(projectDir, path));
8572
+ const assetExists = (path) => existsSync12(resolve7(projectDir, path));
8519
8573
  rewriteAssetPaths(
8520
8574
  document2.querySelectorAll("[src], [href], [srcset]"),
8521
8575
  entryPath,
@@ -9081,11 +9135,11 @@ function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height,
9081
9135
  }
9082
9136
  function resolveEntryHtmlPath(input) {
9083
9137
  const { projectDir, workDir, entryFile, log } = input;
9084
- const htmlPath = join18(projectDir, entryFile);
9138
+ const htmlPath = join19(projectDir, entryFile);
9085
9139
  const rawEntry = readTextFile2(htmlPath);
9086
9140
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
9087
- const projectIndexPath = join18(projectDir, "index.html");
9088
- if (!existsSync12(projectIndexPath)) {
9141
+ const projectIndexPath = join19(projectDir, "index.html");
9142
+ if (!existsSync13(projectIndexPath)) {
9089
9143
  throw new Error(
9090
9144
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
9091
9145
  );
@@ -9100,11 +9154,19 @@ function resolveEntryHtmlPath(input) {
9100
9154
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
9101
9155
  );
9102
9156
  }
9103
- const wrapperPath = join18(workDir, "standalone-entry.html");
9157
+ const wrapperPath = join19(workDir, "standalone-entry.html");
9104
9158
  writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
9105
9159
  log.info("Extracted standalone entry from index.html host context", { entryFile });
9106
9160
  return wrapperPath;
9107
9161
  }
9162
+ function applyChroma444Gate(cfg, chromaSubsampling, gate, log) {
9163
+ if (!cfg.useDrawElement || chromaSubsampling !== "444") return gate;
9164
+ cfg.useDrawElement = false;
9165
+ log.info(
9166
+ "[Render] Fast capture: chromaSubsampling 444 captures lossless PNG frames, so disabling drawElementImage for this render. Capture uses the platform's baseline route."
9167
+ );
9168
+ return "chroma_444";
9169
+ }
9108
9170
  async function runCompileStage(input) {
9109
9171
  const {
9110
9172
  projectDir,
@@ -9121,7 +9183,7 @@ async function runCompileStage(input) {
9121
9183
  } = input;
9122
9184
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log });
9123
9185
  const compileStart = Date.now();
9124
- const compiled = await compileForRender(projectDir, htmlPath, join18(workDir, "downloads"), {
9186
+ const compiled = await compileForRender(projectDir, htmlPath, join19(workDir, "downloads"), {
9125
9187
  log,
9126
9188
  failClosedFontFetch: failClosedFontFetch === true,
9127
9189
  allowSystemFontCapture,
@@ -9129,7 +9191,7 @@ async function runCompileStage(input) {
9129
9191
  variables: input.variables,
9130
9192
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
9131
9193
  pageMotionBlur: input.pageMotionBlur,
9132
- animatedGifCacheDir: cfg.extractCacheDir ? join18(cfg.extractCacheDir, "animated-gif") : void 0,
9194
+ animatedGifCacheDir: cfg.extractCacheDir ? join19(cfg.extractCacheDir, "animated-gif") : void 0,
9133
9195
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout
9134
9196
  });
9135
9197
  assertNotAborted();
@@ -9156,6 +9218,7 @@ async function runCompileStage(input) {
9156
9218
  "[Render] Fast capture: composition uses shader transitions, so disabling drawElementImage so page-side compositing stays available."
9157
9219
  );
9158
9220
  }
9221
+ deCompileGate = applyChroma444Gate(cfg, job.config.chromaSubsampling, deCompileGate, log);
9159
9222
  if (!cfg.useDrawElement && cfg.pageSideCompositingAutoDisabled) {
9160
9223
  cfg.enablePageSideCompositing = true;
9161
9224
  cfg.pageSideCompositingAutoDisabled = false;
@@ -9186,7 +9249,7 @@ async function runCompileStage(input) {
9186
9249
  };
9187
9250
  await preflightCompositionAssetMediaTypes({
9188
9251
  projectDir,
9189
- compiledDir: join18(workDir, "compiled"),
9252
+ compiledDir: join19(workDir, "compiled"),
9190
9253
  composition,
9191
9254
  signal: abortSignal
9192
9255
  });
@@ -9232,7 +9295,7 @@ async function runCompileStage(input) {
9232
9295
 
9233
9296
  // src/services/render/stages/probeStage.ts
9234
9297
  import { createHash as createHash7 } from "node:crypto";
9235
- import { basename as basename6, join as join19 } from "node:path";
9298
+ import { basename as basename6, join as join20 } from "node:path";
9236
9299
  import { parseHTML as parseHTML6 } from "linkedom";
9237
9300
  import {
9238
9301
  closeCaptureSession as closeCaptureSession4,
@@ -9267,11 +9330,19 @@ function isActionableProbeFailure(line) {
9267
9330
 
9268
9331
  // src/services/render/captureImageFormat.ts
9269
9332
  function resolveCaptureImageFormat(input) {
9270
- return input.needsAlpha || input.motionBlur ? "png" : "jpeg";
9333
+ return input.needsAlpha || input.motionBlur || input.chromaSubsampling === "444" ? "png" : "jpeg";
9271
9334
  }
9272
9335
  function resolveCaptureJpegQuality(quality) {
9273
9336
  return quality === "draft" ? 80 : 100;
9274
9337
  }
9338
+ function resolveCaptureSurface(input, quality) {
9339
+ const format = resolveCaptureImageFormat(input);
9340
+ return {
9341
+ format,
9342
+ quality: format === "png" ? void 0 : resolveCaptureJpegQuality(quality),
9343
+ transparent: input.needsAlpha
9344
+ };
9345
+ }
9275
9346
 
9276
9347
  // src/services/render/stages/probeStage.ts
9277
9348
  var FRAME_BOUNDARY_EPSILON = 1e-3;
@@ -9441,22 +9512,22 @@ async function runProbeStage(input) {
9441
9512
  });
9442
9513
  fileServer = await createFileServer({
9443
9514
  projectDir,
9444
- compiledDir: join19(workDir, "compiled"),
9515
+ compiledDir: join20(workDir, "compiled"),
9445
9516
  port: 0,
9446
9517
  preHeadScripts: [VIRTUAL_TIME_SHIM],
9447
9518
  fps: job.config.fps
9448
9519
  });
9449
9520
  assertNotAborted();
9450
9521
  const motionBlur = job.config.motionBlur;
9451
- const captureFormat = resolveCaptureImageFormat({ needsAlpha, motionBlur });
9452
9522
  const captureOpts = {
9453
9523
  recordReferenceBackground: input.recordReferenceBackground,
9454
9524
  width,
9455
9525
  height,
9456
9526
  fps: job.config.fps,
9457
- format: captureFormat,
9458
- transparent: needsAlpha,
9459
- quality: captureFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
9527
+ ...resolveCaptureSurface(
9528
+ { needsAlpha, motionBlur, chromaSubsampling: job.config.chromaSubsampling },
9529
+ job.config.quality
9530
+ ),
9460
9531
  variables: job.config.variables,
9461
9532
  deviceScaleFactor,
9462
9533
  motionBlur,
@@ -9471,7 +9542,7 @@ async function runProbeStage(input) {
9471
9542
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
9472
9543
  probeSession = await createCaptureSession4(
9473
9544
  fileServer.url,
9474
- join19(workDir, "probe"),
9545
+ join20(workDir, "probe"),
9475
9546
  captureOpts,
9476
9547
  null,
9477
9548
  probeCfg
@@ -9556,7 +9627,7 @@ async function runProbeStage(input) {
9556
9627
  });
9557
9628
  probeSession = await createCaptureSession4(
9558
9629
  fileServer.url,
9559
- join19(workDir, "probe-screenshot"),
9630
+ join20(workDir, "probe-screenshot"),
9560
9631
  captureOpts,
9561
9632
  null,
9562
9633
  { ...probeCfg, forceScreenshot: true }
@@ -9594,7 +9665,7 @@ async function runProbeStage(input) {
9594
9665
  compiled,
9595
9666
  resolutions,
9596
9667
  projectDir,
9597
- join19(workDir, "downloads")
9668
+ join20(workDir, "downloads")
9598
9669
  );
9599
9670
  assertNotAborted();
9600
9671
  composition.videos = compiled.videos;
@@ -9785,7 +9856,7 @@ async function runProbeStage(input) {
9785
9856
  }
9786
9857
  await preflightCompositionAssetMediaTypes({
9787
9858
  projectDir,
9788
- compiledDir: join19(workDir, "compiled"),
9859
+ compiledDir: join20(workDir, "compiled"),
9789
9860
  composition,
9790
9861
  signal: abortSignal
9791
9862
  });
@@ -9919,8 +9990,8 @@ function validateRenderDuration(input) {
9919
9990
  }
9920
9991
 
9921
9992
  // src/services/render/stages/extractVideosStage.ts
9922
- import { existsSync as existsSync13 } from "node:fs";
9923
- import { join as join20 } from "node:path";
9993
+ import { existsSync as existsSync14 } from "node:fs";
9994
+ import { join as join21 } from "node:path";
9924
9995
  import {
9925
9996
  classifyVideoExtractionError,
9926
9997
  createFrameLookupTable as createFrameLookupTable3,
@@ -10189,7 +10260,7 @@ async function runExtractVideosStage(input) {
10189
10260
  const probeFailures = await Promise.all(
10190
10261
  composition.videos.map(async (v) => {
10191
10262
  const videoPath = resolveProjectRelativeSrc3(v.src, projectDir, compiledDir);
10192
- if (!existsSync13(videoPath)) return null;
10263
+ if (!existsSync14(videoPath)) return null;
10193
10264
  try {
10194
10265
  const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata3(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata3(videoPath), {
10195
10266
  signal: abortSignal,
@@ -10227,7 +10298,7 @@ async function runExtractVideosStage(input) {
10227
10298
  const probed = await Promise.all(
10228
10299
  composition.images.map(async (img) => {
10229
10300
  const imgPath = resolveProjectRelativeSrc3(img.src, projectDir, compiledDir);
10230
- if (!existsSync13(imgPath)) return null;
10301
+ if (!existsSync14(imgPath)) return null;
10231
10302
  const colorSpace = await probeColorSpaceSafely(imgPath, log);
10232
10303
  if (isHdrColorSpace2(colorSpace)) {
10233
10304
  nativeHdrImageIds.add(img.id);
@@ -10261,14 +10332,14 @@ async function runExtractVideosStage(input) {
10261
10332
  // because short boundary counts can differ by one frame.
10262
10333
  {
10263
10334
  fps: job.config.fps,
10264
- outputDir: join20(compiledDir, "__hyperframes_video_frames"),
10335
+ outputDir: join21(compiledDir, "__hyperframes_video_frames"),
10265
10336
  format: job.config.videoFrameFormat ?? "auto",
10266
10337
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
10267
10338
  timelineEnd: composition.duration,
10268
10339
  maxTransientRetries: extractionPolicy.maxTransientRetries,
10269
10340
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
10270
10341
  deferRangeExtraction,
10271
- contentKeyedDirs: [join20(compiledDir, REMOTE_MEDIA_SUBDIR)],
10342
+ contentKeyedDirs: [join21(compiledDir, REMOTE_MEDIA_SUBDIR)],
10272
10343
  urlByAbsentLocalPath,
10273
10344
  onProgress: ({ planned = 0, done = 0 }) => {
10274
10345
  framesPlanned += planned;
@@ -10347,7 +10418,7 @@ async function appendVideoAudioFromProbe(input) {
10347
10418
  videos.map(async (video) => {
10348
10419
  const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc3(video.src, projectDir, compiledDir);
10349
10420
  const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
10350
- if (!isHttpUrl2(readFrom) && !existsSync13(readFrom)) return null;
10421
+ if (!isHttpUrl2(readFrom) && !existsSync14(readFrom)) return null;
10351
10422
  const metadata = await extractMediaMetadata3(readFrom);
10352
10423
  const window2 = await resolveFinalFrameExtractionWindow2(
10353
10424
  readFrom,
@@ -10367,7 +10438,7 @@ async function appendVideoAudioFromProbe(input) {
10367
10438
  }
10368
10439
 
10369
10440
  // src/services/render/videoLayerPassthroughPlan.ts
10370
- import { existsSync as existsSync14 } from "node:fs";
10441
+ import { existsSync as existsSync15 } from "node:fs";
10371
10442
  import {
10372
10443
  buildVideoLayerInput,
10373
10444
  isHttpUrl as isHttpUrl3,
@@ -10435,7 +10506,7 @@ async function planVideoLayerPassthrough(input) {
10435
10506
  const { video } = q;
10436
10507
  if (isHttpUrl3(video.src)) return { reason: "remote_source" };
10437
10508
  const path = resolveProjectRelativeSrc4(video.src, input.projectDir, input.compiledDir);
10438
- if (!existsSync14(path)) return { reason: "source_missing" };
10509
+ if (!existsSync15(path)) return { reason: "source_missing" };
10439
10510
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
10440
10511
  if ("reason" in layout) return layout;
10441
10512
  const layer = await buildVideoLayerInput(
@@ -10450,8 +10521,8 @@ async function planVideoLayerPassthrough(input) {
10450
10521
  }
10451
10522
 
10452
10523
  // src/services/render/stages/audioStage.ts
10453
- import { existsSync as existsSync16 } from "node:fs";
10454
- import { join as join23 } from "node:path";
10524
+ import { existsSync as existsSync17 } from "node:fs";
10525
+ import { join as join24 } from "node:path";
10455
10526
  import {
10456
10527
  MIXED_AUDIO_FILENAME,
10457
10528
  audioFailureDiagnostics,
@@ -10461,8 +10532,8 @@ import {
10461
10532
  } from "@hyperframes/engine";
10462
10533
 
10463
10534
  // src/services/render/audioDeliveryLimit.ts
10464
- import { existsSync as existsSync15 } from "node:fs";
10465
- import { dirname as dirname10, join as join22 } from "node:path";
10535
+ import { existsSync as existsSync16 } from "node:fs";
10536
+ import { dirname as dirname10, join as join23 } from "node:path";
10466
10537
  import {
10467
10538
  applyAudioFxChain,
10468
10539
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -10472,7 +10543,7 @@ import {
10472
10543
 
10473
10544
  // src/services/render/audioPadTrim.ts
10474
10545
  import { spawn } from "node:child_process";
10475
- import { dirname as dirname9, join as join21 } from "node:path";
10546
+ import { dirname as dirname9, join as join22 } from "node:path";
10476
10547
  import {
10477
10548
  DEFAULT_CONFIG,
10478
10549
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -10752,7 +10823,7 @@ async function constrainAacTruePeak(input) {
10752
10823
  }
10753
10824
  async function cutSource(input, scratchDir, attenuationDb) {
10754
10825
  if (!input.sourcePath || !input.rewriteSource) return true;
10755
- const cutPath = join21(scratchDir, "source.wav");
10826
+ const cutPath = join22(scratchDir, "source.wav");
10756
10827
  try {
10757
10828
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
10758
10829
  if (!result.success) throw new Error(result.error);
@@ -10767,7 +10838,7 @@ async function enforceAacTruePeak(input) {
10767
10838
  let scratchDir;
10768
10839
  try {
10769
10840
  scratchDir = createStagingDir3(dirname9(input.audioPath), ".true-peak-");
10770
- const correctedPath = join21(scratchDir, "audio.m4a");
10841
+ const correctedPath = join22(scratchDir, "audio.m4a");
10771
10842
  const measurements = [];
10772
10843
  let attenuationDb = 0;
10773
10844
  let sourcePeakDbfs;
@@ -10970,14 +11041,14 @@ async function limitDeliveryPeaks(input, deps = {
10970
11041
  applyChain: applyAudioFxChain,
10971
11042
  encode: encodeAac2,
10972
11043
  rename: renameWithRetry6,
10973
- sourceExists: existsSync15
11044
+ sourceExists: existsSync16
10974
11045
  }) {
10975
11046
  const { audioPath, sourcePath, signal, timeoutMs } = input;
10976
11047
  if (!deps.sourceExists(sourcePath)) return { success: true };
10977
11048
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
10978
11049
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
10979
11050
  const alternating = ["a", "b"].map(
10980
- (k) => join22(dirname10(sourcePath), `audio-source-limited-${k}.wav`)
11051
+ (k) => join23(dirname10(sourcePath), `audio-source-limited-${k}.wav`)
10981
11052
  );
10982
11053
  let encodedFrom;
10983
11054
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -11049,7 +11120,7 @@ function runAudioStage(input) {
11049
11120
  }
11050
11121
  async function runAudioStageScoped(input) {
11051
11122
  const stageStart = Date.now();
11052
- const pcmSourcePath = join23(input.workDir, "audio-source.wav");
11123
+ const pcmSourcePath = join24(input.workDir, "audio-source.wav");
11053
11124
  const duration = input.totalFrames * input.fps.den / input.fps.num;
11054
11125
  let deliverySourcePath;
11055
11126
  try {
@@ -11065,7 +11136,7 @@ async function runAudioStageScoped(input) {
11065
11136
  );
11066
11137
  audioLoweredDb = guard.loweredDb;
11067
11138
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
11068
- if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
11139
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
11069
11140
  deliverySourcePath = pcmSourcePath;
11070
11141
  }
11071
11142
  }
@@ -11114,7 +11185,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11114
11185
  assertNotAborted,
11115
11186
  log
11116
11187
  } = input;
11117
- const audioOutputPath = join23(workDir, MIXED_AUDIO_FILENAME);
11188
+ const audioOutputPath = join24(workDir, MIXED_AUDIO_FILENAME);
11118
11189
  let hasAudio = false;
11119
11190
  let audioError;
11120
11191
  let audioFailures;
@@ -11125,7 +11196,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11125
11196
  audioResult = await processCompositionAudio(
11126
11197
  audios,
11127
11198
  projectDir,
11128
- join23(workDir, "audio-work"),
11199
+ join24(workDir, "audio-work"),
11129
11200
  audioOutputPath,
11130
11201
  duration,
11131
11202
  abortSignal,
@@ -11193,8 +11264,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11193
11264
  }
11194
11265
 
11195
11266
  // src/services/render/stages/captureStage.ts
11196
- import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11197
- import { join as join24 } from "node:path";
11267
+ import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
11268
+ import { join as join25 } from "node:path";
11198
11269
  import {
11199
11270
  classifyCaptureFailure as classifyCaptureFailure2,
11200
11271
  frameFileExtension,
@@ -11264,16 +11335,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
11264
11335
  }
11265
11336
  function measureCaptureFrameBytes(workDir, framesDir) {
11266
11337
  let total = sampleDirectoryBytes(framesDir);
11267
- if (!existsSync17(workDir)) return total;
11338
+ if (!existsSync18(workDir)) return total;
11268
11339
  for (const attempt of readdirSync4(workDir)) {
11269
11340
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
11270
- total += sampleDirectoryBytes(join24(workDir, attempt));
11341
+ total += sampleDirectoryBytes(join25(workDir, attempt));
11271
11342
  continue;
11272
11343
  }
11273
11344
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
11274
- const attemptDir = join24(workDir, attempt);
11345
+ const attemptDir = join25(workDir, attempt);
11275
11346
  for (const name of readdirSync4(attemptDir)) {
11276
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join24(attemptDir, name));
11347
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join25(attemptDir, name));
11277
11348
  }
11278
11349
  }
11279
11350
  return total;
@@ -11571,8 +11642,8 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
11571
11642
  }
11572
11643
 
11573
11644
  // src/services/render/stages/captureHdrStage.ts
11574
- import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
11575
- import { join as join28 } from "node:path";
11645
+ import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
11646
+ import { join as join29 } from "node:path";
11576
11647
  import {
11577
11648
  closeCaptureSession as closeCaptureSession7,
11578
11649
  cloneCaptureWarnings as cloneCaptureWarnings2,
@@ -11644,7 +11715,7 @@ function createHdrImageTransferCache(options = {}) {
11644
11715
  }
11645
11716
 
11646
11717
  // src/services/render/stages/captureHdrSequentialLoop.ts
11647
- import { join as join25 } from "node:path";
11718
+ import { join as join26 } from "node:path";
11648
11719
  import {
11649
11720
  TRANSITIONS,
11650
11721
  crossfade
@@ -11769,7 +11840,7 @@ async function runSequentialLayeredFrameLoop(input) {
11769
11840
  );
11770
11841
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
11771
11842
  writeFileExclusiveSync(
11772
- join25(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
11843
+ join26(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
11773
11844
  normalCanvas
11774
11845
  );
11775
11846
  }
@@ -11801,7 +11872,7 @@ async function runSequentialLayeredFrameLoop(input) {
11801
11872
  }
11802
11873
 
11803
11874
  // src/services/render/stages/captureHdrHybridLoop.ts
11804
- import { join as join27 } from "node:path";
11875
+ import { join as join28 } from "node:path";
11805
11876
  import {
11806
11877
  TRANSITIONS as TRANSITIONS2,
11807
11878
  closeCaptureSession as closeCaptureSession6,
@@ -11815,9 +11886,9 @@ import {
11815
11886
  // src/services/shaderTransitionWorkerPool.ts
11816
11887
  import { Worker } from "node:worker_threads";
11817
11888
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
11818
- import { dirname as dirname11, join as join26 } from "node:path";
11889
+ import { dirname as dirname11, join as join27 } from "node:path";
11819
11890
  import { createRequire } from "node:module";
11820
- import { existsSync as existsSync18 } from "node:fs";
11891
+ import { existsSync as existsSync19 } from "node:fs";
11821
11892
  import { cpus as cpus2 } from "node:os";
11822
11893
  function resolveWorkerEntry(explicit) {
11823
11894
  if (explicit && explicit.length > 0) {
@@ -11829,9 +11900,9 @@ function resolveWorkerEntry(explicit) {
11829
11900
  return { path: override, isTs };
11830
11901
  }
11831
11902
  const moduleDir = dirname11(fileURLToPath3(import.meta.url));
11832
- const jsPath = join26(moduleDir, "shaderTransitionWorker.js");
11833
- if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
11834
- const tsPath = join26(moduleDir, "shaderTransitionWorker.ts");
11903
+ const jsPath = join27(moduleDir, "shaderTransitionWorker.js");
11904
+ if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
11905
+ const tsPath = join27(moduleDir, "shaderTransitionWorker.ts");
11835
11906
  return { path: tsPath, isTs: true };
11836
11907
  }
11837
11908
  function buildExecArgv(entryIsTs) {
@@ -12199,7 +12270,7 @@ async function runHybridLayeredFrameLoop(input) {
12199
12270
  );
12200
12271
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
12201
12272
  writeFileExclusiveSync(
12202
- join27(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12273
+ join28(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12203
12274
  canvas
12204
12275
  );
12205
12276
  }
@@ -12390,8 +12461,8 @@ async function runCaptureHdrStage(input) {
12390
12461
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
12391
12462
  }
12392
12463
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
12393
- const debugDumpDir = debugDumpEnabled ? join28(framesDir, "debug-composite") : null;
12394
- if (debugDumpDir && !existsSync19(debugDumpDir)) {
12464
+ const debugDumpDir = debugDumpEnabled ? join29(framesDir, "debug-composite") : null;
12465
+ if (debugDumpDir && !existsSync20(debugDumpDir)) {
12395
12466
  mkdirSync10(debugDumpDir, { recursive: true });
12396
12467
  }
12397
12468
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -12548,16 +12619,16 @@ async function runCaptureHdrStage(input) {
12548
12619
  // src/services/render/stages/encodeStage.ts
12549
12620
  import {
12550
12621
  copyFileSync as copyFileSync4,
12551
- existsSync as existsSync20,
12622
+ existsSync as existsSync21,
12552
12623
  mkdirSync as mkdirSync11,
12553
12624
  readdirSync as readdirSync5,
12554
- readFileSync as readFileSync8,
12625
+ readFileSync as readFileSync9,
12555
12626
  rmSync as rmSync11,
12556
12627
  statSync as statSync8,
12557
12628
  writeFileSync as writeFileSync6
12558
12629
  } from "node:fs";
12559
12630
  import { readFile as readFile2 } from "node:fs/promises";
12560
- import { dirname as dirname12, join as join29 } from "node:path";
12631
+ import { dirname as dirname12, join as join30 } from "node:path";
12561
12632
  import {
12562
12633
  encodeFramesChunkedConcat,
12563
12634
  encodeFramesFromDir,
@@ -12645,7 +12716,7 @@ async function reencodeWithClearedWholeFrames(argsInput, run, startTime) {
12645
12716
  const error = formatFfmpegError(result.exitCode, result.stderr);
12646
12717
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
12647
12718
  }
12648
- const gif = readFileSync8(outputPath);
12719
+ const gif = readFileSync9(outputPath);
12649
12720
  if (!clearGifFramesBeforeNext(gif)) {
12650
12721
  const error = "[FFmpeg] GIF output could not be parsed to clear its frames";
12651
12722
  return gifEncodeFailure(startTime, outputPath, error);
@@ -12678,11 +12749,11 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
12678
12749
  return gifEncodeFailure(startTime, outputPath, error, result.failureReason);
12679
12750
  }
12680
12751
  }
12681
- if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync8(outputPath)) !== false) {
12752
+ if (input.preserveAlpha && gifClearsAfterLeavingFrameInPlace(readFileSync9(outputPath)) !== false) {
12682
12753
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
12683
12754
  if (failure) return failure;
12684
12755
  }
12685
- const fileSize = existsSync20(outputPath) ? statSync8(outputPath).size : 0;
12756
+ const fileSize = existsSync21(outputPath) ? statSync8(outputPath).size : 0;
12686
12757
  return {
12687
12758
  success: true,
12688
12759
  outputPath,
@@ -12768,7 +12839,7 @@ function encodeWhileCapturing(input, totalFrames) {
12768
12839
  await new Promise((resolve11) => wake = resolve11);
12769
12840
  }
12770
12841
  if (signal.aborted) return;
12771
- const mergedPath = join29(input.framesDir, formatCaptureFrameName(next, "jpg"));
12842
+ const mergedPath = join30(input.framesDir, formatCaptureFrameName(next, "jpg"));
12772
12843
  const frame = await readLandedFrame(landed.get(next), mergedPath);
12773
12844
  landed.delete(next);
12774
12845
  if (!await stream.writeFrame(frame)) {
@@ -12843,7 +12914,7 @@ async function runEncodeStage(input) {
12843
12914
  const stage5Start = Date.now();
12844
12915
  if (isPngSequence) {
12845
12916
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
12846
- if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
12917
+ if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
12847
12918
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
12848
12919
  if (captured.length === 0) {
12849
12920
  throw new Error(
@@ -12851,11 +12922,11 @@ async function runEncodeStage(input) {
12851
12922
  );
12852
12923
  }
12853
12924
  captured.forEach((name, i) => {
12854
- const dst = join29(outputPath, formatExportFrameName(i, "png"));
12855
- copyFileSync4(join29(framesDir, name), dst);
12925
+ const dst = join30(outputPath, formatExportFrameName(i, "png"));
12926
+ copyFileSync4(join30(framesDir, name), dst);
12856
12927
  });
12857
- if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
12858
- copyFileSync4(audioOutputPath, join29(outputPath, MIXED_AUDIO_FILENAME2));
12928
+ if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
12929
+ copyFileSync4(audioOutputPath, join30(outputPath, MIXED_AUDIO_FILENAME2));
12859
12930
  log.info(
12860
12931
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
12861
12932
  );
@@ -12875,7 +12946,7 @@ async function runEncodeStage(input) {
12875
12946
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
12876
12947
  fps: job.config.fps,
12877
12948
  loop,
12878
- palettePath: join29(dirname12(videoOnlyPath), "gif-palette.png"),
12949
+ palettePath: join30(dirname12(videoOnlyPath), "gif-palette.png"),
12879
12950
  preserveAlpha: needsAlpha,
12880
12951
  signal: abortSignal,
12881
12952
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -13086,7 +13157,7 @@ function sampleDirectoryBytes(dir) {
13086
13157
  continue;
13087
13158
  }
13088
13159
  for (const name of entries) {
13089
- const full = join30(current, name);
13160
+ const full = join31(current, name);
13090
13161
  try {
13091
13162
  const st = statSync9(full);
13092
13163
  if (st.isDirectory()) {
@@ -13242,8 +13313,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
13242
13313
  const ranges = [];
13243
13314
  let rangeStart = null;
13244
13315
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13245
- const framePath = join30(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13246
- const missing = !existsSync21(framePath) || statSync9(framePath).size <= 8;
13316
+ const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13317
+ const missing = !existsSync22(framePath) || statSync9(framePath).size <= 8;
13247
13318
  if (missing && rangeStart === null) {
13248
13319
  rangeStart = frameIndex;
13249
13320
  } else if (!missing && rangeStart !== null) {
@@ -13259,7 +13330,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
13259
13330
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
13260
13331
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
13261
13332
  const batches = [];
13262
- const outputDirFor = (batchIndex, workerId) => join30(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
13333
+ const outputDirFor = (batchIndex, workerId) => join31(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
13263
13334
  if (stride > 1) {
13264
13335
  const spans = /* @__PURE__ */ new Map();
13265
13336
  for (const range of ranges) {
@@ -13319,8 +13390,8 @@ function getNextRetryWorkerCount(currentWorkers) {
13319
13390
  return Math.max(1, Math.floor(currentWorkers / 2));
13320
13391
  }
13321
13392
  function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
13322
- if (platform2 === "win32" || platform2 === "darwin") return join30(systemTempDir, "hf-render-");
13323
- return join30(dirname13(outputPath), `work-${jobId}-`);
13393
+ if (platform2 === "win32" || platform2 === "darwin") return join31(systemTempDir, "hf-render-");
13394
+ return join31(dirname13(outputPath), `work-${jobId}-`);
13324
13395
  }
13325
13396
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
13326
13397
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -13333,13 +13404,20 @@ function resetCaptureAttemptProgress(job) {
13333
13404
  job.framesRendered = 0;
13334
13405
  }
13335
13406
  var FIRST_FRAME_STALL_MS = 3e5;
13407
+ var FIRST_FRAME_STARTUP_FACTOR = 2;
13408
+ var FIRST_FRAME_STALL_CEILING_MS = 9e5;
13336
13409
  var TAIL_STALL_MS = FIRST_FRAME_STALL_MS;
13337
- function frameStallRule(job, totalFrames) {
13410
+ function firstFrameWindowMs(probeStartupMs) {
13411
+ const fromStartup = (probeStartupMs ?? 0) * FIRST_FRAME_STARTUP_FACTOR;
13412
+ if (!Number.isFinite(fromStartup)) return FIRST_FRAME_STALL_MS;
13413
+ return Math.max(FIRST_FRAME_STALL_MS, Math.min(FIRST_FRAME_STALL_CEILING_MS, fromStartup));
13414
+ }
13415
+ function frameStallRule(job, totalFrames, probeStartupMs) {
13338
13416
  const noProgressMs = resolveCaptureStallTimeoutMs();
13339
13417
  return {
13340
13418
  progress: () => job.framesRendered ?? 0,
13341
13419
  noProgressMs,
13342
- firstProgressMs: Math.max(FIRST_FRAME_STALL_MS, noProgressMs),
13420
+ firstProgressMs: Math.max(firstFrameWindowMs(probeStartupMs), noProgressMs),
13343
13421
  complete: () => (job.framesRendered ?? 0) >= totalFrames,
13344
13422
  tailMs: Math.max(TAIL_STALL_MS, noProgressMs),
13345
13423
  detail: () => describeWorkerPhases(job),
@@ -13367,8 +13445,8 @@ The composition is too large for the available memory. To reduce memory pressure
13367
13445
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
13368
13446
  let captured = 0;
13369
13447
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
13370
- const framePath = join30(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13371
- if (existsSync21(framePath)) captured++;
13448
+ const framePath = join31(framesDir, formatCaptureFrameName(frameIndex, frameExt));
13449
+ if (existsSync22(framePath)) captured++;
13372
13450
  }
13373
13451
  return captured;
13374
13452
  }
@@ -13393,7 +13471,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
13393
13471
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
13394
13472
  });
13395
13473
  pendingTransientRetry = false;
13396
- const attemptWorkDir = join30(options.workDir, `capture-attempt-${attempt}`);
13474
+ const attemptWorkDir = join31(options.workDir, `capture-attempt-${attempt}`);
13397
13475
  const batches = missingRanges ? buildMissingFrameRetryBatches(
13398
13476
  missingRanges,
13399
13477
  currentWorkers,
@@ -14026,18 +14104,19 @@ function deVerifyFallbackTelemetry(err) {
14026
14104
  }
14027
14105
  function resolveRenderDebugDir() {
14028
14106
  const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname13(fileURLToPath4(import.meta.url)), "../..");
14029
- return join30(producerRoot, ".debug");
14107
+ return join31(producerRoot, ".debug");
14030
14108
  }
14031
14109
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
14032
14110
  validateHlsRenderConfig(job.config);
14033
14111
  validateDeliveryEncoderConfig(job.config);
14112
+ validateChromaSubsamplingConfig(job.config);
14034
14113
  const debugDir = resolveRenderDebugDir();
14035
14114
  const outputDir = dirname13(outputPath);
14036
- if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
14037
- const workDir = job.config.debug ? join30(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14115
+ if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
14116
+ const workDir = job.config.debug ? join31(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14038
14117
  const pipelineStart = Date.now();
14039
14118
  const baseLog = job.config.logger ?? defaultLogger;
14040
- const logPath = job.config.debug ? join30(workDir, "render.log") : null;
14119
+ const logPath = job.config.debug ? join31(workDir, "render.log") : null;
14041
14120
  const execution = new RenderExecutionContext({
14042
14121
  request: { renderJobId: job.id, projectDir, outputPath },
14043
14122
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -14099,7 +14178,7 @@ async function executeRenderPipeline(input) {
14099
14178
  imageDecodeFailures: 0
14100
14179
  };
14101
14180
  let hdrPerf;
14102
- const perfOutputPath = join30(workDir, "perf-summary.json");
14181
+ const perfOutputPath = join31(workDir, "perf-summary.json");
14103
14182
  const cfg = { ...job.config.producerConfig ?? resolveConfig2() };
14104
14183
  const observability = new RenderObservabilityRecorder({
14105
14184
  pipelineStartMs: pipelineStart,
@@ -14175,7 +14254,7 @@ async function executeRenderPipeline(input) {
14175
14254
  job.startedAt = /* @__PURE__ */ new Date();
14176
14255
  assertNotAborted();
14177
14256
  assertConfiguredFfmpegBinariesExist();
14178
- if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
14257
+ if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
14179
14258
  if (job.config.debug) {
14180
14259
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
14181
14260
  }
@@ -14204,8 +14283,8 @@ async function executeRenderPipeline(input) {
14204
14283
  requestedWorkers: job.config.workers ?? "auto"
14205
14284
  });
14206
14285
  const entryFile = job.config.entryFile || "index.html";
14207
- const htmlPath = join30(projectDir, entryFile);
14208
- if (!existsSync21(htmlPath)) {
14286
+ const htmlPath = join31(projectDir, entryFile);
14287
+ if (!existsSync22(htmlPath)) {
14209
14288
  throw new Error(`Entry file not found: ${htmlPath}`);
14210
14289
  }
14211
14290
  assertNotAborted();
@@ -14381,7 +14460,7 @@ async function executeRenderPipeline(input) {
14381
14460
  canvas: { width, height },
14382
14461
  page: probeSession.page,
14383
14462
  projectDir,
14384
- compiledDir: join30(workDir, "compiled")
14463
+ compiledDir: join31(workDir, "compiled")
14385
14464
  });
14386
14465
  if (videoLayerPlan.videoId === void 0) {
14387
14466
  log.info(`[Render] Video layer passthrough off: ${videoLayerPlan.reason}`);
@@ -14399,7 +14478,7 @@ async function executeRenderPipeline(input) {
14399
14478
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
14400
14479
  code: "extract_video"
14401
14480
  });
14402
- const compiledDir = join30(workDir, "compiled");
14481
+ const compiledDir = join31(workDir, "compiled");
14403
14482
  const segmentsCapture = (layeredOrEffectRoute) => shouldSegmentCapture({
14404
14483
  env: process.env,
14405
14484
  durationSeconds: probeResult.duration,
@@ -14530,7 +14609,7 @@ async function executeRenderPipeline(input) {
14530
14609
  try {
14531
14610
  fileServer = await createFileServer({
14532
14611
  projectDir,
14533
- compiledDir: join30(workDir, "compiled"),
14612
+ compiledDir: join31(workDir, "compiled"),
14534
14613
  port: 0,
14535
14614
  preHeadScripts: [VIRTUAL_TIME_SHIM],
14536
14615
  fps: job.config.fps
@@ -14548,8 +14627,8 @@ async function executeRenderPipeline(input) {
14548
14627
  if (!activeFileServer) {
14549
14628
  throw new Error("File server failed to initialize before frame capture");
14550
14629
  }
14551
- const framesDir = join30(workDir, "captured-frames");
14552
- if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
14630
+ const framesDir = join31(workDir, "captured-frames");
14631
+ if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
14553
14632
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
14554
14633
  code: "start_browsers"
14555
14634
  });
@@ -14568,18 +14647,28 @@ async function executeRenderPipeline(input) {
14568
14647
  forceScreenshot: captureForceScreenshot
14569
14648
  });
14570
14649
  const videoCaptureBeyondViewport = resolveVideoCaptureBeyondViewport(composition.videos.length);
14571
- const captureImageFormat = resolveCaptureImageFormat({
14572
- needsAlpha,
14573
- motionBlur: job.config.motionBlur
14574
- });
14650
+ const captureSurface = resolveCaptureSurface(
14651
+ {
14652
+ needsAlpha,
14653
+ motionBlur: job.config.motionBlur,
14654
+ chromaSubsampling: job.config.chromaSubsampling
14655
+ },
14656
+ job.config.quality
14657
+ );
14658
+ if (job.config.chromaSubsampling === "444") {
14659
+ log.info("[Render] Capture: png (chromaSubsampling 444, lossless)");
14660
+ }
14575
14661
  const captureOptions = {
14576
14662
  width,
14577
14663
  height,
14578
14664
  fps: job.config.fps,
14579
- format: videoLayer ? "png" : captureImageFormat,
14580
- transparent: needsAlpha || videoLayer !== void 0,
14581
- ...videoLayer ? { hiddenElementIds: [videoLayer.videoId] } : {},
14582
- quality: captureImageFormat === "png" ? void 0 : resolveCaptureJpegQuality(job.config.quality),
14665
+ ...captureSurface,
14666
+ ...videoLayer ? {
14667
+ format: "png",
14668
+ quality: void 0,
14669
+ transparent: true,
14670
+ hiddenElementIds: [videoLayer.videoId]
14671
+ } : {},
14583
14672
  variables: job.config.variables,
14584
14673
  deviceScaleFactor,
14585
14674
  motionBlur: job.config.motionBlur,
@@ -14686,6 +14775,7 @@ async function executeRenderPipeline(input) {
14686
14775
  );
14687
14776
  const nativeHdrIds = /* @__PURE__ */ new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
14688
14777
  const hasHdrContent = Boolean(effectiveHdr && nativeHdrIds.size > 0);
14778
+ assertChromaSubsamplingSdr(job.config, hasHdrContent);
14689
14779
  if (hasHdrContent) assertOutputScaleSupported(deviceScaleFactor, "hdr_layered");
14690
14780
  routePageMotionBlur = pageMotionBlurForRoute({ hasHdrContent, useLayeredComposite: false });
14691
14781
  const deSingleMinFrames = resolveDeSingleMinFrames(process.env);
@@ -15113,7 +15203,7 @@ async function executeRenderPipeline(input) {
15113
15203
  hls: ".mp4"
15114
15204
  };
15115
15205
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
15116
- const videoOnlyPath = join30(workDir, `video-only${videoExt}`);
15206
+ const videoOnlyPath = join31(workDir, `video-only${videoExt}`);
15117
15207
  const usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15118
15208
  if (usePageSideCompositingForTransitions) {
15119
15209
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -15268,7 +15358,9 @@ async function executeRenderPipeline(input) {
15268
15358
  usePageSideCompositing: capturePlan.usePageSideCompositing,
15269
15359
  hasHdrContent: capturePlan.hasHdrContent,
15270
15360
  hasShaderTransitions: compiled.hasShaderTransitions,
15271
- isPngSequence
15361
+ isPngSequence,
15362
+ captureImageFormat: captureOptions.format ?? "jpeg",
15363
+ chromaSubsampling: job.config.chromaSubsampling ?? "420"
15272
15364
  });
15273
15365
  const encoderHdr = hasHdrContent ? effectiveHdr : void 0;
15274
15366
  const presetFormat = outputFormat === "webm" || outputFormat === "mov" ? outputFormat : "mp4";
@@ -15276,7 +15368,8 @@ async function executeRenderPipeline(input) {
15276
15368
  job.config.quality,
15277
15369
  presetFormat,
15278
15370
  encoderHdr,
15279
- job.config.proresProfile
15371
+ job.config.proresProfile,
15372
+ job.config.chromaSubsampling
15280
15373
  );
15281
15374
  if (job.config.crf != null && job.config.videoBitrate) {
15282
15375
  log.warn(
@@ -15358,7 +15451,7 @@ async function executeRenderPipeline(input) {
15358
15451
  onProgress
15359
15452
  });
15360
15453
  },
15361
- { stall: frameStallRule(job, totalFrames) }
15454
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15362
15455
  );
15363
15456
  lastBrowserConsole = hdrRes.lastBrowserConsole;
15364
15457
  layeredCaptureWarnings.push(...hdrRes.warnings);
@@ -15399,7 +15492,7 @@ async function executeRenderPipeline(input) {
15399
15492
  pageMotionBlur: job.config.pageMotionBlur,
15400
15493
  captureQuality: captureOptions.quality
15401
15494
  });
15402
- const segmentDir = segmentDirFor(join30(projectDir, "renders"), segmentPlanHash);
15495
+ const segmentDir = segmentDirFor(join31(projectDir, "renders"), segmentPlanHash);
15403
15496
  let completedSegments = /* @__PURE__ */ new Set();
15404
15497
  if (job.config.resumeSegments === true) {
15405
15498
  const existing = readSegmentManifest(segmentDir);
@@ -15810,7 +15903,7 @@ async function executeRenderPipeline(input) {
15810
15903
  interleaveFrames: overlap !== null,
15811
15904
  openAttempt
15812
15905
  }),
15813
- { stall: frameStallRule(job, totalFrames) }
15906
+ { stall: frameStallRule(job, totalFrames, perfStages.browserProbeMs) }
15814
15907
  );
15815
15908
  let captureRes;
15816
15909
  try {
@@ -15940,7 +16033,7 @@ async function executeRenderPipeline(input) {
15940
16033
  })
15941
16034
  );
15942
16035
  const totalElapsed = Date.now() - pipelineStart;
15943
- const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
16036
+ const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
15944
16037
  recordTransientRetryObservability();
15945
16038
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
15946
16039
  const observabilitySummary = observability.summary({
@@ -16021,8 +16114,8 @@ async function executeRenderPipeline(input) {
16021
16114
  }
16022
16115
  }
16023
16116
  if (job.config.debug) {
16024
- if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
16025
- const debugOutput = join30(workDir, `output${videoExt}`);
16117
+ if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
16118
+ const debugOutput = join31(workDir, `output${videoExt}`);
16026
16119
  copyFileSync5(stagedOutputPath, debugOutput);
16027
16120
  }
16028
16121
  }
@@ -16133,15 +16226,15 @@ async function executeRenderPipeline(input) {
16133
16226
 
16134
16227
  // src/services/hyperframeLint.ts
16135
16228
  import {
16136
- existsSync as existsSync22,
16137
- readFileSync as readFileSync9,
16229
+ existsSync as existsSync23,
16230
+ readFileSync as readFileSync10,
16138
16231
  statSync as statSync10,
16139
16232
  openSync as openSync5,
16140
16233
  fstatSync as fstatSync3,
16141
16234
  closeSync as closeSync5,
16142
16235
  constants as constants3
16143
16236
  } from "node:fs";
16144
- import { resolve as resolve9, join as join31, relative as relative3, isAbsolute as isAbsolute3, sep as sep3 } from "node:path";
16237
+ import { resolve as resolve9, join as join32, relative as relative3, isAbsolute as isAbsolute3, sep as sep3 } from "node:path";
16145
16238
  import { lintHyperframeHtml } from "@hyperframes/lint";
16146
16239
  function isStringRecord(value) {
16147
16240
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -16180,14 +16273,14 @@ function readEntryHtml(filePath) {
16180
16273
  }
16181
16274
  try {
16182
16275
  if (!fstatSync3(fd).isFile()) return null;
16183
- return readFileSync9(fd, "utf-8");
16276
+ return readFileSync10(fd, "utf-8");
16184
16277
  } finally {
16185
16278
  closeSync5(fd);
16186
16279
  }
16187
16280
  }
16188
16281
  function readProjectEntryFile(projectDir, preferredEntryFile) {
16189
16282
  const absProjectDir = resolve9(projectDir);
16190
- if (!existsSync22(absProjectDir) || !statSync10(absProjectDir).isDirectory()) {
16283
+ if (!existsSync23(absProjectDir) || !statSync10(absProjectDir).isDirectory()) {
16191
16284
  return { error: `Project directory not found: ${absProjectDir}` };
16192
16285
  }
16193
16286
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -16209,7 +16302,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
16209
16302
  }
16210
16303
  }
16211
16304
  return {
16212
- error: `No HTML entry file found in project directory: ${join31(absProjectDir, preferredEntryFile || "index.html")}`
16305
+ error: `No HTML entry file found in project directory: ${join32(absProjectDir, preferredEntryFile || "index.html")}`
16213
16306
  };
16214
16307
  }
16215
16308
  function prepareHyperframeLintBody(body) {
@@ -16255,8 +16348,8 @@ async function runHyperframeLint(prepared) {
16255
16348
  // src/services/healthWorker.ts
16256
16349
  import { Worker as Worker2 } from "node:worker_threads";
16257
16350
  import { fileURLToPath as fileURLToPath5 } from "node:url";
16258
- import { dirname as dirname14, join as join32 } from "node:path";
16259
- import { existsSync as existsSync23 } from "node:fs";
16351
+ import { dirname as dirname14, join as join33 } from "node:path";
16352
+ import { existsSync as existsSync24 } from "node:fs";
16260
16353
  var DEFAULT_HEALTH_PORT = 9848;
16261
16354
  async function startHealthWorker(options = {}) {
16262
16355
  const log = options.logger ?? defaultLogger2();
@@ -16331,9 +16424,9 @@ function defaultLogger2() {
16331
16424
  }
16332
16425
  function resolveWorkerEntry2() {
16333
16426
  const here = dirname14(fileURLToPath5(import.meta.url));
16334
- const candidates = [join32(here, "healthWorkerThread.js"), join32(here, "healthWorkerThread.ts")];
16427
+ const candidates = [join33(here, "healthWorkerThread.js"), join33(here, "healthWorkerThread.ts")];
16335
16428
  for (const candidate of candidates) {
16336
- if (existsSync23(candidate)) return candidate;
16429
+ if (existsSync24(candidate)) return candidate;
16337
16430
  }
16338
16431
  return void 0;
16339
16432
  }
@@ -16373,7 +16466,7 @@ import {
16373
16466
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
16374
16467
  } from "@hyperframes/engine";
16375
16468
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
16376
- import { extname as extname4, isAbsolute as isAbsolute4, join as join33, relative as relative4, sep as sep4 } from "node:path";
16469
+ import { extname as extname4, isAbsolute as isAbsolute4, join as join35, relative as relative4, sep as sep4 } from "node:path";
16377
16470
  import {
16378
16471
  fpsToNumber as fpsToNumber9,
16379
16472
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -16399,11 +16492,15 @@ import {
16399
16492
  // src/services/distributed/chunkFrames.ts
16400
16493
  import {
16401
16494
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
16402
- createVideoFrameInjector as createVideoFrameInjector3
16495
+ createVideoFrameInjector as createVideoFrameInjector3,
16496
+ mediaIdPathSegment as mediaIdPathSegment3
16403
16497
  } from "@hyperframes/engine";
16404
16498
 
16405
16499
  // src/services/distributed/shared.ts
16406
16500
  import { execFile as execFileCallback } from "node:child_process";
16501
+ import { dirname as dirname15, join as join34 } from "node:path";
16502
+ import { existsSync as existsSync25, readFileSync as readFileSync11 } from "node:fs";
16503
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
16407
16504
  import { promisify as promisify2 } from "node:util";
16408
16505
  import {
16409
16506
  getFfmpegBinary,
@@ -16411,6 +16508,30 @@ import {
16411
16508
  } from "@hyperframes/engine";
16412
16509
  var PLAN_AUDIO_RELATIVE_PATH = MIXED_AUDIO_FILENAME3;
16413
16510
  var execFile = promisify2(execFileCallback);
16511
+ var cachedProducerVersion = null;
16512
+ function readProducerVersion() {
16513
+ if (cachedProducerVersion !== null) return cachedProducerVersion;
16514
+ const startDir = dirname15(fileURLToPath6(import.meta.url));
16515
+ let current = startDir;
16516
+ for (let i = 0; i < 10; i++) {
16517
+ const candidate = join34(current, "package.json");
16518
+ if (existsSync25(candidate)) {
16519
+ try {
16520
+ const pkg = JSON.parse(readFileSync11(candidate, "utf-8"));
16521
+ if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
16522
+ cachedProducerVersion = pkg.version;
16523
+ return pkg.version;
16524
+ }
16525
+ } catch {
16526
+ }
16527
+ }
16528
+ const parent = dirname15(current);
16529
+ if (parent === current) break;
16530
+ current = parent;
16531
+ }
16532
+ cachedProducerVersion = "0.0.0-unknown";
16533
+ return cachedProducerVersion;
16534
+ }
16414
16535
 
16415
16536
  // src/services/distributed/chunkWeights.ts
16416
16537
  import { resolveFrameFormat } from "@hyperframes/engine";
@@ -16491,9 +16612,9 @@ var PLAN_ROOT_CATEGORY = {
16491
16612
  var PLAN_DIR_SIZE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024;
16492
16613
  var FREEZE_OWNED_PLAN_FILES = [
16493
16614
  "plan.json",
16494
- join33("meta", "composition.json"),
16495
- join33("meta", "encoder.json"),
16496
- join33("meta", "chunks.json")
16615
+ join35("meta", "composition.json"),
16616
+ join35("meta", "encoder.json"),
16617
+ join35("meta", "chunks.json")
16497
16618
  ];
16498
16619
 
16499
16620
  // src/services/distributed/renderConfigValidation.ts
@@ -16653,6 +16774,7 @@ function assertRequestOptionScalars(options) {
16653
16774
  assertOptionalEnum(options, "proresProfile", PRORES_PROFILE_NAMES2);
16654
16775
  assertOptionalEnum(options, "strictness", ["strict", "best-effort"]);
16655
16776
  assertOptionalEnum(options, "hdrMode", ["auto", "force-hdr", "force-sdr"]);
16777
+ assertOptionalEnum(options, "chromaSubsampling", ["420", "444"]);
16656
16778
  assertOptionalEnum(options, "pageMotionBlur", ["off"]);
16657
16779
  if (options.videoFrameFormat !== void 0 && !isVideoFrameFormat2(options.videoFrameFormat)) {
16658
16780
  throw new Error("Render request videoFrameFormat is invalid");
@@ -16813,7 +16935,15 @@ function parseRenderOptions(body) {
16813
16935
  const format = parseServerFormat(body.format);
16814
16936
  const outputDynamicRange = parseServerOutputDynamicRange(body.outputDynamicRange) ?? fromRenderHdrMode(parseLegacyServerHdrMode(body.hdrMode));
16815
16937
  const encoder = parseEncoderOptions(body, format ?? "mp4");
16816
- const { crf, videoBitrate, videoFrameFormat, keyframeIntervalSeconds, maxBitrate, bufferSize } = encoder.ok ? encoder.options : {};
16938
+ const {
16939
+ crf,
16940
+ videoBitrate,
16941
+ videoFrameFormat,
16942
+ keyframeIntervalSeconds,
16943
+ maxBitrate,
16944
+ bufferSize,
16945
+ chromaSubsampling
16946
+ } = encoder.ok ? encoder.options : {};
16817
16947
  const { variables, outputResolution, outputResolutionAspectAgnostic } = parseRenderOverrides(body);
16818
16948
  return {
16819
16949
  outputPath,
@@ -16826,6 +16956,7 @@ function parseRenderOptions(body) {
16826
16956
  keyframeIntervalSeconds,
16827
16957
  maxBitrate,
16828
16958
  bufferSize,
16959
+ chromaSubsampling,
16829
16960
  useGpu,
16830
16961
  debug,
16831
16962
  forceScreenshot,
@@ -16865,6 +16996,7 @@ function buildRenderJobConfig(input, outputPath, log) {
16865
16996
  keyframeIntervalSeconds: input.keyframeIntervalSeconds,
16866
16997
  maxBitrate: input.maxBitrate,
16867
16998
  bufferSize: input.bufferSize,
16999
+ chromaSubsampling: input.chromaSubsampling,
16868
17000
  useGpu: input.useGpu,
16869
17001
  debug: input.debug,
16870
17002
  strictness: input.strictness,
@@ -16882,16 +17014,29 @@ function buildRenderJobConfig(input, outputPath, log) {
16882
17014
  function resolvePreparedRenderOutput(prepared, rendersDir, log) {
16883
17015
  const { input, cleanupProjectDir } = prepared;
16884
17016
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
16885
- const outputDir = dirname15(absoluteOutputPath);
16886
- if (!existsSync24(outputDir)) mkdirSync13(outputDir, { recursive: true });
17017
+ const outputDir = dirname16(absoluteOutputPath);
17018
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
16887
17019
  return { input, cleanupProjectDir, absoluteOutputPath };
16888
17020
  }
17021
+ function prepareRenderJob(prepared, rendersDir, log) {
17022
+ try {
17023
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
17024
+ const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
17025
+ return { ...output, job };
17026
+ } catch (error) {
17027
+ cleanupTempDir(prepared.cleanupProjectDir, log);
17028
+ return { error: error instanceof Error ? error.message : String(error) };
17029
+ }
17030
+ }
16889
17031
  function validateRenderOverrides(body) {
16890
17032
  const encoder = parseEncoderOptions(body, parseServerFormat(body.format) ?? "mp4");
16891
17033
  if (!encoder.ok) return encoder.error;
16892
17034
  if (body.maxRenderMs !== void 0 && (typeof body.maxRenderMs !== "number" || !Number.isInteger(body.maxRenderMs) || body.maxRenderMs < 0)) {
16893
17035
  return "maxRenderMs must be a non-negative integer number of milliseconds";
16894
17036
  }
17037
+ if (typeof body.workers === "number" && (!Number.isInteger(body.workers) || body.workers < 1)) {
17038
+ return "workers must be a positive integer";
17039
+ }
16895
17040
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
16896
17041
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
16897
17042
  }
@@ -16906,6 +17051,9 @@ function validateRenderOverrides(body) {
16906
17051
  if (outputDynamicRange !== void 0 && legacyHdrMode !== void 0 && outputDynamicRange !== fromRenderHdrMode(legacyHdrMode)) {
16907
17052
  return "outputDynamicRange and legacy hdrMode must describe the same output policy";
16908
17053
  }
17054
+ if (body.chromaSubsampling === "444" && outputDynamicRange === "hdr") {
17055
+ return 'chromaSubsampling "444" is SDR only, not outputDynamicRange "hdr"';
17056
+ }
16909
17057
  return validateOutputResolutionOverride(body);
16910
17058
  }
16911
17059
  function validateOutputResolutionOverride(body) {
@@ -16924,11 +17072,11 @@ function prepareProjectDirectory(projectDir, options) {
16924
17072
  const candidate = nonEmptyString(projectDir);
16925
17073
  if (!candidate) return null;
16926
17074
  const absProjectDir = resolve10(candidate);
16927
- if (!existsSync24(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
17075
+ if (!existsSync26(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
16928
17076
  return { error: `Project directory not found: ${absProjectDir}` };
16929
17077
  }
16930
17078
  const entry = options.entryFile || "index.html";
16931
- if (!existsSync24(resolve10(absProjectDir, entry))) {
17079
+ if (!existsSync26(resolve10(absProjectDir, entry))) {
16932
17080
  return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
16933
17081
  }
16934
17082
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -16949,8 +17097,8 @@ async function resolveInlineRenderHtml(body) {
16949
17097
  }
16950
17098
  function materializeInlineProject(html, options) {
16951
17099
  const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir3();
16952
- const tempProjectDir = mkdtempSync(join34(tempRoot, "producer-project-"));
16953
- writeFileSync8(join34(tempProjectDir, "index.html"), html, "utf-8");
17100
+ const tempProjectDir = mkdtempSync(join36(tempRoot, "producer-project-"));
17101
+ writeFileSync8(join36(tempProjectDir, "index.html"), html, "utf-8");
16954
17102
  return {
16955
17103
  prepared: {
16956
17104
  input: { projectDir: tempProjectDir, ...options },
@@ -17020,7 +17168,7 @@ function cleanupTempDir(dir, log) {
17020
17168
  }
17021
17169
  }
17022
17170
  function outputFileSize(path) {
17023
- return existsSync24(path) ? statSync11(path).size : 0;
17171
+ return existsSync26(path) ? statSync11(path).size : 0;
17024
17172
  }
17025
17173
  function createBlockingProgressReporter(log, requestId) {
17026
17174
  let lastLoggedPct = -10;
@@ -17169,11 +17317,11 @@ function createRenderHandlers(options = {}) {
17169
17317
  if ("error" in preparedResult) {
17170
17318
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
17171
17319
  }
17172
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
17173
- preparedResult.prepared,
17174
- rendersDir,
17175
- log
17176
- );
17320
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
17321
+ if ("error" in preparedJob) {
17322
+ return c.json({ success: false, requestId, error: preparedJob.error }, 400);
17323
+ }
17324
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
17177
17325
  const release = await renderSemaphore.acquire();
17178
17326
  log.info("render started", {
17179
17327
  requestId,
@@ -17181,7 +17329,6 @@ function createRenderHandlers(options = {}) {
17181
17329
  fps: input.fps,
17182
17330
  quality: input.quality
17183
17331
  });
17184
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
17185
17332
  try {
17186
17333
  await executeRenderJob(
17187
17334
  job,
@@ -17249,13 +17396,20 @@ function createRenderHandlers(options = {}) {
17249
17396
  const t0 = Date.now();
17250
17397
  const prepared = await prepareSseRenderRequest(c, stream, requestId);
17251
17398
  if (!prepared) return;
17252
- const { input, cleanupProjectDir, absoluteOutputPath } = resolvePreparedRenderOutput(
17253
- prepared,
17254
- rendersDir,
17255
- log
17256
- );
17399
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log);
17400
+ if ("error" in preparedJob) {
17401
+ await stream.writeSSE({
17402
+ data: JSON.stringify({
17403
+ type: "error",
17404
+ requestId,
17405
+ error: preparedJob.error,
17406
+ stage: "validation"
17407
+ })
17408
+ });
17409
+ return;
17410
+ }
17411
+ const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
17257
17412
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
17258
- const job = createRenderJob(buildRenderJobConfig(input, absoluteOutputPath, log));
17259
17413
  const abortController = new AbortController();
17260
17414
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
17261
17415
  c.req.raw.signal.addEventListener("abort", onRequestAbort, { once: true });
@@ -17299,7 +17453,8 @@ function createRenderHandlers(options = {}) {
17299
17453
  videoDurationSeconds: job.duration ?? null,
17300
17454
  outcome: job.outcome ?? "completed",
17301
17455
  warnings: job.warnings,
17302
- perf: job.perfSummary ?? null
17456
+ perf: job.perfSummary ?? null,
17457
+ producerVersion: readProducerVersion()
17303
17458
  })
17304
17459
  });
17305
17460
  } catch (error) {
@@ -17324,7 +17479,7 @@ function createRenderHandlers(options = {}) {
17324
17479
  if (!artifact) {
17325
17480
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
17326
17481
  }
17327
- if (!existsSync24(artifact.path)) {
17482
+ if (!existsSync26(artifact.path)) {
17328
17483
  store.delete(token);
17329
17484
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
17330
17485
  }
@@ -17344,9 +17499,26 @@ function createRenderHandlers(options = {}) {
17344
17499
  });
17345
17500
  return { render, renderStream, lint, health, outputs, queue };
17346
17501
  }
17502
+ function isCrossOriginBrowserRequest(c) {
17503
+ const fetchSite = c.req.header("sec-fetch-site");
17504
+ if (fetchSite) return fetchSite !== "same-origin" && fetchSite !== "none";
17505
+ const origin = c.req.header("origin");
17506
+ if (!origin) return false;
17507
+ try {
17508
+ return new URL(origin).host !== c.req.header("host");
17509
+ } catch {
17510
+ return true;
17511
+ }
17512
+ }
17347
17513
  function createProducerApp(options = {}) {
17348
17514
  const app = new Hono2();
17349
17515
  const handlers = createRenderHandlers(options);
17516
+ app.post("*", async (c, next) => {
17517
+ if (isCrossOriginBrowserRequest(c)) {
17518
+ return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
17519
+ }
17520
+ await next();
17521
+ });
17350
17522
  app.get("/health", handlers.health);
17351
17523
  app.post("/render", handlers.render);
17352
17524
  app.post("/render/stream", handlers.renderStream);