@hyperframes/producer 0.9.88 → 0.9.90

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
@@ -12,7 +12,7 @@ import {
12
12
  existsSync as existsSync22,
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
- rmSync as rmSync12,
15
+ rmSync as rmSync13,
16
16
  statSync as statSync10,
17
17
  writeFileSync as writeFileSync6,
18
18
  copyFileSync as copyFileSync5,
@@ -362,7 +362,7 @@ import {
362
362
  } from "@hyperframes/engine";
363
363
  import { join as join35, dirname as dirname15, resolve as resolve9 } from "path";
364
364
  import { totalmem as totalmem2 } from "node:os";
365
- import { randomUUID } from "crypto";
365
+ import { randomUUID as randomUUID3 } from "crypto";
366
366
  import { fileURLToPath as fileURLToPath5 } from "url";
367
367
 
368
368
  // src/services/fileServer.ts
@@ -546,11 +546,11 @@ var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (
546
546
  nodeResolve(fileURLToPath2(import.meta.url), "../../..", "renders");
547
547
  var LEADING_PARENT_SEGMENT_RE = /^\.\.(?:[\\/]|$)/;
548
548
  function isPathInside(childPath, parentPath, options = {}) {
549
- const resolvePath = options.pathModule?.resolve ?? nodeResolve;
549
+ const resolvePath2 = options.pathModule?.resolve ?? nodeResolve;
550
550
  const relativePath = options.pathModule?.relative ?? nodeRelative;
551
551
  const isPathAbsolute = options.pathModule?.isAbsolute ?? nodeIsAbsolute;
552
- const absChild = resolvePath(childPath);
553
- const absParent = resolvePath(parentPath);
552
+ const absChild = resolvePath2(childPath);
553
+ const absParent = resolvePath2(parentPath);
554
554
  if (absChild === absParent) return true;
555
555
  const rel = relativePath(absParent, absChild);
556
556
  return rel !== "" && !LEADING_PARENT_SEGMENT_RE.test(rel) && !isPathAbsolute(rel);
@@ -7134,7 +7134,7 @@ function requireOutputDimensions(expected, width, height) {
7134
7134
 
7135
7135
  // src/services/render/stages/compileStage.ts
7136
7136
  import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7137
- import { join as join23, relative as relative4 } from "node:path";
7137
+ import { join as join23, relative as relative5 } from "node:path";
7138
7138
  import { privateCacheRoot } from "@hyperframes/engine";
7139
7139
  import { suggestMatchingPreset } from "@hyperframes/core";
7140
7140
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -7142,8 +7142,8 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
7142
7142
  import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7143
7143
 
7144
7144
  // src/services/compileInWorker.ts
7145
- import { existsSync as existsSync12 } from "node:fs";
7146
- import { dirname as dirname10, join as join22 } from "node:path";
7145
+ import { existsSync as existsSync12, rmSync as rmSync11 } from "node:fs";
7146
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7147
7147
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7148
7148
  import { Worker } from "node:worker_threads";
7149
7149
 
@@ -7449,7 +7449,7 @@ import {
7449
7449
  } from "@hyperframes/core/fonts/embed";
7450
7450
 
7451
7451
  // src/services/animatedGifPrep.ts
7452
- import { createHash as createHash4 } from "node:crypto";
7452
+ import { createHash as createHash4, randomUUID } from "node:crypto";
7453
7453
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7454
7454
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7455
7455
  import { parseHTML as parseHTML3 } from "linkedom";
@@ -7524,6 +7524,8 @@ function resolveLoop(metadata, override) {
7524
7524
  }
7525
7525
  var MAX_LOOP_ITERATIONS = 1e3;
7526
7526
  var MAX_PAD_SECONDS = 3600;
7527
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
7528
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
7527
7529
  function resolveCompositionDurationSeconds(document2) {
7528
7530
  let max = null;
7529
7531
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -7566,7 +7568,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
7566
7568
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
7567
7569
  }
7568
7570
  function buildAnimatedGifTranscodeArgs(input) {
7569
- const args = ["-hide_banner", "-loglevel", "error"];
7571
+ const args = [
7572
+ "-hide_banner",
7573
+ "-loglevel",
7574
+ "error",
7575
+ "-timelimit",
7576
+ String(FFMPEG_SELF_CPU_SECONDS_CAP)
7577
+ ];
7570
7578
  if (input.loopIterations > 1) {
7571
7579
  args.push("-stream_loop", String(input.loopIterations - 1));
7572
7580
  }
@@ -7594,6 +7602,8 @@ function buildAnimatedGifTranscodeArgs(input) {
7594
7602
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
7595
7603
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
7596
7604
  // extension ffmpeg cannot infer the container from.
7605
+ "-fs",
7606
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
7597
7607
  "-f",
7598
7608
  "webm",
7599
7609
  "-y",
@@ -7601,10 +7611,16 @@ function buildAnimatedGifTranscodeArgs(input) {
7601
7611
  );
7602
7612
  return args;
7603
7613
  }
7614
+ function abortError() {
7615
+ const error = new Error("Aborted");
7616
+ error.name = "AbortError";
7617
+ return error;
7618
+ }
7604
7619
  async function runAnimatedGifTranscode(request) {
7605
7620
  const timeout = request.timeoutMs ?? 3e5;
7606
- const result = await runFfmpeg2(request.args, { timeout });
7621
+ const result = await runFfmpeg2(request.args, { timeout, signal: request.signal });
7607
7622
  if (result.success) return;
7623
+ if (request.signal?.aborted) throw abortError();
7608
7624
  if (result.failureReason === "external_interruption") {
7609
7625
  throw encoderFailureError("Animated GIF transcode failed", {
7610
7626
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -7624,7 +7640,7 @@ async function ensurePreparedWebm(input) {
7624
7640
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7625
7641
  }
7626
7642
  if (!isUsableFile(input.cachePath)) {
7627
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
7643
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
7628
7644
  const args = buildAnimatedGifTranscodeArgs({
7629
7645
  inputPath: input.sourcePath,
7630
7646
  outputPath: tmpPath,
@@ -7637,11 +7653,15 @@ async function ensurePreparedWebm(input) {
7637
7653
  inputPath: input.sourcePath,
7638
7654
  outputPath: tmpPath,
7639
7655
  args,
7640
- timeoutMs: input.timeoutMs
7656
+ timeoutMs: input.timeoutMs,
7657
+ signal: input.signal
7641
7658
  });
7642
7659
  if (!isUsableFile(tmpPath)) {
7643
7660
  throw new Error("Animated GIF transcode produced an empty output");
7644
7661
  }
7662
+ if (statSync6(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
7663
+ throw new Error("Animated GIF transcode reached its output size limit");
7664
+ }
7645
7665
  if (!isUsableFile(input.cachePath)) {
7646
7666
  renameWithRetry2(tmpPath, input.cachePath);
7647
7667
  } else {
@@ -7741,6 +7761,7 @@ async function prepareAnimatedGifInputs(html, options) {
7741
7761
  loopIterations,
7742
7762
  padSeconds,
7743
7763
  timeoutMs: options.timeoutMs,
7764
+ signal: options.signal,
7744
7765
  transcode: options.transcode
7745
7766
  });
7746
7767
  const id = ensureElementId(img, document2, i);
@@ -7765,7 +7786,7 @@ async function prepareAnimatedGifInputs(html, options) {
7765
7786
  }
7766
7787
 
7767
7788
  // src/services/heifImagePrep.ts
7768
- import { createHash as createHash5 } from "node:crypto";
7789
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7769
7790
  import {
7770
7791
  closeSync as closeSync5,
7771
7792
  copyFileSync as copyFileSync3,
@@ -7911,6 +7932,13 @@ var HeifToolUnavailableError = class extends Error {
7911
7932
  this.name = "HeifToolUnavailableError";
7912
7933
  }
7913
7934
  };
7935
+ function abortError2() {
7936
+ const error = new Error("Aborted");
7937
+ error.name = "AbortError";
7938
+ return error;
7939
+ }
7940
+ var FFMPEG_SELF_CPU_SECONDS_CAP2 = 300;
7941
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP2 = 256 * 1024 * 1024;
7914
7942
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
7915
7943
  function isHeifBytes(head) {
7916
7944
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -7978,6 +8006,8 @@ async function convertHeifToJpeg(request) {
7978
8006
  "-hide_banner",
7979
8007
  "-loglevel",
7980
8008
  "error",
8009
+ "-timelimit",
8010
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
7981
8011
  ...urlInputArgs3(request.inputPath),
7982
8012
  "-i",
7983
8013
  request.inputPath,
@@ -7986,14 +8016,17 @@ async function convertHeifToJpeg(request) {
7986
8016
  "1",
7987
8017
  "-q:v",
7988
8018
  "2",
8019
+ "-fs",
8020
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
7989
8021
  "-f",
7990
8022
  "mjpeg",
7991
8023
  "-y",
7992
8024
  request.outputPath
7993
8025
  ],
7994
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
8026
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
7995
8027
  );
7996
8028
  if (!result.success) {
8029
+ if (request.signal?.aborted) throw abortError2();
7997
8030
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
7998
8031
  }
7999
8032
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -8027,7 +8060,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8027
8060
  mkdirSync8(dirname7(cachePath), { recursive: true });
8028
8061
  mkdirSync8(dirname7(outputPath), { recursive: true });
8029
8062
  if (!isUsableFile2(cachePath)) {
8030
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
8063
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8031
8064
  const inlinePath = `${tmpPath}.heic`;
8032
8065
  const inputPath = source.path ?? inlinePath;
8033
8066
  try {
@@ -8035,9 +8068,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8035
8068
  await (options.transcode ?? convertHeifToJpeg)({
8036
8069
  inputPath,
8037
8070
  outputPath: tmpPath,
8038
- timeoutMs: options.timeoutMs
8071
+ timeoutMs: options.timeoutMs,
8072
+ signal: options.signal
8039
8073
  });
8040
8074
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
8075
+ if (statSync7(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP2) {
8076
+ throw new Error("conversion reached its output size limit");
8077
+ }
8041
8078
  renameWithRetry3(tmpPath, cachePath);
8042
8079
  } catch (error) {
8043
8080
  const reason = error instanceof Error ? error.message : String(error);
@@ -8108,6 +8145,7 @@ import {
8108
8145
  isNotImagePayload,
8109
8146
  isNotMediaPayload,
8110
8147
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
8148
+ isStructurallyIncompletePngError,
8111
8149
  playlistLeavesItsFolder,
8112
8150
  NotMediaPayloadError,
8113
8151
  probeMediaProfile,
@@ -8186,6 +8224,13 @@ async function notMediaReferences(path, references) {
8186
8224
  if (images.length > 0 && await isNotImagePayload(path)) return images;
8187
8225
  return await playlistLeavesItsFolder(path) ? references : [];
8188
8226
  }
8227
+ function pngCutShort(references) {
8228
+ return references.filter((reference) => reference.expected === "video").map((reference) => ({
8229
+ expected: "video",
8230
+ detected: "image",
8231
+ elementFingerprint: fingerprintElementId(reference.id)
8232
+ }));
8233
+ }
8189
8234
  async function preflightCompositionAssetMediaTypes(input) {
8190
8235
  const references = [
8191
8236
  ...input.composition.videos.map((asset) => ({
@@ -8231,6 +8276,8 @@ async function preflightCompositionAssetMediaTypes(input) {
8231
8276
  profile = await probeMediaProfile(resolvedPath, { signal: input.signal });
8232
8277
  } catch (error) {
8233
8278
  if (input.signal?.aborted) throw input.signal.reason ?? error;
8279
+ if (isStructurallyIncompletePngError(error))
8280
+ mismatches.push(...pngCutShort(pathReferences));
8234
8281
  return;
8235
8282
  }
8236
8283
  for (const reference of pathReferences) {
@@ -9574,8 +9621,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9574
9621
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
9575
9622
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9576
9623
  if (fontFaceBlocks.length === 0) return;
9624
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9577
9625
  const inlineStyle = `<style>/* Inlined external font stylesheet */
9578
- ${fontFaceBlocks.join("\n")}
9626
+ ${fontCssWithLtAsCssEscape}
9579
9627
  </style>`;
9580
9628
  try {
9581
9629
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -9661,7 +9709,16 @@ function localizeFontFaceUrls(html, downloadDir, assets) {
9661
9709
  "Remote font download failed",
9662
9710
  "Localized remote font face(s)",
9663
9711
  assets,
9664
- (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9712
+ (h, url, relPath) => replaceMatches(
9713
+ h,
9714
+ styleBlockMatches(h),
9715
+ (style, css) => replaceInner(
9716
+ style,
9717
+ css,
9718
+ "</style>".length,
9719
+ css.replaceAll(`url(${url})`, `url("${relPath}")`)
9720
+ )
9721
+ )
9665
9722
  );
9666
9723
  }
9667
9724
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
@@ -9841,7 +9898,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9841
9898
  return document2.toString();
9842
9899
  }
9843
9900
  var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
9844
- var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
9901
+ var MEDIA_SRC_NON_URL_CHARS = /[\u0000-\u001f\u007f<>]/;
9845
9902
  function bindVariableMediaSources(html, variables, budget, log) {
9846
9903
  if (!html.includes("data-var-src")) return html;
9847
9904
  const { document: document2 } = parseHTML5(html);
@@ -9856,7 +9913,7 @@ function bindVariableMediaSources(html, variables, budget, log) {
9856
9913
  const bound = boundMediaSrc(el, values);
9857
9914
  if (bound === null) continue;
9858
9915
  const src = bound.trim();
9859
- if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
9916
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_NON_URL_CHARS.test(src)) {
9860
9917
  log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
9861
9918
  length: src.length
9862
9919
  });
@@ -9991,6 +10048,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
9991
10048
  cacheDir: options.animatedGifCacheDir,
9992
10049
  sourceAssets: remoteImageAssets,
9993
10050
  timeoutMs: options.ffmpegProcessTimeout,
10051
+ signal: options.abortSignal,
9994
10052
  allowOutsideFiles: assetRoot === void 0
9995
10053
  });
9996
10054
  if (preparedHeifImages.length > 0) {
@@ -10007,6 +10065,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10007
10065
  cacheDir: options.animatedGifCacheDir,
10008
10066
  sourceAssets: gifSourceAssets,
10009
10067
  timeoutMs: options.ffmpegProcessTimeout,
10068
+ signal: options.abortSignal,
10010
10069
  allowOutsideFiles: assetRoot === void 0
10011
10070
  });
10012
10071
  if (preparedGifs.length > 0) {
@@ -10485,6 +10544,24 @@ function compileTimeoutMs() {
10485
10544
  return Number.isInteger(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_COMPILE_TIMEOUT_MS;
10486
10545
  }
10487
10546
  var warnedMissingEntry = false;
10547
+ var endOnProcessExit = /* @__PURE__ */ new Set();
10548
+ var processExitHooked = false;
10549
+ function onProcessExit(end) {
10550
+ if (!processExitHooked) {
10551
+ processExitHooked = true;
10552
+ process.on("exit", () => {
10553
+ for (const each of endOnProcessExit) each();
10554
+ });
10555
+ }
10556
+ endOnProcessExit.add(end);
10557
+ return () => endOnProcessExit.delete(end);
10558
+ }
10559
+ function tryQuietly(action) {
10560
+ try {
10561
+ action();
10562
+ } catch {
10563
+ }
10564
+ }
10488
10565
  function resolveCompileWorkerEntry(explicit, log) {
10489
10566
  if (explicit) return explicit;
10490
10567
  const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
@@ -10518,6 +10595,26 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10518
10595
  const thread = new Worker(entry, {
10519
10596
  workerData: { projectDir, htmlPath, downloadDir, options: cloneable }
10520
10597
  });
10598
+ const children = /* @__PURE__ */ new Map();
10599
+ const scratchRoots = [downloadDir, options.animatedGifCacheDir].flatMap(
10600
+ (dir) => dir ? [resolvePath(dir)] : []
10601
+ );
10602
+ const isScratch = (path) => scratchRoots.some((root) => {
10603
+ const rel = relative4(root, resolvePath(path));
10604
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute4(rel);
10605
+ });
10606
+ const endChildren = (signal) => {
10607
+ for (const [pid, output] of children) {
10608
+ if (signal) tryQuietly(() => process.kill(pid, "SIGKILL"));
10609
+ if (output) tryQuietly(() => rmSync11(output, { force: true }));
10610
+ }
10611
+ children.clear();
10612
+ };
10613
+ const offProcessExit = onProcessExit(() => endChildren(true));
10614
+ const endThread = () => {
10615
+ endChildren(true);
10616
+ void thread.terminate();
10617
+ };
10521
10618
  let settled = false;
10522
10619
  const settle = (finish) => {
10523
10620
  if (settled) return;
@@ -10528,7 +10625,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10528
10625
  };
10529
10626
  const stop = () => {
10530
10627
  thread.postMessage({ type: "abort" });
10531
- setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
10628
+ setTimeout(endThread, TERMINATE_GRACE_MS).unref();
10532
10629
  };
10533
10630
  const timer = setTimeout(() => {
10534
10631
  stop();
@@ -10541,7 +10638,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10541
10638
  abortSignal?.addEventListener("abort", onAbort, { once: true });
10542
10639
  const retire = (graceMs) => {
10543
10640
  thread.unref();
10544
- setTimeout(() => void thread.terminate(), graceMs).unref();
10641
+ setTimeout(endThread, graceMs).unref();
10545
10642
  };
10546
10643
  thread.on(
10547
10644
  "message",
@@ -10560,13 +10657,22 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10560
10657
  }
10561
10658
  }
10562
10659
  );
10563
- thread.on("error", (error) => settle(() => reject(error)));
10564
10660
  thread.on(
10565
- "exit",
10566
- (code) => settle(
10567
- () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10568
- )
10661
+ "message",
10662
+ ({ type, pid, output }) => {
10663
+ if (pid === void 0) return;
10664
+ if (type === "child") children.set(pid, output && isScratch(output) ? output : void 0);
10665
+ else if (type === "childExit") children.delete(pid);
10666
+ }
10569
10667
  );
10668
+ thread.on("error", (error) => settle(() => reject(error)));
10669
+ thread.on("exit", (code) => {
10670
+ offProcessExit();
10671
+ endChildren(false);
10672
+ settle(
10673
+ () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10674
+ );
10675
+ });
10570
10676
  });
10571
10677
  }
10572
10678
 
@@ -10596,10 +10702,10 @@ function resolveEntryHtmlPath(input) {
10596
10702
  const readEntry = (path) => {
10597
10703
  if (escapesAssetRoot(path, input.assetRoot)) {
10598
10704
  throw new Error(
10599
- `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10705
+ `Entry file "${relative5(projectDir, path)}" leads outside the project folder`
10600
10706
  );
10601
10707
  }
10602
- assertCompositionFileSize2(path, relative4(projectDir, path));
10708
+ assertCompositionFileSize2(path, relative5(projectDir, path));
10603
10709
  return readTextFile2(path);
10604
10710
  };
10605
10711
  const htmlPath = join23(projectDir, entryFile);
@@ -14401,7 +14507,7 @@ import {
14401
14507
  mkdirSync as mkdirSync11,
14402
14508
  readdirSync as readdirSync5,
14403
14509
  readFileSync as readFileSync9,
14404
- rmSync as rmSync11,
14510
+ rmSync as rmSync12,
14405
14511
  statSync as statSync9,
14406
14512
  writeFileSync as writeFileSync5
14407
14513
  } from "node:fs";
@@ -14540,7 +14646,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14540
14646
  fileSize
14541
14647
  };
14542
14648
  } finally {
14543
- rmSync11(input.palettePath, { force: true });
14649
+ rmSync12(input.palettePath, { force: true });
14544
14650
  }
14545
14651
  }
14546
14652
  function startEncodeProgress(job, stage, onProgress) {
@@ -15419,7 +15525,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15419
15525
  function createRenderJob(config) {
15420
15526
  return {
15421
15527
  ...referenceBackgroundResult(void 0),
15422
- id: randomUUID(),
15528
+ id: randomUUID3(),
15423
15529
  config: {
15424
15530
  ...config,
15425
15531
  fps: toFps2(config.fps),
@@ -15934,7 +16040,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15934
16040
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
15935
16041
  return;
15936
16042
  }
15937
- rmSync12(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
16043
+ rmSync13(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
15938
16044
  });
15939
16045
  try {
15940
16046
  await executeRenderPipeline({
@@ -17402,7 +17508,7 @@ async function executeRenderPipeline(input) {
17402
17508
  segmentDir
17403
17509
  });
17404
17510
  }
17405
- if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
17511
+ if (completedSegments.size === 0) rmSync13(segmentDir, { recursive: true, force: true });
17406
17512
  const invokeSegmented = () => {
17407
17513
  if (capturePlan.kind !== "sdr_segmented") {
17408
17514
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17495,7 +17601,7 @@ async function executeRenderPipeline(input) {
17495
17601
  probeSession = null;
17496
17602
  await closeOrphanedProbeForRetry(orphaned, closeCaptureSession8, log, "segmented");
17497
17603
  }
17498
- rmSync12(segmentDir, { recursive: true, force: true });
17604
+ rmSync13(segmentDir, { recursive: true, force: true });
17499
17605
  completedSegments = /* @__PURE__ */ new Set();
17500
17606
  segmentManifest = emptySegmentManifest();
17501
17607
  dedupPerfs.length = 0;
@@ -17534,7 +17640,7 @@ async function executeRenderPipeline(input) {
17534
17640
  );
17535
17641
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
17536
17642
  if (job.config.keepSegments !== true) {
17537
- rmSync12(segmentDir, { recursive: true, force: true });
17643
+ rmSync13(segmentDir, { recursive: true, force: true });
17538
17644
  }
17539
17645
  } else {
17540
17646
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -17811,7 +17917,7 @@ async function executeRenderPipeline(input) {
17811
17917
  "capture_disk",
17812
17918
  "drawElement capture failed; retrying with a fresh screenshot session"
17813
17919
  );
17814
- rmSync12(framesDir, { recursive: true, force: true });
17920
+ rmSync13(framesDir, { recursive: true, force: true });
17815
17921
  mkdirSync12(framesDir, { recursive: true });
17816
17922
  resetCaptureAttemptProgress(job);
17817
17923
  dedupPerfs.length = 0;
@@ -18119,12 +18225,12 @@ import {
18119
18225
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD4,
18120
18226
  referenceBackgroundResult as referenceBackgroundResult6
18121
18227
  } from "@hyperframes/engine";
18122
- import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync18 } from "node:fs";
18228
+ import { mkdirSync as mkdirSync20, mkdtempSync, readFileSync as readFileSync15, rmSync as rmSync19 } from "node:fs";
18123
18229
  import { join as join49 } from "node:path";
18124
18230
  import { tmpdir as tmpdir5 } from "node:os";
18125
18231
 
18126
18232
  // src/services/distributed/mp4Stitch.ts
18127
- import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
18233
+ import { createReadStream as createReadStream4, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync14 } from "node:fs";
18128
18234
  import { open } from "node:fs/promises";
18129
18235
  import { renameWithRetry as renameWithRetry6 } from "@hyperframes/engine";
18130
18236
  import { basename as basename8, dirname as dirname16, join as join36 } from "node:path";
@@ -18503,7 +18609,7 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
18503
18609
  renameWithRetry6(join36(workDir, "out.mp4"), outputPath);
18504
18610
  } finally {
18505
18611
  out.destroy();
18506
- rmSync13(workDir, { recursive: true, force: true });
18612
+ rmSync14(workDir, { recursive: true, force: true });
18507
18613
  }
18508
18614
  }
18509
18615
 
@@ -18520,10 +18626,10 @@ import {
18520
18626
  existsSync as existsSync27,
18521
18627
  linkSync,
18522
18628
  mkdirSync as mkdirSync16,
18523
- rmSync as rmSync14,
18629
+ rmSync as rmSync15,
18524
18630
  writeFileSync as writeFileSync9
18525
18631
  } from "node:fs";
18526
- import { extname as extname6, isAbsolute as isAbsolute4, join as join44, relative as relative7, sep as sep5 } from "node:path";
18632
+ import { extname as extname6, isAbsolute as isAbsolute5, join as join44, relative as relative8, sep as sep5 } from "node:path";
18527
18633
  import {
18528
18634
  fpsToNumber as fpsToNumber9,
18529
18635
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -19197,7 +19303,7 @@ async function readPlanReferenceBackground(input) {
19197
19303
 
19198
19304
  // src/services/render/stages/freezePlan.ts
19199
19305
  import { existsSync as existsSync25, mkdirSync as mkdirSync14, readFileSync as readFileSync11, readdirSync as readdirSync8, writeFileSync as writeFileSync7 } from "node:fs";
19200
- import { join as join41, relative as relative5, resolve as resolve10 } from "node:path";
19306
+ import { join as join41, relative as relative6, resolve as resolve10 } from "node:path";
19201
19307
  import {
19202
19308
  REFERENCE_BACKGROUND_FIELD,
19203
19309
  referenceBackgroundResult as referenceBackgroundResult3
@@ -19420,7 +19526,7 @@ function listPlanFiles(planDir) {
19420
19526
  walk(full);
19421
19527
  } else if (entry.isFile()) {
19422
19528
  results.push({
19423
- planRelativePath: relative5(rootResolved, full).split(/[\\/]+/).join("/"),
19529
+ planRelativePath: relative6(rootResolved, full).split(/[\\/]+/).join("/"),
19424
19530
  absolutePath: full
19425
19531
  });
19426
19532
  }
@@ -19756,7 +19862,7 @@ async function muxChunkWithAudio(input) {
19756
19862
  // src/services/distributed/planSize.ts
19757
19863
  import { createHash as createHash9 } from "node:crypto";
19758
19864
  import { lstatSync as lstatSync4, readdirSync as readdirSync9 } from "node:fs";
19759
- import { extname as extname5, join as join43, relative as relative6 } from "node:path";
19865
+ import { extname as extname5, join as join43, relative as relative7 } from "node:path";
19760
19866
  var MAX_TOP_COMPONENTS = 10;
19761
19867
  var SOURCE_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
19762
19868
  ".aac",
@@ -19845,7 +19951,7 @@ function recordFile(result, components, rootDir, rootKind, filePath) {
19845
19951
  } catch {
19846
19952
  return;
19847
19953
  }
19848
- const rel = relative6(rootDir, filePath);
19954
+ const rel = relative7(rootDir, filePath);
19849
19955
  const segments = rel.split(/[\\/]+/).filter(Boolean);
19850
19956
  const classified = classifyFile(segments, rootKind);
19851
19957
  result.totalBytes += sizeBytes;
@@ -20090,7 +20196,7 @@ var FREEZE_OWNED_PLAN_FILES = [
20090
20196
  ];
20091
20197
  function removeFreezeOwnedPlanFiles(planDir) {
20092
20198
  for (const relativePath of FREEZE_OWNED_PLAN_FILES) {
20093
- rmSync14(join44(planDir, relativePath), { force: true });
20199
+ rmSync15(join44(planDir, relativePath), { force: true });
20094
20200
  }
20095
20201
  }
20096
20202
  function buildChunkSlices(totalFrames, chunkCount, effectiveChunkSize) {
@@ -20229,10 +20335,10 @@ function resolveDistributedEngineConfig(config) {
20229
20335
  };
20230
20336
  }
20231
20337
  function leavesRoot(rel) {
20232
- return rel === ".." || rel.startsWith(`..${sep5}`) || isAbsolute4(rel);
20338
+ return rel === ".." || rel.startsWith(`..${sep5}`) || isAbsolute5(rel);
20233
20339
  }
20234
20340
  function pathInside(root, path) {
20235
- const rel = relative7(root, path);
20341
+ const rel = relative8(root, path);
20236
20342
  return rel === "" || leavesRoot(rel) ? null : rel;
20237
20343
  }
20238
20344
  function stableSourcePath(roots, srcPath) {
@@ -20319,7 +20425,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20319
20425
  throw new Error(`[plan] entry file not found: ${htmlPath}`);
20320
20426
  }
20321
20427
  const workDir = join44(planDir, ".plan-work");
20322
- rmSync14(workDir, { recursive: true, force: true });
20428
+ rmSync15(workDir, { recursive: true, force: true });
20323
20429
  mkdirSync16(workDir, { recursive: true });
20324
20430
  const compiledDir = join44(workDir, "compiled");
20325
20431
  mkdirSync16(compiledDir, { recursive: true });
@@ -20328,7 +20434,7 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
20328
20434
  recursive: true,
20329
20435
  dereference: true,
20330
20436
  filter: (src) => {
20331
- const rel = relative7(projectDir, src);
20437
+ const rel = relative8(projectDir, src);
20332
20438
  if (rel === "") return true;
20333
20439
  if (leavesRoot(rel)) return false;
20334
20440
  if (job.config.allowOutsideProjectAssets) {
@@ -20551,15 +20657,15 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20551
20657
  logPlanStage(log, "extract", stageStarted);
20552
20658
  const stagedVideoFrames = join44(compiledDir, "__hyperframes_video_frames");
20553
20659
  const videoFramesDst = join44(planDir, "video-frames");
20554
- if (existsSync27(videoFramesDst)) rmSync14(videoFramesDst, { recursive: true, force: true });
20660
+ if (existsSync27(videoFramesDst)) rmSync15(videoFramesDst, { recursive: true, force: true });
20555
20661
  const videoSourcesDir = join44(planDir, "video-sources");
20556
- rmSync14(videoSourcesDir, { recursive: true, force: true });
20662
+ rmSync15(videoSourcesDir, { recursive: true, force: true });
20557
20663
  if (existsSync27(stagedVideoFrames)) {
20558
20664
  renameWithRetry7(stagedVideoFrames, videoFramesDst);
20559
20665
  } else {
20560
20666
  mkdirSync16(videoFramesDst, { recursive: true });
20561
20667
  }
20562
- if (existsSync27(finalCompiledDir)) rmSync14(finalCompiledDir, { recursive: true, force: true });
20668
+ if (existsSync27(finalCompiledDir)) rmSync15(finalCompiledDir, { recursive: true, force: true });
20563
20669
  renameWithRetry7(compiledDir, finalCompiledDir);
20564
20670
  const shipVideoSource = createVideoSourceShipper({
20565
20671
  planDir,
@@ -20729,7 +20835,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
20729
20835
  format: config.format
20730
20836
  };
20731
20837
  try {
20732
- rmSync14(workDir, { recursive: true, force: true });
20838
+ rmSync15(workDir, { recursive: true, force: true });
20733
20839
  } catch (err) {
20734
20840
  log.warn("[plan] failed to remove temp work dir", {
20735
20841
  workDir,
@@ -20805,7 +20911,7 @@ async function plan(projectDir, config, planDir, options = {}) {
20805
20911
 
20806
20912
  // src/services/distributed/renderChunk.ts
20807
20913
  import { randomBytes } from "node:crypto";
20808
- import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync17, writeFileSync as writeFileSync12 } from "node:fs";
20914
+ import { existsSync as existsSync30, mkdirSync as mkdirSync19, readFileSync as readFileSync14, readdirSync as readdirSync11, rmSync as rmSync18, writeFileSync as writeFileSync12 } from "node:fs";
20809
20915
  import { join as join48 } from "node:path";
20810
20916
  import {
20811
20917
  assertSwiftShader,
@@ -20837,12 +20943,12 @@ import {
20837
20943
  mkdirSync as mkdirSync18,
20838
20944
  readFileSync as readFileSync13,
20839
20945
  readdirSync as readdirSync10,
20840
- rmSync as rmSync16,
20946
+ rmSync as rmSync17,
20841
20947
  statSync as statSync12,
20842
20948
  writeFileSync as writeFileSync11
20843
20949
  } from "node:fs";
20844
20950
  import { tmpdir as tmpdir4 } from "node:os";
20845
- import { dirname as dirname19, isAbsolute as isAbsolute5, join as join47, relative as relative8, resolve as resolve11, sep as sep6 } from "node:path";
20951
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join47, relative as relative9, resolve as resolve11, sep as sep6 } from "node:path";
20846
20952
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
20847
20953
  import {
20848
20954
  createFrameLookupTable as createFrameLookupTable5,
@@ -20856,7 +20962,7 @@ import {
20856
20962
  existsSync as existsSync28,
20857
20963
  linkSync as linkSync2,
20858
20964
  mkdirSync as mkdirSync17,
20859
- rmSync as rmSync15,
20965
+ rmSync as rmSync16,
20860
20966
  statSync as statSync11,
20861
20967
  writeFileSync as writeFileSync10
20862
20968
  } from "node:fs";
@@ -20947,7 +21053,7 @@ var LocalPlanV2ArtifactPublisher = class {
20947
21053
  }
20948
21054
  renameWithRetry8(temporaryPath, destinationPath);
20949
21055
  } finally {
20950
- rmSync15(stagingDir, { recursive: true, force: true });
21056
+ rmSync16(stagingDir, { recursive: true, force: true });
20951
21057
  }
20952
21058
  }
20953
21059
  async commitManifest(manifestBytes) {
@@ -20964,7 +21070,7 @@ var LocalPlanV2ArtifactPublisher = class {
20964
21070
  }
20965
21071
  async abort() {
20966
21072
  if (!this.#committed) {
20967
- rmSync15(this.temporaryDir, { recursive: true, force: true });
21073
+ rmSync16(this.temporaryDir, { recursive: true, force: true });
20968
21074
  }
20969
21075
  }
20970
21076
  };
@@ -20995,7 +21101,7 @@ function readJsonFile(path, label) {
20995
21101
  }
20996
21102
  function assertSafeRelativePath(path) {
20997
21103
  const normalized = path.split(/[\\/]+/);
20998
- if (path.length === 0 || isAbsolute5(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
21104
+ if (path.length === 0 || isAbsolute6(path) || normalized.some((part) => part === "" || part === "." || part === "..")) {
20999
21105
  throw new PlanV2IntegrityError(`unsafe artifact path: ${JSON.stringify(path)}`);
21000
21106
  }
21001
21107
  }
@@ -21009,7 +21115,7 @@ function listFiles(root) {
21009
21115
  walk(absolutePath);
21010
21116
  } else if (entry.isFile()) {
21011
21117
  files.push({
21012
- path: relative8(rootResolved, absolutePath).split(sep6).join("/"),
21118
+ path: relative9(rootResolved, absolutePath).split(sep6).join("/"),
21013
21119
  absolutePath
21014
21120
  });
21015
21121
  } else {
@@ -21209,7 +21315,7 @@ function collectChunkVideoDependencies(input) {
21209
21315
  for (let frame = chunk.startFrame; frame < chunk.endFrame; frame++) {
21210
21316
  const globalTime = frame * input.fpsDen / input.fpsNum;
21211
21317
  for (const [videoId, payload] of input.table.getActiveFramePayloads(globalTime)) {
21212
- const path = input.deferredSources.get(videoId) ?? relative8(resolve11(input.executionPlanDir), payload.framePath).split(sep6).join("/");
21318
+ const path = input.deferredSources.get(videoId) ?? relative9(resolve11(input.executionPlanDir), payload.framePath).split(sep6).join("/");
21213
21319
  assertSafeRelativePath(path);
21214
21320
  const indexes = mutable.get(path) ?? /* @__PURE__ */ new Set();
21215
21321
  indexes.add(chunk.index);
@@ -21234,7 +21340,7 @@ function writeBlob(sourcePath, destinationPath) {
21234
21340
  copyFileSync8(sourcePath, temporaryPath);
21235
21341
  renameWithRetry9(temporaryPath, destinationPath);
21236
21342
  } finally {
21237
- rmSync16(temporaryDir, { recursive: true, force: true });
21343
+ rmSync17(temporaryDir, { recursive: true, force: true });
21238
21344
  }
21239
21345
  }
21240
21346
  function publishBlobFor(absolutePath, digests) {
@@ -21367,7 +21473,7 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
21367
21473
  renameWithRetry9(tempDir, planV2Dir);
21368
21474
  return resultFromManifest(planV2Dir, publication.manifest);
21369
21475
  } catch (error) {
21370
- rmSync16(tempDir, { recursive: true, force: true });
21476
+ rmSync17(tempDir, { recursive: true, force: true });
21371
21477
  throw error;
21372
21478
  }
21373
21479
  }
@@ -21432,7 +21538,7 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
21432
21538
  }
21433
21539
  throw error;
21434
21540
  } finally {
21435
- rmSync16(stagingRoot, { recursive: true, force: true });
21541
+ rmSync17(stagingRoot, { recursive: true, force: true });
21436
21542
  }
21437
21543
  }
21438
21544
  async function planV2(projectDir, config, planV2Dir) {
@@ -21654,7 +21760,7 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
21654
21760
  );
21655
21761
  renameWithRetry9(tempDir, destinationDir);
21656
21762
  } catch (error) {
21657
- rmSync16(tempDir, { recursive: true, force: true });
21763
+ rmSync17(tempDir, { recursive: true, force: true });
21658
21764
  throw error;
21659
21765
  }
21660
21766
  return {
@@ -22289,7 +22395,7 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22289
22395
  return observedChunkCaptureMode(capturePerfs);
22290
22396
  },
22291
22397
  resetForScreenshotRetry: () => {
22292
- rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22398
+ rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22293
22399
  boxesMeasured();
22294
22400
  mkdirSync19(framesDir, { recursive: true });
22295
22401
  capturePerfs.length = 0;
@@ -22335,8 +22441,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22335
22441
  fps: { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen },
22336
22442
  timeoutMs: cfg.ffmpegProcessTimeout
22337
22443
  });
22338
- rmSync17(videoOnlyPath, { force: true });
22339
- rmSync17(audioScratchPath, { force: true });
22444
+ rmSync18(videoOnlyPath, { force: true });
22445
+ rmSync18(audioScratchPath, { force: true });
22340
22446
  }
22341
22447
  encodeStageMs = Date.now() - encodeStarted;
22342
22448
  } finally {
@@ -22386,8 +22492,8 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
22386
22492
  writeFileSync12(perfPath, `${JSON.stringify(perfPayload, null, 2)}
22387
22493
  `, "utf-8");
22388
22494
  try {
22389
- rmSync17(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22390
- rmSync17(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22495
+ rmSync18(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22496
+ rmSync18(videoFramesDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
22391
22497
  } catch (err) {
22392
22498
  log.warn("[renderChunk] failed to remove work dir", {
22393
22499
  workDir,
@@ -22491,7 +22597,7 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
22491
22597
  framesEncoded: endFrame - startFrame
22492
22598
  };
22493
22599
  } finally {
22494
- rmSync18(workDir, { recursive: true, force: true });
22600
+ rmSync19(workDir, { recursive: true, force: true });
22495
22601
  }
22496
22602
  }
22497
22603
 
@@ -23135,15 +23241,20 @@ import {
23135
23241
 
23136
23242
  // src/server.ts
23137
23243
  import {
23244
+ closeSync as closeSync9,
23245
+ constants as fsConstants,
23138
23246
  existsSync as existsSync33,
23247
+ fstatSync as fstatSync5,
23248
+ lstatSync as lstatSync6,
23139
23249
  mkdirSync as mkdirSync21,
23250
+ openSync as openSync9,
23140
23251
  statSync as statSync14,
23141
23252
  mkdtempSync as mkdtempSync2,
23142
23253
  writeFileSync as writeFileSync13,
23143
- rmSync as rmSync19,
23254
+ rmSync as rmSync20,
23144
23255
  createReadStream as createReadStream6
23145
23256
  } from "node:fs";
23146
- import { resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23257
+ import { basename as basename9, resolve as resolve13, dirname as dirname22, join as join52 } from "node:path";
23147
23258
  import { tmpdir as tmpdir6 } from "node:os";
23148
23259
  import { parseArgs } from "node:util";
23149
23260
  import { isIP } from "node:net";
@@ -23157,6 +23268,7 @@ import {
23157
23268
  referenceBackgroundResult as referenceBackgroundResult7
23158
23269
  } from "@hyperframes/engine";
23159
23270
  import { isSafePath as isSafePath4 } from "@hyperframes/core/safe-path";
23271
+ import { foreignWritablePath } from "@hyperframes/core/cache-dir";
23160
23272
 
23161
23273
  // src/services/hyperframeLint.ts
23162
23274
  import {
@@ -23168,7 +23280,7 @@ import {
23168
23280
  closeSync as closeSync8,
23169
23281
  constants as constants4
23170
23282
  } from "node:fs";
23171
- import { resolve as resolve12, join as join50, relative as relative9, isAbsolute as isAbsolute6, sep as sep7, dirname as dirname20 } from "node:path";
23283
+ import { resolve as resolve12, join as join50, relative as relative10, isAbsolute as isAbsolute7, sep as sep7, dirname as dirname20 } from "node:path";
23172
23284
  import { fileURLToPath as fileURLToPath7 } from "node:url";
23173
23285
  import { Worker as Worker3 } from "node:worker_threads";
23174
23286
  function isStringRecord(value) {
@@ -23214,8 +23326,8 @@ function readEntryHtml(filePath) {
23214
23326
  }
23215
23327
  }
23216
23328
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
23217
- const entryRelativePath = relative9(absProjectDir, absoluteEntryPath);
23218
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep7}`) || isAbsolute6(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
23329
+ const entryRelativePath = relative10(absProjectDir, absoluteEntryPath);
23330
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep7}`) || isAbsolute7(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
23219
23331
  }
23220
23332
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
23221
23333
  const absProjectDir = resolve12(projectDir);
@@ -23620,16 +23732,31 @@ function buildRenderJobConfig(input, outputPath, log) {
23620
23732
  }
23621
23733
  function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
23622
23734
  const { input, cleanupProjectDir } = prepared;
23623
- const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
23735
+ const serverNamed = input.outputPath == null;
23736
+ const outputCandidate = input.outputPath ?? join52(rendersDir, `${basename9(resolve13(input.projectDir))}-${crypto.randomUUID()}.mp4`);
23737
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
23738
+ const outputDir = dirname22(absoluteOutputPath);
23624
23739
  if (confineOutput) {
23625
- mkdirSync21(rendersDir, { recursive: true });
23740
+ mkdirSync21(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23626
23741
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
23627
23742
  throw new Error("outputPath must be inside the renders directory");
23628
23743
  }
23744
+ const foreign = folderAnotherAccountCanChange(outputDir, rendersDir);
23745
+ if (foreign) {
23746
+ throw new Error(
23747
+ `outputPath must be in a folder only this server's account can change; another account can change ${foreign}`
23748
+ );
23749
+ }
23629
23750
  }
23630
- const outputDir = dirname22(absoluteOutputPath);
23631
- if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true });
23632
- return { input, cleanupProjectDir, absoluteOutputPath };
23751
+ if (!existsSync33(outputDir)) mkdirSync21(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
23752
+ return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
23753
+ }
23754
+ var STICKY_BIT = 512;
23755
+ var SERVER_FOLDER_MODE = 493;
23756
+ function folderAnotherAccountCanChange(dir, rendersDir) {
23757
+ const foreign = foreignWritablePath(dir, rendersDir);
23758
+ const stickyRoot = foreign === resolve13(rendersDir) && (lstatSync6(foreign).mode & STICKY_BIT) !== 0;
23759
+ return stickyRoot ? void 0 : foreign;
23633
23760
  }
23634
23761
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
23635
23762
  try {
@@ -23769,35 +23896,74 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
23769
23896
  return fallbackPath;
23770
23897
  }
23771
23898
  }
23772
- function createArtifactStore(ttlMs) {
23899
+ function createArtifactStore(ttlMs, log) {
23773
23900
  const artifacts = /* @__PURE__ */ new Map();
23901
+ const forget = (token) => {
23902
+ const artifact = artifacts.get(token);
23903
+ if (!artifact) return;
23904
+ artifacts.delete(token);
23905
+ if (artifact.pin !== void 0) closeSync9(artifact.pin);
23906
+ if (!artifact.serverNamed) return;
23907
+ try {
23908
+ rmSync20(artifact.path, { force: true });
23909
+ } catch (error) {
23910
+ log.warn("Failed to remove output artifact", {
23911
+ path: artifact.path,
23912
+ error: error instanceof Error ? error.message : String(error)
23913
+ });
23914
+ }
23915
+ };
23774
23916
  const cleanup = setInterval(() => {
23775
23917
  const now = Date.now();
23776
23918
  for (const [token, artifact] of artifacts.entries()) {
23777
- if (artifact.expiresAtMs <= now) {
23778
- artifacts.delete(token);
23779
- }
23919
+ if (artifact.expiresAtMs <= now) forget(token);
23780
23920
  }
23781
23921
  }, 6e4);
23782
23922
  cleanup.unref();
23783
23923
  return {
23784
- register(path) {
23924
+ register(path, serverNamed) {
23925
+ const pin = serverNamed ? openNoFollow(path) : void 0;
23926
+ const stat = pin === void 0 ? lstatSync6(path, { bigint: true, throwIfNoEntry: false }) : fstatSync5(pin, { bigint: true });
23927
+ const identity = stat && fileIdentity(stat);
23785
23928
  const token = crypto.randomUUID();
23786
- artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
23929
+ artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
23787
23930
  return token;
23788
23931
  },
23789
23932
  get(token) {
23790
- return artifacts.get(token);
23933
+ const artifact = artifacts.get(token);
23934
+ if (artifact && artifact.expiresAtMs <= Date.now()) {
23935
+ forget(token);
23936
+ return void 0;
23937
+ }
23938
+ return artifact;
23791
23939
  },
23792
- delete(token) {
23793
- artifacts.delete(token);
23794
- }
23940
+ forget
23795
23941
  };
23796
23942
  }
23943
+ function openArtifact(artifact) {
23944
+ const fd = openNoFollow(artifact.path);
23945
+ if (fd === void 0) return void 0;
23946
+ const stat = fstatSync5(fd, { bigint: true });
23947
+ if (stat.isFile() && fileIdentity(stat) === artifact.identity) return fd;
23948
+ closeSync9(fd);
23949
+ return void 0;
23950
+ }
23951
+ function openNoFollow(path) {
23952
+ try {
23953
+ return openSync9(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
23954
+ } catch (error) {
23955
+ const code = error.code;
23956
+ if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR") return void 0;
23957
+ throw error;
23958
+ }
23959
+ }
23960
+ function fileIdentity(stat) {
23961
+ return `${stat.dev}:${stat.ino}`;
23962
+ }
23797
23963
  function cleanupTempDir(dir, log) {
23798
23964
  if (!dir) return;
23799
23965
  try {
23800
- rmSync19(dir, { recursive: true, force: true });
23966
+ rmSync20(dir, { recursive: true, force: true });
23801
23967
  } catch (error) {
23802
23968
  log.warn("Failed to cleanup temp project dir", {
23803
23969
  cleanupProjectDir: dir,
@@ -23906,10 +24072,10 @@ function createRenderHandlers(options = {}) {
23906
24072
  const log = options.logger ?? defaultLogger;
23907
24073
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
23908
24074
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
23909
- const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
24075
+ const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? mkdtempSync2(join52(tmpdir6(), "hyperframes-renders-"));
23910
24076
  const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
23911
24077
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
23912
- const store = createArtifactStore(artifactTtlMs);
24078
+ const store = createArtifactStore(artifactTtlMs, log);
23913
24079
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
23914
24080
  const renderSemaphore = new Semaphore(maxConcurrentRenders);
23915
24081
  const startTime = Date.now();
@@ -23974,7 +24140,7 @@ function createRenderHandlers(options = {}) {
23974
24140
  if ("error" in preparedJob) {
23975
24141
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
23976
24142
  }
23977
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
24143
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
23978
24144
  const release = await renderSemaphore.acquire();
23979
24145
  log.info("render started", {
23980
24146
  requestId,
@@ -23991,7 +24157,7 @@ function createRenderHandlers(options = {}) {
23991
24157
  );
23992
24158
  const fileSize = outputFileSize(absoluteOutputPath);
23993
24159
  const durationMs = Date.now() - t0;
23994
- const outputToken = store.register(absoluteOutputPath);
24160
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
23995
24161
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
23996
24162
  log.info("render completed", {
23997
24163
  requestId,
@@ -24063,7 +24229,7 @@ function createRenderHandlers(options = {}) {
24063
24229
  });
24064
24230
  return;
24065
24231
  }
24066
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
24232
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
24067
24233
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
24068
24234
  const abortController = new AbortController();
24069
24235
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
@@ -24093,7 +24259,7 @@ function createRenderHandlers(options = {}) {
24093
24259
  ).finally(release);
24094
24260
  clearInterval(keepalive);
24095
24261
  const fileSize = outputFileSize(absoluteOutputPath);
24096
- const outputToken = store.register(absoluteOutputPath);
24262
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
24097
24263
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
24098
24264
  log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
24099
24265
  await stream.writeSSE({
@@ -24136,15 +24302,18 @@ function createRenderHandlers(options = {}) {
24136
24302
  if (!artifact) {
24137
24303
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
24138
24304
  }
24139
- if (!existsSync33(artifact.path)) {
24140
- store.delete(token);
24305
+ const fd = openArtifact(artifact);
24306
+ if (fd === void 0) {
24307
+ store.forget(token);
24141
24308
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
24142
24309
  }
24143
- const stats = statSync14(artifact.path);
24144
- return new Response(createReadStream6(artifact.path), {
24310
+ const { size } = fstatSync5(fd);
24311
+ const body = createReadStream6("", { fd });
24312
+ if (artifact.serverNamed) body.once("end", () => store.forget(token));
24313
+ return new Response(body, {
24145
24314
  headers: {
24146
24315
  "content-type": "video/mp4",
24147
- "content-length": String(stats.size),
24316
+ "content-length": String(size),
24148
24317
  "cache-control": "no-store"
24149
24318
  }
24150
24319
  });
@@ -24325,7 +24494,7 @@ import {
24325
24494
  import { quantizeTimeToFrame, MEDIA_VISUAL_STYLE_PROPERTIES } from "@hyperframes/engine";
24326
24495
 
24327
24496
  // src/services/distributed/planV2Execution.ts
24328
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync21 } from "node:fs";
24497
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync22 } from "node:fs";
24329
24498
  import { tmpdir as tmpdir7 } from "node:os";
24330
24499
  import { join as join54 } from "node:path";
24331
24500
 
@@ -24340,11 +24509,11 @@ import {
24340
24509
  mkdirSync as mkdirSync22,
24341
24510
  readFileSync as readFileSync17,
24342
24511
  readdirSync as readdirSync12,
24343
- rmSync as rmSync20,
24512
+ rmSync as rmSync21,
24344
24513
  statSync as statSync15
24345
24514
  } from "node:fs";
24346
24515
  import { localContainerInputArgs as localContainerInputArgs2 } from "@hyperframes/parsers/ff-binaries";
24347
- import { basename as basename9, dirname as dirname23, join as join53 } from "node:path";
24516
+ import { basename as basename10, dirname as dirname23, join as join53 } from "node:path";
24348
24517
  import {
24349
24518
  appendRateCapArgs as appendRateCapArgs2,
24350
24519
  writeVideoConcatList,
@@ -24396,7 +24565,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
24396
24565
  if (!existsSync34(dirname23(outputPath))) {
24397
24566
  mkdirSync22(dirname23(outputPath), { recursive: true });
24398
24567
  }
24399
- const workDir = createStagingDir7(dirname23(outputPath), `${basename9(outputPath)}.assemble-work-`);
24568
+ const workDir = createStagingDir7(dirname23(outputPath), `${basename10(outputPath)}.assemble-work-`);
24400
24569
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
24401
24570
  const stageMs = {};
24402
24571
  const ctx = {
@@ -24427,7 +24596,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
24427
24596
  });
24428
24597
  } finally {
24429
24598
  try {
24430
- rmSync20(workDir, { recursive: true, force: true });
24599
+ rmSync21(workDir, { recursive: true, force: true });
24431
24600
  } catch (err) {
24432
24601
  log.warn("[assemble] failed to remove work dir", {
24433
24602
  workDir,
@@ -24630,7 +24799,7 @@ function readCfrEncoder(planDir, format) {
24630
24799
  return encoderJson;
24631
24800
  }
24632
24801
  function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, startTimeMs) {
24633
- if (existsSync34(outputPath)) rmSync20(outputPath, { recursive: true, force: true });
24802
+ if (existsSync34(outputPath)) rmSync21(outputPath, { recursive: true, force: true });
24634
24803
  mkdirSync22(outputPath, { recursive: true });
24635
24804
  let globalIdx = 0;
24636
24805
  for (const chunkDir of chunkPaths) {
@@ -24681,7 +24850,7 @@ async function renderChunkV2(planV2Dir, chunkIndex, outputChunkPath, options) {
24681
24850
  materializePlanV2Target(planV2Dir, { role: "chunk", chunkIndex }, materializedPlanDir);
24682
24851
  return await renderChunk(materializedPlanDir, chunkIndex, outputChunkPath, options);
24683
24852
  } finally {
24684
- rmSync21(workRoot, { recursive: true, force: true });
24853
+ rmSync22(workRoot, { recursive: true, force: true });
24685
24854
  }
24686
24855
  }
24687
24856
  async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
@@ -24701,7 +24870,7 @@ async function assembleV2(planV2Dir, chunkPaths, outputPath, options) {
24701
24870
  options
24702
24871
  );
24703
24872
  } finally {
24704
- rmSync21(workRoot, { recursive: true, force: true });
24873
+ rmSync22(workRoot, { recursive: true, force: true });
24705
24874
  }
24706
24875
  }
24707
24876