@hyperframes/producer 0.9.66 → 0.9.68

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,16 +9,16 @@ import {
9
9
  // src/services/renderOrchestrator.ts
10
10
  import { audioFailureDiagnostics as audioFailureDiagnostics2, usableCpuCount as usableCpuCount2 } from "@hyperframes/engine";
11
11
  import {
12
- existsSync as existsSync21,
12
+ existsSync as existsSync22,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync12,
16
- statSync as statSync11,
16
+ statSync as statSync10,
17
17
  writeFileSync as writeFileSync7,
18
18
  copyFileSync as copyFileSync5,
19
19
  appendFileSync
20
20
  } from "fs";
21
- import { tmpdir as tmpdir2 } from "node:os";
21
+ import { tmpdir as tmpdir3 } from "node:os";
22
22
  import {
23
23
  chainCapture,
24
24
  fpsToNumber as fpsToNumber8,
@@ -360,7 +360,7 @@ import {
360
360
  referenceBackgroundResult,
361
361
  createReferenceBackgroundRecorder
362
362
  } from "@hyperframes/engine";
363
- import { join as join32, dirname as dirname14, resolve as resolve8 } from "path";
363
+ import { join as join34, dirname as dirname14, resolve as resolve9 } from "path";
364
364
  import { totalmem as totalmem2 } from "node:os";
365
365
  import { randomUUID } from "crypto";
366
366
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -1267,13 +1267,13 @@ function createFileServer(options) {
1267
1267
  if (!streamOwnsFd) closeSync(fd);
1268
1268
  }
1269
1269
  });
