@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.
@@ -18,15 +18,20 @@ function requireOutputDimensions(expected, width, height) {
18
18
 
19
19
  // src/server.ts
20
20
  import {
21
+ closeSync as closeSync7,
22
+ constants as fsConstants,
21
23
  existsSync as existsSync26,
24
+ fstatSync as fstatSync5,
25
+ lstatSync as lstatSync4,
22
26
  mkdirSync as mkdirSync13,
27
+ openSync as openSync7,
23
28
  statSync as statSync12,
24
29
  mkdtempSync,
25
30
  writeFileSync as writeFileSync7,
26
- rmSync as rmSync13,
31
+ rmSync as rmSync14,
27
32
  createReadStream as createReadStream4
28
33
  } from "node:fs";
29
- import { resolve as resolve11, dirname as dirname19, join as join40 } from "node:path";
34
+ import { basename as basename8, resolve as resolve11, dirname as dirname19, join as join40 } from "node:path";
30
35
  import { tmpdir as tmpdir4 } from "node:os";
31
36
  import { parseArgs } from "node:util";
32
37
  import { isIP } from "node:net";
@@ -40,6 +45,7 @@ import {
40
45
  referenceBackgroundResult as referenceBackgroundResult5
41
46
  } from "@hyperframes/engine";
42
47
  import { isSafePath as isSafePath4 } from "@hyperframes/core/safe-path";
48
+ import { foreignWritablePath } from "@hyperframes/core/cache-dir";
43
49
 
44
50
  // src/services/renderOrchestrator.ts
45
51
  import { audioFailureDiagnostics as audioFailureDiagnostics2, cpuBudget } from "@hyperframes/engine";
@@ -47,7 +53,7 @@ import {
47
53
  existsSync as existsSync22,
48
54
  mkdirSync as mkdirSync12,
49
55
  readdirSync as readdirSync6,
50
- rmSync as rmSync12,
56
+ rmSync as rmSync13,
51
57
  statSync as statSync10,
52
58
  writeFileSync as writeFileSync6,
53
59
  copyFileSync as copyFileSync5,
@@ -397,7 +403,7 @@ import {
397
403
  } from "@hyperframes/engine";
398
404
  import { join as join35, dirname as dirname15, resolve as resolve9 } from "path";
399
405
  import { totalmem as totalmem2 } from "node:os";
400
- import { randomUUID } from "crypto";
406
+ import { randomUUID as randomUUID3 } from "crypto";
401
407
  import { fileURLToPath as fileURLToPath5 } from "url";
402
408
 
403
409
  // src/services/fileServer.ts
@@ -581,11 +587,11 @@ var DEFAULT_RENDERS_DIR = process.env.PRODUCER_RENDERS_DIR ?? // fileURLToPath (
581
587
  nodeResolve(fileURLToPath2(import.meta.url), "../../..", "renders");
582
588
  var LEADING_PARENT_SEGMENT_RE = /^\.\.(?:[\\/]|$)/;
583
589
  function isPathInside(childPath, parentPath, options = {}) {
584
- const resolvePath = options.pathModule?.resolve ?? nodeResolve;
590
+ const resolvePath2 = options.pathModule?.resolve ?? nodeResolve;
585
591
  const relativePath = options.pathModule?.relative ?? nodeRelative;
586
592
  const isPathAbsolute = options.pathModule?.isAbsolute ?? nodeIsAbsolute;
587
- const absChild = resolvePath(childPath);
588
- const absParent = resolvePath(parentPath);
593
+ const absChild = resolvePath2(childPath);
594
+ const absParent = resolvePath2(parentPath);
589
595
  if (absChild === absParent) return true;
590
596
  const rel = relativePath(absParent, absChild);
591
597
  return rel !== "" && !LEADING_PARENT_SEGMENT_RE.test(rel) && !isPathAbsolute(rel);
@@ -7149,7 +7155,7 @@ function countAuthoredTimedClips(html) {
7149
7155
 
7150
7156
  // src/services/render/stages/compileStage.ts
7151
7157
  import { existsSync as existsSync13, writeFileSync as writeFileSync4 } from "node:fs";
7152
- import { join as join23, relative as relative4 } from "node:path";
7158
+ import { join as join23, relative as relative5 } from "node:path";
7153
7159
  import { privateCacheRoot } from "@hyperframes/engine";
7154
7160
  import { suggestMatchingPreset } from "@hyperframes/core";
7155
7161
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
@@ -7157,8 +7163,8 @@ import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolu
7157
7163
  import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7158
7164
 
7159
7165
  // src/services/compileInWorker.ts
7160
- import { existsSync as existsSync12 } from "node:fs";
7161
- import { dirname as dirname10, join as join22 } from "node:path";
7166
+ import { existsSync as existsSync12, rmSync as rmSync11 } from "node:fs";
7167
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join22, relative as relative4, resolve as resolvePath } from "node:path";
7162
7168
  import { fileURLToPath as fileURLToPath3 } from "node:url";
7163
7169
  import { Worker } from "node:worker_threads";
7164
7170
 
@@ -7464,7 +7470,7 @@ import {
7464
7470
  } from "@hyperframes/core/fonts/embed";
7465
7471
 
7466
7472
  // src/services/animatedGifPrep.ts
7467
- import { createHash as createHash4 } from "node:crypto";
7473
+ import { createHash as createHash4, randomUUID } from "node:crypto";
7468
7474
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7469
7475
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7470
7476
  import { parseHTML as parseHTML3 } from "linkedom";
@@ -7539,6 +7545,8 @@ function resolveLoop(metadata, override) {
7539
7545
  }
7540
7546
  var MAX_LOOP_ITERATIONS = 1e3;
7541
7547
  var MAX_PAD_SECONDS = 3600;
7548
+ var FFMPEG_SELF_CPU_SECONDS_CAP = 3600;
7549
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
7542
7550
  function resolveCompositionDurationSeconds(document2) {
7543
7551
  let max = null;
7544
7552
  for (const el of Array.from(document2.querySelectorAll("[data-composition-id][data-duration]"))) {
@@ -7581,7 +7589,13 @@ function resolvePreparedPlayback(metadata, loopOverride, windowSeconds) {
7581
7589
  return { loopIterations, padSeconds: Math.round(padSeconds * 1e3) / 1e3 };
7582
7590
  }
7583
7591
  function buildAnimatedGifTranscodeArgs(input) {
7584
- const args = ["-hide_banner", "-loglevel", "error"];
7592
+ const args = [
7593
+ "-hide_banner",
7594
+ "-loglevel",
7595
+ "error",
7596
+ "-timelimit",
7597
+ String(FFMPEG_SELF_CPU_SECONDS_CAP)
7598
+ ];
7585
7599
  if (input.loopIterations > 1) {
7586
7600
  args.push("-stream_loop", String(input.loopIterations - 1));
7587
7601
  }
@@ -7609,6 +7623,8 @@ function buildAnimatedGifTranscodeArgs(input) {
7609
7623
  ...input.padSeconds && input.padSeconds > 0 ? ["-vf", `tpad=stop_mode=clone:stop_duration=${input.padSeconds}`] : [],
7610
7624
  // Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
7611
7625
  // extension ffmpeg cannot infer the container from.
7626
+ "-fs",
7627
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
7612
7628
  "-f",
7613
7629
  "webm",
7614
7630
  "-y",
@@ -7616,10 +7632,16 @@ function buildAnimatedGifTranscodeArgs(input) {
7616
7632
  );
7617
7633
  return args;
7618
7634
  }
7635
+ function abortError() {
7636
+ const error = new Error("Aborted");
7637
+ error.name = "AbortError";
7638
+ return error;
7639
+ }
7619
7640
  async function runAnimatedGifTranscode(request) {
7620
7641
  const timeout = request.timeoutMs ?? 3e5;
7621
- const result = await runFfmpeg2(request.args, { timeout });
7642
+ const result = await runFfmpeg2(request.args, { timeout, signal: request.signal });
7622
7643
  if (result.success) return;
7644
+ if (request.signal?.aborted) throw abortError();
7623
7645
  if (result.failureReason === "external_interruption") {
7624
7646
  throw encoderFailureError("Animated GIF transcode failed", {
7625
7647
  error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
@@ -7639,7 +7661,7 @@ async function ensurePreparedWebm(input) {
7639
7661
  mkdirSync7(dirname6(input.outputPath), { recursive: true });
7640
7662
  }
7641
7663
  if (!isUsableFile(input.cachePath)) {
7642
- const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
7664
+ const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
7643
7665
  const args = buildAnimatedGifTranscodeArgs({
7644
7666
  inputPath: input.sourcePath,
7645
7667
  outputPath: tmpPath,
@@ -7652,11 +7674,15 @@ async function ensurePreparedWebm(input) {
7652
7674
  inputPath: input.sourcePath,
7653
7675
  outputPath: tmpPath,
7654
7676
  args,
7655
- timeoutMs: input.timeoutMs
7677
+ timeoutMs: input.timeoutMs,
7678
+ signal: input.signal
7656
7679
  });
7657
7680
  if (!isUsableFile(tmpPath)) {
7658
7681
  throw new Error("Animated GIF transcode produced an empty output");
7659
7682
  }
7683
+ if (statSync6(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
7684
+ throw new Error("Animated GIF transcode reached its output size limit");
7685
+ }
7660
7686
  if (!isUsableFile(input.cachePath)) {
7661
7687
  renameWithRetry2(tmpPath, input.cachePath);
7662
7688
  } else {
@@ -7756,6 +7782,7 @@ async function prepareAnimatedGifInputs(html, options) {
7756
7782
  loopIterations,
7757
7783
  padSeconds,
7758
7784
  timeoutMs: options.timeoutMs,
7785
+ signal: options.signal,
7759
7786
  transcode: options.transcode
7760
7787
  });
7761
7788
  const id = ensureElementId(img, document2, i);
@@ -7780,7 +7807,7 @@ async function prepareAnimatedGifInputs(html, options) {
7780
7807
  }
7781
7808
 
7782
7809
  // src/services/heifImagePrep.ts
7783
- import { createHash as createHash5 } from "node:crypto";
7810
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
7784
7811
  import {
7785
7812
  closeSync as closeSync5,
7786
7813
  copyFileSync as copyFileSync3,
@@ -7926,6 +7953,13 @@ var HeifToolUnavailableError = class extends Error {
7926
7953
  this.name = "HeifToolUnavailableError";
7927
7954
  }
7928
7955
  };
7956
+ function abortError2() {
7957
+ const error = new Error("Aborted");
7958
+ error.name = "AbortError";
7959
+ return error;
7960
+ }
7961
+ var FFMPEG_SELF_CPU_SECONDS_CAP2 = 300;
7962
+ var FFMPEG_SELF_OUTPUT_BYTES_CAP2 = 256 * 1024 * 1024;
7929
7963
  var TOOL_FAILURE_RE = /(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
7930
7964
  function isHeifBytes(head) {
7931
7965
  const bytes = Buffer.from(head.buffer, head.byteOffset, head.byteLength);
@@ -7993,6 +8027,8 @@ async function convertHeifToJpeg(request) {
7993
8027
  "-hide_banner",
7994
8028
  "-loglevel",
7995
8029
  "error",
8030
+ "-timelimit",
8031
+ String(FFMPEG_SELF_CPU_SECONDS_CAP2),
7996
8032
  ...urlInputArgs3(request.inputPath),
7997
8033
  "-i",
7998
8034
  request.inputPath,
@@ -8001,14 +8037,17 @@ async function convertHeifToJpeg(request) {
8001
8037
  "1",
8002
8038
  "-q:v",
8003
8039
  "2",
8040
+ "-fs",
8041
+ String(FFMPEG_SELF_OUTPUT_BYTES_CAP2),
8004
8042
  "-f",
8005
8043
  "mjpeg",
8006
8044
  "-y",
8007
8045
  request.outputPath
8008
8046
  ],
8009
- { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS }
8047
+ { timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal }
8010
8048
  );
8011
8049
  if (!result.success) {
8050
+ if (request.signal?.aborted) throw abortError2();
8012
8051
  throw result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`);
8013
8052
  }
8014
8053
  const out = (await probeJson(request.outputPath, false)).streams?.[0];
@@ -8042,7 +8081,7 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8042
8081
  mkdirSync8(dirname7(cachePath), { recursive: true });
8043
8082
  mkdirSync8(dirname7(outputPath), { recursive: true });
8044
8083
  if (!isUsableFile2(cachePath)) {
8045
- const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
8084
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID2()}`;
8046
8085
  const inlinePath = `${tmpPath}.heic`;
8047
8086
  const inputPath = source.path ?? inlinePath;
8048
8087
  try {
@@ -8050,9 +8089,13 @@ async function ensurePreparedJpeg(source, cachePath, outputPath, options) {
8050
8089
  await (options.transcode ?? convertHeifToJpeg)({
8051
8090
  inputPath,
8052
8091
  outputPath: tmpPath,
8053
- timeoutMs: options.timeoutMs
8092
+ timeoutMs: options.timeoutMs,
8093
+ signal: options.signal
8054
8094
  });
8055
8095
  if (!isUsableFile2(tmpPath)) throw new Error("conversion produced an empty file");
8096
+ if (statSync7(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP2) {
8097
+ throw new Error("conversion reached its output size limit");
8098
+ }
8056
8099
  renameWithRetry3(tmpPath, cachePath);
8057
8100
  } catch (error) {
8058
8101
  const reason = error instanceof Error ? error.message : String(error);
@@ -8123,6 +8166,7 @@ import {
8123
8166
  isNotImagePayload,
8124
8167
  isNotMediaPayload,
8125
8168
  isPrivateUnderAssetRoots as isPrivateUnderAssetRoots2,
8169
+ isStructurallyIncompletePngError,
8126
8170
  playlistLeavesItsFolder,
8127
8171
  NotMediaPayloadError,
8128
8172
  probeMediaProfile,
@@ -8201,6 +8245,13 @@ async function notMediaReferences(path, references) {
8201
8245
  if (images.length > 0 && await isNotImagePayload(path)) return images;
8202
8246
  return await playlistLeavesItsFolder(path) ? references : [];
8203
8247
  }
8248
+ function pngCutShort(references) {
8249
+ return references.filter((reference) => reference.expected === "video").map((reference) => ({
8250
+ expected: "video",
8251
+ detected: "image",
8252
+ elementFingerprint: fingerprintElementId(reference.id)
8253
+ }));
8254
+ }
8204
8255
  async function preflightCompositionAssetMediaTypes(input) {
8205
8256
  const references = [
8206
8257
  ...input.composition.videos.map((asset) => ({
@@ -8246,6 +8297,8 @@ async function preflightCompositionAssetMediaTypes(input) {
8246
8297
  profile = await probeMediaProfile(resolvedPath, { signal: input.signal });
8247
8298
  } catch (error) {
8248
8299
  if (input.signal?.aborted) throw input.signal.reason ?? error;
8300
+ if (isStructurallyIncompletePngError(error))
8301
+ mismatches.push(...pngCutShort(pathReferences));
8249
8302
  return;
8250
8303
  }
8251
8304
  for (const reference of pathReferences) {
@@ -9589,8 +9642,9 @@ async function inlineExternalFontStylesheets(html, budget = new CompositionExpan
9589
9642
  const css = await fetchExternalStylesheetCss(href, fetchSignal);
9590
9643
  const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
9591
9644
  if (fontFaceBlocks.length === 0) return;
9645
+ const fontCssWithLtAsCssEscape = fontFaceBlocks.join("\n").replace(/</g, "\\3c ");
9592
9646
  const inlineStyle = `<style>/* Inlined external font stylesheet */
9593
- ${fontFaceBlocks.join("\n")}
9647
+ ${fontCssWithLtAsCssEscape}
9594
9648
  </style>`;
9595
9649
  try {
9596
9650
  budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
@@ -9673,7 +9727,16 @@ function localizeFontFaceUrls(html, downloadDir, assets) {
9673
9727
  "Remote font download failed",
9674
9728
  "Localized remote font face(s)",
9675
9729
  assets,
9676
- (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9730
+ (h, url, relPath) => replaceMatches(
9731
+ h,
9732
+ styleBlockMatches(h),
9733
+ (style, css) => replaceInner(
9734
+ style,
9735
+ css,
9736
+ "</style>".length,
9737
+ css.replaceAll(`url(${url})`, `url("${relPath}")`)
9738
+ )
9739
+ )
9677
9740
  );
9678
9741
  }
9679
9742
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
@@ -9853,7 +9916,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
9853
9916
  return document2.toString();
9854
9917
  }
9855
9918
  var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
9856
- var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
9919
+ var MEDIA_SRC_NON_URL_CHARS = /[\u0000-\u001f\u007f<>]/;
9857
9920
  function bindVariableMediaSources(html, variables, budget, log) {
9858
9921
  if (!html.includes("data-var-src")) return html;
9859
9922
  const { document: document2 } = parseHTML5(html);
@@ -9868,7 +9931,7 @@ function bindVariableMediaSources(html, variables, budget, log) {
9868
9931
  const bound = boundMediaSrc(el, values);
9869
9932
  if (bound === null) continue;
9870
9933
  const src = bound.trim();
9871
- if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
9934
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_NON_URL_CHARS.test(src)) {
9872
9935
  log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
9873
9936
  length: src.length
9874
9937
  });
@@ -10003,6 +10066,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10003
10066
  cacheDir: options.animatedGifCacheDir,
10004
10067
  sourceAssets: remoteImageAssets,
10005
10068
  timeoutMs: options.ffmpegProcessTimeout,
10069
+ signal: options.abortSignal,
10006
10070
  allowOutsideFiles: assetRoot === void 0
10007
10071
  });
10008
10072
  if (preparedHeifImages.length > 0) {
@@ -10019,6 +10083,7 @@ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, ass
10019
10083
  cacheDir: options.animatedGifCacheDir,
10020
10084
  sourceAssets: gifSourceAssets,
10021
10085
  timeoutMs: options.ffmpegProcessTimeout,
10086
+ signal: options.abortSignal,
10022
10087
  allowOutsideFiles: assetRoot === void 0
10023
10088
  });
10024
10089
  if (preparedGifs.length > 0) {
@@ -10497,6 +10562,24 @@ function compileTimeoutMs() {
10497
10562
  return Number.isInteger(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_COMPILE_TIMEOUT_MS;
10498
10563
  }
10499
10564
  var warnedMissingEntry = false;
10565
+ var endOnProcessExit = /* @__PURE__ */ new Set();
10566
+ var processExitHooked = false;
10567
+ function onProcessExit(end) {
10568
+ if (!processExitHooked) {
10569
+ processExitHooked = true;
10570
+ process.on("exit", () => {
10571
+ for (const each of endOnProcessExit) each();
10572
+ });
10573
+ }
10574
+ endOnProcessExit.add(end);
10575
+ return () => endOnProcessExit.delete(end);
10576
+ }
10577
+ function tryQuietly(action) {
10578
+ try {
10579
+ action();
10580
+ } catch {
10581
+ }
10582
+ }
10500
10583
  function resolveCompileWorkerEntry(explicit, log) {
10501
10584
  if (explicit) return explicit;
10502
10585
  const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
@@ -10530,6 +10613,26 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10530
10613
  const thread = new Worker(entry, {
10531
10614
  workerData: { projectDir, htmlPath, downloadDir, options: cloneable }
10532
10615
  });
10616
+ const children = /* @__PURE__ */ new Map();
10617
+ const scratchRoots = [downloadDir, options.animatedGifCacheDir].flatMap(
10618
+ (dir) => dir ? [resolvePath(dir)] : []
10619
+ );
10620
+ const isScratch = (path) => scratchRoots.some((root) => {
10621
+ const rel = relative4(root, resolvePath(path));
10622
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute4(rel);
10623
+ });
10624
+ const endChildren = (signal) => {
10625
+ for (const [pid, output] of children) {
10626
+ if (signal) tryQuietly(() => process.kill(pid, "SIGKILL"));
10627
+ if (output) tryQuietly(() => rmSync11(output, { force: true }));
10628
+ }
10629
+ children.clear();
10630
+ };
10631
+ const offProcessExit = onProcessExit(() => endChildren(true));
10632
+ const endThread = () => {
10633
+ endChildren(true);
10634
+ void thread.terminate();
10635
+ };
10533
10636
  let settled = false;
10534
10637
  const settle = (finish) => {
10535
10638
  if (settled) return;
@@ -10540,7 +10643,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10540
10643
  };
10541
10644
  const stop = () => {
10542
10645
  thread.postMessage({ type: "abort" });
10543
- setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
10646
+ setTimeout(endThread, TERMINATE_GRACE_MS).unref();
10544
10647
  };
10545
10648
  const timer = setTimeout(() => {
10546
10649
  stop();
@@ -10553,7 +10656,7 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10553
10656
  abortSignal?.addEventListener("abort", onAbort, { once: true });
10554
10657
  const retire = (graceMs) => {
10555
10658
  thread.unref();
10556
- setTimeout(() => void thread.terminate(), graceMs).unref();
10659
+ setTimeout(endThread, graceMs).unref();
10557
10660
  };
10558
10661
  thread.on(
10559
10662
  "message",
@@ -10572,13 +10675,22 @@ async function compileForRenderInWorker(projectDir, htmlPath, downloadDir, optio
10572
10675
  }
10573
10676
  }
10574
10677
  );
10575
- thread.on("error", (error) => settle(() => reject(error)));
10576
10678
  thread.on(
10577
- "exit",
10578
- (code) => settle(
10579
- () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10580
- )
10679
+ "message",
10680
+ ({ type, pid, output }) => {
10681
+ if (pid === void 0) return;
10682
+ if (type === "child") children.set(pid, output && isScratch(output) ? output : void 0);
10683
+ else if (type === "childExit") children.delete(pid);
10684
+ }
10581
10685
  );
10686
+ thread.on("error", (error) => settle(() => reject(error)));
10687
+ thread.on("exit", (code) => {
10688
+ offProcessExit();
10689
+ endChildren(false);
10690
+ settle(
10691
+ () => reject(new Error(`The compile worker exited with code ${code} before answering`))
10692
+ );
10693
+ });
10582
10694
  });
10583
10695
  }
10584
10696
 
@@ -10608,10 +10720,10 @@ function resolveEntryHtmlPath(input) {
10608
10720
  const readEntry = (path) => {
10609
10721
  if (escapesAssetRoot(path, input.assetRoot)) {
10610
10722
  throw new Error(
10611
- `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10723
+ `Entry file "${relative5(projectDir, path)}" leads outside the project folder`
10612
10724
  );
10613
10725
  }
10614
- assertCompositionFileSize2(path, relative4(projectDir, path));
10726
+ assertCompositionFileSize2(path, relative5(projectDir, path));
10615
10727
  return readTextFile2(path);
10616
10728
  };
10617
10729
  const htmlPath = join23(projectDir, entryFile);
@@ -14376,7 +14488,7 @@ import {
14376
14488
  mkdirSync as mkdirSync11,
14377
14489
  readdirSync as readdirSync5,
14378
14490
  readFileSync as readFileSync9,
14379
- rmSync as rmSync11,
14491
+ rmSync as rmSync12,
14380
14492
  statSync as statSync9,
14381
14493
  writeFileSync as writeFileSync5
14382
14494
  } from "node:fs";
@@ -14515,7 +14627,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
14515
14627
  fileSize
14516
14628
  };
14517
14629
  } finally {
14518
- rmSync11(input.palettePath, { force: true });
14630
+ rmSync12(input.palettePath, { force: true });
14519
14631
  }
14520
14632
  }
14521
14633
  function startEncodeProgress(job, stage, onProgress) {
@@ -15394,7 +15506,7 @@ async function executeDiskCaptureWithAdaptiveRetry(options) {
15394
15506
  function createRenderJob(config) {
15395
15507
  return {
15396
15508
  ...referenceBackgroundResult(void 0),
15397
- id: randomUUID(),
15509
+ id: randomUUID3(),
15398
15510
  config: {
15399
15511
  ...config,
15400
15512
  fps: toFps2(config.fps),
@@ -15909,7 +16021,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
15909
16021
  log.info("KEEP_TEMP=1, leaving workDir on disk for inspection", { workDir });
15910
16022
  return;
15911
16023
  }
15912
- rmSync12(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
16024
+ rmSync13(workDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
15913
16025
  });
15914
16026
  try {
15915
16027
  await executeRenderPipeline({
@@ -17377,7 +17489,7 @@ async function executeRenderPipeline(input) {
17377
17489
  segmentDir
17378
17490
  });
17379
17491
  }
17380
- if (completedSegments.size === 0) rmSync12(segmentDir, { recursive: true, force: true });
17492
+ if (completedSegments.size === 0) rmSync13(segmentDir, { recursive: true, force: true });
17381
17493
  const invokeSegmented = () => {
17382
17494
  if (capturePlan.kind !== "sdr_segmented") {
17383
17495
  throw new Error(`Cannot invoke segmented stage with ${capturePlan.kind} plan`);
@@ -17470,7 +17582,7 @@ async function executeRenderPipeline(input) {
17470
17582
  probeSession = null;
17471
17583
  await closeOrphanedProbeForRetry(orphaned, closeCaptureSession8, log, "segmented");
17472
17584
  }
17473
- rmSync12(segmentDir, { recursive: true, force: true });
17585
+ rmSync13(segmentDir, { recursive: true, force: true });
17474
17586
  completedSegments = /* @__PURE__ */ new Set();
17475
17587
  segmentManifest = emptySegmentManifest();
17476
17588
  dedupPerfs.length = 0;
@@ -17509,7 +17621,7 @@ async function executeRenderPipeline(input) {
17509
17621
  );
17510
17622
  updateCaptureObservability({ segmentRetries: segmentedRes.segmentRetries });
17511
17623
  if (job.config.keepSegments !== true) {
17512
- rmSync12(segmentDir, { recursive: true, force: true });
17624
+ rmSync13(segmentDir, { recursive: true, force: true });
17513
17625
  }
17514
17626
  } else {
17515
17627
  capturePlan = replanAfterFailure(capturePlan, { kind: "streaming_unavailable" });
@@ -17786,7 +17898,7 @@ async function executeRenderPipeline(input) {
17786
17898
  "capture_disk",
17787
17899
  "drawElement capture failed; retrying with a fresh screenshot session"
17788
17900
  );
17789
- rmSync12(framesDir, { recursive: true, force: true });
17901
+ rmSync13(framesDir, { recursive: true, force: true });
17790
17902
  mkdirSync12(framesDir, { recursive: true });
17791
17903
  resetCaptureAttemptProgress(job);
17792
17904
  dedupPerfs.length = 0;
@@ -18099,7 +18211,7 @@ import {
18099
18211
  closeSync as closeSync6,
18100
18212
  constants as constants4
18101
18213
  } from "node:fs";
18102
- import { resolve as resolve10, join as join36, relative as relative5, isAbsolute as isAbsolute4, sep as sep5, dirname as dirname16 } from "node:path";
18214
+ import { resolve as resolve10, join as join36, relative as relative6, isAbsolute as isAbsolute5, sep as sep5, dirname as dirname16 } from "node:path";
18103
18215
  import { fileURLToPath as fileURLToPath6 } from "node:url";
18104
18216
  import { Worker as Worker3 } from "node:worker_threads";
18105
18217
  function isStringRecord(value) {
@@ -18145,8 +18257,8 @@ function readEntryHtml(filePath) {
18145
18257
  }
18146
18258
  }
18147
18259
  function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
18148
- const entryRelativePath = relative5(absProjectDir, absoluteEntryPath);
18149
- return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute4(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
18260
+ const entryRelativePath = relative6(absProjectDir, absoluteEntryPath);
18261
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep5}`) || isAbsolute5(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
18150
18262
  }
18151
18263
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
18152
18264
  const absProjectDir = resolve10(projectDir);
@@ -18429,7 +18541,7 @@ import {
18429
18541
  createReferenceBackgroundRecorder as createReferenceBackgroundRecorder2
18430
18542
  } from "@hyperframes/engine";
18431
18543
  import { audioFailureDiagnostics as audioFailureDiagnostics3 } from "@hyperframes/engine";
18432
- import { extname as extname4, isAbsolute as isAbsolute5, join as join39, relative as relative6, sep as sep6 } from "node:path";
18544
+ import { extname as extname4, isAbsolute as isAbsolute6, join as join39, relative as relative7, sep as sep6 } from "node:path";
18433
18545
  import {
18434
18546
  fpsToNumber as fpsToNumber9,
18435
18547
  HF_COLOR_GRADING_ATTR as HF_COLOR_GRADING_ATTR2
@@ -18999,16 +19111,31 @@ function buildRenderJobConfig(input, outputPath, log) {
18999
19111
  }
19000
19112
  function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
19001
19113
  const { input, cleanupProjectDir } = prepared;
19002
- const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
19114
+ const serverNamed = input.outputPath == null;
19115
+ const outputCandidate = input.outputPath ?? join40(rendersDir, `${basename8(resolve11(input.projectDir))}-${crypto.randomUUID()}.mp4`);
19116
+ const absoluteOutputPath = resolveOutputPath(input.projectDir, outputCandidate, rendersDir, log);
19117
+ const outputDir = dirname19(absoluteOutputPath);
19003
19118
  if (confineOutput) {
19004
- mkdirSync13(rendersDir, { recursive: true });
19119
+ mkdirSync13(rendersDir, { recursive: true, mode: SERVER_FOLDER_MODE });
19005
19120
  if (!isSafePath4(rendersDir, absoluteOutputPath)) {
19006
19121
  throw new Error("outputPath must be inside the renders directory");
19007
19122
  }
19123
+ const foreign = folderAnotherAccountCanChange(outputDir, rendersDir);
19124
+ if (foreign) {
19125
+ throw new Error(
19126
+ `outputPath must be in a folder only this server's account can change; another account can change ${foreign}`
19127
+ );
19128
+ }
19008
19129
  }
19009
- const outputDir = dirname19(absoluteOutputPath);
19010
- if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true });
19011
- return { input, cleanupProjectDir, absoluteOutputPath };
19130
+ if (!existsSync26(outputDir)) mkdirSync13(outputDir, { recursive: true, mode: SERVER_FOLDER_MODE });
19131
+ return { input, cleanupProjectDir, absoluteOutputPath, serverNamed };
19132
+ }
19133
+ var STICKY_BIT = 512;
19134
+ var SERVER_FOLDER_MODE = 493;
19135
+ function folderAnotherAccountCanChange(dir, rendersDir) {
19136
+ const foreign = foreignWritablePath(dir, rendersDir);
19137
+ const stickyRoot = foreign === resolve11(rendersDir) && (lstatSync4(foreign).mode & STICKY_BIT) !== 0;
19138
+ return stickyRoot ? void 0 : foreign;
19012
19139
  }
19013
19140
  function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
19014
19141
  try {
@@ -19148,35 +19275,74 @@ function resolveOutputPath(projectDir, outputCandidate, rendersDir, log) {
19148
19275
  return fallbackPath;
19149
19276
  }
19150
19277
  }
19151
- function createArtifactStore(ttlMs) {
19278
+ function createArtifactStore(ttlMs, log) {
19152
19279
  const artifacts = /* @__PURE__ */ new Map();
19280
+ const forget = (token) => {
19281
+ const artifact = artifacts.get(token);
19282
+ if (!artifact) return;
19283
+ artifacts.delete(token);
19284
+ if (artifact.pin !== void 0) closeSync7(artifact.pin);
19285
+ if (!artifact.serverNamed) return;
19286
+ try {
19287
+ rmSync14(artifact.path, { force: true });
19288
+ } catch (error) {
19289
+ log.warn("Failed to remove output artifact", {
19290
+ path: artifact.path,
19291
+ error: error instanceof Error ? error.message : String(error)
19292
+ });
19293
+ }
19294
+ };
19153
19295
  const cleanup = setInterval(() => {
19154
19296
  const now = Date.now();
19155
19297
  for (const [token, artifact] of artifacts.entries()) {
19156
- if (artifact.expiresAtMs <= now) {
19157
- artifacts.delete(token);
19158
- }
19298
+ if (artifact.expiresAtMs <= now) forget(token);
19159
19299
  }
19160
19300
  }, 6e4);
19161
19301
  cleanup.unref();
19162
19302
  return {
19163
- register(path) {
19303
+ register(path, serverNamed) {
19304
+ const pin = serverNamed ? openNoFollow(path) : void 0;
19305
+ const stat = pin === void 0 ? lstatSync4(path, { bigint: true, throwIfNoEntry: false }) : fstatSync5(pin, { bigint: true });
19306
+ const identity = stat && fileIdentity(stat);
19164
19307
  const token = crypto.randomUUID();
19165
- artifacts.set(token, { path, expiresAtMs: Date.now() + ttlMs });
19308
+ artifacts.set(token, { path, identity, pin, serverNamed, expiresAtMs: Date.now() + ttlMs });
19166
19309
  return token;
19167
19310
  },
19168
19311
  get(token) {
19169
- return artifacts.get(token);
19312
+ const artifact = artifacts.get(token);
19313
+ if (artifact && artifact.expiresAtMs <= Date.now()) {
19314
+ forget(token);
19315
+ return void 0;
19316
+ }
19317
+ return artifact;
19170
19318
  },
19171
- delete(token) {
19172
- artifacts.delete(token);
19173
- }
19319
+ forget
19174
19320
  };
19175
19321
  }
19322
+ function openArtifact(artifact) {
19323
+ const fd = openNoFollow(artifact.path);
19324
+ if (fd === void 0) return void 0;
19325
+ const stat = fstatSync5(fd, { bigint: true });
19326
+ if (stat.isFile() && fileIdentity(stat) === artifact.identity) return fd;
19327
+ closeSync7(fd);
19328
+ return void 0;
19329
+ }
19330
+ function openNoFollow(path) {
19331
+ try {
19332
+ return openSync7(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
19333
+ } catch (error) {
19334
+ const code = error.code;
19335
+ if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR") return void 0;
19336
+ throw error;
19337
+ }
19338
+ }
19339
+ function fileIdentity(stat) {
19340
+ return `${stat.dev}:${stat.ino}`;
19341
+ }
19176
19342
  function cleanupTempDir(dir, log) {
19177
19343
  if (!dir) return;
19178
19344
  try {
19179
- rmSync13(dir, { recursive: true, force: true });
19345
+ rmSync14(dir, { recursive: true, force: true });
19180
19346
  } catch (error) {
19181
19347
  log.warn("Failed to cleanup temp project dir", {
19182
19348
  cleanupProjectDir: dir,
@@ -19285,10 +19451,10 @@ function createRenderHandlers(options = {}) {
19285
19451
  const log = options.logger ?? defaultLogger;
19286
19452
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
19287
19453
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
19288
- const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
19454
+ const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? mkdtempSync(join40(tmpdir4(), "hyperframes-renders-"));
19289
19455
  const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
19290
19456
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
19291
- const store = createArtifactStore(artifactTtlMs);
19457
+ const store = createArtifactStore(artifactTtlMs, log);
19292
19458
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
19293
19459
  const renderSemaphore = new Semaphore(maxConcurrentRenders);
19294
19460
  const startTime = Date.now();
@@ -19353,7 +19519,7 @@ function createRenderHandlers(options = {}) {
19353
19519
  if ("error" in preparedJob) {
19354
19520
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
19355
19521
  }
19356
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19522
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19357
19523
  const release = await renderSemaphore.acquire();
19358
19524
  log.info("render started", {
19359
19525
  requestId,
@@ -19370,7 +19536,7 @@ function createRenderHandlers(options = {}) {
19370
19536
  );
19371
19537
  const fileSize = outputFileSize(absoluteOutputPath);
19372
19538
  const durationMs = Date.now() - t0;
19373
- const outputToken = store.register(absoluteOutputPath);
19539
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19374
19540
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19375
19541
  log.info("render completed", {
19376
19542
  requestId,
@@ -19442,7 +19608,7 @@ function createRenderHandlers(options = {}) {
19442
19608
  });
19443
19609
  return;
19444
19610
  }
19445
- const { job, input, cleanupProjectDir, absoluteOutputPath } = preparedJob;
19611
+ const { job, input, cleanupProjectDir, absoluteOutputPath, serverNamed } = preparedJob;
19446
19612
  log.info("render-stream started", { requestId, projectDir: input.projectDir });
19447
19613
  const abortController = new AbortController();
19448
19614
  const onRequestAbort = () => abortController.abort(new RenderCancelledError("request_aborted"));
@@ -19472,7 +19638,7 @@ function createRenderHandlers(options = {}) {
19472
19638
  ).finally(release);
19473
19639
  clearInterval(keepalive);
19474
19640
  const fileSize = outputFileSize(absoluteOutputPath);
19475
- const outputToken = store.register(absoluteOutputPath);
19641
+ const outputToken = store.register(absoluteOutputPath, serverNamed);
19476
19642
  const outputUrl = `${outputUrlPrefix}/${outputToken}`;
19477
19643
  log.info("render-stream completed", { requestId, fileSize, perf: job.perfSummary ?? null });
19478
19644
  await stream.writeSSE({
@@ -19515,15 +19681,18 @@ function createRenderHandlers(options = {}) {
19515
19681
  if (!artifact) {
19516
19682
  return c.json({ success: false, error: "Output artifact not found or expired" }, 404);
19517
19683
  }
19518
- if (!existsSync26(artifact.path)) {
19519
- store.delete(token);
19684
+ const fd = openArtifact(artifact);
19685
+ if (fd === void 0) {
19686
+ store.forget(token);
19520
19687
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
19521
19688
  }
19522
- const stats = statSync12(artifact.path);
19523
- return new Response(createReadStream4(artifact.path), {
19689
+ const { size } = fstatSync5(fd);
19690
+ const body = createReadStream4("", { fd });
19691
+ if (artifact.serverNamed) body.once("end", () => store.forget(token));
19692
+ return new Response(body, {
19524
19693
  headers: {
19525
19694
  "content-type": "video/mp4",
19526
- "content-length": String(stats.size),
19695
+ "content-length": String(size),
19527
19696
  "cache-control": "no-store"
19528
19697
  }
19529
19698
  });