1270
- return new Promise((resolve13, reject) => {
1270
+ return new Promise((resolve14, reject) => {
1271
1271
  const connections = /* @__PURE__ */ new Set();
1272
1272
  const server = serve({ fetch: app.fetch, port, hostname: "127.0.0.1" }, (info) => {
1273
1273
  const bound = port === 0 ? settleOnBrowserSafePort(server, "127.0.0.1") : Promise.resolve(info.port);
1274
1274
  bound.then((boundPort) => {
1275
1275
  listeningPort = boundPort;
1276
- resolve13({
1276
+ resolve14({
1277
1277
  url: `http://localhost:${boundPort}`,
1278
1278
  port: boundPort,
1279
1279
  addPreHeadScript: (script) => {
@@ -1839,10 +1839,96 @@ function buildRenderErrorDetails(input) {
1839
1839
  perfStages: Object.keys(input.perfStages).length > 0 ? { ...input.perfStages } : void 0,
1840
1840
  hdrDiagnostics: input.hdrDiagnostics.videoExtractionFailures > 0 || input.hdrDiagnostics.imageDecodeFailures > 0 ? { ...input.hdrDiagnostics } : void 0,
1841
1841
  observability: input.observability,
1842
- subTimelineWait: input.subTimelineWait
1842
+ subTimelineWait: input.subTimelineWait,
1843
+ missingPath: input.missingPath
1843
1844
  };
1844
1845
  }
1845
1846
 
1847
+ // src/services/render/missingPath.ts
1848
+ import { existsSync as existsSync4, lstatSync, readlinkSync } from "node:fs";
1849
+ import { tmpdir } from "node:os";
1850
+ import { basename as basename3, join as join4, relative as relative2, resolve as resolve4, isAbsolute as isAbsolute2, sep as sep3 } from "node:path";
1851
+ import { errnoMissingPathOf } from "@hyperframes/core/missing-path";
1852
+ var SYNCED = /onedrive|dropbox|icloud|mobile documents|clouddocs|google ?drive|cloudstorage/i;
1853
+ var inside = (path, folder) => {
1854
+ const rel = relative2(resolve4(folder), resolve4(path));
1855
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
1856
+ };
1857
+ function lstatOrNull(path) {
1858
+ try {
1859
+ return lstatSync(path);
1860
+ } catch {
1861
+ return null;
1862
+ }
1863
+ }
1864
+ var ROOT_SCOPES = [
1865
+ ["tempRoot", "temp_root"],
1866
+ ["cacheDir", "cache_root"],
1867
+ ["workDir", "work_dir"]
1868
+ ];
1869
+ var NAME_SCOPES = [
1870
+ [/\.partial/, "cache_partial"],
1871
+ [/^hfcache-/, "cache_entry"],
1872
+ [/^hyperframes-extract-cache/, "cache_root"],
1873
+ [/^(hf-render-|work-[0-9a-f]{8}-)/, "work_dir"]
1874
+ ];
1875
+ function scopeOfGone(path, where, throughLink) {
1876
+ const root = ROOT_SCOPES.find(([key]) => {
1877
+ const dir = where[key];
1878
+ return !!dir && resolve4(path) === resolve4(dir);
1879
+ });
1880
+ if (root) return root[1];
1881
+ const name = basename3(path);
1882
+ return NAME_SCOPES.find(([pattern]) => pattern.test(name))?.[1] ?? (throughLink ? "link_target" : "other");
1883
+ }
1884
+ var MAX_LINK_HOPS = 4;
1885
+ function rootOf(path, where) {
1886
+ if (inside(path, where.tempRoot)) return "system_temp";
1887
+ if (where.cacheDir && inside(path, where.cacheDir)) return "cache_dir";
1888
+ return "other";
1889
+ }
1890
+ var ownerOf = (path, where) => [where.tempRoot, where.cacheDir, where.workDir].filter((root) => !!root && inside(path, root)).sort((a, b) => resolve4(a).length - resolve4(b).length)[0];
1891
+ var linkTarget = (link, folder) => resolve4(folder, readlinkSync(link).replace(/^\\\\\?\\/, ""));
1892
+ function goneAt(path, last, where, hops) {
1893
+ const scope = scopeOfGone(path, where, hops > 0);
1894
+ return last && scope === "other" ? "file" : scope;
1895
+ }
1896
+ function highestGone(path, where, hops = 0) {
1897
+ const root = ownerOf(path, where);
1898
+ if (!root || hops > MAX_LINK_HOPS) return "link_target";
1899
+ if (!existsSync4(root)) return scopeOfGone(root, where, hops > 0);
1900
+ const parts = relative2(resolve4(root), resolve4(path)).split(sep3).filter(Boolean);
1901
+ let at = resolve4(root);
1902
+ for (const [index, part] of parts.entries()) {
1903
+ const next = join4(at, part);
1904
+ const stat = lstatOrNull(next);
1905
+ if (!stat) return goneAt(next, index === parts.length - 1, where, hops);
1906
+ at = stat.isSymbolicLink() ? linkTarget(next, at) : next;
1907
+ const gone = at === next ? void 0 : highestGone(at, where, hops + 1);
1908
+ if (gone) return gone;
1909
+ }
1910
+ return void 0;
1911
+ }
1912
+ var isSpawnFailure = (error) => !!error?.syscall?.startsWith("spawn");
1913
+ function describeMissingPath(error, {
1914
+ cacheDir,
1915
+ workDir,
1916
+ tempRoot = tmpdir()
1917
+ } = {}) {
1918
+ try {
1919
+ const path = errnoMissingPathOf(error);
1920
+ if (!path || isSpawnFailure(error)) return void 0;
1921
+ const where = { tempRoot, cacheDir, workDir };
1922
+ return {
1923
+ scope: ownerOf(path, where) ? highestGone(path, where) ?? "other" : scopeOfGone(path, where, false),
1924
+ synced: SYNCED.test(path),
1925
+ root: rootOf(path, where)
1926
+ };
1927
+ } catch {
1928
+ return void 0;
1929
+ }
1930
+ }
1931
+
1846
1932
  // src/services/render/renderEventPublisher.ts
1847
1933
  import { cloneCaptureWarnings } from "@hyperframes/engine";
1848
1934
  var FLUSH_TIMEOUT_MS = 1e4;
@@ -1878,8 +1964,8 @@ var OrderedRenderEventPublisher = class {
1878
1964
  let timer;
1879
1965
  const drained = await Promise.race([
1880
1966
  this.tail.then(() => true),
1881
- new Promise((resolve13) => {
1882
- timer = setTimeout(() => resolve13(false), FLUSH_TIMEOUT_MS);
1967
+ new Promise((resolve14) => {
1968
+ timer = setTimeout(() => resolve14(false), FLUSH_TIMEOUT_MS);
1883
1969
  })
1884
1970
  ]);
1885
1971
  clearTimeout(timer);
@@ -1983,8 +2069,8 @@ var RenderExecutionContext = class {
1983
2069
  };
1984
2070
 
1985
2071
  // src/services/render/artifactTransaction.ts
1986
- import { closeSync as closeSync2, existsSync as existsSync5, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
1987
- import { basename as basename4, dirname as dirname4, extname as extname2, join as join5, resolve as resolve4 } from "node:path";
2072
+ import { closeSync as closeSync2, existsSync as existsSync6, fstatSync as fstatSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, rmSync as rmSync3 } from "node:fs";
2073
+ import { basename as basename5, dirname as dirname4, extname as extname2, join as join6, resolve as resolve5 } from "node:path";
1988
2074
  import { HLS_MASTER_PLAYLIST, HLS_VIDEO_PLAYLIST, renameWithRetry } from "@hyperframes/engine";
1989
2075
 
1990
2076
  // src/utils/ffprobe.ts
@@ -1996,16 +2082,16 @@ import {
1996
2082
 
1997
2083
  // src/services/render/renderDirOwner.ts
1998
2084
  import {
1999
- existsSync as existsSync4,
2000
- lstatSync,
2085
+ existsSync as existsSync5,
2086
+ lstatSync as lstatSync2,
2001
2087
  readFileSync as readFileSync2,
2002
2088
  readdirSync,
2003
- readlinkSync,
2089
+ readlinkSync as readlinkSync2,
2004
2090
  rmSync as rmSync2,
2005
2091
  writeFileSync as writeFileSync2
2006
2092
  } from "node:fs";
2007
2093
  import { hostname, uptime } from "node:os";
2008
- import { basename as basename3, dirname as dirname3, join as join4 } from "node:path";
2094
+ import { basename as basename4, dirname as dirname3, join as join5 } from "node:path";
2009
2095
  import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
2010
2096
  import { createStagingDir } from "@hyperframes/core/atomic-file";
2011
2097
  var OWNER_FILE = "owner.json";
@@ -2023,13 +2109,13 @@ function pidScope() {
2023
2109
  host: hostname(),
2024
2110
  // Without /proc (macOS, Windows) the boot time, to the minute, stands in for the boot id.
2025
2111
  boot: attempt(() => readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim()) ?? attempt(() => String(Math.round(Date.now() / 6e4 - uptime() / 60))),
2026
- pidns: attempt(() => readlinkSync("/proc/self/ns/pid"))
2112
+ pidns: attempt(() => readlinkSync2("/proc/self/ns/pid"))
2027
2113
  };
2028
2114
  }
2029
2115
  function createOwnedRenderDir(prefix) {
2030
- const dir = createStagingDir(dirname3(prefix), basename3(prefix));
2116
+ const dir = createStagingDir(dirname3(prefix), basename4(prefix));
2031
2117
  const owner = { pid: process.pid, ...pidScope() };
2032
- writeFileSync2(join4(dir, OWNER_FILE), JSON.stringify(owner));
2118
+ writeFileSync2(join5(dir, OWNER_FILE), JSON.stringify(owner));
2033
2119
  return dir;
2034
2120
  }
2035
2121
  function alive(pid) {
@@ -2052,7 +2138,7 @@ function inThisPidScope(owner) {
2052
2138
  function ownerState(dir) {
2053
2139
  let owner;
2054
2140
  try {
2055
- owner = JSON.parse(readFileSync2(join4(dir, OWNER_FILE), "utf-8"));
2141
+ owner = JSON.parse(readFileSync2(join5(dir, OWNER_FILE), "utf-8"));
2056
2142
  } catch (error) {
2057
2143
  return error.code === "ENOENT" ? "none" : "unknown";
2058
2144
  }
@@ -2063,16 +2149,16 @@ function ownerState(dir) {
2063
2149
  return alive(pid) ? "live" : "gone";
2064
2150
  }
2065
2151
  function newestWriteMs(path) {
2066
- const stat = lstatSync(path);
2152
+ const stat = lstatSync2(path);
2067
2153
  if (!stat.isDirectory()) return stat.mtimeMs;
2068
2154
  return readdirSync(path).reduce(
2069
- (newest, name) => Math.max(newest, newestWriteMs(join4(path, name))),
2155
+ (newest, name) => Math.max(newest, newestWriteMs(join5(path, name))),
2070
2156
  stat.mtimeMs
2071
2157
  );
2072
2158
  }
2073
2159
  function isAbandoned(dir, ownerlessIdleMs, now) {
2074
2160
  try {
2075
- if (!lstatSync(dir).isDirectory() || existsSync4(join4(dir, TRANSACTION_BACKUP))) return false;
2161
+ if (!lstatSync2(dir).isDirectory() || existsSync5(join5(dir, TRANSACTION_BACKUP))) return false;
2076
2162
  const owner = ownerState(dir);
2077
2163
  if (owner === "gone") return true;
2078
2164
  return owner === "none" && ownerlessIdleMs !== void 0 && now - newestWriteMs(dir) >= ownerlessIdleMs;
@@ -2088,7 +2174,7 @@ function listAbandonedRenderDirs(parent, options = {}) {
2088
2174
  return [];
2089
2175
  }
2090
2176
  const now = Date.now();
2091
- return names.filter((name) => (options.names ?? RENDER_TEMP_DIR).test(name)).map((name) => join4(parent, name)).filter((dir) => isAbandoned(dir, options.ownerlessIdleMs, now));
2177
+ return names.filter((name) => (options.names ?? RENDER_TEMP_DIR).test(name)).map((name) => join5(parent, name)).filter((dir) => isAbandoned(dir, options.ownerlessIdleMs, now));
2092
2178
  }
2093
2179
  function createRenderWorkDir(prefix, outputDir) {
2094
2180
  for (const parent of /* @__PURE__ */ new Set([outputDir, dirname3(prefix)])) {
@@ -2104,7 +2190,7 @@ function createRenderWorkDir(prefix, outputDir) {
2104
2190
 
2105
2191
  // src/services/render/artifactTransaction.ts
2106
2192
  var defaultFileSystem = {
2107
- existsSync: existsSync5,
2193
+ existsSync: existsSync6,
2108
2194
  renameSync: (source, destination) => renameWithRetry(source, destination),
2109
2195
  rmSync: rmSync3
2110
2196
  };
@@ -2137,8 +2223,8 @@ function buildArtifactExpectation(input) {
2137
2223
  function createSiblingTransactionDirectory(destination) {
2138
2224
  const parent = dirname4(destination);
2139
2225
  const extension = extname2(destination);
2140
- const stem = extension ? basename4(destination, extension) : basename4(destination);
2141
- return createOwnedRenderDir(join5(parent, `.${stem}.hf-transaction-`));
2226
+ const stem = extension ? basename5(destination, extension) : basename5(destination);
2227
+ return createOwnedRenderDir(join6(parent, `.${stem}.hf-transaction-`));
2142
2228
  }
2143
2229
  function assertReadableNonEmptyFile(path) {
2144
2230
  const fd = openSync2(path, "r");
@@ -2156,7 +2242,7 @@ function collectDirectoryFiles(root) {
2156
2242
  const files = [];
2157
2243
  const visit = (directory) => {
2158
2244
  for (const entry of readdirSync2(directory, { withFileTypes: true })) {
2159
- const path = join5(directory, entry.name);
2245
+ const path = join6(directory, entry.name);
2160
2246
  if (entry.isDirectory()) visit(path);
2161
2247
  else if (entry.isFile()) files.push(path);
2162
2248
  }
@@ -2211,10 +2297,10 @@ var ArtifactTransaction = class {
2211
2297
  this.kind = kind;
2212
2298
  this.fileSystem = fileSystem;
2213
2299
  this.logger = logger;
2214
- this.destinationPath = resolve4(destinationPath);
2300
+ this.destinationPath = resolve5(destinationPath);
2215
2301
  this.transactionDirectory = createSiblingTransactionDirectory(this.destinationPath);
2216
- this.stagingPath = join5(this.transactionDirectory, basename4(this.destinationPath));
2217
- this.backupPath = join5(this.transactionDirectory, TRANSACTION_BACKUP);
2302
+ this.stagingPath = join6(this.transactionDirectory, basename5(this.destinationPath));
2303
+ this.backupPath = join6(this.transactionDirectory, TRANSACTION_BACKUP);
2218
2304
  this.durationProbe = durationProbe;
2219
2305
  }
2220
2306
  kind;
@@ -2257,19 +2343,19 @@ var ArtifactTransaction = class {
2257
2343
  */
2258
2344
  async assertDirectoryExpectation(expected, files) {
2259
2345
  for (const required of expected.requiredFiles ?? []) {
2260
- const path = join5(this.stagingPath, required);
2261
- if (!existsSync5(path)) {
2346
+ const path = join6(this.stagingPath, required);
2347
+ if (!existsSync6(path)) {
2262
2348
  throw new Error(`Render artifact directory is missing ${required}: ${this.stagingPath}`);
2263
2349
  }
2264
2350
  assertReadableNonEmptyFile(path);
2265
2351
  }
2266
2352
  if (expected.probeTarget !== void 0) {
2267
- await this.assertArtifactDuration(expected, join5(this.stagingPath, expected.probeTarget));
2353
+ await this.assertArtifactDuration(expected, join6(this.stagingPath, expected.probeTarget));
2268
2354
  return;
2269
2355
  }
2270
2356
  if (expected.expectedFrames === void 0) return;
2271
2357
  const frameCount = files.filter(
2272
- (file) => dirname4(file) === this.stagingPath && /^frame_\d+\.png$/.test(basename4(file))
2358
+ (file) => dirname4(file) === this.stagingPath && /^frame_\d+\.png$/.test(basename5(file))
2273
2359
  ).length;
2274
2360
  if (frameCount === 0) {
2275
2361
  throw new Error(
@@ -2507,8 +2593,8 @@ function replanAfterFailure(plan2, failure) {
2507
2593
  }
2508
2594
 
2509
2595
  // src/services/render/stages/captureSegmentedStage.ts
2510
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2511
- import { join as join9 } from "node:path";
2596
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, rmSync as rmSync6, statSync as statSync4 } from "node:fs";
2597
+ import { join as join12 } from "node:path";
2512
2598
  import {
2513
2599
  captureFrameToBuffer as captureFrameToBuffer2,
2514
2600
  closeCaptureSession as closeCaptureSession2,
@@ -2929,7 +3015,7 @@ import {
2929
3015
 
2930
3016
  // src/services/hdrCompositor.ts
2931
3017
  import { readSync as readSync2 } from "fs";
2932
- import { join as join6 } from "path";
3018
+ import { join as join7 } from "path";
2933
3019
  import {
2934
3020
  captureAlphaPng,
2935
3021
  applyDomLayerMask,
@@ -3369,7 +3455,7 @@ async function compositeHdrFrame(ctx, canvas, time, fullStacking, elementFilter,
3369
3455
  if (shouldLog && debugDumpDir) {
3370
3456
  const after = countNonZeroRgb48(canvas);
3371
3457
  const dumpName = `frame_${String(debugFrameIndex).padStart(4, "0")}_layer_${String(layerIdx).padStart(2, "0")}_dom.png`;
3372
- const dumpPath = join6(debugDumpDir, dumpName);
3458
+ const dumpPath = join7(debugDumpDir, dumpName);
3373
3459
  writeFileExclusiveSync(dumpPath, domPng);
3374
3460
  log.info("[diag] dom layer blit", {
3375
3461
  frame: debugFrameIndex,
@@ -3424,7 +3510,7 @@ import { fpsToFfmpegArg, fpsToNumber as fpsToNumber3 } from "@hyperframes/core";
3424
3510
 
3425
3511
  // src/services/hdrFrameWindows.ts
3426
3512
  import { closeSync as closeSync3, constants as constants2, openSync as openSync3, rmSync as rmSync4 } from "node:fs";
3427
- import { join as join7 } from "node:path";
3513
+ import { join as join8 } from "node:path";
3428
3514
  function createHdrFrameWindows(opts) {
3429
3515
  const { dir, frameSize, windowFrames, maxResident, extract } = opts;
3430
3516
  let totalFrames = opts.totalFrames;
@@ -3448,7 +3534,7 @@ function createHdrFrameWindows(opts) {
3448
3534
  const firstFrame = index * windowFrames;
3449
3535
  const w = {
3450
3536
  firstFrame,
3451
- path: join7(dir, `window-${index}.rgb48le`),
3537
+ path: join8(dir, `window-${index}.rgb48le`),
3452
3538
  frames: 0,
3453
3539
  fd: -1,
3454
3540
  pins: 0,
@@ -4195,6 +4281,7 @@ function cleanupEndedHdrVideos(args) {
4195
4281
  }
4196
4282
 
4197
4283
  // src/services/render/segmentPlan.ts
4284
+ import { join as join9 } from "node:path";
4198
4285
  var DEFAULT_SEGMENT_FRAMES = 3e3;
4199
4286
  var MIN_SEGMENT_FRAMES = 30;
4200
4287
  function assertPositiveInteger(name, value) {
@@ -4215,6 +4302,9 @@ function planSegments(totalFrames, segmentFrames) {
4215
4302
  }
4216
4303
  return slices;
4217
4304
  }
4305
+ function segmentOutputPath(segmentDir, index) {
4306
+ return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
4307
+ }
4218
4308
  function resolveSegmentFrames(env) {
4219
4309
  const raw = env.HF_SEGMENT_FRAMES;
4220
4310
  if (raw === void 0 || raw.trim() === "") return DEFAULT_SEGMENT_FRAMES;
@@ -4232,6 +4322,144 @@ function createSegmentQueue(slices) {
4232
4322
  };
4233
4323
  }
4234
4324
 
4325
+ // src/services/render/segmentManifest.ts
4326
+ import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
4327
+ import {
4328
+ createReadStream as createReadStream2,
4329
+ existsSync as existsSync7,
4330
+ lstatSync as lstatSync3,
4331
+ mkdirSync as mkdirSync3,
4332
+ readFileSync as readFileSync4,
4333
+ writeFileSync as writeFileSync3
4334
+ } from "node:fs";
4335
+ import { join as join10 } from "node:path";
4336
+ import { previewToken } from "@hyperframes/core/preview-proof";
4337
+ import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
4338
+ var MANIFEST_FILENAME = "segments.json";
4339
+ function computeSegmentPlanHash(input) {
4340
+ const ordered = [
4341
+ input.compositionHash,
4342
+ input.cliVersion,
4343
+ String(input.totalFrames),
4344
+ String(input.segmentFrames),
4345
+ `${input.fps.num}/${input.fps.den}`,
4346
+ `${input.width}x${input.height}`,
4347
+ input.codec,
4348
+ input.preset,
4349
+ input.quality === void 0 ? "" : String(input.quality),
4350
+ input.bitrate ?? "",
4351
+ input.pixelFormat ?? "",
4352
+ input.imageFormat,
4353
+ input.useGpu ? "gpu" : "cpu",
4354
+ `${input.outputWidth}x${input.outputHeight}`,
4355
+ input.motionBlur,
4356
+ input.pageMotionBlur ?? "",
4357
+ input.captureQuality === void 0 ? "" : String(input.captureQuality)
4358
+ ];
4359
+ const delivery = [input.maxBitrate, input.bufferSize, input.gopSize].map((v) => v ?? "");
4360
+ if (delivery.some((v) => v !== "")) ordered.push(...delivery.map(String));
4361
+ return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
4362
+ }
4363
+ function segmentDirFor(projectRendersDir, planHash) {
4364
+ return join10(projectRendersDir, ".hf-segments", planHash);
4365
+ }
4366
+ function hasNumber(value, key) {
4367
+ return key in value && typeof Reflect.get(value, key) === "number";
4368
+ }
4369
+ function hasString(value, key) {
4370
+ return key in value && typeof Reflect.get(value, key) === "string";
4371
+ }
4372
+ function isEntry(value) {
4373
+ if (typeof value !== "object" || value === null) return false;
4374
+ return hasNumber(value, "index") && hasNumber(value, "startFrame") && hasNumber(value, "endFrame") && hasString(value, "path") && hasNumber(value, "bytes") && hasString(value, "sha256") && hasString(value, "completedAt");
4375
+ }
4376
+ function isManifest(value) {
4377
+ if (typeof value !== "object" || value === null) return false;
4378
+ const completed = Reflect.get(value, "completed");
4379
+ return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
4380
+ }
4381
+ function readSegmentManifest(segmentDir) {
4382
+ const path = join10(segmentDir, MANIFEST_FILENAME);
4383
+ if (!existsSync7(path)) return null;
4384
+ try {
4385
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
4386
+ return isManifest(parsed) ? parsed : null;
4387
+ } catch {
4388
+ return null;
4389
+ }
4390
+ }
4391
+ function segmentManifestKey(token = previewToken()) {
4392
+ return token ? createHmac("sha256", token).update("segment-manifest").digest() : null;
4393
+ }
4394
+ function manifestMac(manifest, key) {
4395
+ const signed = [
4396
+ manifest.planHash,
4397
+ manifest.totalFrames,
4398
+ manifest.segmentFrames,
4399
+ manifest.completed.map((e) => [e.index, e.startFrame, e.endFrame, e.bytes, e.sha256])
4400
+ ];
4401
+ return createHmac("sha256", key).update(JSON.stringify(signed)).digest("hex");
4402
+ }
4403
+ function signSegmentManifest(manifest, key) {
4404
+ const { version, planHash, totalFrames, segmentFrames, completed } = manifest;
4405
+ const unsigned = { version, planHash, totalFrames, segmentFrames, completed };
4406
+ return key ? { ...unsigned, mac: manifestMac(unsigned, key) } : unsigned;
4407
+ }
4408
+ function hasValidMac(manifest, key) {
4409
+ if (!key || typeof manifest.mac !== "string") return false;
4410
+ const expected = Buffer.from(manifestMac(manifest, key), "hex");
4411
+ const actual = Buffer.from(manifest.mac, "hex");
4412
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
4413
+ }
4414
+ async function hashSegmentFile(path) {
4415
+ const hash = createHash2("sha256");
4416
+ for await (const chunk of createReadStream2(path)) hash.update(chunk);
4417
+ return hash.digest("hex");
4418
+ }
4419
+ function writeSegmentManifest(segmentDir, manifest, key) {
4420
+ mkdirSync3(segmentDir, { recursive: true });
4421
+ const tmp = join10(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
4422
+ writeFileSync3(tmp, JSON.stringify(signSegmentManifest(manifest, key), null, 2), "utf-8");
4423
+ renameWithRetry2(tmp, join10(segmentDir, MANIFEST_FILENAME));
4424
+ }
4425
+ async function probeSegmentFrameCount(path, probe) {
4426
+ try {
4427
+ const meta = await probe(path);
4428
+ if (!Number.isFinite(meta.videoStreamDurationSeconds) || !Number.isFinite(meta.fps))
4429
+ return null;
4430
+ if (meta.fps <= 0) return null;
4431
+ return Math.round(meta.videoStreamDurationSeconds * meta.fps);
4432
+ } catch {
4433
+ return null;
4434
+ }
4435
+ }
4436
+ function plannedSlice(entry, plan2) {
4437
+ const slice = Number.isInteger(entry.index) ? plan2[entry.index] : void 0;
4438
+ if (!slice || slice.startFrame !== entry.startFrame || slice.endFrame !== entry.endFrame) {
4439
+ return void 0;
4440
+ }
4441
+ return slice;
4442
+ }
4443
+ function isPlainFileOfSize(path, bytes) {
4444
+ const stat = lstatSync3(path, { throwIfNoEntry: false });
4445
+ return stat !== void 0 && stat.isFile() && stat.size > 0 && stat.size === bytes;
4446
+ }
4447
+ async function validateCompletedSegments(manifest, check) {
4448
+ const ok = /* @__PURE__ */ new Set();
4449
+ if (manifest.planHash !== check.expectedHash || !hasValidMac(manifest, check.key)) return ok;
4450
+ for (const entry of manifest.completed) {
4451
+ const slice = plannedSlice(entry, check.plan);
4452
+ if (!slice) continue;
4453
+ const path = segmentOutputPath(check.segmentDir, slice.index);
4454
+ if (!isPlainFileOfSize(path, entry.bytes)) continue;
4455
+ if (await hashSegmentFile(path) !== entry.sha256) continue;
4456
+ const frames = await check.probeFrames(path);
4457
+ if (frames !== slice.endFrame - slice.startFrame) continue;
4458
+ ok.add(slice.index);
4459
+ }
4460
+ return ok;
4461
+ }
4462
+
4235
4463
  // src/services/render/segmentRecycle.ts
4236
4464
  var DEFAULT_SEGMENT_BROWSER_RECYCLE = 3;
4237
4465
  function resolveSegmentBrowserRecycle(env) {
@@ -4248,8 +4476,8 @@ function isTargetLossError(error) {
4248
4476
 
4249
4477
  // src/services/render/stages/captureStreamingStage.ts
4250
4478
  import { mkdtemp, writeFile } from "node:fs/promises";
4251
- import { tmpdir } from "node:os";
4252
- import { join as join8 } from "node:path";
4479
+ import { tmpdir as tmpdir2 } from "node:os";
4480
+ import { join as join11 } from "node:path";
4253
4481
  import {
4254
4482
  DrawElementVerificationError,
4255
4483
  captureFrameToBuffer,
@@ -4343,7 +4571,7 @@ var SequentialCaptureStallError = class extends Error {
4343
4571
  }
4344
4572
  };
4345
4573
  function raceAgainstStall(promise, deadlineMs, input, signal) {
4346
- return new Promise((resolve13, reject) => {
4574
+ return new Promise((resolve14, reject) => {
4347
4575
  const clock = createStallClock();
4348
4576
  const trip = () => reject(
4349
4577
  signal?.aborted ? new Error(
@@ -4368,7 +4596,7 @@ function raceAgainstStall(promise, deadlineMs, input, signal) {
4368
4596
  promise.then(
4369
4597
  (value) => {
4370
4598
  clearTimeout(timer);
4371
- resolve13(value);
4599
+ resolve14(value);
4372
4600
  },
4373
4601
  (error) => {
4374
4602
  clearTimeout(timer);
@@ -4472,11 +4700,11 @@ async function verifyDrawElementSample(session, idx, buf, ctx) {
4472
4700
  return;
4473
4701
  }
4474
4702
  if (db < verifyMinDb) {
4475
- const dumpDir = await mkdtemp(join8(tmpdir(), "hf-de-verify-fail-")).catch(() => null);
4703
+ const dumpDir = await mkdtemp(join11(tmpdir2(), "hf-de-verify-fail-")).catch(() => null);
4476
4704
  if (dumpDir) {
4477
4705
  await Promise.all([
4478
- writeFile(join8(dumpDir, `frame-${idx}-de.jpg`), buf),
4479
- writeFile(join8(dumpDir, `frame-${idx}-truth.jpg`), truth)
4706
+ writeFile(join11(dumpDir, `frame-${idx}-de.jpg`), buf),
4707
+ writeFile(join11(dumpDir, `frame-${idx}-truth.jpg`), truth)
4480
4708
  ]).catch(() => {
4481
4709
  });
4482
4710
  }
@@ -5046,9 +5274,6 @@ async function runCaptureStreamingStage(input) {
5046
5274
  }
5047
5275
 
5048
5276
  // src/services/render/stages/captureSegmentedStage.ts
5049
- function segmentOutputPath(segmentDir, index) {
5050
- return join9(segmentDir, `segment_${String(index).padStart(5, "0")}.mp4`);
5051
- }
5052
5277
  function segmentEncoderOptions(base, segment) {
5053
5278
  return {
5054
5279
  ...base,
@@ -5146,7 +5371,8 @@ async function captureSegmentToEncoder(ctx, segment) {
5146
5371
  path: segmentPath,
5147
5372
  // Recorded so resume can prove the file on disk is the one that
5148
5373
  // finished; absent only in unit tests, whose fake encoder writes none.
5149
- bytes: existsSync6(segmentPath) ? statSync4(segmentPath).size : 0
5374
+ bytes: existsSync8(segmentPath) ? statSync4(segmentPath).size : 0,
5375
+ sha256: existsSync8(segmentPath) ? await hashSegmentFile(segmentPath) : ""
5150
5376
  });
5151
5377
  return encodeResult;
5152
5378
  } finally {
@@ -5380,8 +5606,8 @@ async function runCaptureSegmentedStage(input) {
5380
5606
  const { log, dedupPerfs, assertNotAborted } = input;
5381
5607
  const deps = { ...DEFAULT_DEPS, ...input.deps };
5382
5608
  const segments = planSegments(input.totalFrames, input.segmentFrames);
5383
- const segmentDir = input.segmentDir ?? join9(input.workDir, "segments");
5384
- mkdirSync3(segmentDir, { recursive: true });
5609
+ const segmentDir = input.segmentDir ?? join12(input.workDir, "segments");
5610
+ mkdirSync4(segmentDir, { recursive: true });
5385
5611
  const skip = input.completedSegments ?? /* @__PURE__ */ new Set();
5386
5612
  const pending = segments.filter((s) => !skip.has(s.index));
5387
5613
  for (const index of skip) log.info("[Render] segment skipped (resume)", { index });
@@ -5536,7 +5762,7 @@ function startRenderEtaGuard(options) {
5536
5762
  }
5537
5763
 
5538
5764
  // src/services/render/captureCost.ts
5539
- import { join as join10 } from "node:path";
5765
+ import { join as join13 } from "node:path";
5540
5766
  import { fpsToNumber as fpsToNumber4 } from "@hyperframes/core";
5541
5767
  import {
5542
5768
  calculateOptimalWorkers,
@@ -5789,7 +6015,7 @@ async function runCaptureCalibration(input) {
5789
6015
  });
5790
6016
  let calibration;
5791
6017
  try {
5792
- calibration = await runOneCalibration(join10(workDir, "capture-calibration"), calibrationCfg);
6018
+ calibration = await runOneCalibration(join13(workDir, "capture-calibration"), calibrationCfg);
5793
6019
  } catch (error) {
5794
6020
  const shouldFallback = !forceScreenshot && shouldFallbackToScreenshotAfterCalibrationError(error);
5795
6021
  if (!shouldFallback) {
@@ -5823,7 +6049,7 @@ async function runCaptureCalibration(input) {
5823
6049
  const screenshotCfg = createCaptureCalibrationConfig({ ...cfg, forceScreenshot: true });
5824
6050
  try {
5825
6051
  calibration = await runOneCalibration(
5826
- join10(workDir, "capture-calibration-screenshot"),
6052
+ join13(workDir, "capture-calibration-screenshot"),
5827
6053
  screenshotCfg
5828
6054
  );
5829
6055
  } catch (fallbackError) {
@@ -5887,8 +6113,8 @@ function checkPageNeverReady(input) {
5887
6113
  }
5888
6114
 
5889
6115
  // src/services/render/deferredVideoFrames.ts
5890
- import { mkdirSync as mkdirSync4, rmSync as rmSync7 } from "node:fs";
5891
- import { dirname as dirname5, join as join11 } from "node:path";
6116
+ import { mkdirSync as mkdirSync5, rmSync as rmSync7 } from "node:fs";
6117
+ import { dirname as dirname5, join as join14 } from "node:path";
5892
6118
  import {
5893
6119
  createFrameLookupTable,
5894
6120
  extractVideoFramesRange,
@@ -5933,7 +6159,7 @@ async function extractDeferredFrames(input) {
5933
6159
  const shown = shownDeferredFrameIndexes(input, input.frames, input.fps);
5934
6160
  return Promise.all(
5935
6161
  deferred.map(async (video) => {
5936
- const outputDir = join11(input.outputRoot, mediaIdPathSegment2(video.videoId));
6162
+ const outputDir = join14(input.outputRoot, mediaIdPathSegment2(video.videoId));
5937
6163
  const indexes = [...shown.get(video.videoId) ?? []].sort((a, b) => a - b);
5938
6164
  if (indexes.length === 0) {
5939
6165
  return { ...video, outputDir, framePaths: /* @__PURE__ */ new Map(), ownedByLookup: false };
@@ -5989,7 +6215,7 @@ async function extractAllDeferredFrames(extracted, input) {
5989
6215
  maxTransientRetries: input.maxTransientRetries,
5990
6216
  onRetry: () => {
5991
6217
  rmSync7(video.outputDir, { recursive: true, force: true });
5992
- mkdirSync4(video.outputDir, { recursive: true });
6218
+ mkdirSync5(video.outputDir, { recursive: true });
5993
6219
  }
5994
6220
  }
5995
6221
  );
@@ -6080,14 +6306,14 @@ async function measureLocalShownBoxes(page, videos, fps, duration, log) {
6080
6306
  }
6081
6307
 
6082
6308
  // src/services/render/segmentVideoFrames.ts
6083
- import { mkdirSync as mkdirSync5, rmSync as rmSync8 } from "node:fs";
6084
- import { join as join12 } from "node:path";
6309
+ import { mkdirSync as mkdirSync6, rmSync as rmSync8 } from "node:fs";
6310
+ import { join as join15 } from "node:path";
6085
6311
  import {
6086
6312
  createFrameLookupTable as createFrameLookupTable2,
6087
6313
  createVideoFrameInjector
6088
6314
  } from "@hyperframes/engine";
6089
6315
  function segmentFramesDir(rootDir, index) {
6090
- return join12(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6316
+ return join15(rootDir, "segment-frames", `segment_${String(index).padStart(5, "0")}`);
6091
6317
  }
6092
6318
  function createSegmentVideoFrames(input) {
6093
6319
  const extractFrames = input.extractFrames ?? extractDeferredFrames;
@@ -6118,7 +6344,7 @@ function createSegmentVideoFrames(input) {
6118
6344
  let onDemandCalls = 0;
6119
6345
  const onDemandHook = () => Object.assign(
6120
6346
  async (page, time, heldVideoTime) => {
6121
- const dir = join12(
6347
+ const dir = join15(
6122
6348
  input.rootDir,
6123
6349
  "segment-frames",
6124
6350
  `on-demand_${String(onDemandCalls++).padStart(5, "0")}`
@@ -6135,11 +6361,11 @@ function createSegmentVideoFrames(input) {
6135
6361
  );
6136
6362
  return {
6137
6363
  async forFrames(frames, name) {
6138
- const dir = join12(input.rootDir, "segment-frames", name);
6364
+ const dir = join15(input.rootDir, "segment-frames", name);
6139
6365
  const release = () => rmSync8(dir, { recursive: true, force: true });
6140
6366
  try {
6141
6367
  release();
6142
- mkdirSync5(dir, { recursive: true });
6368
+ mkdirSync6(dir, { recursive: true });
6143
6369
  const table = await tableFor([...frames], dir);
6144
6370
  return { injector: () => createVideoFrameInjector(table, input.injectorOptions), release };
6145
6371
  } catch (error) {
@@ -6168,7 +6394,7 @@ function createSegmentVideoFrames(input) {
6168
6394
  folder = dir;
6169
6395
  try {
6170
6396
  rmSync8(dir, { recursive: true, force: true });
6171
- mkdirSync5(dir, { recursive: true });
6397
+ mkdirSync6(dir, { recursive: true });
6172
6398
  injector = await injectorFor(
6173
6399
  Array.from(
6174
6400
  { length: segment.endFrame - segment.startFrame },
@@ -6188,7 +6414,7 @@ function createSegmentVideoFrames(input) {
6188
6414
 
6189
6415
  // src/services/render/videoFrameWindow.ts
6190
6416
  import { readdirSync as readdirSync3, statSync as statSync5 } from "node:fs";
6191
- import { join as join13 } from "node:path";
6417
+ import { join as join16 } from "node:path";
6192
6418
  function shouldWindowVideoFrames(args) {
6193
6419
  return args.segmented && args.env.HF_VIDEO_FRAME_WINDOW?.trim().toLowerCase() === "true";
6194
6420
  }
@@ -6201,7 +6427,7 @@ function directoryBytes(path) {
6201
6427
  return 0;
6202
6428
  }
6203
6429
  for (const entry of entries) {
6204
- const child3 = join13(path, entry.name);
6430
+ const child3 = join16(path, entry.name);
6205
6431
  try {
6206
6432
  bytes += entry.isDirectory() ? directoryBytes(child3) : statSync5(child3).size;
6207
6433
  } catch {
@@ -6219,7 +6445,7 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6219
6445
  ...worker,
6220
6446
  async prepare(segment) {
6221
6447
  await worker.prepare(segment);
6222
- const held = directoryBytes(join13(rootDir, "segment-frames"));
6448
+ const held = directoryBytes(join16(rootDir, "segment-frames"));
6223
6449
  if (held > peak) {
6224
6450
  peak = held;
6225
6451
  onPeak(peak);
@@ -6230,95 +6456,6 @@ function trackSegmentFramePeak(frames, rootDir, onPeak) {
6230
6456
  };
6231
6457
  }
6232
6458
 
6233
- // src/services/render/segmentManifest.ts
6234
- import { createHash as createHash2 } from "node:crypto";
6235
- import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync4, statSync as statSync6, writeFileSync as writeFileSync3 } from "node:fs";
6236
- import { join as join14 } from "node:path";
6237
- import { renameWithRetry as renameWithRetry2 } from "@hyperframes/engine";
6238
- var MANIFEST_FILENAME = "segments.json";
6239
- function computeSegmentPlanHash(input) {
6240
- const ordered = [
6241
- input.compositionHash,
6242
- input.cliVersion,
6243
- String(input.totalFrames),
6244
- String(input.segmentFrames),
6245
- `${input.fps.num}/${input.fps.den}`,
6246
- `${input.width}x${input.height}`,
6247
- input.codec,
6248
- input.preset,
6249
- input.quality === void 0 ? "" : String(input.quality),
6250
- input.bitrate ?? "",
6251
- input.pixelFormat ?? "",
6252
- input.imageFormat,
6253
- input.useGpu ? "gpu" : "cpu",
6254
- `${input.outputWidth}x${input.outputHeight}`,
6255
- input.motionBlur,
6256
- input.pageMotionBlur ?? "",
6257
- input.captureQuality === void 0 ? "" : String(input.captureQuality)
6258
- ];
6259
- const delivery = [input.maxBitrate, input.bufferSize, input.gopSize].map((v) => v ?? "");
6260
- if (delivery.some((v) => v !== "")) ordered.push(...delivery.map(String));
6261
- return createHash2("sha256").update(ordered.join(" ")).digest("hex").slice(0, 16);
6262
- }
6263
- function segmentDirFor(projectRendersDir, planHash) {
6264
- return join14(projectRendersDir, ".hf-segments", planHash);
6265
- }
6266
- function hasNumber(value, key) {
6267
- return key in value && typeof Reflect.get(value, key) === "number";
6268
- }
6269
- function hasString(value, key) {
6270
- return key in value && typeof Reflect.get(value, key) === "string";
6271
- }
6272
- function isEntry(value) {
6273
- if (typeof value !== "object" || value === null) return false;
6274
- return hasNumber(value, "index") && hasNumber(value, "startFrame") && hasNumber(value, "endFrame") && hasString(value, "path") && hasNumber(value, "bytes") && hasString(value, "completedAt");
6275
- }
6276
- function isManifest(value) {
6277
- if (typeof value !== "object" || value === null) return false;
6278
- const completed = Reflect.get(value, "completed");
6279
- return Reflect.get(value, "version") === 1 && hasString(value, "planHash") && hasNumber(value, "totalFrames") && hasNumber(value, "segmentFrames") && Array.isArray(completed) && completed.every(isEntry);
6280
- }
6281
- function readSegmentManifest(segmentDir) {
6282
- const path = join14(segmentDir, MANIFEST_FILENAME);
6283
- if (!existsSync7(path)) return null;
6284
- try {
6285
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
6286
- return isManifest(parsed) ? parsed : null;
6287
- } catch {
6288
- return null;
6289
- }
6290
- }
6291
- function writeSegmentManifest(segmentDir, manifest) {
6292
- mkdirSync6(segmentDir, { recursive: true });
6293
- const tmp = join14(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);
6294
- writeFileSync3(tmp, JSON.stringify(manifest, null, 2), "utf-8");
6295
- renameWithRetry2(tmp, join14(segmentDir, MANIFEST_FILENAME));
6296
- }
6297
- async function probeSegmentFrameCount(path, probe) {
6298
- try {
6299
- const meta = await probe(path);
6300
- if (!Number.isFinite(meta.videoStreamDurationSeconds) || !Number.isFinite(meta.fps))
6301
- return null;
6302
- if (meta.fps <= 0) return null;
6303
- return Math.round(meta.videoStreamDurationSeconds * meta.fps);
6304
- } catch {
6305
- return null;
6306
- }
6307
- }
6308
- async function validateCompletedSegments(manifest, expectedHash, probeFrames) {
6309
- const ok = /* @__PURE__ */ new Set();
6310
- if (manifest.planHash !== expectedHash) return ok;
6311
- for (const entry of manifest.completed) {
6312
- if (!existsSync7(entry.path)) continue;
6313
- const size = statSync6(entry.path).size;
6314
- if (size <= 0 || size !== entry.bytes) continue;
6315
- const frames = await probeFrames(entry.path);
6316
- if (frames !== entry.endFrame - entry.startFrame) continue;
6317
- ok.add(entry.index);
6318
- }
6319
- return ok;
6320
- }
6321
-
6322
6459
  // src/services/render/hdrMode.ts
6323
6460
  import {
6324
6461
  analyzeCompositionHdr,
@@ -6914,15 +7051,15 @@ function requireOutputDimensions(expected, width, height) {
6914
7051
  }
6915
7052
 
6916
7053
  // src/services/render/stages/compileStage.ts
6917
- import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6918
- import { join as join20, relative as relative3 } from "node:path";
7054
+ import { existsSync as existsSync13, writeFileSync as writeFileSync5 } from "node:fs";
7055
+ import { join as join22, relative as relative4 } from "node:path";
6919
7056
  import { privateCacheRoot } from "@hyperframes/engine";
6920
7057
  import { suggestMatchingPreset } from "@hyperframes/core";
6921
7058
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6922
7059
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6923
7060
 
6924
7061
  // src/services/compositionSizeLimit.ts
6925
- import { statSync as statSync7 } from "node:fs";
7062
+ import { statSync as statSync6 } from "node:fs";
6926
7063
  var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
6927
7064
  var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
6928
7065
  var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
@@ -6945,6 +7082,8 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6945
7082
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6946
7083
  );
6947
7084
  var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
7085
+ var REMOTE_SCRIPTS = "remote scripts";
7086
+ var REMOTE_STYLESHEETS = "remote stylesheets";
6948
7087
  function generatedTooLarge(file, bytes) {
6949
7088
  if (file === "composition variables") {
6950
7089
  return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
@@ -6952,6 +7091,9 @@ function generatedTooLarge(file, bytes) {
6952
7091
  if (file === "variable media sources") {
6953
7092
  return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
6954
7093
  }
7094
+ if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
7095
+ return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
7096
+ }
6955
7097
  return `Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ${megabytes(bytes)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`;
6956
7098
  }
6957
7099
  var CompositionExpansionBudget = class {
@@ -6993,7 +7135,7 @@ var CompositionExpansionBudget = class {
6993
7135
  function assertCompositionFileSize(path, file) {
6994
7136
  let bytes;
6995
7137
  try {
6996
- const stats = statSync7(path);
7138
+ const stats = statSync6(path);
6997
7139
  if (!stats.isFile()) return;
6998
7140
  bytes = stats.size;
6999
7141
  } catch {
@@ -7018,20 +7160,20 @@ import {
7018
7160
  stylesheetLinkMatches
7019
7161
  } from "@hyperframes/parsers/css-url-scans";
7020
7162
  import { createHash as createHash6 } from "node:crypto";
7021
- import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7022
- import { join as join19, dirname as dirname9, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
7163
+ import { createReadStream as createReadStream3, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7164
+ import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7023
7165
  import { parseHTML as parseHTML5 } from "linkedom";
7024
7166
 
7025
7167
  // src/services/bundledScripts.ts
7026
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
7027
- import { join as join15 } from "node:path";
7168
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";
7169
+ import { join as join17 } from "node:path";
7028
7170
  import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
7029
7171
  var GSAP_VENDOR_DIR_ENV = "HYPERFRAMES_GSAP_VENDOR_DIR";
7030
7172
  function bundledScript(url) {
7031
7173
  const dir = process.env[GSAP_VENDOR_DIR_ENV];
7032
7174
  if (!dir || url !== `${gsapCdnDist()}gsap.min.js`) return null;
7033
- const file = join15(dir, "gsap.min.js");
7034
- return existsSync8(file) ? readFileSync5(file) : null;
7175
+ const file = join17(dir, "gsap.min.js");
7176
+ return existsSync9(file) ? readFileSync5(file) : null;
7035
7177
  }
7036
7178
 
7037
7179
  // src/services/htmlCompiler.ts
@@ -7264,6 +7406,7 @@ function placeAudio(audio, window2) {
7264
7406
  import {
7265
7407
  analyzeKeyframeIntervals,
7266
7408
  assertMediaPayload,
7409
+ createConcurrencyLimit,
7267
7410
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots3,
7268
7411
  NotMediaPayloadError as NotMediaPayloadError2,
7269
7412
  parseMasterFxChain,
@@ -7288,8 +7431,8 @@ import {
7288
7431
 
7289
7432
  // src/services/animatedGifPrep.ts
7290
7433
  import { createHash as createHash4 } from "node:crypto";
7291
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7292
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7434
+ import { copyFileSync as copyFileSync2, existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7435
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7293
7436
  import { parseHTML as parseHTML3 } from "linkedom";
7294
7437
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
7295
7438
  import {
@@ -7334,20 +7477,20 @@ function resolveLocalImageSourcePath(src, options) {
7334
7477
  const { basePath } = splitUrlSuffix(trimmed);
7335
7478
  const normalizedBase = normalizeRelPath(basePath);
7336
7479
  const mapped = options.sourceAssets?.get(trimmed) ?? options.sourceAssets?.get(basePath) ?? options.sourceAssets?.get(normalizedBase);
7337
- if (mapped && existsSync9(mapped)) return mapped;
7480
+ if (mapped && existsSync10(mapped)) return mapped;
7338
7481
  if (isHttpUrl(trimmed)) return null;
7339
7482
  const projectRelative = basePath.startsWith("/") ? basePath.slice(1) : basePath;
7340
7483
  const candidates = [
7341
- isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7342
- resolve5(options.downloadDir, normalizedBase)
7484
+ isAbsolute3(basePath) ? basePath : resolve6(options.projectDir, projectRelative),
7485
+ resolve6(options.downloadDir, normalizedBase)
7343
7486
  ];
7344
7487
  const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7345
7488
  const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7346
- return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7489
+ return candidates.find((candidate) => allowed(candidate) && existsSync10(candidate)) ?? null;
7347
7490
  }
7348
7491
  function isUsableFile(path) {
7349
7492
  try {
7350
- const stat = statSync8(path);
7493
+ const stat = statSync7(path);
7351
7494
  return stat.isFile() && stat.size > 0;
7352
7495
  } catch {
7353
7496
  return false;
@@ -7455,10 +7598,10 @@ async function runAnimatedGifTranscode(request) {
7455
7598
  throw result.error ?? new Error(`Animated GIF transcode failed (${result.exitCode}): ${result.stderr.slice(-500)}`);
7456
7599
  }
7457
7600
  async function ensurePreparedWebm(input) {
7458
- if (!existsSync9(dirname6(input.cachePath))) {
7601
+ if (!existsSync10(dirname6(input.cachePath))) {
7459
7602
  mkdirSync7(dirname6(input.cachePath), { recursive: true });
7460
7603
  }
7461
- if (!existsSync9(dirname6(input.outputPath))) {
7604
+ if (!existsSync10(dirname6(input.outputPath))) {
7462
7605
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7463
7606
  }
7464
7607
  if (!isUsableFile(input.cachePath)) {
@@ -7490,7 +7633,7 @@ async function ensurePreparedWebm(input) {
7490
7633
  throw error;
7491
7634
  }
7492
7635
  }
7493
- if (resolve5(input.outputPath) !== resolve5(input.cachePath) && !isUsableFile(input.outputPath)) {
7636
+ if (resolve6(input.outputPath) !== resolve6(input.cachePath) && !isUsableFile(input.outputPath)) {
7494
7637
  copyFileSync2(input.cachePath, input.outputPath);
7495
7638
  }
7496
7639
  }
@@ -7542,7 +7685,7 @@ function replaceImageWithVideo(input) {
7542
7685
  return video;
7543
7686
  }
7544
7687
  async function prepareAnimatedGifInputs(html, options) {
7545
- const outputDir = options.outputDir ?? join16(options.downloadDir, PREPARED_GIF_SUBDIR);
7688
+ const outputDir = options.outputDir ?? join18(options.downloadDir, PREPARED_GIF_SUBDIR);
7546
7689
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_GIF_SUBDIR);
7547
7690
  const cacheDir = options.cacheDir ?? outputDir;
7548
7691
  const { document: document2 } = parseHTML3(html);
@@ -7569,8 +7712,8 @@ async function prepareAnimatedGifInputs(html, options) {
7569
7712
  );
7570
7713
  const hash = computePreparedGifHash(bytes, loopIterations, padSeconds);
7571
7714
  const filename = `${CACHE_SCHEMA}-${hash.slice(0, 24)}.webm`;
7572
- const cachePath = join16(cacheDir, filename);
7573
- const outputPath = join16(outputDir, filename);
7715
+ const cachePath = join18(cacheDir, filename);
7716
+ const outputPath = join18(outputDir, filename);
7574
7717
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7575
7718
  await ensurePreparedWebm({
7576
7719
  sourcePath,
@@ -7612,10 +7755,10 @@ import {
7612
7755
  readFileSync as readFileSync7,
7613
7756
  readSync as readSync3,
7614
7757
  rmSync as rmSync10,
7615
- statSync as statSync9,
7758
+ statSync as statSync8,
7616
7759
  writeFileSync as writeFileSync4
7617
7760
  } from "node:fs";
7618
- import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
7761
+ import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
7619
7762
  import { parseHTML as parseHTML4 } from "linkedom";
7620
7763
  import { renameWithRetry as renameWithRetry4, runFfmpeg as runFfmpeg3, runFfprobe, urlInputArgs as urlInputArgs3 } from "@hyperframes/engine";
7621
7764
 
@@ -7684,10 +7827,10 @@ var Semaphore = class {
7684
7827
  this.active++;
7685
7828
  return () => this.release();
7686
7829
  }
7687
- return new Promise((resolve13) => {
7830
+ return new Promise((resolve14) => {
7688
7831
  this.queue.push(() => {
7689
7832
  this.active++;
7690
- resolve13(() => this.release());
7833
+ resolve14(() => this.release());
7691
7834
  });
7692
7835
  });
7693
7836
  }
@@ -7856,7 +7999,7 @@ function resolveImageSource(src, options) {
7856
7999
  }
7857
8000
  function isUsableFile2(path) {
7858
8001
  try {
7859
- return statSync9(path).size > 0;
8002
+ return statSync8(path).size > 0;
7860
8003
  } catch {
7861
8004
  return false;
7862
8005
  }
@@ -7885,12 +8028,12 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
7885
8028
  rmSync10(inlinePath, { force: true });
7886
8029
  }
7887
8030
  }
7888
- if (resolve6(outputPath) !== resolve6(cachePath) && !isUsableFile2(outputPath)) {
8031
+ if (resolve7(outputPath) !== resolve7(cachePath) && !isUsableFile2(outputPath)) {
7889
8032
  copyFileSync3(cachePath, outputPath);
7890
8033
  }
7891
8034
  }
7892
8035
  async function prepareHeifImageInputs(html, options) {
7893
- const outputDir = options.outputDir ?? join17(options.downloadDir, PREPARED_HEIF_SUBDIR);
8036
+ const outputDir = options.outputDir ?? join19(options.downloadDir, PREPARED_HEIF_SUBDIR);
7894
8037
  const outputSrcPrefix = normalizeRelPath(options.outputSrcPrefix ?? PREPARED_HEIF_SUBDIR);
7895
8038
  const cacheDir = options.cacheDir ?? outputDir;
7896
8039
  const preparedAssets = /* @__PURE__ */ new Map();
@@ -7911,7 +8054,7 @@ async function prepareHeifImageInputs(html, options) {
7911
8054
  await Promise.all(
7912
8055
  [...unique].map(
7913
8056
  ([filename, source]) => withMediaProbeSlot(
7914
- () => ensurePreparedJpeg(source, join17(cacheDir, filename), join17(outputDir, filename), options)
8057
+ () => ensurePreparedJpeg(source, join19(cacheDir, filename), join19(outputDir, filename), options)
7915
8058
  ).catch((error) => {
7916
8059
  if (!options.onFailure) throw error;
7917
8060
  failed.add(filename);
@@ -7923,8 +8066,8 @@ async function prepareHeifImageInputs(html, options) {
7923
8066
  if (failed.has(filename)) continue;
7924
8067
  const outputSrc = `${outputSrcPrefix}/${filename}`;
7925
8068
  img.setAttribute("src", outputSrc);
7926
- preparedAssets.set(outputSrc, join17(outputDir, filename));
7927
- preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join17(outputDir, filename) });
8069
+ preparedAssets.set(outputSrc, join19(outputDir, filename));
8070
+ preparedImages.push({ sourceSrc: src, outputSrc, outputPath: join19(outputDir, filename) });
7928
8071
  }
7929
8072
  return { html: document2.toString(), preparedAssets, preparedImages };
7930
8073
  }
@@ -7934,8 +8077,8 @@ import { createStudioPositionSeekReapplyScript } from "@hyperframes/studio-serve
7934
8077
  import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position-edits-render";
7935
8078
 
7936
8079
  // src/services/assetMediaType.ts
7937
- import { existsSync as existsSync10 } from "node:fs";
7938
- import { dirname as dirname8, join as join18 } from "node:path";
8080
+ import { existsSync as existsSync11 } from "node:fs";
8081
+ import { dirname as dirname8, join as join20 } from "node:path";
7939
8082
  import {
7940
8083
  fingerprintElementId,
7941
8084
  isHttpUrl as isHttpUrl2,
@@ -7988,11 +8131,11 @@ function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
7988
8131
  ]);
7989
8132
  }
7990
8133
  function mediaAssetRoots(projectDir, compiledDir) {
7991
- return [projectDir, compiledDir, join18(dirname8(compiledDir), "downloads")];
8134
+ return [projectDir, compiledDir, join20(dirname8(compiledDir), "downloads")];
7992
8135
  }
7993
8136
  function dropMediaOutsideProject(input) {
7994
8137
  const { projectDir, workDir, composition, log } = input;
7995
- const compiledDir = join18(workDir, "compiled");
8138
+ const compiledDir = join20(workDir, "compiled");
7996
8139
  const roots = mediaAssetRoots(projectDir, compiledDir);
7997
8140
  const staysInside = ({ id, src }) => {
7998
8141
  if (!src || isHttpUrl2(src)) return true;
@@ -8047,7 +8190,7 @@ async function preflightCompositionAssetMediaTypes(input) {
8047
8190
  input.projectDir,
8048
8191
  input.compiledDir
8049
8192
  );
8050
- if (!existsSync10(resolvedPath)) continue;
8193
+ if (!existsSync11(resolvedPath)) continue;
8051
8194
  byPath.set(resolvedPath, [...byPath.get(resolvedPath) ?? [], reference]);
8052
8195
  }
8053
8196
  const mismatches = [];
@@ -8138,7 +8281,7 @@ function normalizeCompositionSrcs(html, projectDir) {
8138
8281
  if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
8139
8282
  const file = resolveCompositionSrc(projectDir, value);
8140
8283
  if (file === null) return whole;
8141
- return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
8284
+ return `${name}${quote}${relative3(projectDir, file).split(sep4).join("/")}${quote}`;
8142
8285
  });
8143
8286
  }
8144
8287
  var COMPOSITION_FILE = /\.html?$/i;
@@ -8343,8 +8486,8 @@ function detectShaderTransitionUsage(html) {
8343
8486
  async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
8344
8487
  let filePath = src;
8345
8488
  if (isHttpUrl(src)) {
8346
- const remoteDir = join19(downloadDir, REMOTE_MEDIA_SUBDIR);
8347
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8489
+ const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8490
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8348
8491
  try {
8349
8492
  filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8350
8493
  onTelemetry: logRemoteDownloadTelemetry
@@ -8354,7 +8497,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8354
8497
  }
8355
8498
  } else {
8356
8499
  filePath = decodedUrlPath(src);
8357
- if (!filePath.startsWith("/")) filePath = join19(baseDir, filePath);
8500
+ if (!filePath.startsWith("/")) filePath = join21(baseDir, filePath);
8358
8501
  if (escapesAssetRoot(filePath, assetRoot) || isPrivateUnderAssetRoots3(filePath, [projectDir, downloadDir])) {
8359
8502
  return { duration: null, resolvedPath: filePath };
8360
8503
  }
@@ -8363,7 +8506,7 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8363
8506
  return { duration: null, resolvedPath: filePath };
8364
8507
  }
8365
8508
  }
8366
- if (!isHttpUrl(filePath) && !existsSync11(filePath)) {
8509
+ if (!isHttpUrl(filePath) && !existsSync12(filePath)) {
8367
8510
  return { duration: null, resolvedPath: filePath };
8368
8511
  }
8369
8512
  const withSrcContext = (error) => {
@@ -8733,7 +8876,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8733
8876
  parseHostVariables: parseHostVariableValues,
8734
8877
  resolveFilePath: (srcPath) => {
8735
8878
  const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
8736
- return file && relative2(projectDir, file).split(sep3).join("/");
8879
+ return file && relative3(projectDir, file).split(sep4).join("/");
8737
8880
  },
8738
8881
  resolveHtml: (srcPath) => {
8739
8882
  const compHtml = resolveMountHtml(srcPath);
@@ -8897,7 +9040,8 @@ async function downloadScript(src, mirror) {
8897
9040
  }
8898
9041
  return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15e3 });
8899
9042
  }
8900
- async function inlineExternalScripts(html) {
9043
+ var MAX_CONCURRENT_SCRIPT_FETCHES = 4;
9044
+ async function inlineExternalScripts(html, budget = new CompositionExpansionBudget()) {
8901
9045
  const fullHtml = ensureFullDocument(html);
8902
9046
  const wrappedFragment = fullHtml !== html;
8903
9047
  const { document: document2 } = parseHTML5(fullHtml);
@@ -8911,20 +9055,52 @@ async function inlineExternalScripts(html) {
8911
9055
  }
8912
9056
  if (externalScripts.length === 0) return html;
8913
9057
  const mirror = operatorGsapMirror();
9058
+ const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
9059
+ const stop = new AbortController();
9060
+ const fail = (error) => {
9061
+ stop.abort(error);
9062
+ throw error;
9063
+ };
9064
+ const charge = (bytes) => {
9065
+ try {
9066
+ budget.chargeGenerated(REMOTE_SCRIPTS, bytes);
9067
+ } catch (error) {
9068
+ fail(error);
9069
+ }
9070
+ };
9071
+ const fetches = /* @__PURE__ */ new Map();
9072
+ const fetchOnce = (src) => {
9073
+ let bytes = fetches.get(src);
9074
+ if (!bytes) {
9075
+ bytes = limit(async () => {
9076
+ if (stop.signal.aborted) throw stop.signal.reason;
9077
+ const downloaded = await downloadScript(src, mirror);
9078
+ charge(downloaded.byteLength);
9079
+ return downloaded;
9080
+ }, stop.signal);
9081
+ fetches.set(src, bytes);
9082
+ }
9083
+ return bytes;
9084
+ };
9085
+ const placed = /* @__PURE__ */ new Set();
8914
9086
  const downloads = await Promise.allSettled(
8915
9087
  externalScripts.map(async ({ el, src }) => {
8916
9088
  const integrity = el.getAttribute("integrity") || "";
8917
- const bundled = bundledScript(src);
8918
- if (bundled && matchesScriptIntegrity(bundled, integrity)) {
8919
- return { src, text: new TextDecoder().decode(bundled) };
8920
- }
8921
- const bytes = await downloadScript(src, mirror);
8922
- if (!matchesScriptIntegrity(bytes, integrity)) {
8923
- throw new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`);
9089
+ let bytes = bundledScript(src);
9090
+ if (bytes && matchesScriptIntegrity(bytes, integrity)) {
9091
+ charge(bytes.byteLength);
9092
+ } else {
9093
+ bytes = await fetchOnce(src);
9094
+ if (!matchesScriptIntegrity(bytes, integrity)) {
9095
+ fail(new ScriptIntegrityError(`Subresource integrity mismatch for ${src}`));
9096
+ }
9097
+ if (placed.has(src)) charge(bytes.byteLength);
9098
+ placed.add(src);
8924
9099
  }
8925
9100
  return { src, text: new TextDecoder().decode(bytes) };
8926
9101
  })
8927
9102
  );
9103
+ if (stop.signal.aborted) throw stop.signal.reason;
8928
9104
  for (let i = 0; i < downloads.length; i++) {
8929
9105
  const download = downloads[i];
8930
9106
  const { el, src } = externalScripts[i];
@@ -8951,18 +9127,18 @@ ${safeText}
8951
9127
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8952
9128
  }
8953
9129
  function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8954
- const absProjectDir = resolve7(projectDir);
9130
+ const absProjectDir = resolve8(projectDir);
8955
9131
  const externalAssets = /* @__PURE__ */ new Map();
8956
9132
  const leftOut = /* @__PURE__ */ new Set();
8957
9133
  function processPath(rawPath) {
8958
9134
  const trimmed = rawPath.trim();
8959
9135
  if (isNonRelativeUrl(trimmed)) return null;
8960
- const absPath = resolve7(absProjectDir, trimmed);
9136
+ const absPath = resolve8(absProjectDir, trimmed);
8961
9137
  if (isPathInside(absPath, absProjectDir)) {
8962
9138
  return null;
8963
9139
  }
8964
9140
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8965
- if (!onShare && !existsSync11(absPath)) return null;
9141
+ if (!onShare && !existsSync12(absPath)) return null;
8966
9142
  const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8967
9143
  if (refusal) {
8968
9144
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
@@ -9015,7 +9191,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9015
9191
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9016
9192
  async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9017
9193
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9018
- if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9194
+ if (!existsSync12(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9019
9195
  const urlToLocal = /* @__PURE__ */ new Map();
9020
9196
  await Promise.all(
9021
9197
  [...urlSet].map(async (url) => {
@@ -9038,7 +9214,7 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9038
9214
  const remoteMediaAssets = /* @__PURE__ */ new Map();
9039
9215
  const urlToRelPath = /* @__PURE__ */ new Map();
9040
9216
  for (const [url, absPath] of urlToLocal) {
9041
- const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename5(absPath)}`;
9217
+ const relPath = `${REMOTE_MEDIA_SUBDIR}/${basename6(absPath)}`;
9042
9218
  remoteMediaAssets.set(relPath, absPath);
9043
9219
  urlToRelPath.set(url, relPath);
9044
9220
  }
@@ -9055,7 +9231,7 @@ async function localizeRemoteMediaSources(html, downloadDir) {
9055
9231
  const localized = await downloadAndRewriteUrls(
9056
9232
  urlSet,
9057
9233
  html,
9058
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9234
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9059
9235
  "Remote media download failed",
9060
9236
  "Localized remote media source(s)"
9061
9237
  );
@@ -9078,7 +9254,7 @@ async function localizeRemoteImageSources(html, downloadDir) {
9078
9254
  return downloadAndRewriteUrls(
9079
9255
  urlSet,
9080
9256
  html,
9081
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9257
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9082
9258
  "Remote image download failed",
9083
9259
  "Localized remote image source(s)"
9084
9260
  );
@@ -9091,7 +9267,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
9091
9267
  return downloadAndRewriteUrls(
9092
9268
  urlSet,
9093
9269
  html,
9094
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9270
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9095
9271
  "Remote background-image download failed",
9096
9272
  "Localized remote background-image(s)",
9097
9273
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
@@ -9148,48 +9324,50 @@ function matchingBraces(css) {
9148
9324
  }
9149
9325
  return closes;
9150
9326
  }
9151
- async function inlineExternalFontStylesheets(html) {
9152
- const hrefRe = /\bhref=["']([^"']+)["']/i;
9153
- const linkMatches = [];
9327
+ function remoteFontStylesheetHref(tag) {
9328
+ const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9329
+ if (!href || !/^https?:\/\//i.test(href) || isGoogleFontsUrl(href)) return void 0;
9330
+ return href;
9331
+ }
9332
+ async function inlineExternalFontStylesheets(html, budget = new CompositionExpansionBudget()) {
9333
+ const hrefs = /* @__PURE__ */ new Set();
9154
9334
  for (const { parts } of stylesheetLinkMatches(html)) {
9155
- const tag = parts[0];
9156
- const hrefMatch = hrefRe.exec(tag);
9157
- if (!hrefMatch?.[1]) continue;
9158
- const href = hrefMatch[1];
9159
- if (!/^https?:\/\//i.test(href)) continue;
9160
- if (isGoogleFontsUrl(href)) continue;
9161
- linkMatches.push({ fullMatch: tag, href });
9162
- }
9163
- if (linkMatches.length === 0) return html;
9164
- const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9165
- const fetches = [];
9166
- for (let i = 0; i < linkMatches.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9167
- const batch = linkMatches.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9168
- const results = await Promise.all(
9169
- batch.map(async ({ fullMatch, href }) => {
9170
- const css = await fetchExternalStylesheetCss(href);
9171
- return { fullMatch, href, css };
9172
- })
9173
- );
9174
- fetches.push(...results);
9335
+ const href = remoteFontStylesheetHref(parts[0]);
9336
+ if (href) hrefs.add(href);
9175
9337
  }
9176
- let result = html;
9177
- for (const { fullMatch, href, css } of fetches) {
9178
- if (css === null) continue;
9179
- const fontFaceBlocks = extractFontFaceBlocks(css);
9180
- if (fontFaceBlocks.length === 0) continue;
9181
- const identity = safeDownloadUrlIdentity(href);
9182
- const inlineStyle = `<style>/* Inlined external font stylesheet */
9338
+ if (hrefs.size === 0) return html;
9339
+ const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
9340
+ const inlineByHref = /* @__PURE__ */ new Map();
9341
+ const unique = [...hrefs];
9342
+ for (let i = 0; i < unique.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
9343
+ const batch = unique.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
9344
+ const sheets = await Promise.all(batch.map(fetchExternalStylesheetCss));
9345
+ batch.forEach((href, index) => {
9346
+ const css = sheets[index];
9347
+ const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9348
+ if (fontFaceBlocks.length === 0) return;
9349
+ const inlineStyle = `<style>/* Inlined external font stylesheet */
9183
9350
  ${fontFaceBlocks.join("\n")}
9184
9351
  </style>`;
9185
- result = result.replace(fullMatch, inlineStyle);
9186
- defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9187
- count: fontFaceBlocks.length,
9188
- urlFingerprint: identity.urlFingerprint,
9189
- host: identity.host
9352
+ budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9353
+ inlineByHref.set(href, inlineStyle);
9354
+ const identity = safeDownloadUrlIdentity(href);
9355
+ defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
9356
+ count: fontFaceBlocks.length,
9357
+ urlFingerprint: identity.urlFingerprint,
9358
+ host: identity.host
9359
+ });
9190
9360
  });
9191
9361
  }
9192
- return result;
9362
+ const placed = /* @__PURE__ */ new Set();
9363
+ return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
9364
+ const href = remoteFontStylesheetHref(tag);
9365
+ const inlineStyle = href ? inlineByHref.get(href) : void 0;
9366
+ if (!href || !inlineStyle) return tag;
9367
+ if (placed.has(href)) budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
9368
+ placed.add(href);
9369
+ return inlineStyle;
9370
+ });
9193
9371
  }
9194
9372
  function projectStylesheetFontFamilies(html, projectDir) {
9195
9373
  const families = [];
@@ -9198,14 +9376,14 @@ function projectStylesheetFontFamilies(html, projectDir) {
9198
9376
  } of stylesheetLinkMatches(html)) {
9199
9377
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
9200
9378
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
9201
- const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9202
- if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
9379
+ const sheet = resolve8(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
9380
+ if (!isPathInside(sheet, projectDir) || !existsSync12(sheet)) continue;
9203
9381
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
9204
9382
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
9205
9383
  const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
9206
9384
  const path = decodedUrlPath(url);
9207
- const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname9(sheet), path);
9208
- return isPathInside(file, projectDir) && existsSync11(file);
9385
+ const file = path.startsWith("/") ? resolve8(projectDir, `.${path}`) : resolve8(dirname9(sheet), path);
9386
+ return isPathInside(file, projectDir) && existsSync12(file);
9209
9387
  });
9210
9388
  if (family && shipsFile) families.push(family);
9211
9389
  }
@@ -9245,7 +9423,7 @@ function localizeFontFaceUrls(html, downloadDir) {
9245
9423
  return downloadAndRewriteUrls(
9246
9424
  collectFontFaceUrls(html),
9247
9425
  html,
9248
- join19(downloadDir, REMOTE_MEDIA_SUBDIR),
9426
+ join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9249
9427
  "Remote font download failed",
9250
9428
  "Localized remote font face(s)",
9251
9429
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
@@ -9255,7 +9433,7 @@ var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
9255
9433
  async function readLocalFont(absPath) {
9256
9434
  const chunks = [];
9257
9435
  let totalBytes = 0;
9258
- for await (const chunk of createReadStream2(absPath)) {
9436
+ for await (const chunk of createReadStream3(absPath)) {
9259
9437
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
9260
9438
  totalBytes += buffer.length;
9261
9439
  if (totalBytes > MAX_LOCAL_FONT_DATA_URI_BYTES) {
@@ -9266,7 +9444,7 @@ async function readLocalFont(absPath) {
9266
9444
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9267
9445
  }
9268
9446
  async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9269
- const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
9447
+ const absPath = localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath);
9270
9448
  if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9271
9449
  if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9272
9450
  return void 0;
@@ -9356,8 +9534,8 @@ function renderGsapDist() {
9356
9534
  function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9357
9535
  let gsapDist;
9358
9536
  const exists = (path) => {
9359
- const file = resolve7(projectDir, path);
9360
- return !namesAnotherNetworkRoot2(projectDir, file) && existsSync11(file);
9537
+ const file = resolve8(projectDir, path);
9538
+ return !namesAnotherNetworkRoot2(projectDir, file) && existsSync12(file);
9361
9539
  };
9362
9540
  return replaceGsapDistScripts(html, (full, prefix, src, file, suffix) => {
9363
9541
  if (/^https?:\/\//i.test(src)) return full;
@@ -9369,7 +9547,7 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
9369
9547
  }
9370
9548
  function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9371
9549
  if (!isPathInside(htmlPath, projectDir)) return html;
9372
- const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9550
+ const entryPath = relative3(projectDir, htmlPath).replace(/\\/g, "/");
9373
9551
  if (!entryPath.includes("/")) return html;
9374
9552
  const { document: document2 } = parseHTML5(html);
9375
9553
  const assetExists = projectAssetExists(projectDir);
@@ -9429,7 +9607,7 @@ function bindVariableMediaSources(html, variables, budget, log) {
9429
9607
  }
9430
9608
  return changed ? document2.toString() : html;
9431
9609
  }
9432
- var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9610
+ var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative3(projectDir, htmlPath).split(sep4).join("/") : basename6(htmlPath);
9433
9611
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9434
9612
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9435
9613
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
@@ -9442,7 +9620,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9442
9620
  if (!COMPOSITION_FILE.test(htmlPath)) {
9443
9621
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9444
9622
  }
9445
- assertCompositionFileSize(htmlPath, basename5(htmlPath));
9623
+ assertCompositionFileSize(htmlPath, basename6(htmlPath));
9446
9624
  const budget = new CompositionExpansionBudget();
9447
9625
  const entryHtml = rebaseDirectEntryAssetPaths(
9448
9626
  readTextFile(htmlPath),
@@ -9494,7 +9672,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9494
9672
  const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
9495
9673
  const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
9496
9674
  const fontSheetHtml = await inlineExternalFontStylesheets(
9497
- promoteCssImportsToLinkTags(sanitizedHtml)
9675
+ promoteCssImportsToLinkTags(sanitizedHtml),
9676
+ budget
9498
9677
  );
9499
9678
  const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
9500
9679
  injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml))
@@ -9506,7 +9685,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9506
9685
  projectFontFamilies: projectStylesheetFontFamilies(fontSheetHtml, projectDir),
9507
9686
  abortSignal: options.abortSignal
9508
9687
  });
9509
- const assembledHtml = await inlineExternalScripts(coalescedHtml);
9688
+ const assembledHtml = await inlineExternalScripts(coalescedHtml, budget);
9510
9689
  const HF_POSITION_ATTRS = [
9511
9690
  'data-hf-studio-path-offset="true"',
9512
9691
  'data-hf-studio-box-size="true"',
@@ -9598,8 +9777,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9598
9777
  const advised = /* @__PURE__ */ new Set();
9599
9778
  for (const video of videos) {
9600
9779
  if (isHttpUrl(video.src)) continue;
9601
- const videoPath = resolve7(projectDir, video.src);
9602
- if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync11(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9780
+ const videoPath = resolve8(projectDir, video.src);
9781
+ if (advised.has(videoPath) || namesAnotherNetworkRoot2(projectDir, videoPath) || !existsSync12(videoPath) || escapesAssetRoot(videoPath, assetRoot) || isPrivateUnderAssetRoots3(videoPath, [projectDir, downloadDir]))
9603
9782
  continue;
9604
9783
  advised.add(videoPath);
9605
9784
  const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
@@ -10014,7 +10193,7 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
10014
10193
  function animatedGifCacheDir(extractCacheDir) {
10015
10194
  try {
10016
10195
  const root = extractCacheDir && privateCacheRoot(extractCacheDir);
10017
- return root ? join20(root, "animated-gif") : void 0;
10196
+ return root ? join22(root, "animated-gif") : void 0;
10018
10197
  } catch {
10019
10198
  return void 0;
10020
10199
  }
@@ -10036,17 +10215,17 @@ function resolveEntryHtmlPath(input) {
10036
10215
  const readEntry = (path) => {
10037
10216
  if (escapesAssetRoot(path, input.assetRoot)) {
10038
10217
  throw new Error(
10039
- `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
10218
+ `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10040
10219
  );
10041
10220
  }
10042
- assertCompositionFileSize(path, relative3(projectDir, path));
10221
+ assertCompositionFileSize(path, relative4(projectDir, path));
10043
10222
  return readTextFile2(path);
10044
10223
  };
10045
- const htmlPath = join20(projectDir, entryFile);
10224
+ const htmlPath = join22(projectDir, entryFile);
10046
10225
  const rawEntry = readEntry(htmlPath);
10047
10226
  if (entryFile === "index.html" || !isTemplateEntry(rawEntry)) return htmlPath;
10048
- const projectIndexPath = join20(projectDir, "index.html");
10049
- if (!existsSync12(projectIndexPath)) {
10227
+ const projectIndexPath = join22(projectDir, "index.html");
10228
+ if (!existsSync13(projectIndexPath)) {
10050
10229
  throw new Error(
10051
10230
  `Template entry file "${entryFile}" requires a project index.html to extract its render shell.`
10052
10231
  );
@@ -10061,7 +10240,7 @@ function resolveEntryHtmlPath(input) {
10061
10240
  `Entry file "${entryFile}" is not mounted from index.html via data-composition-src, so it cannot be rendered independently.`
10062
10241
  );
10063
10242
  }
10064
- const wrapperPath = join20(workDir, "standalone-entry.html");
10243
+ const wrapperPath = join22(workDir, "standalone-entry.html");
10065
10244
  writeFileSync5(wrapperPath, standaloneHtml, "utf-8");
10066
10245
  log.info("Extracted standalone entry from index.html host context", { entryFile });
10067
10246
  return wrapperPath;
@@ -10091,7 +10270,7 @@ async function runCompileStage(input) {
10091
10270
  const assetRoot = job.config.allowOutsideProjectAssets ? void 0 : projectDir;
10092
10271
  const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log, assetRoot });
10093
10272
  const compileStart = Date.now();
10094
- const compiled = await compileForRender(projectDir, htmlPath, join20(workDir, "downloads"), {
10273
+ const compiled = await compileForRender(projectDir, htmlPath, join22(workDir, "downloads"), {
10095
10274
  log,
10096
10275
  failClosedFontFetch: failClosedFontFetch === true,
10097
10276
  allowSystemFontCapture,
@@ -10166,7 +10345,7 @@ async function runCompileStage(input) {
10166
10345
  });
10167
10346
  await preflightCompositionAssetMediaTypes({
10168
10347
  projectDir,
10169
- compiledDir: join20(workDir, "compiled"),
10348
+ compiledDir: join22(workDir, "compiled"),
10170
10349
  composition,
10171
10350
  signal: abortSignal
10172
10351
  });
@@ -10214,7 +10393,7 @@ async function runCompileStage(input) {
10214
10393
 
10215
10394
  // src/services/render/stages/probeStage.ts
10216
10395
  import { createHash as createHash7 } from "node:crypto";
10217
- import { basename as basename6, join as join21 } from "node:path";
10396
+ import { basename as basename7, join as join23 } from "node:path";
10218
10397
  import { parseHTML as parseHTML6 } from "linkedom";
10219
10398
  import {
10220
10399
  closeCaptureSession as closeCaptureSession4,
@@ -10462,7 +10641,7 @@ function probeRequiresBrowser(args) {
10462
10641
  function reportedLengthSource(source) {
10463
10642
  if (!source) return null;
10464
10643
  if (source.from !== "media") return { from: source.from };
10465
- const name = basename6(source.src.split(/[?#]/, 1)[0] ?? "");
10644
+ const name = basename7(source.src.split(/[?#]/, 1)[0] ?? "");
10466
10645
  const srcHash = createHash7("sha256").update(name).digest("hex").slice(0, 12);
10467
10646
  return { from: "media", tag: source.tag, trimmed: source.trimmed, srcHash };
10468
10647
  }
@@ -10528,7 +10707,7 @@ async function runProbeStage(input) {
10528
10707
  });
10529
10708
  fileServer = await createFileServer({
10530
10709
  projectDir,
10531
- compiledDir: join21(workDir, "compiled"),
10710
+ compiledDir: join23(workDir, "compiled"),
10532
10711
  port: 0,
10533
10712
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10534
10713
  fps: job.config.fps,
@@ -10565,7 +10744,7 @@ async function runProbeStage(input) {
10565
10744
  log.info("Creating capture session...", { attempt, maxAttempts: PROBE_MAX_ATTEMPTS });
10566
10745
  probeSession = await createCaptureSession4(
10567
10746
  fileServer.url,
10568
- join21(workDir, "probe"),
10747
+ join23(workDir, "probe"),
10569
10748
  captureOpts,
10570
10749
  null,
10571
10750
  probeCfg
@@ -10650,7 +10829,7 @@ async function runProbeStage(input) {
10650
10829
  });
10651
10830
  probeSession = await createCaptureSession4(
10652
10831
  fileServer.url,
10653
- join21(workDir, "probe-screenshot"),
10832
+ join23(workDir, "probe-screenshot"),
10654
10833
  captureOpts,
10655
10834
  null,
10656
10835
  { ...probeCfg, forceScreenshot: true }
@@ -10688,7 +10867,7 @@ async function runProbeStage(input) {
10688
10867
  compiled,
10689
10868
  resolutions,
10690
10869
  projectDir,
10691
- join21(workDir, "downloads"),
10870
+ join23(workDir, "downloads"),
10692
10871
  job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10693
10872
  { includeScripts: job.config.includeOutsideScripts }
10694
10873
  );
@@ -10888,7 +11067,7 @@ async function runProbeStage(input) {
10888
11067
  });
10889
11068
  await preflightCompositionAssetMediaTypes({
10890
11069
  projectDir,
10891
- compiledDir: join21(workDir, "compiled"),
11070
+ compiledDir: join23(workDir, "compiled"),
10892
11071
  composition,
10893
11072
  signal: abortSignal
10894
11073
  });
@@ -11055,8 +11234,8 @@ function validateDistributedDuration(input) {
11055
11234
  }
11056
11235
 
11057
11236
  // src/services/render/stages/extractVideosStage.ts
11058
- import { existsSync as existsSync13 } from "node:fs";
11059
- import { join as join22 } from "node:path";
11237
+ import { existsSync as existsSync14 } from "node:fs";
11238
+ import { join as join24 } from "node:path";
11060
11239
  import {
11061
11240
  classifyVideoExtractionError,
11062
11241
  createFrameLookupTable as createFrameLookupTable3,
@@ -11420,7 +11599,7 @@ async function runExtractVideosStage(input) {
11420
11599
  // because short boundary counts can differ by one frame.
11421
11600
  {
11422
11601
  fps: job.config.fps,
11423
- outputDir: join22(compiledDir, "__hyperframes_video_frames"),
11602
+ outputDir: join24(compiledDir, "__hyperframes_video_frames"),
11424
11603
  format: job.config.videoFrameFormat ?? "auto",
11425
11604
  toneMapHdrToSdr: rendersSdrOnly(job.config, composition),
11426
11605
  timelineEnd: composition.duration,
@@ -11428,7 +11607,7 @@ async function runExtractVideosStage(input) {
11428
11607
  collectProbeFailures: extractionPolicy.failureMode === "enforce",
11429
11608
  deferRangeExtraction,
11430
11609
  shownBoxes,
11431
- contentKeyedDirs: [join22(compiledDir, REMOTE_MEDIA_SUBDIR)],
11610
+ contentKeyedDirs: [join24(compiledDir, REMOTE_MEDIA_SUBDIR)],
11432
11611
  urlByAbsentLocalPath,
11433
11612
  assetRoots,
11434
11613
  onProgress: ({ planned = 0, done = 0 }) => {
@@ -11508,7 +11687,7 @@ function isPublicHttpsUrl(url) {
11508
11687
  }
11509
11688
  }
11510
11689
  function opensLocally(path, assetRoots) {
11511
- return existsSync13(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11690
+ return existsSync14(path) && (!assetRoots || assetRootsRefusal(path, assetRoots) === null);
11512
11691
  }
11513
11692
  function localProbeSource(src, input) {
11514
11693
  const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
@@ -11520,7 +11699,7 @@ async function remoteProbeSource(video, input) {
11520
11699
  if (!isPublicHttpsUrl(video.src)) return null;
11521
11700
  if (!resolveRestrictPageNetwork()) return video.src;
11522
11701
  if (!video.hasAudio || video.hidden) return null;
11523
- const downloadDir = input.downloadDir ?? join22(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11702
+ const downloadDir = input.downloadDir ?? join24(input.compiledDir, REMOTE_MEDIA_SUBDIR);
11524
11703
  try {
11525
11704
  return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
11526
11705
  onTelemetry: writeUrlDownloadTelemetry2
@@ -11561,7 +11740,7 @@ async function appendVideoAudioFromProbe(input) {
11561
11740
  }
11562
11741
 
11563
11742
  // src/services/render/videoLayerPassthroughPlan.ts
11564
- import { existsSync as existsSync14 } from "node:fs";
11743
+ import { existsSync as existsSync15 } from "node:fs";
11565
11744
  import {
11566
11745
  buildVideoLayerInput,
11567
11746
  isHttpUrl as isHttpUrl4,
@@ -11629,7 +11808,7 @@ async function planVideoLayerPassthrough(input) {
11629
11808
  const { video } = q;
11630
11809
  if (isHttpUrl4(video.src)) return { reason: "remote_source" };
11631
11810
  const path = resolveProjectRelativeSrc5(video.src, input.projectDir, input.compiledDir);
11632
- if (!existsSync14(path)) return { reason: "source_missing" };
11811
+ if (!existsSync15(path)) return { reason: "source_missing" };
11633
11812
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
11634
11813
  if ("reason" in layout) return layout;
11635
11814
  const layer = await buildVideoLayerInput(
@@ -11644,8 +11823,8 @@ async function planVideoLayerPassthrough(input) {
11644
11823
  }
11645
11824
 
11646
11825
  // src/services/render/stages/audioStage.ts
11647
- import { existsSync as existsSync16 } from "node:fs";
11648
- import { join as join25 } from "node:path";
11826
+ import { existsSync as existsSync17 } from "node:fs";
11827
+ import { join as join27 } from "node:path";
11649
11828
  import {
11650
11829
  MIXED_AUDIO_FILENAME,
11651
11830
  audioFailureDiagnostics,
@@ -11656,8 +11835,8 @@ import {
11656
11835
  } from "@hyperframes/engine";
11657
11836
 
11658
11837
  // src/services/render/audioDeliveryLimit.ts
11659
- import { existsSync as existsSync15 } from "node:fs";
11660
- import { dirname as dirname11, join as join24 } from "node:path";
11838
+ import { existsSync as existsSync16 } from "node:fs";
11839
+ import { dirname as dirname11, join as join26 } from "node:path";
11661
11840
  import {
11662
11841
  applyAudioFxChain,
11663
11842
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -11667,7 +11846,7 @@ import {
11667
11846
 
11668
11847
  // src/services/render/audioPadTrim.ts
11669
11848
  import { spawn } from "node:child_process";
11670
- import { dirname as dirname10, join as join23 } from "node:path";
11849
+ import { dirname as dirname10, join as join25 } from "node:path";
11671
11850
  import {
11672
11851
  DEFAULT_CONFIG,
11673
11852
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -11948,7 +12127,7 @@ async function constrainAacTruePeak(input) {
11948
12127
  }
11949
12128
  async function cutSource(input, scratchDir, attenuationDb) {
11950
12129
  if (!input.sourcePath || !input.rewriteSource) return true;
11951
- const cutPath = join23(scratchDir, "source.wav");
12130
+ const cutPath = join25(scratchDir, "source.wav");
11952
12131
  try {
11953
12132
  const result = await input.rewriteSource(input.sourcePath, cutPath, gainFilter(attenuationDb));
11954
12133
  if (!result.success) throw new Error(result.error);
@@ -11963,7 +12142,7 @@ async function enforceAacTruePeak(input) {
11963
12142
  let scratchDir;
11964
12143
  try {
11965
12144
  scratchDir = createStagingDir3(dirname10(input.audioPath), ".true-peak-");
11966
- const correctedPath = join23(scratchDir, "audio.m4a");
12145
+ const correctedPath = join25(scratchDir, "audio.m4a");
11967
12146
  const measurements = [];
11968
12147
  let attenuationDb = 0;
11969
12148
  let sourcePeakDbfs;
@@ -12176,14 +12355,14 @@ async function limitDeliveryPeaks(input, deps = {
12176
12355
  applyChain: applyAudioFxChain,
12177
12356
  encode: encodeAac2,
12178
12357
  rename: renameWithRetry6,
12179
- sourceExists: existsSync15
12358
+ sourceExists: existsSync16
12180
12359
  }) {
12181
12360
  const { audioPath, sourcePath, signal, timeoutMs } = input;
12182
12361
  if (!deps.sourceExists(sourcePath)) return { success: true };
12183
12362
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
12184
12363
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
12185
12364
  const alternating = ["a", "b"].map(
12186
- (k) => join24(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12365
+ (k) => join26(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
12187
12366
  );
12188
12367
  let encodedFrom;
12189
12368
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -12256,7 +12435,7 @@ function runAudioStage(input) {
12256
12435
  }
12257
12436
  async function runAudioStageScoped(input) {
12258
12437
  const stageStart = Date.now();
12259
- const pcmSourcePath = join25(input.workDir, "audio-source.wav");
12438
+ const pcmSourcePath = join27(input.workDir, "audio-source.wav");
12260
12439
  const duration = input.totalFrames * input.fps.den / input.fps.num;
12261
12440
  let deliverySourcePath;
12262
12441
  try {
@@ -12272,7 +12451,7 @@ async function runAudioStageScoped(input) {
12272
12451
  );
12273
12452
  audioLoweredDb = guard.loweredDb;
12274
12453
  input.log?.info("[audio] phases", { ...result.audioPhaseMs, guard: Date.now() - guardStart });
12275
- if (input.keepDeliverySource && !guard.sourceStale && existsSync16(pcmSourcePath)) {
12454
+ if (input.keepDeliverySource && !guard.sourceStale && existsSync17(pcmSourcePath)) {
12276
12455
  deliverySourcePath = pcmSourcePath;
12277
12456
  }
12278
12457
  }
@@ -12321,7 +12500,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12321
12500
  assertNotAborted,
12322
12501
  log
12323
12502
  } = input;
12324
- const audioOutputPath = join25(workDir, MIXED_AUDIO_FILENAME);
12503
+ const audioOutputPath = join27(workDir, MIXED_AUDIO_FILENAME);
12325
12504
  let hasAudio = false;
12326
12505
  let audioError;
12327
12506
  let audioFailures;
@@ -12401,8 +12580,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
12401
12580
  }
12402
12581
 
12403
12582
  // src/services/render/stages/captureStage.ts
12404
- import { existsSync as existsSync17, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12405
- import { join as join26 } from "node:path";
12583
+ import { existsSync as existsSync18, readdirSync as readdirSync4, statfsSync as statfsSync2 } from "node:fs";
12584
+ import { join as join28 } from "node:path";
12406
12585
  import {
12407
12586
  classifyCaptureFailure as classifyCaptureFailure2,
12408
12587
  frameFileExtension,
@@ -12472,16 +12651,16 @@ function diskCaptureShortfallError(needBytes, freeBytes, framesDir, basis, remed
12472
12651
  }
12473
12652
  function measureCaptureFrameBytes(workDir, framesDir) {
12474
12653
  let total = sampleDirectoryBytes(framesDir);
12475
- if (!existsSync17(workDir)) return total;
12654
+ if (!existsSync18(workDir)) return total;
12476
12655
  for (const attempt of readdirSync4(workDir)) {
12477
12656
  if (/^retry-\d+-batch-\d+-worker-\d+$/.test(attempt)) {
12478
- total += sampleDirectoryBytes(join26(workDir, attempt));
12657
+ total += sampleDirectoryBytes(join28(workDir, attempt));
12479
12658
  continue;
12480
12659
  }
12481
12660
  if (!/^capture-attempt-\d+$/.test(attempt)) continue;
12482
- const attemptDir = join26(workDir, attempt);
12661
+ const attemptDir = join28(workDir, attempt);
12483
12662
  for (const name of readdirSync4(attemptDir)) {
12484
- if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join26(attemptDir, name));
12663
+ if (/^worker-\d+$/.test(name)) total += sampleDirectoryBytes(join28(attemptDir, name));
12485
12664
  }
12486
12665
  }
12487
12666
  return total;
@@ -12779,8 +12958,8 @@ async function captureSessionFrames(session, { input, rangeStart, rangeEnd, resu
12779
12958
  }
12780
12959
 
12781
12960
  // src/services/render/stages/captureHdrStage.ts
12782
- import { existsSync as existsSync19, mkdirSync as mkdirSync10 } from "node:fs";
12783
- import { join as join30 } from "node:path";
12961
+ import { existsSync as existsSync20, mkdirSync as mkdirSync10 } from "node:fs";
12962
+ import { join as join32 } from "node:path";
12784
12963
  import {
12785
12964
  closeCaptureSession as closeCaptureSession7,
12786
12965
  cloneCaptureWarnings as cloneCaptureWarnings2,
@@ -12852,7 +13031,7 @@ function createHdrImageTransferCache(options = {}) {
12852
13031
  }
12853
13032
 
12854
13033
  // src/services/render/stages/captureHdrSequentialLoop.ts
12855
- import { join as join27 } from "node:path";
13034
+ import { join as join29 } from "node:path";
12856
13035
  import {
12857
13036
  TRANSITIONS,
12858
13037
  crossfade
@@ -12977,7 +13156,7 @@ async function runSequentialLayeredFrameLoop(input) {
12977
13156
  );
12978
13157
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
12979
13158
  writeFileExclusiveSync(
12980
- join27(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13159
+ join29(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
12981
13160
  normalCanvas
12982
13161
  );
12983
13162
  }
@@ -13009,7 +13188,7 @@ async function runSequentialLayeredFrameLoop(input) {
13009
13188
  }
13010
13189
 
13011
13190
  // src/services/render/stages/captureHdrHybridLoop.ts
13012
- import { join as join29 } from "node:path";
13191
+ import { join as join31 } from "node:path";
13013
13192
  import {
13014
13193
  TRANSITIONS as TRANSITIONS2,
13015
13194
  closeCaptureSession as closeCaptureSession6,
@@ -13023,10 +13202,10 @@ import {
13023
13202
  // src/services/shaderTransitionWorkerPool.ts
13024
13203
  import { Worker } from "node:worker_threads";
13025
13204
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
13026
- import { dirname as dirname12, join as join28 } from "node:path";
13205
+ import { dirname as dirname12, join as join30 } from "node:path";
13027
13206
  import { createRequire } from "node:module";
13028
13207
  import { usableCpuCount } from "@hyperframes/engine";
13029
- import { existsSync as existsSync18 } from "node:fs";
13208
+ import { existsSync as existsSync19 } from "node:fs";
13030
13209
  function resolveWorkerEntry(explicit) {
13031
13210
  if (explicit && explicit.length > 0) {
13032
13211
  return { path: explicit, isTs: explicit.endsWith(".ts") };
@@ -13037,9 +13216,9 @@ function resolveWorkerEntry(explicit) {
13037
13216
  return { path: override, isTs };
13038
13217
  }
13039
13218
  const moduleDir = dirname12(fileURLToPath3(import.meta.url));
13040
- const jsPath = join28(moduleDir, "shaderTransitionWorker.js");
13041
- if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
13042
- const tsPath = join28(moduleDir, "shaderTransitionWorker.ts");
13219
+ const jsPath = join30(moduleDir, "shaderTransitionWorker.js");
13220
+ if (existsSync19(jsPath)) return { path: jsPath, isTs: false };
13221
+ const tsPath = join30(moduleDir, "shaderTransitionWorker.ts");
13043
13222
  return { path: tsPath, isTs: true };
13044
13223
  }
13045
13224
  function buildExecArgv(entryIsTs) {
@@ -13182,8 +13361,8 @@ async function createShaderTransitionWorkerPool(opts) {
13182
13361
  if (terminated) {
13183
13362
  throw new Error("shader-blend pool already terminated");
13184
13363
  }
13185
- return new Promise((resolve13, reject) => {
13186
- const task = traceEnabled ? { req, resolve: resolve13, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve13, reject };
13364
+ return new Promise((resolve14, reject) => {
13365
+ const task = traceEnabled ? { req, resolve: resolve14, reject, enqueuedAtMs: Date.now(), traceId: ++nextTaskId } : { req, resolve: resolve14, reject };
13187
13366
  const idle = slots.find((s) => !s.busy && !s.dead);
13188
13367
  if (idle) {
13189
13368
  queue.unshift(task);
@@ -13407,7 +13586,7 @@ async function runHybridLayeredFrameLoop(input) {
13407
13586
  );
13408
13587
  if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
13409
13588
  writeFileExclusiveSync(
13410
- join29(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13589
+ join31(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`),
13411
13590
  canvas
13412
13591
  );
13413
13592
  }
@@ -13603,8 +13782,8 @@ async function runCaptureHdrStage(input) {
13603
13782
  if (hdrVideoFrameSources.has(v.id)) hdrVideoEndTimes.set(v.id, v.end);
13604
13783
  }
13605
13784
  const debugDumpEnabled = process.env.KEEP_TEMP === "1";
13606
- const debugDumpDir = debugDumpEnabled ? join30(framesDir, "debug-composite") : null;
13607
- if (debugDumpDir && !existsSync19(debugDumpDir)) {
13785
+ const debugDumpDir = debugDumpEnabled ? join32(framesDir, "debug-composite") : null;
13786
+ if (debugDumpDir && !existsSync20(debugDumpDir)) {
13608
13787
  mkdirSync10(debugDumpDir, { recursive: true });
13609
13788
  }
13610
13789
  const compositeTransfer = resolveCompositeTransfer(hasHdrContent, effectiveHdr);
@@ -13763,16 +13942,16 @@ async function runCaptureHdrStage(input) {
13763
13942
  // src/services/render/stages/encodeStage.ts
13764
13943
  import {
13765
13944
  copyFileSync as copyFileSync4,
13766
- existsSync as existsSync20,
13945
+ existsSync as existsSync21,
13767
13946
  mkdirSync as mkdirSync11,
13768
13947
  readdirSync as readdirSync5,
13769
13948
  readFileSync as readFileSync9,
13770
13949
  rmSync as rmSync11,
13771
- statSync as statSync10,
13950
+ statSync as statSync9,
13772
13951
  writeFileSync as writeFileSync6
13773
13952
  } from "node:fs";
13774
13953
  import { readFile as readFile2 } from "node:fs/promises";
13775
- import { dirname as dirname13, join as join31 } from "node:path";
13954
+ import { dirname as dirname13, join as join33 } from "node:path";
13776
13955
  import {
13777
13956
  encodeFramesChunkedConcat,
13778
13957
  encodeFramesFromDir,
@@ -13897,7 +14076,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13897
14076
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13898
14077
  if (failure) return failure;
13899
14078
  }
13900
- const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
14079
+ const fileSize = existsSync21(outputPath) ? statSync9(outputPath).size : 0;
13901
14080
  return {
13902
14081
  success: true,
13903
14082
  outputPath,
@@ -13988,10 +14167,10 @@ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13988
14167
  const stream = await encoder;
13989
14168
  for (let next = 0; next < totalFrames; next++) {
13990
14169
  while (!landed.has(next) && !captureDone && !signal.aborted) {
13991
- await new Promise((resolve13) => wake = resolve13);
14170
+ await new Promise((resolve14) => wake = resolve14);
13992
14171
  }
13993
14172
  if (signal.aborted) return;
13994
- const mergedPath = join31(input.framesDir, formatCaptureFrameName(next, "jpg"));
14173
+ const mergedPath = join33(input.framesDir, formatCaptureFrameName(next, "jpg"));
13995
14174
  const frame = await readLandedFrame(landed.get(next), mergedPath);
13996
14175
  landed.delete(next);
13997
14176
  if (!await stream.writeFrame(frame)) {
@@ -14066,7 +14245,7 @@ async function runEncodeStage(input) {
14066
14245
  const stage5Start = Date.now();
14067
14246
  if (isPngSequence) {
14068
14247
  const encoded = startEncodeProgress(job, "Writing PNG sequence", onProgress);
14069
- if (!existsSync20(outputPath)) mkdirSync11(outputPath, { recursive: true });
14248
+ if (!existsSync21(outputPath)) mkdirSync11(outputPath, { recursive: true });
14070
14249
  const captured = readdirSync5(framesDir).filter((name) => name.endsWith(".png")).sort();
14071
14250
  if (captured.length === 0) {
14072
14251
  throw new Error(
@@ -14074,11 +14253,11 @@ async function runEncodeStage(input) {
14074
14253
  );
14075
14254
  }
14076
14255
  captured.forEach((name, i) => {
14077
- const dst = join31(outputPath, formatExportFrameName(i, "png"));
14078
- copyFileSync4(join31(framesDir, name), dst);
14256
+ const dst = join33(outputPath, formatExportFrameName(i, "png"));
14257
+ copyFileSync4(join33(framesDir, name), dst);
14079
14258
  });
14080
- if (hasAudio && audioOutputPath && existsSync20(audioOutputPath)) {
14081
- copyFileSync4(audioOutputPath, join31(outputPath, MIXED_AUDIO_FILENAME2));
14259
+ if (hasAudio && audioOutputPath && existsSync21(audioOutputPath)) {
14260
+ copyFileSync4(audioOutputPath, join33(outputPath, MIXED_AUDIO_FILENAME2));
14082
14261
  log.info(
14083
14262
  `[Render] png-sequence: ${MIXED_AUDIO_FILENAME2} sidecar written to ${outputPath}/${MIXED_AUDIO_FILENAME2}`
14084
14263
  );
@@ -14098,7 +14277,7 @@ async function runEncodeStage(input) {
14098
14277
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
14099
14278
  fps: job.config.fps,
14100
14279
  loop,
14101
- palettePath: join31(dirname13(videoOnlyPath), "gif-palette.png"),
14280
+ palettePath: join33(dirname13(videoOnlyPath), "gif-palette.png"),
14102
14281
  preserveAlpha: needsAlpha,
14103
14282
  signal: abortSignal,
14104
14283
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -14309,9 +14488,9 @@ function sampleDirectoryBytes(dir) {
14309
14488
  continue;
14310
14489
  }
14311
14490
  for (const name of entries) {
14312
- const full = join32(current, name);
14491
+ const full = join34(current, name);
14313
14492
  try {
14314
- const st = statSync11(full);
14493
+ const st = statSync10(full);
14315
14494
  if (st.isDirectory()) {
14316
14495
  stack.push(full);
14317
14496
  } else if (st.isFile()) {
@@ -14345,6 +14524,7 @@ function summarizeExtractionObservability(extractionResult, videoCount, coverage
14345
14524
  vfrPreflightCount: phaseBreakdown?.vfrPreflightCount,
14346
14525
  cacheHits: phaseBreakdown?.cacheHits,
14347
14526
  cacheMisses: phaseBreakdown?.cacheMisses,
14527
+ cachePublishFailures: phaseBreakdown?.cachePublishFailures,
14348
14528
  transientRetries: phaseBreakdown?.transientRetries,
14349
14529
  ...coverageGauges,
14350
14530
  authoredTimedClipCount
@@ -14466,8 +14646,8 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14466
14646
  const ranges = [];
14467
14647
  let rangeStart = null;
14468
14648
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14469
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14470
- const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14649
+ const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14650
+ const missing = !existsSync22(framePath) || statSync10(framePath).size <= 8;
14471
14651
  if (missing && rangeStart === null) {
14472
14652
  rangeStart = frameIndex;
14473
14653
  } else if (!missing && rangeStart !== null) {
@@ -14483,7 +14663,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14483
14663
  function buildMissingFrameRetryBatches(ranges, maxWorkers, workDir, attempt, rangeStart = 0, stride = 1) {
14484
14664
  const workersPerBatch = Math.max(1, Math.floor(maxWorkers));
14485
14665
  const batches = [];
14486
- const outputDirFor = (batchIndex, workerId) => join32(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14666
+ const outputDirFor = (batchIndex, workerId) => join34(workDir, `retry-${attempt}-batch-${batchIndex}-worker-${workerId}`);
14487
14667
  if (stride > 1) {
14488
14668
  const spans = /* @__PURE__ */ new Map();
14489
14669
  for (const range of ranges) {
@@ -14542,9 +14722,9 @@ function createCaptureObservabilityUpdater(observability, platform2 = process.pl
14542
14722
  function getNextRetryWorkerCount(currentWorkers) {
14543
14723
  return Math.max(1, Math.floor(currentWorkers / 2));
14544
14724
  }
14545
- function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
14546
- if (platform2 === "win32" || platform2 === "darwin") return join32(systemTempDir, "hf-render-");
14547
- return join32(dirname14(outputPath), `work-${jobId}-`);
14725
+ function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir3()) {
14726
+ if (platform2 === "win32" || platform2 === "darwin") return join34(systemTempDir, "hf-render-");
14727
+ return join34(dirname14(outputPath), `work-${jobId}-`);
14548
14728
  }
14549
14729
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
14550
14730
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -14599,8 +14779,8 @@ The composition is too large for the available memory. To reduce memory pressure
14599
14779
  function countCapturedFrames(totalFrames, framesDir, frameExt) {
14600
14780
  let captured = 0;
14601
14781
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14602
- const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14603
- if (existsSync21(framePath)) captured++;
14782
+ const framePath = join34(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14783
+ if (existsSync22(framePath)) captured++;
14604
14784
  }
14605
14785
  return captured;
14606
14786
  }
@@ -14625,7 +14805,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
14625
14805
  reason: attempt === 0 ? "initial" : pendingTransientRetry ? "transient-retry" : "retry"
14626
14806
  });
14627
14807
  pendingTransientRetry = false;
14628
- const attemptWorkDir = join32(options.workDir, `capture-attempt-${attempt}`);
14808
+ const attemptWorkDir = join34(options.workDir, `capture-attempt-${attempt}`);
14629
14809
  const batches = missingRanges ? buildMissingFrameRetryBatches(
14630
14810
  missingRanges,
14631
14811
  currentWorkers,
@@ -15272,8 +15452,8 @@ function deVerifyFallbackTelemetry(err) {
15272
15452
  };
15273
15453
  }
15274
15454
  function resolveRenderDebugDir() {
15275
- const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname14(fileURLToPath4(import.meta.url)), "../..");
15276
- return join32(producerRoot, ".debug");
15455
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve9(process.env.PRODUCER_RENDERS_DIR, "..") : resolve9(dirname14(fileURLToPath4(import.meta.url)), "../..");
15456
+ return join34(producerRoot, ".debug");
15277
15457
  }
15278
15458
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
15279
15459
  validateHlsRenderConfig(job.config);
@@ -15281,11 +15461,11 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15281
15461
  validateChromaSubsamplingConfig(job.config);
15282
15462
  const debugDir = resolveRenderDebugDir();
15283
15463
  const outputDir = dirname14(outputPath);
15284
- if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
15285
- const workDir = job.config.debug ? join32(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15464
+ if (!existsSync22(outputDir)) mkdirSync12(outputDir, { recursive: true });
15465
+ const workDir = job.config.debug ? join34(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
15286
15466
  const pipelineStart = Date.now();
15287
15467
  const baseLog = job.config.logger ?? defaultLogger;
15288
- const logPath = job.config.debug ? join32(workDir, "render.log") : null;
15468
+ const logPath = job.config.debug ? join34(workDir, "render.log") : null;
15289
15469
  const execution = new RenderExecutionContext({
15290
15470
  request: { renderJobId: job.id, projectDir, outputPath },
15291
15471
  logger: logPath ? createRenderFileLogger(logPath, baseLog) : baseLog,
@@ -15316,6 +15496,15 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15316
15496
  await execution.dispose();
15317
15497
  }
15318
15498
  }
15499
+ function loadResumeKeyOrWarn(resume, log) {
15500
+ const key = segmentManifestKey();
15501
+ if (resume && !key) {
15502
+ log.warn(
15503
+ "[Render] --resume: no preview token could be read or created, so every segment will be captured again"
15504
+ );
15505
+ }
15506
+ return key;
15507
+ }
15319
15508
  async function executeRenderPipeline(input) {
15320
15509
  const {
15321
15510
  job,
@@ -15353,7 +15542,7 @@ async function executeRenderPipeline(input) {
15353
15542
  imageDecodeFailures: 0
15354
15543
  };
15355
15544
  let hdrPerf;
15356
- const perfOutputPath = join32(workDir, "perf-summary.json");
15545
+ const perfOutputPath = join34(workDir, "perf-summary.json");
15357
15546
  const cfg = { ...job.config.producerConfig ?? resolveConfig2() };
15358
15547
  const observability = new RenderObservabilityRecorder({
15359
15548
  pipelineStartMs: pipelineStart,
@@ -15429,7 +15618,7 @@ async function executeRenderPipeline(input) {
15429
15618
  job.startedAt = /* @__PURE__ */ new Date();
15430
15619
  assertNotAborted();
15431
15620
  assertConfiguredFfmpegBinariesExist();
15432
- if (!existsSync21(workDir)) mkdirSync12(workDir, { recursive: true });
15621
+ if (!existsSync22(workDir)) mkdirSync12(workDir, { recursive: true });
15433
15622
  if (job.config.debug) {
15434
15623
  log.info("[Render] Debug artifacts enabled", { workDir, logPath });
15435
15624
  }
@@ -15458,8 +15647,8 @@ async function executeRenderPipeline(input) {
15458
15647
  requestedWorkers: job.config.workers ?? "auto"
15459
15648
  });
15460
15649
  const entryFile = job.config.entryFile || "index.html";
15461
- const htmlPath = join32(projectDir, entryFile);
15462
- if (!existsSync21(htmlPath)) {
15650
+ const htmlPath = join34(projectDir, entryFile);
15651
+ if (!existsSync22(htmlPath)) {
15463
15652
  throw new Error(`Entry file not found: ${htmlPath}`);
15464
15653
  }
15465
15654
  assertNotAborted();
@@ -15555,7 +15744,7 @@ async function executeRenderPipeline(input) {
15555
15744
  const largerThanCanvas = await oversizedVideos(
15556
15745
  composition.videos,
15557
15746
  projectDir,
15558
- join32(workDir, "compiled"),
15747
+ join34(workDir, "compiled"),
15559
15748
  { width: outputWidth, height: outputHeight }
15560
15749
  );
15561
15750
  const probeResult = await observeRenderStage(
@@ -15652,7 +15841,7 @@ async function executeRenderPipeline(input) {
15652
15841
  canvas: { width, height },
15653
15842
  page: probeSession.page,
15654
15843
  projectDir,
15655
- compiledDir: join32(workDir, "compiled")
15844
+ compiledDir: join34(workDir, "compiled")
15656
15845
  });
15657
15846
  if (videoLayerPlan.videoId === void 0) {
15658
15847
  log.info(`[Render] Video layer passthrough off: ${videoLayerPlan.reason}`);
@@ -15670,7 +15859,7 @@ async function executeRenderPipeline(input) {
15670
15859
  updateJobStatus(job, "preprocessing", "Extracting video frames", 10, onProgress, {
15671
15860
  code: "extract_video"
15672
15861
  });
15673
- const compiledDir = join32(workDir, "compiled");
15862
+ const compiledDir = join34(workDir, "compiled");
15674
15863
  const segmentsCapture = (layeredOrEffectRoute) => shouldSegmentCapture({
15675
15864
  env: process.env,
15676
15865
  durationSeconds: probeResult.duration,
@@ -15806,7 +15995,7 @@ async function executeRenderPipeline(input) {
15806
15995
  try {
15807
15996
  fileServer = await createFileServer({
15808
15997
  projectDir,
15809
- compiledDir: join32(workDir, "compiled"),
15998
+ compiledDir: join34(workDir, "compiled"),
15810
15999
  port: 0,
15811
16000
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15812
16001
  fps: job.config.fps,
@@ -15826,8 +16015,8 @@ async function executeRenderPipeline(input) {
15826
16015
  if (!activeFileServer) {
15827
16016
  throw new Error("File server failed to initialize before frame capture");
15828
16017
  }
15829
- const framesDir = join32(workDir, "captured-frames");
15830
- if (!existsSync21(framesDir)) mkdirSync12(framesDir, { recursive: true });
16018
+ const framesDir = join34(workDir, "captured-frames");
16019
+ if (!existsSync22(framesDir)) mkdirSync12(framesDir, { recursive: true });
15831
16020
  updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
15832
16021
  code: "start_browsers"
15833
16022
  });
@@ -16407,7 +16596,7 @@ async function executeRenderPipeline(input) {
16407
16596
  hls: ".mp4"
16408
16597
  };
16409
16598
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
16410
- const videoOnlyPath = join32(workDir, `video-only${videoExt}`);
16599
+ const videoOnlyPath = join34(workDir, `video-only${videoExt}`);
16411
16600
  let usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
16412
16601
  if (usePageSideCompositingForTransitions) {
16413
16602
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
@@ -16724,16 +16913,19 @@ async function executeRenderPipeline(input) {
16724
16913
  pageMotionBlur: job.config.pageMotionBlur,
16725
16914
  captureQuality: captureOptions.quality
16726
16915
  });
16727
- const segmentDir = segmentDirFor(join32(projectDir, "renders"), segmentPlanHash);
16916
+ const segmentDir = segmentDirFor(join34(projectDir, "renders"), segmentPlanHash);
16917
+ const manifestKey = loadResumeKeyOrWarn(job.config.resumeSegments === true, log);
16728
16918
  let completedSegments = /* @__PURE__ */ new Set();
16729
16919
  if (job.config.resumeSegments === true) {
16730
16920
  const existing = readSegmentManifest(segmentDir);
16731
16921
  if (existing) {
16732
- completedSegments = await validateCompletedSegments(
16733
- existing,
16734
- segmentPlanHash,
16735
- (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
16736
- );
16922
+ completedSegments = await validateCompletedSegments(existing, {
16923
+ expectedHash: segmentPlanHash,
16924
+ segmentDir,
16925
+ plan: planSegments(totalFrames, segmentFrames),
16926
+ key: manifestKey,
16927
+ probeFrames: (path) => probeSegmentFrameCount(path, extractMediaMetadata5)
16928
+ });
16737
16929
  log.info(`[Render] resuming: ${completedSegments.size} segments complete`, {
16738
16930
  segmentDir
16739
16931
  });
@@ -16807,7 +16999,7 @@ async function executeRenderPipeline(input) {
16807
16999
  ...segmentManifest.completed.filter((e) => e.index !== entry.index),
16808
17000
  { ...entry, completedAt: (/* @__PURE__ */ new Date()).toISOString() }
16809
17001
  ];
16810
- writeSegmentManifest(segmentDir, segmentManifest);
17002
+ writeSegmentManifest(segmentDir, segmentManifest, manifestKey);
16811
17003
  },
16812
17004
  updateCaptureObservability
16813
17005
  })
@@ -17268,7 +17460,7 @@ async function executeRenderPipeline(input) {
17268
17460
  })
17269
17461
  );
17270
17462
  const totalElapsed = Date.now() - pipelineStart;
17271
- const tmpPeakBytes = existsSync21(workDir) ? sampleDirectoryBytes(workDir) : 0;
17463
+ const tmpPeakBytes = existsSync22(workDir) ? sampleDirectoryBytes(workDir) : 0;
17272
17464
  recordTransientRetryObservability();
17273
17465
  observability.checkpoint("pipeline", "artifact validated", { totalElapsedMs: totalElapsed });
17274
17466
  const observabilitySummary = observability.summary({
@@ -17349,8 +17541,8 @@ async function executeRenderPipeline(input) {
17349
17541
  }
17350
17542
  }
17351
17543
  if (job.config.debug) {
17352
- if (!isPngSequence && !isHls && existsSync21(stagedOutputPath)) {
17353
- const debugOutput = join32(workDir, `output${videoExt}`);
17544
+ if (!isPngSequence && !isHls && existsSync22(stagedOutputPath)) {
17545
+ const debugOutput = join34(workDir, `output${videoExt}`);
17354
17546
  copyFileSync5(stagedOutputPath, debugOutput);
17355
17547
  }
17356
17548
  }
@@ -17429,7 +17621,8 @@ async function executeRenderPipeline(input) {
17429
17621
  perfStages,
17430
17622
  hdrDiagnostics,
17431
17623
  observability: observabilitySummary,
17432
- subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs)
17624
+ subTimelineWait: worstSubTimelineWaitOutcome(dedupPerfs),
17625
+ missingPath: describeMissingPath(error, { cacheDir: cfg.extractCacheDir, workDir })
17433
17626
  });
17434
17627
  publishRenderFailure(
17435
17628
  job,
@@ -17468,14 +17661,14 @@ import {
17468
17661
  referenceBackgroundResult as referenceBackgroundResult6
17469
17662
  } from "@hyperframes/engine";
17470
17663
  import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync18 } from "node:fs";
17471
- import { join as join46 } from "node:path";
17472
- import { tmpdir as tmpdir4 } from "node:os";
17664
+ import { join as join48 } from "node:path";
17665
+ import { tmpdir as tmpdir5 } from "node:os";
17473
17666
 
17474
17667
  // src/services/distributed/mp4Stitch.ts
17475
- import { createReadStream as createReadStream3, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
17668
+ import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
17476
17669
  import { open } from "node:fs/promises";
17477
17670
  import { renameWithRetry as renameWithRetry7 } from "@hyperframes/engine";
17478
- import { basename as basename7, dirname as dirname15, join as join33 } from "node:path";
17671
+ import { basename as basename8, dirname as dirname15, join as join35 } from "node:path";
17479
17672
  import { finished, pipeline } from "node:stream/promises";
17480
17673
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
17481
17674
  function boxAt(src, off, at, limit) {
@@ -17828,7 +18021,7 @@ function fileRange(path) {
17828
18021
  }
17829
18022
  async function copyPayload(path, layout, index, out) {
17830
18023
  const { payloadStart, payloadEnd } = layout;
17831
- const payload = createReadStream3(path, { start: payloadStart, end: payloadEnd - 1 });
18024
+ const payload = createReadStream4(path, { start: payloadStart, end: payloadEnd - 1 });
17832
18025
  await pipeline(payload, out, { end: false });
17833
18026
  if (payload.bytesRead !== payloadEnd - payloadStart) {
17834
18027
  throw new Error(
@@ -17841,14 +18034,14 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
17841
18034
  const layouts = await Promise.all(sourcePaths.map((path) => readMp4Layout(fileRange(path))));
17842
18035
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
17843
18036
  mkdirSync13(dirname15(outputPath), { recursive: true });
17844
- const workDir = createStagingDir4(dirname15(outputPath), `${basename7(outputPath)}.stitch-`);
17845
- const out = createWriteStream(join33(workDir, "out.mp4"));
18037
+ const workDir = createStagingDir4(dirname15(outputPath), `${basename8(outputPath)}.stitch-`);
18038
+ const out = createWriteStream(join35(workDir, "out.mp4"));
17846
18039
  try {
17847
18040
  out.write(header);
17848
18041
  for (const [i, path] of sourcePaths.entries()) await copyPayload(path, layouts[i], i, out);
17849
18042
  out.end();
17850
18043
  await finished(out);
17851
- renameWithRetry7(join33(workDir, "out.mp4"), outputPath);
18044
+ renameWithRetry7(join35(workDir, "out.mp4"), outputPath);
17852
18045
  } finally {
17853
18046
  out.destroy();
17854
18047
  rmSync13(workDir, { recursive: true, force: true });
@@ -17865,13 +18058,13 @@ import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframe
17865
18058
  import {
17866
18059
  copyFileSync as copyFileSync6,
17867
18060
  cpSync as cpSync2,
17868
- existsSync as existsSync26,
18061
+ existsSync as existsSync27,
17869
18062
  linkSync,
17870
18063
  mkdirSync as mkdirSync16,
17871
18064
  rmSync as rmSync14,
17872
18065
  writeFileSync as writeFileSync10
17873
18066
  } from "node:fs";
17874
- import { extname as extname6, isAbsolute as isAbsolute3, join as join41, relative as relative6, sep as sep4 } from "node:path";
18067
+ import { extname as extname6, isAbsolute as isAbsolute4, join as join43, relative as relative7, sep as sep5 } from "node:path";
17875
18068
  import {
17876
18069
  fpsToNumber as fpsToNumber9,
17877
18070
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -17888,7 +18081,7 @@ import {
17888
18081
  } from "@hyperframes/engine";
17889
18082
 
17890
18083
  // src/services/distributed/planFrameCost.ts
17891
- import { join as join36 } from "node:path";
18084
+ import { join as join38 } from "node:path";
17892
18085
  import {
17893
18086
  closeCaptureSession as closeCaptureSession9,
17894
18087
  createCaptureSession as createCaptureSession9,
@@ -17897,8 +18090,8 @@ import {
17897
18090
  } from "@hyperframes/engine";
17898
18091
 
17899
18092
  // src/services/distributed/chunkFrames.ts
17900
- import { existsSync as existsSync23, readdirSync as readdirSync7 } from "node:fs";
17901
- import { extname as extname4, join as join35 } from "node:path";
18093
+ import { existsSync as existsSync24, readdirSync as readdirSync7 } from "node:fs";
18094
+ import { extname as extname4, join as join37 } from "node:path";
17902
18095
  import {
17903
18096
  compositionRequiresWebGpu as compositionRequiresWebGpu3,
17904
18097
  createVideoFrameInjector as createVideoFrameInjector3,
@@ -17907,8 +18100,8 @@ import {
17907
18100
 
17908
18101
  // src/services/distributed/shared.ts
17909
18102
  import { execFile as execFileCallback } from "node:child_process";
17910
- import { dirname as dirname16, join as join34 } from "node:path";
17911
- import { existsSync as existsSync22, readFileSync as readFileSync10 } from "node:fs";
18103
+ import { dirname as dirname16, join as join36 } from "node:path";
18104
+ import { existsSync as existsSync23, readFileSync as readFileSync10 } from "node:fs";
17912
18105
  import { fileURLToPath as fileURLToPath5 } from "node:url";
17913
18106
  import { promisify as promisify2 } from "node:util";
17914
18107
  import {
@@ -17923,8 +18116,8 @@ function isPlanAudioArtifactPath(path) {
17923
18116
  }
17924
18117
  function resolvePlanAudioPath(planDir) {
17925
18118
  for (const name of [PLAN_AUDIO_RELATIVE_PATH, PLAN_AUDIO_LEGACY_RELATIVE_PATH]) {
17926
- const candidate = join34(planDir, name);
17927
- if (existsSync22(candidate)) return candidate;
18119
+ const candidate = join36(planDir, name);
18120
+ if (existsSync23(candidate)) return candidate;
17928
18121
  }
17929
18122
  return null;
17930
18123
  }
@@ -18188,8 +18381,8 @@ function readProducerVersion() {
18188
18381
  const startDir = dirname16(fileURLToPath5(import.meta.url));
18189
18382
  let current = startDir;
18190
18383
  for (let i = 0; i < 10; i++) {
18191
- const candidate = join34(current, "package.json");
18192
- if (existsSync22(candidate)) {
18384
+ const candidate = join36(current, "package.json");
18385
+ if (existsSync23(candidate)) {
18193
18386
  try {
18194
18387
  const pkg = JSON.parse(readFileSync10(candidate, "utf-8"));
18195
18388
  if (pkg.name === "@hyperframes/producer" && typeof pkg.version === "string") {
@@ -18243,8 +18436,8 @@ function frameNumberFromFileName(name) {
18243
18436
  function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v1") {
18244
18437
  const result = [];
18245
18438
  for (const v of videos) {
18246
- const outputDir = join35(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
18247
- if (!existsSync23(outputDir)) {
18439
+ const outputDir = join37(planDir, "video-frames", mediaIdPathSegment3(v.videoId));
18440
+ if (!existsSync24(outputDir)) {
18248
18441
  throw new Error(
18249
18442
  `[renderChunk] planDir missing extracted video frames for ${JSON.stringify(v.videoId)}: ${outputDir} not present. plan() should have written frames here; the planDir is malformed.`
18250
18443
  );
@@ -18262,7 +18455,7 @@ function rebuildExtractedFramesFromPlanDir(planDir, videos, indexMode = "dense-v
18262
18455
  if (!frameName) continue;
18263
18456
  const frameNumber = indexMode === "sparse-v2" ? frameNumberFromFileName(frameName) : null;
18264
18457
  const frameIndex = frameNumber === null ? i : frameNumber - 1;
18265
- framePaths.set(frameIndex, join35(outputDir, frameName));
18458
+ framePaths.set(frameIndex, join37(outputDir, frameName));
18266
18459
  }
18267
18460
  result.push({
18268
18461
  videoId: v.videoId,
@@ -18342,8 +18535,8 @@ async function extractDeferredVideoFramesForChunk(input) {
18342
18535
  sourceOf: (video) => {
18343
18536
  const range = planned.get(video.videoId).deferredRange;
18344
18537
  const remoteUrl = remoteSources[range.sourcePath];
18345
- const sourcePath = remoteUrl ?? join35(input.planDir, ...range.sourcePath.split("/"));
18346
- if (remoteUrl === void 0 && !existsSync23(sourcePath)) {
18538
+ const sourcePath = remoteUrl ?? join37(input.planDir, ...range.sourcePath.split("/"));
18539
+ if (remoteUrl === void 0 && !existsSync24(sourcePath)) {
18347
18540
  throw new RenderChunkValidationError(
18348
18541
  MISSING_PLAN_ARTIFACT,
18349
18542
  `[renderChunk] planDir is missing the source for video ${JSON.stringify(video.videoId)}: ${range.sourcePath}`
@@ -18373,12 +18566,12 @@ async function measurePlanSecondsPerFrame(input) {
18373
18566
  planVideos,
18374
18567
  frames: sampled,
18375
18568
  fps: fpsRatio,
18376
- outputRoot: join36(workDir, "frame-cost-video-frames"),
18569
+ outputRoot: join38(workDir, "frame-cost-video-frames"),
18377
18570
  cfg: input.cfg
18378
18571
  })
18379
18572
  ];
18380
18573
  const lookup = extracted.length > 0 ? createFrameLookupTable4(planVideos.videos, extracted, resolveRenderFpsConfig(fpsRatio).value) : null;
18381
- const compiledDir = join36(planDir, "compiled");
18574
+ const compiledDir = join38(planDir, "compiled");
18382
18575
  const fileServer = await createFileServer({
18383
18576
  projectDir: compiledDir,
18384
18577
  compiledDir,
@@ -18390,7 +18583,7 @@ async function measurePlanSecondsPerFrame(input) {
18390
18583
  try {
18391
18584
  session = await createCaptureSession9(
18392
18585
  fileServer.url,
18393
- join36(workDir, "frame-cost"),
18586
+ join38(workDir, "frame-cost"),
18394
18587
  buildChunkCaptureOptions({
18395
18588
  dimensions: { ...input, fpsNum: fps, fpsDen: 1 },
18396
18589
  encoder: input,
@@ -18487,7 +18680,7 @@ function buildWeightedChunkSlices(weights, chunkCount, minFrames, maxFrames) {
18487
18680
  }
18488
18681
 
18489
18682
  // src/services/render/planReferenceBackground.ts
18490
- import { join as join37 } from "node:path";
18683
+ import { join as join39 } from "node:path";
18491
18684
  import {
18492
18685
  closeCaptureSession as closeCaptureSession10,
18493
18686
  createCaptureSession as createCaptureSession10,
@@ -18500,14 +18693,14 @@ async function readPlanReferenceBackground(input) {
18500
18693
  try {
18501
18694
  server = await createFileServer({
18502
18695
  projectDir: input.projectDir,
18503
- compiledDir: join37(input.workDir, "compiled"),
18696
+ compiledDir: join39(input.workDir, "compiled"),
18504
18697
  port: 0,
18505
18698
  preHeadScripts: [VIRTUAL_TIME_SHIM],
18506
18699
  fps: input.options.fps
18507
18700
  });
18508
18701
  session = await createCaptureSession10(
18509
18702
  server.url,
18510
- join37(input.workDir, "reference"),
18703
+ join39(input.workDir, "reference"),
18511
18704
  {
18512
18705
  ...input.options,
18513
18706
  requiresWebGpu: false
@@ -18543,8 +18736,8 @@ async function readPlanReferenceBackground(input) {
18543
18736
  }
18544
18737
 
18545
18738
  // src/services/render/stages/freezePlan.ts
18546
- import { existsSync as existsSync24, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
18547
- import { join as join38, relative as relative4, resolve as resolve9 } from "node:path";
18739
+ import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
18740
+ import { join as join40, relative as relative5, resolve as resolve10 } from "node:path";
18548
18741
  import {
18549
18742
  REFERENCE_BACKGROUND_FIELD,
18550
18743
  referenceBackgroundResult as referenceBackgroundResult3
@@ -18643,7 +18836,7 @@ function readPlanProtocolV1(planJson, capabilities = DISTRIBUTED_RENDER_CAPABILI
18643
18836
 
18644
18837
  // src/services/render/stages/planHash.ts
18645
18838
  import { createHash as createHash8 } from "node:crypto";
18646
- import { closeSync as closeSync5, createReadStream as createReadStream4, openSync as openSync5, readSync as readSync5 } from "node:fs";
18839
+ import { closeSync as closeSync5, createReadStream as createReadStream5, openSync as openSync5, readSync as readSync5 } from "node:fs";
18647
18840
  var PLAN_HASH_SCHEMA_PREFIX = "hyperframes-plan-hash-v1\0";
18648
18841
  var FIELD_DELIMITER = Buffer.from([0]);
18649
18842
  function computePlanHash(input) {
@@ -18715,7 +18908,7 @@ function sha256File(path) {
18715
18908
  }
18716
18909
  async function sha256FileAsync(path) {
18717
18910
  const hash = createHash8("sha256");
18718
- for await (const chunk of createReadStream4(path, { highWaterMark: 1024 * 1024 })) {
18911
+ for await (const chunk of createReadStream5(path, { highWaterMark: 1024 * 1024 })) {
18719
18912
  hash.update(chunk);
18720
18913
  }
18721
18914
  return hash.digest("hex");
@@ -18737,7 +18930,7 @@ function planFileSha256(absolutePath, digests) {
18737
18930
  return sha256;
18738
18931
  }
18739
18932
  async function prehashPlanFiles(dir, digests) {
18740
- if (!existsSync24(dir)) return;
18933
+ if (!existsSync25(dir)) return;
18741
18934
  for (const { absolutePath } of listPlanFiles(dir)) {
18742
18935
  if (!digests.has(absolutePath)) digests.set(absolutePath, await sha256FileAsync(absolutePath));
18743
18936
  }
@@ -18758,16 +18951,16 @@ function stripUndefined(value) {
18758
18951
  }
18759
18952
  function listPlanFiles(planDir) {
18760
18953
  const results = [];
18761
- const rootResolved = resolve9(planDir);
18954
+ const rootResolved = resolve10(planDir);
18762
18955
  function walk(dir) {
18763
18956
  const entries = readdirSync8(dir, { withFileTypes: true });
18764
18957
  for (const entry of entries) {
18765
- const full = join38(dir, entry.name);
18958
+ const full = join40(dir, entry.name);
18766
18959
  if (entry.isDirectory()) {
18767
18960
  walk(full);
18768
18961
  } else if (entry.isFile()) {
18769
18962
  results.push({
18770
- planRelativePath: relative4(rootResolved, full).split(/[\\/]+/).join("/"),
18963
+ planRelativePath: relative5(rootResolved, full).split(/[\\/]+/).join("/"),
18771
18964
  absolutePath: full
18772
18965
  });
18773
18966
  }
@@ -18803,19 +18996,19 @@ var PLAN_REMOTE_FILES_RELATIVE_PATH = "meta/remote-files.json";
18803
18996
  function writePlanRemoteFiles(planDir, files) {
18804
18997
  if (files.length === 0) return;
18805
18998
  const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : 1);
18806
- writeFileSync8(join38(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
18999
+ writeFileSync8(join40(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH), JSON.stringify(sorted), "utf-8");
18807
19000
  }
18808
19001
  function readPlanRemoteFiles(planDir) {
18809
- const path = join38(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
18810
- return existsSync24(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
19002
+ const path = join40(planDir, PLAN_REMOTE_FILES_RELATIVE_PATH);
19003
+ return existsSync25(path) ? JSON.parse(readFileSync11(path, "utf-8")) : [];
18811
19004
  }
18812
19005
  function recomputePlanHashFromPlanDir(planDir, digests) {
18813
- const planJsonPath = join38(planDir, "plan.json");
18814
- const encoderJsonPath = join38(planDir, "meta", "encoder.json");
18815
- if (!existsSync24(planJsonPath)) {
19006
+ const planJsonPath = join40(planDir, "plan.json");
19007
+ const encoderJsonPath = join40(planDir, "meta", "encoder.json");
19008
+ if (!existsSync25(planJsonPath)) {
18816
19009
  throw new Error(`[freezePlan] plan.json missing: ${planJsonPath}`);
18817
19010
  }
18818
- if (!existsSync24(encoderJsonPath)) {
19011
+ if (!existsSync25(encoderJsonPath)) {
18819
19012
  throw new Error(`[freezePlan] meta/encoder.json missing: ${encoderJsonPath}`);
18820
19013
  }
18821
19014
  const planJson = JSON.parse(readFileSync11(planJsonPath, "utf-8"));
@@ -18845,21 +19038,21 @@ async function freezePlan(input) {
18845
19038
  hasAudio,
18846
19039
  digests
18847
19040
  } = input;
18848
- if (!existsSync24(planDir)) {
19041
+ if (!existsSync25(planDir)) {
18849
19042
  throw new Error(`[freezePlan] planDir does not exist: ${planDir}`);
18850
19043
  }
18851
- const metaDir = join38(planDir, "meta");
18852
- if (!existsSync24(metaDir)) mkdirSync14(metaDir, { recursive: true });
19044
+ const metaDir = join40(planDir, "meta");
19045
+ if (!existsSync25(metaDir)) mkdirSync14(metaDir, { recursive: true });
18853
19046
  writeFileSync8(
18854
- join38(metaDir, "composition.json"),
19047
+ join40(metaDir, "composition.json"),
18855
19048
  `${JSON.stringify(composition, null, 2)}
18856
19049
  `,
18857
19050
  "utf-8"
18858
19051
  );
18859
19052
  const encoderForCanonical = stripUndefined(encoder);
18860
19053
  const encoderConfigCanonicalJson = canonicalJsonStringify(encoderForCanonical);
18861
- writeFileSync8(join38(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
18862
- writeFileSync8(join38(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
19054
+ writeFileSync8(join40(metaDir, "encoder.json"), encoderConfigCanonicalJson, "utf-8");
19055
+ writeFileSync8(join40(metaDir, "chunks.json"), `${JSON.stringify(chunks, null, 2)}
18863
19056
  `, "utf-8");
18864
19057
  const { compositionHtml, assets } = collectPlanAssetShas(planDir, digests);
18865
19058
  const planHash = computePlanHash({
@@ -18884,7 +19077,7 @@ async function freezePlan(input) {
18884
19077
  duration: durationSeconds,
18885
19078
  hasAudio
18886
19079
  };
18887
- const planJsonPath = join38(planDir, "plan.json");
19080
+ const planJsonPath = join40(planDir, "plan.json");
18888
19081
  writeFileSync8(planJsonPath, `${JSON.stringify(planJson, null, 2)}
18889
19082
  `, "utf-8");
18890
19083
  return { planJsonPath, planHash };
@@ -18926,9 +19119,9 @@ function applyRuntimeEnvSnapshot(snapshot, env = process.env) {
18926
19119
  }
18927
19120
 
18928
19121
  // src/services/distributed/chunkAudio.ts
18929
- import { closeSync as closeSync6, existsSync as existsSync25, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
19122
+ import { closeSync as closeSync6, existsSync as existsSync26, ftruncateSync, mkdirSync as mkdirSync15, openSync as openSync6, readFileSync as readFileSync12 } from "node:fs";
18930
19123
  import { writeFileSync as writeFileSync9, writeSync } from "node:fs";
18931
- import { join as join39 } from "node:path";
19124
+ import { join as join41 } from "node:path";
18932
19125
  import { appendRenderProvenanceArgs, describeFfmpegFailure as describeFfmpegFailure4, runFfmpeg as runFfmpeg7 } from "@hyperframes/engine";
18933
19126
  function audioCutForChunk(grid, chunks, index, fps) {
18934
19127
  const firstPacketAt = (frame) => Math.min(
@@ -19016,7 +19209,7 @@ async function writeChunkAudioSlices(input) {
19016
19209
  });
19017
19210
  const bytes = readFileSync12(input.audioPath);
19018
19211
  const layout = { sizeBytes: bytes.length, payloadStart, payloadEnd, partStarts: {} };
19019
- mkdirSync15(join39(input.planDir, SLICE_DIR), { recursive: true });
19212
+ mkdirSync15(join41(input.planDir, SLICE_DIR), { recursive: true });
19020
19213
  input.chunks.forEach((_, index) => {
19021
19214
  const cut = audioCutForChunk(grid, input.chunks, index, input.fps);
19022
19215
  if (!cut) return;
@@ -19024,17 +19217,17 @@ async function writeChunkAudioSlices(input) {
19024
19217
  const start = offsets[cut.firstPacket];
19025
19218
  layout.partStarts[index] = start;
19026
19219
  const end = offsets[last] + track.sizes[last];
19027
- writeFileSync9(join39(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
19220
+ writeFileSync9(join41(input.planDir, chunkAudioSlicePath(index)), bytes.subarray(start, end));
19028
19221
  });
19029
19222
  const frame = [bytes.subarray(0, payloadStart), bytes.subarray(payloadEnd)];
19030
- writeFileSync9(join39(input.planDir, SLICE_FRAME), Buffer.concat(frame));
19031
- writeFileSync9(join39(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
19223
+ writeFileSync9(join41(input.planDir, SLICE_FRAME), Buffer.concat(frame));
19224
+ writeFileSync9(join41(input.planDir, SLICE_LAYOUT), JSON.stringify(layout));
19032
19225
  }
19033
19226
  function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19034
- const layoutPath = join39(planDir, SLICE_LAYOUT);
19035
- if (!existsSync25(layoutPath)) return resolvePlanAudioPath(planDir);
19227
+ const layoutPath = join41(planDir, SLICE_LAYOUT);
19228
+ if (!existsSync26(layoutPath)) return resolvePlanAudioPath(planDir);
19036
19229
  const layout = JSON.parse(readFileSync12(layoutPath, "utf-8"));
19037
- const frame = readFileSync12(join39(planDir, SLICE_FRAME));
19230
+ const frame = readFileSync12(join41(planDir, SLICE_FRAME));
19038
19231
  const fd = openSync6(scratchPath, "w");
19039
19232
  try {
19040
19233
  writeSync(fd, frame, 0, layout.payloadStart, 0);
@@ -19047,7 +19240,7 @@ function chunkAudioSource(planDir, chunkIndex, scratchPath) {
19047
19240
  );
19048
19241
  const start = layout.partStarts[chunkIndex];
19049
19242
  if (start !== void 0) {
19050
- const part = readFileSync12(join39(planDir, chunkAudioSlicePath(chunkIndex)));
19243
+ const part = readFileSync12(join41(planDir, chunkAudioSlicePath(chunkIndex)));
19051
19244
  writeSync(fd, part, 0, part.length, start);
19052
19245
  }
19053
19246
  ftruncateSync(fd, layout.sizeBytes);
@@ -19102,8 +19295,8 @@ async function muxChunkWithAudio(input) {
19102
19295
 
19103
19296
  // src/services/distributed/planSize.ts
19104
19297
  import { createHash as createHash9 } from "node:crypto";
19105
- import { lstatSync as lstatSync2, readdirSync as readdirSync9 } from "node:fs";
19106
- import { extname as extname5, join as join40, relative as relative5 } from "node:path";
19298
+ import { lstatSync as lstatSync4, readdirSync as readdirSync9 } from "node:fs";
19299
+ import { extname as extname5, join as join42, relative as relative6 } from "node:path";
19107
19300
  var MAX_TOP_COMPONENTS = 10;
19108
19301
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
19109
19302
  ".aac",
@@ -19186,13 +19379,13 @@ function addCategoryBytes(result, category, filePath, sizeBytes) {
19186
19379
  function recordFile(result, components, rootDir, rootKind, filePath) {
19187
19380
  let sizeBytes;
19188
19381
  try {
19189
- const stat = lstatSync2(filePath);
19382
+ const stat = lstatSync4(filePath);
19190
19383
  if (!stat.isFile()) return;
19191
19384
  sizeBytes = stat.size;
19192
19385
  } catch {
19193
19386
  return;
19194
19387
  }
19195
- const rel = relative5(rootDir, filePath);
19388
+ const rel = relative6(rootDir, filePath);
19196
19389
  const segments = rel.split(/[\\/]+/).filter(Boolean);
19197
19390
  const classified = classifyFile(segments, rootKind);
19198
19391
  result.totalBytes += sizeBytes;
@@ -19215,7 +19408,7 @@ function walkRegularFiles(dir, visit) {
19215
19408
  return;
19216
19409
  }
19217
19410
  for (const entry of entries) {
19218
- const full = join40(dir, entry.name);
19411
+ const full = join42(dir, entry.name);
19219
19412
  if (entry.isDirectory()) {
19220
19413
  walkRegularFiles(full, visit);
19221
19414
  } else if (entry.isFile()) {
@@ -19431,13 +19624,13 @@ function assertPositiveInteger2(name, value) {
19431
19624
  }
19432
19625
  var FREEZE_OWNED_PLAN_FILES = [
19433
19626
  "plan.json",
19434
- join41("meta", "composition.json"),
19435
- join41("meta", "encoder.json"),
19436
- join41("meta", "chunks.json")
19627
+ join43("meta", "composition.json"),
19628
+ join43("meta", "encoder.json"),
19629
+ join43("meta", "chunks.json")
19437
19630
  ];
19438
19631
  function removeFreezeOwnedPlanFiles(planDir) {
19439
19632
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
19440
- rmSync14(join41(planDir, relativePath), { force: true });
19633
+ rmSync14(join43(planDir, relativePath), { force: true });
19441
19634
  }
19442
19635
  }
19443
19636
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -19576,16 +19769,16 @@ function resolveDistributedEngineConfig(config) {
19576
19769
  };
19577
19770
  }
19578
19771
  function leavesRoot(rel) {
19579
- return rel === ".." || rel.startsWith(`..${sep4}`) || isAbsolute3(rel);
19772
+ return rel === ".." || rel.startsWith(`..${sep5}`) || isAbsolute4(rel);
19580
19773
  }
19581
19774
  function pathInside(root, path) {
19582
- const rel = relative6(root, path);
19775
+ const rel = relative7(root, path);
19583
19776
  return rel === "" || leavesRoot(rel) ? null : rel;
19584
19777
  }
19585
19778
  function stableSourcePath(roots, srcPath) {
19586
19779
  for (const [root, prefix] of roots) {
19587
19780
  const rel = pathInside(root, srcPath);
19588
- if (rel !== null) return [prefix, ...rel.split(sep4)].filter(Boolean).join("/");
19781
+ if (rel !== null) return [prefix, ...rel.split(sep5)].filter(Boolean).join("/");
19589
19782
  }
19590
19783
  return srcPath;
19591
19784
  }
@@ -19595,19 +19788,19 @@ function createVideoSourceShipper(input) {
19595
19788
  const known = shipped.get(srcPath);
19596
19789
  if (known) return known;
19597
19790
  const stagedRel = pathInside(input.workVideoFramesDir, srcPath);
19598
- const current = stagedRel === null ? srcPath : join41(input.planDir, "video-frames", stagedRel);
19791
+ const current = stagedRel === null ? srcPath : join43(input.planDir, "video-frames", stagedRel);
19599
19792
  let result = null;
19600
19793
  for (const root of stagedRel === null ? [input.workCompiledDir, input.projectDir] : []) {
19601
19794
  const rel = pathInside(root, srcPath);
19602
- if (rel !== null && (existsSync26(join41(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
19603
- result = ["compiled", ...rel.split(sep4)].join("/");
19795
+ if (rel !== null && (existsSync27(join43(input.planDir, "compiled", rel)) || input.isRemote(srcPath))) {
19796
+ result = ["compiled", ...rel.split(sep5)].join("/");
19604
19797
  break;
19605
19798
  }
19606
19799
  }
19607
19800
  if (result === null) {
19608
19801
  result = `video-sources/${shipped.size}${extname6(current)}`;
19609
- const destination = join41(input.planDir, ...result.split("/"));
19610
- mkdirSync16(join41(input.planDir, "video-sources"), { recursive: true });
19802
+ const destination = join43(input.planDir, ...result.split("/"));
19803
+ mkdirSync16(join43(input.planDir, "video-sources"), { recursive: true });
19611
19804
  try {
19612
19805
  linkSync(current, destination);
19613
19806
  } catch {
@@ -19627,7 +19820,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19627
19820
  useGpu: false,
19628
19821
  browserGpuMode: "software"
19629
19822
  });
19630
- if (!existsSync26(planDir)) mkdirSync16(planDir, { recursive: true });
19823
+ if (!existsSync27(planDir)) mkdirSync16(planDir, { recursive: true });
19631
19824
  const log = config.logger ?? defaultLogger;
19632
19825
  const sizeLimitBytes = options.executionPlanSizeLimitBytes ?? config.planDirSizeLimitBytes ?? PLAN_DIR_SIZE_LIMIT_BYTES;
19633
19826
  const abortSignal = config.abortSignal;
@@ -19661,21 +19854,21 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19661
19854
  includeOutsideScripts: options.includeOutsideScripts === true
19662
19855
  });
19663
19856
  const entryFile = config.entryFile ?? "index.html";
19664
- const htmlPath = join41(projectDir, entryFile);
19665
- if (!existsSync26(htmlPath)) {
19857
+ const htmlPath = join43(projectDir, entryFile);
19858
+ if (!existsSync27(htmlPath)) {
19666
19859
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
19667
19860
  }
19668
- const workDir = join41(planDir, ".plan-work");
19861
+ const workDir = join43(planDir, ".plan-work");
19669
19862
  rmSync14(workDir, { recursive: true, force: true });
19670
19863
  mkdirSync16(workDir, { recursive: true });
19671
- const compiledDir = join41(workDir, "compiled");
19864
+ const compiledDir = join43(workDir, "compiled");
19672
19865
  mkdirSync16(compiledDir, { recursive: true });
19673
19866
  let stageStarted = Date.now();
19674
19867
  cpSync2(projectDir, compiledDir, {
19675
19868
  recursive: true,
19676
19869
  dereference: true,
19677
19870
  filter: (src) => {
19678
- const rel = relative6(projectDir, src);
19871
+ const rel = relative7(projectDir, src);
19679
19872
  if (rel === "") return true;
19680
19873
  if (leavesRoot(rel)) return false;
19681
19874
  if (job.config.allowOutsideProjectAssets) {
@@ -19683,15 +19876,15 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19683
19876
  const policy = { includeScripts: job.config.includeOutsideScripts };
19684
19877
  if (refusesOutsideLink(projectDir, src, warn, policy)) return false;
19685
19878
  } else if (!isSafePath2(projectDir, src)) return false;
19686
- const firstSegment = rel.split(sep4, 1)[0];
19879
+ const firstSegment = rel.split(sep5, 1)[0];
19687
19880
  return firstSegment === void 0 || !PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(firstSegment);
19688
19881
  }
19689
19882
  });
19690
19883
  logPlanStage(log, "copy", stageStarted);
19691
- const finalCompiledDir = join41(planDir, "compiled");
19884
+ const finalCompiledDir = join43(planDir, "compiled");
19692
19885
  const needsAlpha = outputNeedsAlpha(config.format);
19693
19886
  const remoteFiles = Object.entries(options.remoteFiles ?? {});
19694
- const remoteLocalPath = (rel) => join41(projectDir, ...rel.split("/"));
19887
+ const remoteLocalPath = (rel) => join43(projectDir, ...rel.split("/"));
19695
19888
  for (const [, file] of remoteFiles) {
19696
19889
  declareContentAddressedUrl(file.url, file.sha256);
19697
19890
  if (file.probeFactsUrl) declareProbeFactsUrl(file.url, file.probeFactsUrl);
@@ -19896,17 +20089,17 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
19896
20089
  let stageStarted = Date.now();
19897
20090
  const extractResult = await extractPlanVideos(c, options.deferVideoExtraction);
19898
20091
  logPlanStage(log, "extract", stageStarted);
19899
- const stagedVideoFrames = join41(compiledDir, "__hyperframes_video_frames");
19900
- const videoFramesDst = join41(planDir, "video-frames");
19901
- if (existsSync26(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
19902
- const videoSourcesDir = join41(planDir, "video-sources");
20092
+ const stagedVideoFrames = join43(compiledDir, "__hyperframes_video_frames");
20093
+ const videoFramesDst = join43(planDir, "video-frames");
20094
+ if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
20095
+ const videoSourcesDir = join43(planDir, "video-sources");
19903
20096
  rmSync14(videoSourcesDir, { recursive: true, force: true });
19904
- if (existsSync26(stagedVideoFrames)) {
20097
+ if (existsSync27(stagedVideoFrames)) {
19905
20098
  renameWithRetry8(stagedVideoFrames, videoFramesDst);
19906
20099
  } else {
19907
20100
  mkdirSync16(videoFramesDst, { recursive: true });
19908
20101
  }
19909
- if (existsSync26(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
20102
+ if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
19910
20103
  renameWithRetry8(compiledDir, finalCompiledDir);
19911
20104
  const shipVideoSource = createVideoSourceShipper({
19912
20105
  planDir,
@@ -19936,7 +20129,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
19936
20129
  };
19937
20130
  })
19938
20131
  });
19939
- mkdirSync16(join41(planDir, "meta"), { recursive: true });
20132
+ mkdirSync16(join43(planDir, "meta"), { recursive: true });
19940
20133
  writePlanRemoteFiles(
19941
20134
  planDir,
19942
20135
  remoteFiles.map(([rel, { sha256, sizeBytes }]) => ({
@@ -19946,7 +20139,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
19946
20139
  }))
19947
20140
  );
19948
20141
  writeFileSync10(
19949
- join41(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
20142
+ join43(planDir, PLAN_VIDEOS_META_RELATIVE_PATH),
19950
20143
  JSON.stringify(planVideosJson, null, 2),
19951
20144
  "utf-8"
19952
20145
  );
@@ -20026,11 +20219,11 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20026
20219
  if (audioResult?.audioError) {
20027
20220
  applyDistributedAudioWarningPolicy(job, audioResult.audioError, audioResult.audioFailures, log);
20028
20221
  }
20029
- const planAudioPath = join41(planDir, PLAN_AUDIO_RELATIVE_PATH);
20030
- if (audioResult?.hasAudio && existsSync26(audioResult.audioOutputPath)) {
20222
+ const planAudioPath = join43(planDir, PLAN_AUDIO_RELATIVE_PATH);
20223
+ if (audioResult?.hasAudio && existsSync27(audioResult.audioOutputPath)) {
20031
20224
  renameWithRetry8(audioResult.audioOutputPath, planAudioPath);
20032
20225
  }
20033
- if (chunksCarryAudio && existsSync26(planAudioPath)) {
20226
+ if (chunksCarryAudio && existsSync27(planAudioPath)) {
20034
20227
  if (options.sliceChunkAudio) {
20035
20228
  stageStarted = Date.now();
20036
20229
  await writeChunkAudioSlices({
@@ -20152,8 +20345,8 @@ async function plan(projectDir, config, planDir, options = {}) {
20152
20345
 
20153
20346
  // src/services/distributed/renderChunk.ts
20154
20347
  import { randomBytes } from "node:crypto";
20155
- import { existsSync as existsSync29, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
20156
- import { join as join45 } from "node:path";
20348
+ import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync13 } from "node:fs";
20349
+ import { join as join47 } from "node:path";
20157
20350
  import {
20158
20351
  assertSwiftShader,
20159
20352
  BROWSER_GPU_NOT_SOFTWARE as BROWSER_GPU_NOT_SOFTWARE4,
@@ -20179,17 +20372,17 @@ import {
20179
20372
  } from "@hyperframes/engine";
20180
20373
  import {
20181
20374
  copyFileSync as copyFileSync8,
20182
- existsSync as existsSync28,
20183
- lstatSync as lstatSync3,
20375
+ existsSync as existsSync29,
20376
+ lstatSync as lstatSync5,
20184
20377
  mkdirSync as mkdirSync18,
20185
20378
  readFileSync as readFileSync13,
20186
20379
  readdirSync as readdirSync10,
20187
20380
  rmSync as rmSync16,
20188
- statSync as statSync13,
20381
+ statSync as statSync12,
20189
20382
  writeFileSync as writeFileSync12
20190
20383
  } from "node:fs";
20191
- import { tmpdir as tmpdir3 } from "node:os";
20192
- import { dirname as dirname18, isAbsolute as isAbsolute4, join as join44, relative as relative7, resolve as resolve10, sep as sep5 } from "node:path";
20384
+ import { tmpdir as tmpdir4 } from "node:os";
20385
+ import { dirname as dirname18, isAbsolute as isAbsolute5, join as join46, relative as relative8, resolve as resolve11, sep as sep6 } from "node:path";
20193
20386
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
20194
20387
  import {
20195
20388
  createFrameLookupTable as createFrameLookupTable5,
@@ -20200,15 +20393,15 @@ import {
20200
20393
  // src/services/distributed/planV2Publisher.ts
20201
20394
  import {
20202
20395
  copyFileSync as copyFileSync7,
20203
- existsSync as existsSync27,
20396
+ existsSync as existsSync28,
20204
20397
  linkSync as linkSync2,
20205
20398
  mkdirSync as mkdirSync17,
20206
20399
  rmSync as rmSync15,
20207
- statSync as statSync12,
20400
+ statSync as statSync11,
20208
20401
  writeFileSync as writeFileSync11
20209
20402
  } from "node:fs";
20210
20403
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
20211
- import { dirname as dirname17, join as join43 } from "node:path";
20404
+ import { dirname as dirname17, join as join45 } from "node:path";
20212
20405
 
20213
20406
  // src/services/distributed/planV2Errors.ts
20214
20407
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -20223,7 +20416,7 @@ var PlanV2IntegrityError = class extends Error {
20223
20416
  };
20224
20417
 
20225
20418
  // src/services/distributed/planV2Layout.ts
20226
- import { join as join42 } from "node:path";
20419
+ import { join as join44 } from "node:path";
20227
20420
  var SHA256_PATTERN = /^[0-9a-f]{64}$/;
20228
20421
  function assertPlanV2Sha256(value, field) {
20229
20422
  if (typeof value !== "string" || !SHA256_PATTERN.test(value)) {
@@ -20233,7 +20426,7 @@ function assertPlanV2Sha256(value, field) {
20233
20426
  }
20234
20427
  function planV2BlobPath(root, sha256) {
20235
20428
  const digest = assertPlanV2Sha256(sha256, "artifact sha256");
20236
- return join42(root, "artifacts", "sha256", digest.slice(0, 2), digest);
20429
+ return join44(root, "artifacts", "sha256", digest.slice(0, 2), digest);
20237
20430
  }
20238
20431
 
20239
20432
  // src/services/distributed/planV2Publisher.ts
@@ -20264,7 +20457,7 @@ var LocalPlanV2ArtifactPublisher = class {
20264
20457
  #linkFile;
20265
20458
  #committed = false;
20266
20459
  constructor(destinationDir, options = {}) {
20267
- if (existsSync27(destinationDir)) {
20460
+ if (existsSync28(destinationDir)) {
20268
20461
  throw new PlanV2IntegrityError(`output directory already exists: ${destinationDir}`);
20269
20462
  }
20270
20463
  this.destinationDir = destinationDir;
@@ -20274,17 +20467,17 @@ var LocalPlanV2ArtifactPublisher = class {
20274
20467
  }
20275
20468
  async putBlob(blob) {
20276
20469
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
20277
- const sourceSize = statSync12(blob.sourcePath).size;
20470
+ const sourceSize = statSync11(blob.sourcePath).size;
20278
20471
  if (sourceSize !== blob.sizeBytes) {
20279
20472
  throw new PlanV2IntegrityError(
20280
20473
  `published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`
20281
20474
  );
20282
20475
  }
20283
20476
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
20284
- if (existsSync27(destinationPath)) return;
20477
+ if (existsSync28(destinationPath)) return;
20285
20478
  mkdirSync17(dirname17(destinationPath), { recursive: true });
20286
20479
  const stagingDir = createStagingDir5(dirname17(destinationPath), ".plan-v2-blob-");
20287
- const temporaryPath = join43(stagingDir, "blob");
20480
+ const temporaryPath = join45(stagingDir, "blob");
20288
20481
  try {
20289
20482
  try {
20290
20483
  this.#linkFile(blob.sourcePath, temporaryPath);
@@ -20299,13 +20492,13 @@ var LocalPlanV2ArtifactPublisher = class {
20299
20492
  }
20300
20493
  async commitManifest(manifestBytes) {
20301
20494
  for (const digest of new Set(manifestDigests(manifestBytes))) {
20302
- if (!existsSync27(planV2BlobPath(this.temporaryDir, digest))) {
20495
+ if (!existsSync28(planV2BlobPath(this.temporaryDir, digest))) {
20303
20496
  throw new PlanV2IntegrityError(
20304
20497
  `cannot commit manifest before referenced blob is durable: ${digest}`
20305
20498
  );
20306
20499
  }
20307
20500
  }
20308
- writeFileSync11(join43(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
20501
+ writeFileSync11(join45(this.temporaryDir, "plan.json"), manifestBytes, "utf-8");
20309
20502
  renameWithRetry9(this.temporaryDir, this.destinationDir);
20310
20503
  this.#committed = true;
20311
20504
  }
@@ -20342,21 +20535,21 @@ function readJsonFile(path, label) {
20342
20535
  }
20343
20536
  function assertSafeRelativePath(path) {
20344
20537
  const normalized = path.split(/[\\/]+/);
20345
- if (path.length === 0 || isAbsolute4(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
20538
+ if (path.length === 0 || isAbsolute5(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
20346
20539
  throw new PlanV2IntegrityError(`unsafe artifact path: ${JSON.stringify(path)}`);
20347
20540
  }
20348
20541
  }
20349
20542
  function listFiles(root) {
20350
20543
  const files = [];
20351
- const rootResolved = resolve10(root);
20544
+ const rootResolved = resolve11(root);
20352
20545
  function walk(dir) {
20353
20546
  for (const entry of readdirSync10(dir, { withFileTypes: true })) {
20354
- const absolutePath = join44(dir, entry.name);
20547
+ const absolutePath = join46(dir, entry.name);
20355
20548
  if (entry.isDirectory()) {
20356
20549
  walk(absolutePath);
20357
20550
  } else if (entry.isFile()) {
20358
20551
  files.push({
20359
- path: relative7(rootResolved, absolutePath).split(sep5).join("/"),
20552
+ path: relative8(rootResolved, absolutePath).split(sep6).join("/"),
20360
20553
  absolutePath
20361
20554
  });
20362
20555
  } else {
@@ -20370,7 +20563,7 @@ function listFiles(root) {
20370
20563
  return files.sort((a, b) => a.path.localeCompare(b.path));
20371
20564
  }
20372
20565
  function assertValidExtractionCacheCompleteSentinel(path) {
20373
- const sentinel = lstatSync3(path);
20566
+ const sentinel = lstatSync5(path);
20374
20567
  if (!sentinel.isFile() || sentinel.size !== 0) {
20375
20568
  throw new PlanV2IntegrityError(
20376
20569
  `${EXTRACTION_CACHE_COMPLETE_SENTINEL} must be a zero-byte regular file`
@@ -20378,13 +20571,13 @@ function assertValidExtractionCacheCompleteSentinel(path) {
20378
20571
  }
20379
20572
  }
20380
20573
  function validateExtractionCacheCompleteSentinels(executionPlanDir) {
20381
- const videoRoot = join44(executionPlanDir, "video-frames");
20382
- if (!existsSync28(videoRoot)) return;
20574
+ const videoRoot = join46(executionPlanDir, "video-frames");
20575
+ if (!existsSync29(videoRoot)) return;
20383
20576
  for (const videoEntry of readdirSync10(videoRoot, { withFileTypes: true })) {
20384
20577
  if (!videoEntry.isDirectory()) continue;
20385
- const videoDir = join44(videoRoot, videoEntry.name);
20578
+ const videoDir = join46(videoRoot, videoEntry.name);
20386
20579
  if (readdirSync10(videoDir).includes(EXTRACTION_CACHE_COMPLETE_SENTINEL)) {
20387
- const sentinelPath = join44(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
20580
+ const sentinelPath = join46(videoDir, EXTRACTION_CACHE_COMPLETE_SENTINEL);
20388
20581
  assertValidExtractionCacheCompleteSentinel(sentinelPath);
20389
20582
  }
20390
20583
  }
@@ -20394,9 +20587,9 @@ function isExtractionCacheCompleteSentinelPath(path) {
20394
20587
  return segments.length === 3 && segments[0] === "video-frames" && segments[1] !== "" && segments[2] === EXTRACTION_CACHE_COMPLETE_SENTINEL;
20395
20588
  }
20396
20589
  function resolveExtractedVideoOutputDir(planDir, videoId) {
20397
- const videoRoot = resolve10(planDir, "video-frames");
20398
- const outputDir = resolve10(videoRoot, mediaIdPathSegment4(videoId));
20399
- if (outputDir === videoRoot || !outputDir.startsWith(`${videoRoot}${sep5}`)) {
20590
+ const videoRoot = resolve11(planDir, "video-frames");
20591
+ const outputDir = resolve11(videoRoot, mediaIdPathSegment4(videoId));
20592
+ if (outputDir === videoRoot || !outputDir.startsWith(`${videoRoot}${sep6}`)) {
20400
20593
  throw new PlanV2IntegrityError(`unsafe extracted video id: ${JSON.stringify(videoId)}`);
20401
20594
  }
20402
20595
  return outputDir;
@@ -20431,7 +20624,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
20431
20624
  if (video.deferredRange) {
20432
20625
  const framePaths2 = /* @__PURE__ */ new Map();
20433
20626
  for (let index = 0; index < video.totalFrames; index++) {
20434
- framePaths2.set(index, join44(outputDir, String(index)));
20627
+ framePaths2.set(index, join46(outputDir, String(index)));
20435
20628
  }
20436
20629
  return { ...video, outputDir, framePaths: framePaths2, ownedByLookup: false };
20437
20630
  }
@@ -20439,7 +20632,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
20439
20632
  const framePaths = /* @__PURE__ */ new Map();
20440
20633
  for (const frameName of frameNames) {
20441
20634
  if (frameName === EXTRACTION_CACHE_COMPLETE_SENTINEL) {
20442
- assertValidExtractionCacheCompleteSentinel(join44(outputDir, frameName));
20635
+ assertValidExtractionCacheCompleteSentinel(join46(outputDir, frameName));
20443
20636
  continue;
20444
20637
  }
20445
20638
  const match = /(\d+)(?=\.[^.]+$)/.exec(frameName);
@@ -20458,7 +20651,7 @@ function listVideoFramePaths(executionPlanDir, videos) {
20458
20651
  `duplicate extracted frame index ${frameIndex} in ${outputDir}`
20459
20652
  );
20460
20653
  }
20461
- framePaths.set(frameIndex, join44(outputDir, frameName));
20654
+ framePaths.set(frameIndex, join46(outputDir, frameName));
20462
20655
  }
20463
20656
  return {
20464
20657
  ...video,
@@ -20479,8 +20672,8 @@ function parsePlanVideosJson2(value) {
20479
20672
  }
20480
20673
  }
20481
20674
  function materializeExtractedVideoDirectories(planDir) {
20482
- const videosPath = join44(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20483
- if (!existsSync28(videosPath)) return;
20675
+ const videosPath = join46(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20676
+ if (!existsSync29(videosPath)) return;
20484
20677
  const videos = parsePlanVideosJson2(readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH));
20485
20678
  for (const video of videos.extracted) {
20486
20679
  mkdirSync18(resolveExtractedVideoOutputDir(planDir, video.videoId), { recursive: true });
@@ -20513,13 +20706,13 @@ function parseChunkSlices(value) {
20513
20706
  });
20514
20707
  }
20515
20708
  function buildVideoChunkDependencies(executionPlanDir, dimensions) {
20516
- const videoRoot = join44(executionPlanDir, "video-frames");
20517
- const hasExtractedFrames = existsSync28(videoRoot) && listFiles(videoRoot).length > 0;
20518
- const videosPath = join44(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20519
- if (!existsSync28(videosPath)) {
20709
+ const videoRoot = join46(executionPlanDir, "video-frames");
20710
+ const hasExtractedFrames = existsSync29(videoRoot) && listFiles(videoRoot).length > 0;
20711
+ const videosPath = join46(executionPlanDir, PLAN_VIDEOS_META_RELATIVE_PATH);
20712
+ if (!existsSync29(videosPath)) {
20520
20713
  return hasExtractedFrames ? { mode: "full-source-pack", dependencies: null } : { mode: "exact-rendered-frames", dependencies: /* @__PURE__ */ new Map() };
20521
20714
  }
20522
- const chunksPath = join44(executionPlanDir, "meta", "chunks.json");
20715
+ const chunksPath = join46(executionPlanDir, "meta", "chunks.json");
20523
20716
  const videos = readJsonFile(videosPath, PLAN_VIDEOS_META_RELATIVE_PATH);
20524
20717
  const chunks = readJsonFile(chunksPath, "meta/chunks.json");
20525
20718
  const parsedVideos = parsePlanVideosJson2(videos);
@@ -20556,7 +20749,7 @@ function collectChunkVideoDependencies(input) {
20556
20749
  for (let frame = chunk.startFrame; frame < chunk.endFrame; frame++) {
20557
20750
  const globalTime = frame * input.fpsDen / input.fpsNum;
20558
20751
  for (const [videoId, payload] of input.table.getActiveFramePayloads(globalTime)) {
20559
- const path = input.deferredSources.get(videoId) ?? relative7(resolve10(input.executionPlanDir), payload.framePath).split(sep5).join("/");
20752
+ const path = input.deferredSources.get(videoId) ?? relative8(resolve11(input.executionPlanDir), payload.framePath).split(sep6).join("/");
20560
20753
  assertSafeRelativePath(path);
20561
20754
  const indexes = mutable.get(path) ?? /* @__PURE__ */ new Set();
20562
20755
  indexes.add(chunk.index);
@@ -20573,10 +20766,10 @@ function computeManifestHash(manifest) {
20573
20766
  return sha256Hex(`${PLAN_V2_HASH_PREFIX}${canonicalJsonStringify(manifestPayload(manifest))}`);
20574
20767
  }
20575
20768
  function writeBlob(sourcePath, destinationPath) {
20576
- if (existsSync28(destinationPath)) return;
20769
+ if (existsSync29(destinationPath)) return;
20577
20770
  mkdirSync18(dirname18(destinationPath), { recursive: true });
20578
20771
  const temporaryDir = createStagingDir6(dirname18(destinationPath), ".plan-v2-blob-");
20579
- const temporaryPath = join44(temporaryDir, "blob");
20772
+ const temporaryPath = join46(temporaryDir, "blob");
20580
20773
  try {
20581
20774
  copyFileSync8(sourcePath, temporaryPath);
20582
20775
  renameWithRetry10(temporaryPath, destinationPath);
@@ -20588,7 +20781,7 @@ function publishBlobFor(absolutePath, digests) {
20588
20781
  return {
20589
20782
  sourcePath: absolutePath,
20590
20783
  sha256: planFileSha256(absolutePath, digests),
20591
- sizeBytes: statSync13(absolutePath).size
20784
+ sizeBytes: statSync12(absolutePath).size
20592
20785
  };
20593
20786
  }
20594
20787
  async function putBlobs(publisher, blobs) {
@@ -20612,8 +20805,8 @@ async function putTasks(tasks) {
20612
20805
  if (failure) throw failure.reason;
20613
20806
  }
20614
20807
  function buildPlanV2Publication(executionPlanDir, digests) {
20615
- const executionPlanPath = join44(executionPlanDir, "plan.json");
20616
- if (!existsSync28(executionPlanPath)) {
20808
+ const executionPlanPath = join46(executionPlanDir, "plan.json");
20809
+ if (!existsSync29(executionPlanPath)) {
20617
20810
  throw new PlanV2IntegrityError(`execution plan is missing plan.json: ${executionPlanPath}`);
20618
20811
  }
20619
20812
  const executionPlanValue = readJsonFile(executionPlanPath, "execution plan.json");
@@ -20640,7 +20833,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
20640
20833
  }
20641
20834
  validateExtractionCacheCompleteSentinels(executionPlanDir);
20642
20835
  const videoDependencyPlan = buildVideoChunkDependencies(executionPlanDir, dimensions);
20643
- const encoder = readJsonFile(join44(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
20836
+ const encoder = readJsonFile(join46(executionPlanDir, "meta", "encoder.json"), "meta/encoder.json");
20644
20837
  const files = listFiles(executionPlanDir);
20645
20838
  const chunkAudio = !isRecord3(encoder) || encoder.chunksCarryAudio !== true ? "none" : files.some((file) => chunkAudioSliceTarget(file.path) !== null) ? "sliced" : "whole";
20646
20839
  for (const file of files) {
@@ -20693,7 +20886,7 @@ function buildPlanV2Publication(executionPlanDir, digests) {
20693
20886
  };
20694
20887
  }
20695
20888
  function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
20696
- if (existsSync28(planV2Dir)) {
20889
+ if (existsSync29(planV2Dir)) {
20697
20890
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
20698
20891
  }
20699
20892
  const publication = buildPlanV2Publication(executionPlanDir);
@@ -20707,7 +20900,7 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
20707
20900
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
20708
20901
  }
20709
20902
  writeFileSync12(
20710
- join44(tempDir, "plan.json"),
20903
+ join46(tempDir, "plan.json"),
20711
20904
  canonicalJsonStringify(publication.manifest),
20712
20905
  "utf-8"
20713
20906
  );
@@ -20748,7 +20941,7 @@ async function publishExecutionPlan(executionPlanDir, publisher, { digests, log
20748
20941
  }
20749
20942
  }
20750
20943
  async function planV2WithPublisher(projectDir, config, publisher, options = {}) {
20751
- const stagingRoot = createStagingDir6(options.stagingParentDir ?? tmpdir3(), ".execution-plan-");
20944
+ const stagingRoot = createStagingDir6(options.stagingParentDir ?? tmpdir4(), ".execution-plan-");
20752
20945
  const digests = /* @__PURE__ */ new Map();
20753
20946
  try {
20754
20947
  const planned = await buildLocalExecutionPlan(projectDir, config, stagingRoot, {
@@ -20759,7 +20952,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
20759
20952
  // artifactTargets ships every compiled/ file to all chunks, so each is in the manifest.
20760
20953
  whileAudioMixes: () => putBlobs(
20761
20954
  publisher,
20762
- listFiles(join44(stagingRoot, "compiled")).map(
20955
+ listFiles(join46(stagingRoot, "compiled")).map(
20763
20956
  (file) => publishBlobFor(file.absolutePath, digests)
20764
20957
  )
20765
20958
  ),
@@ -20783,7 +20976,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
20783
20976
  }
20784
20977
  }
20785
20978
  async function planV2(projectDir, config, planV2Dir) {
20786
- if (existsSync28(planV2Dir)) {
20979
+ if (existsSync29(planV2Dir)) {
20787
20980
  throw new PlanV2IntegrityError(`output directory already exists: ${planV2Dir}`);
20788
20981
  }
20789
20982
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
@@ -20800,7 +20993,7 @@ function resultFromManifest(planV2Dir, manifest) {
20800
20993
  isRecord3(executionPlan) ? executionPlan[REFERENCE_BACKGROUND_FIELD3] : void 0
20801
20994
  ),
20802
20995
  planDir: planV2Dir,
20803
- manifestPath: join44(planV2Dir, "plan.json"),
20996
+ manifestPath: join46(planV2Dir, "plan.json"),
20804
20997
  planProtocol: PLAN_PROTOCOL_V2,
20805
20998
  planHash: manifest.planHash,
20806
20999
  sourcePlanV1Hash: getPlanV2ExecutionPlanHash(manifest),
@@ -20936,8 +21129,8 @@ function parsePlanV2Manifest(value) {
20936
21129
  return parsed;
20937
21130
  }
20938
21131
  function readPlanV2Manifest(planV2Dir) {
20939
- const manifestPath = join44(planV2Dir, "plan.json");
20940
- if (!existsSync28(manifestPath)) {
21132
+ const manifestPath = join46(planV2Dir, "plan.json");
21133
+ if (!existsSync29(manifestPath)) {
20941
21134
  throw new PlanV2IntegrityError(`missing v2 manifest: ${manifestPath}`);
20942
21135
  }
20943
21136
  const value = readJsonFile(manifestPath, "v2 manifest");
@@ -20956,10 +21149,10 @@ function listPlanV2ArtifactsForTarget(manifest, target) {
20956
21149
  }
20957
21150
  function verifyBlob(planV2Dir, artifact) {
20958
21151
  const sourcePath = planV2BlobPath(planV2Dir, artifact.sha256);
20959
- if (!existsSync28(sourcePath)) {
21152
+ if (!existsSync29(sourcePath)) {
20960
21153
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
20961
21154
  }
20962
- const stats = statSync13(sourcePath);
21155
+ const stats = statSync12(sourcePath);
20963
21156
  if (!stats.isFile() || stats.size !== artifact.sizeBytes) {
20964
21157
  throw new PlanV2IntegrityError(`artifact size mismatch for ${artifact.path}`);
20965
21158
  }
@@ -20969,7 +21162,7 @@ function verifyBlob(planV2Dir, artifact) {
20969
21162
  return sourcePath;
20970
21163
  }
20971
21164
  function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}) {
20972
- if (existsSync28(destinationDir)) {
21165
+ if (existsSync29(destinationDir)) {
20973
21166
  throw new PlanV2IntegrityError(`materialization destination already exists: ${destinationDir}`);
20974
21167
  }
20975
21168
  const manifest = readPlanV2Manifest(planV2Dir);
@@ -20985,13 +21178,13 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
20985
21178
  const tempDir = createStagingDir6(dirname18(destinationDir), ".plan-v2-materialize-");
20986
21179
  try {
20987
21180
  for (const { artifact, sourcePath } of verified) {
20988
- const destinationPath = join44(tempDir, ...artifact.path.split("/"));
21181
+ const destinationPath = join46(tempDir, ...artifact.path.split("/"));
20989
21182
  mkdirSync18(dirname18(destinationPath), { recursive: true });
20990
21183
  copyFileSync8(sourcePath, destinationPath);
20991
21184
  }
20992
21185
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
20993
21186
  writeFileSync12(
20994
- join44(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
21187
+ join46(tempDir, PLAN_V2_MATERIALIZATION_MARKER),
20995
21188
  canonicalJsonStringify({
20996
21189
  manifest,
20997
21190
  target,
@@ -21014,7 +21207,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21014
21207
  // Join the artifact's OWN name, not the current constant: a plan written
21015
21208
  // before the container change carries the legacy name, and materializing it
21016
21209
  // under the new one would point at a file that was never written.
21017
- audioPath: target.role === "assembler" ? audioArtifact ? join44(destinationDir, audioArtifact.path) : null : null
21210
+ audioPath: target.role === "assembler" ? audioArtifact ? join46(destinationDir, audioArtifact.path) : null : null
21018
21211
  };
21019
21212
  }
21020
21213
  function assertRemoteSources(remoteSources, artifacts) {
@@ -21033,8 +21226,8 @@ function validatePlanV2MaterializedTarget(planDir, expectedTarget) {
21033
21226
  return readValidatedPlanV2Materialization(planDir, expectedTarget)?.manifest ?? null;
21034
21227
  }
21035
21228
  function readValidatedPlanV2Materialization(planDir, expectedTarget) {
21036
- const markerPath = join44(planDir, PLAN_V2_MATERIALIZATION_MARKER);
21037
- if (!existsSync28(markerPath)) return null;
21229
+ const markerPath = join46(planDir, PLAN_V2_MATERIALIZATION_MARKER);
21230
+ if (!existsSync29(markerPath)) return null;
21038
21231
  const marker = readJsonFile(markerPath, "materialization marker");
21039
21232
  if (!isRecord3(marker) || !isRecord3(marker.manifest) || !isRecord3(marker.target)) {
21040
21233
  throw new PlanV2IntegrityError("malformed materialization marker");
@@ -21051,8 +21244,8 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
21051
21244
  assertRemoteSources(remoteSources, required);
21052
21245
  for (const artifact of required) {
21053
21246
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
21054
- const path = join44(planDir, ...artifact.path.split("/"));
21055
- if (!existsSync28(path) || statSync13(path).size !== artifact.sizeBytes) {
21247
+ const path = join46(planDir, ...artifact.path.split("/"));
21248
+ if (!existsSync29(path) || statSync12(path).size !== artifact.sizeBytes) {
21056
21249
  throw new PlanV2IntegrityError(
21057
21250
  `materialized artifact missing or truncated: ${artifact.path}`
21058
21251
  );
@@ -21183,7 +21376,7 @@ function hashChunkOutput(outputPath, kind) {
21183
21376
  if (kind === "file") return sha256Hex(readFileSync14(outputPath));
21184
21377
  const entries = readdirSync11(outputPath).filter((name) => /\.(png|jpg|jpeg)$/i.test(name)).sort();
21185
21378
  const lines = entries.map(
21186
- (name) => `${name}\0${sha256Hex(readFileSync14(join45(outputPath, name)))}`
21379
+ (name) => `${name}\0${sha256Hex(readFileSync14(join47(outputPath, name)))}`
21187
21380
  );
21188
21381
  return sha256Hex(lines.join("\0"));
21189
21382
  }
@@ -21200,10 +21393,10 @@ function resolveLockedVp9CpuUsed(lockedEncoder) {
21200
21393
  async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21201
21394
  const start = Date.now();
21202
21395
  const log = defaultLogger;
21203
- const planJsonPath = join45(planDir, "plan.json");
21204
- const encoderJsonPath = join45(planDir, "meta", "encoder.json");
21205
- const chunksJsonPath = join45(planDir, "meta", "chunks.json");
21206
- if (!existsSync29(planJsonPath)) {
21396
+ const planJsonPath = join47(planDir, "plan.json");
21397
+ const encoderJsonPath = join47(planDir, "meta", "encoder.json");
21398
+ const chunksJsonPath = join47(planDir, "meta", "chunks.json");
21399
+ if (!existsSync30(planJsonPath)) {
21207
21400
  throw new RenderChunkValidationError(
21208
21401
  MISSING_PLAN_ARTIFACT,
21209
21402
  `[renderChunk] planDir is missing required artifact: ${planJsonPath}`
@@ -21219,7 +21412,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21219
21412
  const v2Manifest = v2Materialization?.manifest ?? null;
21220
21413
  const remoteSources = v2Materialization?.remoteSources ?? {};
21221
21414
  for (const required of [encoderJsonPath, chunksJsonPath]) {
21222
- if (!existsSync29(required)) {
21415
+ if (!existsSync30(required)) {
21223
21416
  throw new RenderChunkValidationError(
21224
21417
  MISSING_PLAN_ARTIFACT,
21225
21418
  `[renderChunk] planDir is missing required artifact: ${required}`
@@ -21228,9 +21421,9 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21228
21421
  }
21229
21422
  const encoder = JSON.parse(readFileSync14(encoderJsonPath, "utf-8"));
21230
21423
  const chunks = JSON.parse(readFileSync14(chunksJsonPath, "utf-8"));
21231
- const videosJsonPath = join45(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
21424
+ const videosJsonPath = join47(planDir, PLAN_VIDEOS_META_RELATIVE_PATH);
21232
21425
  let planVideos = null;
21233
- if (existsSync29(videosJsonPath)) {
21426
+ if (existsSync30(videosJsonPath)) {
21234
21427
  try {
21235
21428
  planVideos = validatePlanVideosForChunk(JSON.parse(readFileSync14(videosJsonPath, "utf-8")));
21236
21429
  } catch (err) {
@@ -21260,8 +21453,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21260
21453
  }
21261
21454
  const range = resolveChunkFrameRange(slice, chunkIndex, options?.frameRange);
21262
21455
  const framesInChunk = range.endFrame - range.startFrame;
21263
- const compiledDir = join45(planDir, "compiled");
21264
- if (!existsSync29(compiledDir)) {
21456
+ const compiledDir = join47(planDir, "compiled");
21457
+ if (!existsSync30(compiledDir)) {
21265
21458
  throw new RenderChunkValidationError(
21266
21459
  MISSING_PLAN_ARTIFACT,
21267
21460
  `[renderChunk] planDir missing compiled/ directory: ${compiledDir}`
@@ -21319,7 +21512,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21319
21512
  };
21320
21513
  const workDir = `${outputChunkPath}.work.${process.pid}.${randomBytes(4).toString("hex")}`;
21321
21514
  mkdirSync19(workDir, { recursive: true });
21322
- const framesDir = join45(workDir, "captured-frames");
21515
+ const framesDir = join47(workDir, "captured-frames");
21323
21516
  mkdirSync19(framesDir, { recursive: true });
21324
21517
  const videoFramesDir = `${workDir}.video-frames`;
21325
21518
  const chunkFrameNumbers = Array.from({ length: framesInChunk }, (_, i) => range.startFrame + i);
@@ -21344,7 +21537,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21344
21537
  dimensions: plan2.dimensions,
21345
21538
  encoder,
21346
21539
  videoCount: planVideos?.videos.length ?? 0,
21347
- html: readFileSync14(join45(compiledDir, "index.html"), "utf-8"),
21540
+ html: readFileSync14(join47(compiledDir, "index.html"), "utf-8"),
21348
21541
  // The plan ships a deferred source only to chunks that show it; don't wait on the rest.
21349
21542
  skipReadinessVideoIds: deferredVideos.filter(
21350
21543
  (video) => !shownFrames.get(video.videoId)?.size || remoteVideoIds.has(video.videoId)
@@ -21378,8 +21571,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21378
21571
  const verifyInWorker = chunkWorkerCount > 1 && !forceScreenshotForChunk;
21379
21572
  let boxesMeasured;
21380
21573
  let boxesFailed;
21381
- const boxesReady = new Promise((resolve13, reject) => {
21382
- boxesMeasured = resolve13;
21574
+ const boxesReady = new Promise((resolve14, reject) => {
21575
+ boxesMeasured = resolve14;
21383
21576
  boxesFailed = reject;
21384
21577
  });
21385
21578
  boxesReady.catch(() => {
@@ -21513,10 +21706,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21513
21706
  const effectiveBitrate = encoder.crf != null ? void 0 : encoder.bitrate;
21514
21707
  const videoOnlyPath = encoder.chunksCarryAudio ? `${outputChunkPath}.video.mp4` : outputChunkPath;
21515
21708
  if (isPngSequence) {
21516
- if (!existsSync29(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
21709
+ if (!existsSync30(outputChunkPath)) mkdirSync19(outputChunkPath, { recursive: true });
21517
21710
  } else {
21518
- const outDir = join45(outputChunkPath, "..");
21519
- if (!existsSync29(outDir)) mkdirSync19(outDir, { recursive: true });
21711
+ const outDir = join47(outputChunkPath, "..");
21712
+ if (!existsSync30(outDir)) mkdirSync19(outDir, { recursive: true });
21520
21713
  }
21521
21714
  const encodeInput = {
21522
21715
  job,
@@ -21792,10 +21985,10 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
21792
21985
  if (config.cfr === true) {
21793
21986
  throw new RenderSpanUnsupportedError("--start/--end cannot be combined with a cfr re-encode.");
21794
21987
  }
21795
- const workDir = mkdtempSync(join46(tmpdir4(), "hf-render-span-"));
21988
+ const workDir = mkdtempSync(join48(tmpdir5(), "hf-render-span-"));
21796
21989
  try {
21797
- const planDir = join46(workDir, "plan");
21798
- const partsDir = join46(workDir, "parts");
21990
+ const planDir = join48(workDir, "plan");
21991
+ const partsDir = join48(workDir, "parts");
21799
21992
  mkdirSync20(partsDir, { recursive: true });
21800
21993
  const planned = await plan(
21801
21994
  projectDir,
@@ -21814,7 +22007,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
21814
22007
  planned.totalFrames
21815
22008
  );
21816
22009
  const slices = JSON.parse(
21817
- readFileSync15(join46(planDir, "meta", "chunks.json"), "utf-8")
22010
+ readFileSync15(join48(planDir, "meta", "chunks.json"), "utf-8")
21818
22011
  );
21819
22012
  const parts = [];
21820
22013
  for (const slice of slices) {
@@ -21824,7 +22017,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
21824
22017
  };
21825
22018
  if (range.endFrame <= range.startFrame) continue;
21826
22019
  throwIfAborted(config.abortSignal);
21827
- const part = join46(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`);
22020
+ const part = join48(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`);
21828
22021
  await renderChunk(planDir, slice.index, part, { frameRange: range });
21829
22022
  parts.push(part);
21830
22023
  }
@@ -22480,16 +22673,16 @@ import {
22480
22673
 
22481
22674
  // src/server.ts
22482
22675
  import {
22483
- existsSync as existsSync32,
22676
+ existsSync as existsSync33,
22484
22677
  mkdirSync as mkdirSync21,
22485
- statSync as statSync15,
22678
+ statSync as statSync14,
22486
22679
  mkdtempSync as mkdtempSync2,
22487
22680
  writeFileSync as writeFileSync14,
22488
22681
  rmSync as rmSync19,
22489
- createReadStream as createReadStream5
22682
+ createReadStream as createReadStream6
22490
22683
  } from "node:fs";
22491
- import { resolve as resolve12, dirname as dirname21, join as join49 } from "node:path";
22492
- import { tmpdir as tmpdir5 } from "node:os";
22684
+ import { resolve as resolve13, dirname as dirname21, join as join51 } from "node:path";
22685
+ import { tmpdir as tmpdir6 } from "node:os";
22493
22686
  import { parseArgs } from "node:util";
22494
22687
  import { isIP } from "node:net";
22495
22688
  import crypto from "node:crypto";
@@ -22505,15 +22698,15 @@ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
22505
22698
 
22506
22699
  // src/services/hyperframeLint.ts
22507
22700
  import {
22508
- existsSync as existsSync30,
22701
+ existsSync as existsSync31,
22509
22702
  readFileSync as readFileSync16,
22510
- statSync as statSync14,
22703
+ statSync as statSync13,
22511
22704
  openSync as openSync7,
22512
22705
  fstatSync as fstatSync3,
22513
22706
  closeSync as closeSync7,
22514
22707
  constants as constants3
22515
22708
  } from "node:fs";
22516
- import { resolve as resolve11, join as join47, relative as relative8, isAbsolute as isAbsolute5, sep as sep6, dirname as dirname19 } from "node:path";
22709
+ import { resolve as resolve12, join as join49, relative as relative9, isAbsolute as isAbsolute6, sep as sep7, dirname as dirname19 } from "node:path";
22517
22710
  import { fileURLToPath as fileURLToPath6 } from "node:url";
22518
22711
  import { Worker as Worker2 } from "node:worker_threads";
22519
22712
  function isStringRecord(value) {
@@ -22548,7 +22741,7 @@ function readEntryHtml(filePath) {
22548
22741
  } catch (error) {
22549
22742
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
22550
22743
  return null;
22551
- if (!statSync14(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22744
+ if (!statSync13(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22552
22745
  throw error;
22553
22746
  }
22554
22747
  try {
@@ -22559,19 +22752,19 @@ function readEntryHtml(filePath) {
22559
22752
  }
22560
22753
  }
22561
22754
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
22562
- const entryRelativePath = relative8(absProjectDir, absoluteEntryPath);
22563
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep6}`) || isAbsolute5(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
22755
+ const entryRelativePath = relative9(absProjectDir, absoluteEntryPath);
22756
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep7}`) || isAbsolute6(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
22564
22757
  }
22565
22758
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
22566
- const absProjectDir = resolve11(projectDir);
22567
- if (!existsSync30(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22759
+ const absProjectDir = resolve12(projectDir);
22760
+ if (!existsSync31(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
22568
22761
  return { error: `Project directory not found: ${absProjectDir}` };
22569
22762
  }
22570
22763
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
22571
22764
  (value) => typeof value === "string" && value.trim().length > 0
22572
22765
  );
22573
22766
  for (const entryFile of entryCandidates) {
22574
- const absoluteEntryPath = resolve11(absProjectDir, entryFile);
22767
+ const absoluteEntryPath = resolve12(absProjectDir, entryFile);
22575
22768
  if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) {
22576
22769
  return { error: `Entry file must stay inside project directory: ${entryFile}` };
22577
22770
  }
@@ -22585,7 +22778,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
22585
22778
  }
22586
22779
  }
22587
22780
  return {
22588
- error: `No HTML entry file found in project directory: ${join47(absProjectDir, preferredEntryFile || "index.html")}`
22781
+ error: `No HTML entry file found in project directory: ${join49(absProjectDir, preferredEntryFile || "index.html")}`
22589
22782
  };
22590
22783
  }
22591
22784
  function prepareHyperframeLintBody(body, isAllowedEntry) {
@@ -22631,16 +22824,16 @@ function takeLintSlot(limit, waitMs) {
22631
22824
  running++;
22632
22825
  return Promise.resolve(true);
22633
22826
  }
22634
- return new Promise((resolve13) => {
22827
+ return new Promise((resolve14) => {
22635
22828
  const entry = () => {
22636
22829
  clearTimeout(timer);
22637
22830
  running++;
22638
- resolve13(true);
22831
+ resolve14(true);
22639
22832
  };
22640
22833
  const timer = setTimeout(
22641
22834
  () => {
22642
22835
  waiting.splice(waiting.indexOf(entry), 1);
22643
- resolve13(false);
22836
+ resolve14(false);
22644
22837
  },
22645
22838
  Math.max(0, waitMs)
22646
22839
  );
@@ -22654,8 +22847,8 @@ function freeLintSlot() {
22654
22847
  function resolveLintWorkerEntry() {
22655
22848
  const here = dirname19(fileURLToPath6(import.meta.url));
22656
22849
  for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
22657
- const candidate = join47(here, name);
22658
- if (existsSync30(candidate)) return candidate;
22850
+ const candidate = join49(here, name);
22851
+ if (existsSync31(candidate)) return candidate;
22659
22852
  }
22660
22853
  return void 0;
22661
22854
  }
@@ -22725,8 +22918,8 @@ async function runHyperframeLint(prepared, options = {}) {
22725
22918
  // src/services/healthWorker.ts
22726
22919
  import { Worker as Worker3 } from "node:worker_threads";
22727
22920
  import { fileURLToPath as fileURLToPath7 } from "node:url";
22728
- import { dirname as dirname20, join as join48 } from "node:path";
22729
- import { existsSync as existsSync31 } from "node:fs";
22921
+ import { dirname as dirname20, join as join50 } from "node:path";
22922
+ import { existsSync as existsSync32 } from "node:fs";
22730
22923
  var DEFAULT_HEALTH_PORT = 9848;
22731
22924
  async function startHealthWorker(options = {}) {
22732
22925
  const log = options.logger ?? defaultLogger2();
@@ -22744,12 +22937,12 @@ async function startHealthWorker(options = {}) {
22744
22937
  stdout: false,
22745
22938
  stderr: false
22746
22939
  });
22747
- await new Promise((resolve13, reject) => {
22940
+ await new Promise((resolve14, reject) => {
22748
22941
  const onMessage = (msg) => {
22749
22942
  if (msg?.type === "listening") {
22750
22943
  worker.off("error", onError);
22751
22944
  worker.off("message", onMessage);
22752
- resolve13();
22945
+ resolve14();
22753
22946
  } else if (msg?.type === "listen-error") {
22754
22947
  worker.off("error", onError);
22755
22948
  worker.off("message", onMessage);
@@ -22801,9 +22994,9 @@ function defaultLogger2() {
22801
22994
  }
22802
22995
  function resolveWorkerEntry2() {
22803
22996
  const here = dirname20(fileURLToPath7(import.meta.url));
22804
- const candidates = [join48(here, "healthWorkerThread.js"), join48(here, "healthWorkerThread.ts")];
22997
+ const candidates = [join50(here, "healthWorkerThread.js"), join50(here, "healthWorkerThread.ts")];
22805
22998
  for (const candidate of candidates) {
22806
- if (existsSync31(candidate)) return candidate;
22999
+ if (existsSync32(candidate)) return candidate;
22807
23000
  }
22808
23001
  return void 0;
22809
23002
  }
@@ -22973,7 +23166,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
22973
23166
  }
22974
23167
  }
22975
23168
  const outputDir = dirname21(absoluteOutputPath);
22976
- if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
23169
+ if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
22977
23170
  return { input, cleanupProjectDir, absoluteOutputPath };
22978
23171
  }
22979
23172
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
@@ -23034,7 +23227,7 @@ function validateOutputResolutionOverride(body) {
23034
23227
  var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
23035
23228
  function resolveRenderRequestPolicy(options) {
23036
23229
  return {
23037
- projectsDir: resolve12(
23230
+ projectsDir: resolve13(
23038
23231
  options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd())
23039
23232
  ),
23040
23233
  allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1"
@@ -23049,14 +23242,14 @@ function isAllowedEntryPath(policy, projectDir, path) {
23049
23242
  function prepareProjectDirectory(projectDir, options, policy) {
23050
23243
  const candidate = nonEmptyString(projectDir);
23051
23244
  if (!candidate) return null;
23052
- const absProjectDir = policy ? resolve12(policy.projectsDir, candidate) : resolve12(candidate);
23245
+ const absProjectDir = policy ? resolve13(policy.projectsDir, candidate) : resolve13(candidate);
23053
23246
  const shown = policy ? candidate : absProjectDir;
23054
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync15(absProjectDir).isDirectory()) {
23247
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync33(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
23055
23248
  return { error: `Project directory not found: ${shown}` };
23056
23249
  }
23057
23250
  const entry = options.entryFile || "index.html";
23058
- const entryPath = resolve12(absProjectDir, entry);
23059
- if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync32(entryPath)) {
23251
+ const entryPath = resolve13(absProjectDir, entry);
23252
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync33(entryPath)) {
23060
23253
  return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
23061
23254
  }
23062
23255
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
@@ -23076,9 +23269,9 @@ async function resolveInlineRenderHtml(body) {
23076
23269
  }
23077
23270
  }
23078
23271
  function materializeInlineProject(html, options) {
23079
- const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir5();
23080
- const tempProjectDir = mkdtempSync2(join49(tempRoot, "producer-project-"));
23081
- writeFileSync14(join49(tempProjectDir, "index.html"), html, "utf-8");
23272
+ const tempRoot = process.env.PRODUCER_TMP_PROJECT_DIR || tmpdir6();
23273
+ const tempProjectDir = mkdtempSync2(join51(tempRoot, "producer-project-"));
23274
+ writeFileSync14(join51(tempProjectDir, "index.html"), html, "utf-8");
23082
23275
  return {
23083
23276
  prepared: {
23084
23277
  input: { projectDir: tempProjectDir, ...options },
@@ -23106,7 +23299,7 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
23106
23299
  try {
23107
23300
  return resolveRenderPaths(projectDir, outputCandidate, rendersDir).absoluteOutputPath;
23108
23301
  } catch (error) {
23109
- const fallbackPath = resolve12(rendersDir, `producer-fallback-${Date.now()}.mp4`);
23302
+ const fallbackPath = resolve13(rendersDir, `producer-fallback-${Date.now()}.mp4`);
23110
23303
  log.warn("Failed to resolve output path, using fallback", {
23111
23304
  fallback: fallbackPath,
23112
23305
  error: error instanceof Error ? error.message : String(error)
@@ -23154,7 +23347,7 @@ function publicPerfSummary(job) {
23154
23347
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
23155
23348
  }
23156
23349
  function outputFileSize(path) {
23157
- return existsSync32(path) ? statSync15(path).size : 0;
23350
+ return existsSync33(path) ? statSync14(path).size : 0;
23158
23351
  }
23159
23352
  function createBlockingProgressReporter(log, requestId) {
23160
23353
  let lastLoggedPct = -10;
@@ -23274,7 +23467,7 @@ function createRenderHandlers(options = {}) {
23274
23467
  const lintProjectDir = nonEmptyString(body.projectDir);
23275
23468
  let isAllowedEntry;
23276
23469
  if (policy && lintProjectDir) {
23277
- const absProjectDir = resolve12(policy.projectsDir, lintProjectDir);
23470
+ const absProjectDir = resolve13(policy.projectsDir, lintProjectDir);
23278
23471
  if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) {
23279
23472
  const error = `Project directory not found: ${lintProjectDir}`;
23280
23473
  return c.json({ success: false, requestId, error }, 400);
@@ -23481,12 +23674,12 @@ function createRenderHandlers(options = {}) {
23481
23674
  if (!artifact) {
23482
23675
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
23483
23676
  }
23484
- if (!existsSync32(artifact.path)) {
23677
+ if (!existsSync33(artifact.path)) {
23485
23678
  store.delete(token);
23486
23679
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
23487
23680
  }
23488
- const stats = statSync15(artifact.path);
23489
- return new Response(createReadStream5(artifact.path), {
23681
+ const stats = statSync14(artifact.path);
23682
+ return new Response(createReadStream6(artifact.path), {
23490
23683
  headers: {
23491
23684
  "content-type": "video/mp4",
23492
23685
  "content-length": String(stats.size),
@@ -23646,7 +23839,7 @@ function startServer(options = {}) {
23646
23839
  process.on("SIGINT", () => shutdown("SIGINT"));
23647
23840
  return server;
23648
23841
  }
23649
- var entryScript = process.argv[1] ? resolve12(process.argv[1]) : "";
23842
+ var entryScript = process.argv[1] ? resolve13(process.argv[1]) : "";
23650
23843
  var isPublicServerEntry = entryScript.endsWith("/public-server.js") || entryScript.endsWith("/src/server.ts");
23651
23844
  if (isPublicServerEntry) {
23652
23845
  const { values } = parseArgs({
@@ -23671,8 +23864,8 @@ import { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes
23671
23864
 
23672
23865
  // src/services/distributed/planV2Execution.ts
23673
23866
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "node:fs";
23674
- import { tmpdir as tmpdir6 } from "node:os";
23675
- import { join as join51 } from "node:path";
23867
+ import { tmpdir as tmpdir7 } from "node:os";
23868
+ import { join as join53 } from "node:path";
23676
23869
 
23677
23870
  // src/services/distributed/assemble.ts
23678
23871
  import {
@@ -23681,18 +23874,19 @@ import {
23681
23874
  } from "@hyperframes/engine";
23682
23875
  import {
23683
23876
  cpSync as cpSync3,
23684
- existsSync as existsSync33,
23877
+ existsSync as existsSync34,
23685
23878
  mkdirSync as mkdirSync22,
23686
23879
  readFileSync as readFileSync17,
23687
23880
  readdirSync as readdirSync12,
23688
23881
  rmSync as rmSync20,
23689
- statSync as statSync16,
23882
+ statSync as statSync15,
23690
23883
  writeFileSync as writeFileSync15
23691
23884
  } from "node:fs";
23692
- import { basename as basename8, dirname as dirname22, join as join50 } from "node:path";
23885
+ import { basename as basename9, dirname as dirname22, join as join52 } from "node:path";
23693
23886
  import {
23694
23887
  appendRateCapArgs as appendRateCapArgs2,
23695
23888
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
23889
+ concatListInputArgs,
23696
23890
  describeFfmpegFailure as describeFfmpegFailure5,
23697
23891
  getEncoderPreset as getEncoderPreset6,
23698
23892
  MIXED_AUDIO_FILENAME as MIXED_AUDIO_FILENAME4,
@@ -23731,15 +23925,15 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23731
23925
  outputPath,
23732
23926
  durationMs: Date.now() - start,
23733
23927
  framesEncoded: plan2.totalFrames,
23734
- fileSize: statSync16(outputPath).size
23928
+ fileSize: statSync15(outputPath).size
23735
23929
  };
23736
23930
  }
23737
23931
  const format = plan2.dimensions.format;
23738
23932
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
23739
- if (!existsSync33(dirname22(outputPath))) {
23933
+ if (!existsSync34(dirname22(outputPath))) {
23740
23934
  mkdirSync22(dirname22(outputPath), { recursive: true });
23741
23935
  }
23742
- const workDir = createStagingDir7(dirname22(outputPath), `${basename8(outputPath)}.assemble-work-`);
23936
+ const workDir = createStagingDir7(dirname22(outputPath), `${basename9(outputPath)}.assemble-work-`);
23743
23937
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
23744
23938
  const stageMs = {};
23745
23939
  const ctx = {
@@ -23759,8 +23953,8 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23759
23953
  };
23760
23954
  try {
23761
23955
  const videoSources = cfrEncoder ? [await reencodeCfr(ctx, chunkPaths, cfrEncoder)] : chunkPaths;
23762
- const finalPath = join50(workDir, `output.${format}`);
23763
- const audio = audioPath !== null && existsSync33(audioPath) ? audioPath : null;
23956
+ const finalPath = join52(workDir, `output.${format}`);
23957
+ const audio = audioPath !== null && existsSync34(audioPath) ? audioPath : null;
23764
23958
  await writeJoined(ctx, videoSources, audio, finalPath);
23765
23959
  renameWithRetry11(finalPath, outputPath);
23766
23960
  log.info("[assemble] stage timings", {
@@ -23778,7 +23972,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23778
23972
  });
23779
23973
  }
23780
23974
  }
23781
- const fileSize = existsSync33(outputPath) ? statSync16(outputPath).size : 0;
23975
+ const fileSize = existsSync34(outputPath) ? statSync15(outputPath).size : 0;
23782
23976
  return {
23783
23977
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
23784
23978
  outputPath,
@@ -23788,15 +23982,15 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23788
23982
  };
23789
23983
  }
23790
23984
  function readAssemblePlan(planDir, chunkPaths) {
23791
- const planJsonPath = join50(planDir, "plan.json");
23792
- const chunksJsonPath = join50(planDir, "meta", "chunks.json");
23793
- if (!existsSync33(planJsonPath)) {
23985
+ const planJsonPath = join52(planDir, "plan.json");
23986
+ const chunksJsonPath = join52(planDir, "meta", "chunks.json");
23987
+ if (!existsSync34(planJsonPath)) {
23794
23988
  throw new Error(`[assemble] planDir missing plan.json: ${planJsonPath}`);
23795
23989
  }
23796
23990
  const plan2 = JSON.parse(readFileSync17(planJsonPath, "utf-8"));
23797
23991
  readPlanProtocolV1(plan2, DISTRIBUTED_RENDER_CAPABILITIES.roles.assembler);
23798
23992
  validatePlanV2MaterializedTarget(planDir, { role: "assembler" });
23799
- if (!existsSync33(chunksJsonPath)) {
23993
+ if (!existsSync34(chunksJsonPath)) {
23800
23994
  throw new Error(`[assemble] planDir missing meta/chunks.json: ${chunksJsonPath}`);
23801
23995
  }
23802
23996
  const chunks = JSON.parse(readFileSync17(chunksJsonPath, "utf-8"));
@@ -23811,7 +24005,7 @@ function readAssemblePlan(planDir, chunkPaths) {
23811
24005
  }
23812
24006
  }
23813
24007
  for (const path of chunkPaths.flat()) {
23814
- if (!existsSync33(path)) {
24008
+ if (!existsSync34(path)) {
23815
24009
  throw new Error(`[assemble] chunk path does not exist: ${path}`);
23816
24010
  }
23817
24011
  }
@@ -23840,7 +24034,7 @@ function cfrEncodeArgs(inputArgs, encoder, fpsArg) {
23840
24034
  return args;
23841
24035
  }
23842
24036
  async function reencodeCfr(ctx, chunkPaths, encoder) {
23843
- const cfrOutputPath = join50(ctx.workDir, `cfr.${ctx.format}`);
24037
+ const cfrOutputPath = join52(ctx.workDir, `cfr.${ctx.format}`);
23844
24038
  const cfrArgs = cfrEncodeArgs(videoInputArgs(ctx, chunkPaths), encoder, ctx.fpsArg);
23845
24039
  appendRenderProvenanceArgs2(cfrArgs, cfrOutputPath);
23846
24040
  cfrArgs.push("-y", cfrOutputPath);
@@ -23867,7 +24061,7 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
23867
24061
  );
23868
24062
  return;
23869
24063
  }
23870
- const paddedAudioPath = join50(ctx.workDir, "audio-padded.m4a");
24064
+ const paddedAudioPath = join52(ctx.workDir, "audio-padded.m4a");
23871
24065
  const padTrimResult = await ctx.timed(
23872
24066
  "audioMs",
23873
24067
  () => padOrTrimAudioToVideoFrameCount({
@@ -23907,11 +24101,11 @@ async function writeJoined(ctx, videoSources, audioPath, finalPath) {
23907
24101
  }
23908
24102
  }
23909
24103
  function concatDemuxerInput(chunkPaths, workDir, fpsArg) {
23910
- const listPath = join50(workDir, "concat-list.txt");
24104
+ const listPath = join52(workDir, "concat-list.txt");
23911
24105
  const body = chunkPaths.map((path) => `file '${path.replace(/'/g, "'\\''")}'`).join("\n");
23912
24106
  writeFileSync15(listPath, `${body}
23913
24107
  `, "utf-8");
23914
- return ["-r", fpsArg, "-f", "concat", "-safe", "0", "-i", listPath];
24108
+ return ["-r", fpsArg, ...concatListInputArgs(listPath)];
23915
24109
  }
23916
24110
  async function probeJoinedFrameInfo(videoPaths, fps, signal) {
23917
24111
  const infos = await Promise.all(
@@ -23945,12 +24139,12 @@ function stitchesSeparateAudio(planDir) {
23945
24139
  return lockedAudio(planDir).separateAudio === true;
23946
24140
  }
23947
24141
  function planFormat(planDir) {
23948
- const plan2 = JSON.parse(readFileSync17(join50(planDir, "plan.json"), "utf-8"));
24142
+ const plan2 = JSON.parse(readFileSync17(join52(planDir, "plan.json"), "utf-8"));
23949
24143
  return plan2.dimensions.format;
23950
24144
  }
23951
24145
  function lockedAudio(planDir) {
23952
- const encoderJsonPath = join50(planDir, "meta", "encoder.json");
23953
- if (!existsSync33(encoderJsonPath)) return {};
24146
+ const encoderJsonPath = join52(planDir, "meta", "encoder.json");
24147
+ if (!existsSync34(encoderJsonPath)) return {};
23954
24148
  return JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
23955
24149
  }
23956
24150
  function readCfrEncoder(planDir, format) {
@@ -23959,8 +24153,8 @@ function readCfrEncoder(planDir, format) {
23959
24153
  `[assemble] cfr=true is only supported for format="mp4" (got "${format}"). Stream-copy paths for webm and mov already produce exact avg_frame_rate; cfr re-encode is not needed.`
23960
24154
  );
23961
24155
  }
23962
- const encoderJsonPath = join50(planDir, "meta", "encoder.json");
23963
- if (!existsSync33(encoderJsonPath)) {
24156
+ const encoderJsonPath = join52(planDir, "meta", "encoder.json");
24157
+ if (!existsSync34(encoderJsonPath)) {
23964
24158
  throw new Error(`[assemble] planDir missing meta/encoder.json: ${encoderJsonPath}`);
23965
24159
  }
23966
24160
  const encoderJson = JSON.parse(readFileSync17(encoderJsonPath, "utf-8"));
@@ -23972,11 +24166,11 @@ function readCfrEncoder(planDir, format) {
23972
24166
  return encoderJson;
23973
24167
  }
23974
24168
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
23975
- if (existsSync33(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
24169
+ if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
23976
24170
  mkdirSync22(outputPath, { recursive: true });
23977
24171
  let globalIdx = 0;
23978
24172
  for (const chunkDir of chunkPaths) {
23979
- if (!statSync16(chunkDir).isDirectory()) {
24173
+ if (!statSync15(chunkDir).isDirectory()) {
23980
24174
  throw new Error(
23981
24175
  `[assemble] png-sequence chunk must be a directory: ${chunkDir} (got a file)`
23982
24176
  );
@@ -23986,8 +24180,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23986
24180
  throw new Error(`[assemble] png-sequence chunk has no frames: ${chunkDir}`);
23987
24181
  }
23988
24182
  for (const frame of frames) {
23989
- const dst = join50(outputPath, formatExportFrameName(globalIdx, "png"));
23990
- cpSync3(join50(chunkDir, frame), dst);
24183
+ const dst = join52(outputPath, formatExportFrameName(globalIdx, "png"));
24184
+ cpSync3(join52(chunkDir, frame), dst);
23991
24185
  globalIdx += 1;
23992
24186
  }
23993
24187
  }
@@ -23996,14 +24190,14 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23996
24190
  `[assemble] png-sequence frame count mismatch: merged ${globalIdx} frames vs plan.totalFrames=${totalFrames}. Using on-disk count.`
23997
24191
  );
23998
24192
  }
23999
- if (audioPath !== null && existsSync33(audioPath)) {
24000
- const sidecar = join50(outputPath, MIXED_AUDIO_FILENAME4);
24193
+ if (audioPath !== null && existsSync34(audioPath)) {
24194
+ const sidecar = join52(outputPath, MIXED_AUDIO_FILENAME4);
24001
24195
  cpSync3(audioPath, sidecar);
24002
24196
  }
24003
24197
  let fileSize = 0;
24004
24198
  for (const name of readdirSync12(outputPath)) {
24005
24199
  try {
24006
- fileSize += statSync16(join50(outputPath, name)).size;
24200
+ fileSize += statSync15(join52(outputPath, name)).size;
24007
24201
  } catch {
24008
24202
  }
24009
24203
  }
@@ -24017,8 +24211,8 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
24017
24211
 
24018
24212
  // src/services/distributed/planV2Execution.ts
24019
24213
  async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
24020
- const workRoot = mkdtempSync3(join51(tmpdir6(), "hf-plan-v2-chunk-"));
24021
- const materializedPlanDir = join51(workRoot, "plan");
24214
+ const workRoot = mkdtempSync3(join53(tmpdir7(), "hf-plan-v2-chunk-"));
24215
+ const materializedPlanDir = join53(workRoot, "plan");
24022
24216
  try {
24023
24217
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
24024
24218
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
@@ -24027,8 +24221,8 @@ async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
24027
24221
  }
24028
24222
  }
24029
24223
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
24030
- const workRoot = mkdtempSync3(join51(tmpdir6(), "hf-plan-v2-assembler-"));
24031
- const materializedPlanDir = join51(workRoot, "plan");
24224
+ const workRoot = mkdtempSync3(join53(tmpdir7(), "hf-plan-v2-assembler-"));
24225
+ const materializedPlanDir = join53(workRoot, "plan");
24032
24226
  try {
24033
24227
  const materialized = materializePlanV2Target(
24034
24228
  planV2Dir,