@hyperframes/producer 0.9.52 → 0.9.54

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
@@ -67,7 +67,7 @@ import {
67
67
  referenceBackgroundResult,
68
68
  createReferenceBackgroundRecorder
69
69
  } from "@hyperframes/engine";
70
- import { join as join32, dirname as dirname13, resolve as resolve8 } from "path";
70
+ import { join as join32, dirname as dirname14, resolve as resolve8 } from "path";
71
71
  import { totalmem as totalmem2 } from "node:os";
72
72
  import { randomUUID } from "crypto";
73
73
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -75,7 +75,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
75
75
  // src/services/fileServer.ts
76
76
  import { Hono } from "hono";
77
77
  import { serve } from "@hono/node-server";
78
- import { settleOnBrowserSafePort } from "@hyperframes/engine";
78
+ import { answerOwnLoopbackHostOnly, settleOnBrowserSafePort } from "@hyperframes/engine";
79
79
  import {
80
80
  existsSync as existsSync2,
81
81
  realpathSync,
@@ -92,7 +92,7 @@ import { Readable } from "node:stream";
92
92
  import { join as join2, extname, resolve as resolve2, sep as sep2 } from "node:path";
93
93
  import { injectScriptsAtHeadStart, injectScriptsIntoHtml } from "@hyperframes/core/compiler";
94
94
  import { fpsToNumber } from "@hyperframes/core";
95
- import { isPrivateFileUnder, isVcsOrSecretPath } from "@hyperframes/core/safe-path";
95
+ import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
96
96
  import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
97
97
  import { openRangeEnd } from "@hyperframes/studio-server/media-range";
98
98
 
@@ -315,6 +315,7 @@ var MIME_TYPES = {
315
315
  ".css": "text/css; charset=utf-8",
316
316
  ".js": "application/javascript; charset=utf-8",
317
317
  ".mjs": "application/javascript; charset=utf-8",
318
+ ".cjs": "application/javascript; charset=utf-8",
318
319
  ".json": "application/json; charset=utf-8",
319
320
  ".cube": "text/plain; charset=utf-8",
320
321
  ".png": "image/png",
@@ -858,6 +859,12 @@ function createFileServer(options) {
858
859
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
859
860
  const app = new Hono();
860
861
  const warnLeftOut = (line) => console.warn(`[FileServer] ${line}`);
862
+ let listeningPort = -1;
863
+ app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
864
+ await next();
865
+ c.res.headers.set("X-Content-Type-Options", "nosniff");
866
+ });
867
+ answerOwnLoopbackHostOnly(app, () => listeningPort);
861
868
  app.get("/*", async (c) => {
862
869
  let requestPath = c.req.path;
863
870
  if (requestPath === "/") requestPath = "/index.html";
@@ -867,7 +874,7 @@ function createFileServer(options) {
867
874
  const candidate = join2(root, relativePath);
868
875
  const resolveSymlinks = !allowOutsideProjectAssets && root !== compiledDir;
869
876
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
870
- if (isPrivateFileUnder(root, candidate, isVcsOrSecretPath)) continue;
877
+ if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
871
878
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
872
879
  if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut)) continue;
873
880
  file = openRegularFile(candidate);
@@ -953,6 +960,7 @@ function createFileServer(options) {
953
960
  const server = serve({ fetch: app.fetch, port, hostname: "127.0.0.1" }, (info) => {
954
961
  const bound = port === 0 ? settleOnBrowserSafePort(server, "127.0.0.1") : Promise.resolve(info.port);
955
962
  bound.then((boundPort) => {
963
+ listeningPort = boundPort;
956
964
  resolve13({
957
965
  url: `http://localhost:${boundPort}`,
958
966
  port: boundPort,
@@ -1119,6 +1127,9 @@ import {
1119
1127
  import {
1120
1128
  mediaIdPathSegment
1121
1129
  } from "@hyperframes/engine";
1130
+ function audioWorkDir(workDir) {
1131
+ return join3(workDir, "audio-work");
1132
+ }
1122
1133
  var BROWSER_MEDIA_EPSILON = 1e-4;
1123
1134
  function resolveBrowserMediaEnd(start, end, duration) {
1124
1135
  return Number.isFinite(duration) && duration > 0 ? start + duration : end;
@@ -6516,15 +6527,29 @@ function countAuthoredTimedClips(html) {
6516
6527
  // src/services/render/stages/compileStage.ts
6517
6528
  import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6518
6529
  import { join as join20, relative as relative3 } from "node:path";
6530
+ import { privateCacheRoot } from "@hyperframes/engine";
6519
6531
  import { suggestMatchingPreset } from "@hyperframes/core";
6520
6532
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6521
6533
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6522
6534
 
6523
6535
  // src/services/htmlCompiler.ts
6524
6536
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6537
+ import {
6538
+ cssRuleMatches,
6539
+ cssUrlMatches,
6540
+ fontFaceBlockMatches,
6541
+ hasBackgroundImageDeclaration,
6542
+ importRuleMatches,
6543
+ localFontFaceUrlMatches,
6544
+ remoteBackgroundUrlMatches,
6545
+ remoteFontFaceUrlMatches,
6546
+ replaceMatches,
6547
+ styleBlockMatches,
6548
+ stylesheetLinkMatches
6549
+ } from "@hyperframes/parsers/css-url-scans";
6525
6550
  import { createHash as createHash6 } from "node:crypto";
6526
6551
  import { createReadStream as createReadStream2, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
6527
- import { join as join19, dirname as dirname8, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
6552
+ import { join as join19, dirname as dirname9, resolve as resolve7, basename as basename5, relative as relative2, sep as sep3 } from "path";
6528
6553
  import { parseHTML as parseHTML5 } from "linkedom";
6529
6554
 
6530
6555
  // src/services/bundledScripts.ts
@@ -6547,7 +6572,6 @@ import {
6547
6572
  extractResolvedMedia,
6548
6573
  clampDurations,
6549
6574
  shouldClampResolvedMediaDuration,
6550
- CSS_URL_RE,
6551
6575
  isNonRelativeUrl,
6552
6576
  parseStrictFiniteTimingNumber,
6553
6577
  readMediaStart,
@@ -6597,7 +6621,7 @@ import {
6597
6621
  readTextFile,
6598
6622
  resolveCompositionSrc
6599
6623
  } from "@hyperframes/parsers/asset-resolution";
6600
- import { isPrivateFileUnder as isPrivateFileUnder2, isVcsOrSecretPath as isVcsOrSecretPath2 } from "@hyperframes/core/safe-path";
6624
+ import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
6601
6625
 
6602
6626
  // src/services/renderMediaCollector.ts
6603
6627
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7429,9 +7453,11 @@ import { getPositionEditsRenderScript } from "@hyperframes/core/runtime/position
7429
7453
 
7430
7454
  // src/services/assetMediaType.ts
7431
7455
  import { existsSync as existsSync10 } from "node:fs";
7432
- import { join as join18 } from "node:path";
7456
+ import { dirname as dirname8, join as join18 } from "node:path";
7433
7457
  import {
7434
7458
  fingerprintElementId,
7459
+ isHttpUrl as isHttpUrl2,
7460
+ isInsideAssetRoots,
7435
7461
  isNotMediaPayload,
7436
7462
  playlistLeavesItsFolder,
7437
7463
  NotMediaPayloadError,
@@ -7477,17 +7503,17 @@ function assertAssetMediaTypeProfile(expected, profile, elementIdentity) {
7477
7503
  }
7478
7504
  ]);
7479
7505
  }
7480
- function isRemoteOrInlineSource(src) {
7481
- return /^(?:https?:|data:|blob:|about:)/i.test(src.trim());
7506
+ function mediaAssetRoots(projectDir, compiledDir) {
7507
+ return [projectDir, compiledDir, join18(dirname8(compiledDir), "downloads")];
7482
7508
  }
7483
7509
  function dropMediaOutsideProject(input) {
7484
7510
  const { projectDir, workDir, composition, log } = input;
7485
7511
  const compiledDir = join18(workDir, "compiled");
7486
- const roots = [projectDir, compiledDir, join18(workDir, "downloads")];
7512
+ const roots = mediaAssetRoots(projectDir, compiledDir);
7487
7513
  const staysInside = ({ id, src }) => {
7488
- if (!src || isRemoteOrInlineSource(src)) return true;
7514
+ if (!src || isHttpUrl2(src)) return true;
7489
7515
  const path = resolveProjectRelativeSrc3(src, projectDir, compiledDir);
7490
- if (roots.some((root) => !escapesAssetRoot(path, root))) return true;
7516
+ if (isInsideAssetRoots(path, roots)) return true;
7491
7517
  if (input.allowOutsideProjectAssets) {
7492
7518
  const refusal = outsideAssetRefusal(projectDir, path);
7493
7519
  if (refusal) log.warn(`[Render] ${leftOutOfRender(`Media "${id}"`, src, refusal)}`);
@@ -7525,7 +7551,7 @@ async function preflightCompositionAssetMediaTypes(input) {
7525
7551
  ];
7526
7552
  const byPath = /* @__PURE__ */ new Map();
7527
7553
  for (const reference of references) {
7528
- if (!reference.src || isRemoteOrInlineSource(reference.src)) continue;
7554
+ if (!reference.src || isHttpUrl2(reference.src)) continue;
7529
7555
  const resolvedPath = resolveProjectRelativeSrc3(
7530
7556
  reference.src,
7531
7557
  input.projectDir,
@@ -7625,11 +7651,17 @@ function normalizeCompositionSrcs(html, projectDir) {
7625
7651
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
7626
7652
  });
7627
7653
  }
7628
- function resolveCompositionFile(projectDir, src, assetRoot) {
7654
+ var COMPOSITION_FILE = /\.html?$/i;
7655
+ var NOT_A_COMPOSITION_FILE = "it is not an .html file, so it is refused";
7656
+ function resolveCompositionPath(projectDir, src, assetRoot) {
7629
7657
  const file = resolveCompositionSrc(projectDir, src);
7630
7658
  return file === null || escapesAssetRoot(file, assetRoot) ? null : file;
7631
7659
  }
7632
- var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isVcsOrSecretPath2);
7660
+ function resolveCompositionFile(projectDir, src, assetRoot) {
7661
+ const file = resolveCompositionPath(projectDir, src, assetRoot);
7662
+ return file !== null && COMPOSITION_FILE.test(file) ? file : null;
7663
+ }
7664
+ var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
7633
7665
  function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
7634
7666
  const { document: document2 } = parseHTML5(html);
7635
7667
  const hosts = [...document2.querySelectorAll("[data-composition-src]")];
@@ -7638,7 +7670,7 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
7638
7670
  const srcPath = el.getAttribute("data-composition-src");
7639
7671
  if (!srcPath) continue;
7640
7672
  if (isUnresolvedAssetPlaceholder(srcPath)) continue;
7641
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
7673
+ const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
7642
7674
  if (filePath === null) {
7643
7675
  problems.push({ srcPath, detail: "it is outside the project folder" });
7644
7676
  continue;
@@ -7648,7 +7680,14 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
7648
7680
  continue;
7649
7681
  }
7650
7682
  if (isPrivateCompositionFile(projectDir, filePath)) {
7651
- problems.push({ srcPath, detail: "it is git metadata or an env file" });
7683
+ problems.push({
7684
+ srcPath,
7685
+ detail: "it is git metadata, an env file or a private tool record"
7686
+ });
7687
+ continue;
7688
+ }
7689
+ if (!COMPOSITION_FILE.test(filePath)) {
7690
+ problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
7652
7691
  continue;
7653
7692
  }
7654
7693
  if (visited.has(filePath)) continue;
@@ -7746,7 +7785,6 @@ var THREE_D_CONTEXT_PATTERN = /transform-style\s*:\s*preserve-3d|backface-visibi
7746
7785
  function detectThreeDTransformUsage(html) {
7747
7786
  return THREE_D_CONTEXT_PATTERN.test(html);
7748
7787
  }
7749
- var BACKGROUND_IMAGE_DECL_PATTERN = /(?:^|;|\{)\s*background(?:-image)?\s*:[^;}]*(?:\bgradient\s*\(|url\s*\()/i;
7750
7788
  function detectAncestorBackgroundImage(html) {
7751
7789
  const { document: document2 } = parseHTML5(html);
7752
7790
  const root = document2.querySelector("[data-composition-id]");
@@ -7758,13 +7796,13 @@ function detectAncestorBackgroundImage(html) {
7758
7796
  }
7759
7797
  for (const el of ancestors) {
7760
7798
  const style = el.getAttribute("style");
7761
- if (style && BACKGROUND_IMAGE_DECL_PATTERN.test(`{${style}}`)) return true;
7799
+ if (style && hasBackgroundImageDeclaration(`{${style}}`)) return true;
7762
7800
  }
7763
7801
  for (const styleEl of document2.querySelectorAll("style")) {
7764
7802
  const css = styleEl.textContent ?? "";
7765
- for (const rule of css.matchAll(/([^{}]+)\{([^}]*)\}/g)) {
7766
- const [, selectorList = "", declarations = ""] = rule;
7767
- if (!BACKGROUND_IMAGE_DECL_PATTERN.test(`{${declarations}}`)) continue;
7803
+ for (const { parts: rule } of cssRuleMatches(css)) {
7804
+ const [, selectorList, declarations] = rule;
7805
+ if (!hasBackgroundImageDeclaration(`{${declarations}}`)) continue;
7768
7806
  for (const selector of selectorList.split(",")) {
7769
7807
  const sel = selector.trim();
7770
7808
  if (!sel || sel.startsWith("@")) continue;
@@ -7974,7 +8012,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
7974
8012
  workItems.map(async (item) => {
7975
8013
  const { html: compiledSub } = await compileHtmlFile(
7976
8014
  rewriteUnresolvableGsapToCdn(item.rawSubHtml, projectDir, item.srcPath),
7977
- dirname8(item.filePath),
8015
+ dirname9(item.filePath),
7978
8016
  downloadDir,
7979
8017
  void 0,
7980
8018
  urlByAbsentLocalPath,
@@ -8085,7 +8123,6 @@ function coalesceHeadStylesAndBodyScripts(html) {
8085
8123
  el.textContent = dedupedStyles[i] ?? "";
8086
8124
  });
8087
8125
  const styleEls = head ? Array.from(head.querySelectorAll("style")) : [];
8088
- const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
8089
8126
  for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
8090
8127
  const imports = [];
8091
8128
  const cssParts = [];
@@ -8093,7 +8130,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8093
8130
  for (const el of run) {
8094
8131
  const raw = (el.textContent || "").trim();
8095
8132
  if (!raw) continue;
8096
- const nonImportCss = raw.replace(importRe, (match) => {
8133
+ const nonImportCss = replaceMatches(raw, importRuleMatches(raw), (match) => {
8097
8134
  const cleaned = match.trim();
8098
8135
  if (!seenImports.has(cleaned)) {
8099
8136
  seenImports.add(cleaned);
@@ -8403,7 +8440,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8403
8440
  for (const styleEl of document2.querySelectorAll("style")) {
8404
8441
  const css = styleEl.textContent || "";
8405
8442
  if (!css.includes("url(")) continue;
8406
- const rewritten = css.replace(CSS_URL_RE, (full, quote, rawUrl) => {
8443
+ const rewritten = replaceMatches(css, cssUrlMatches(css), (full, quote, rawUrl) => {
8407
8444
  const result = processPath((rawUrl || "").trim());
8408
8445
  if (!result) return full;
8409
8446
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -8413,7 +8450,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8413
8450
  for (const el of document2.querySelectorAll("[style]")) {
8414
8451
  const style = el.getAttribute("style") || "";
8415
8452
  if (!style.includes("url(")) continue;
8416
- const rewritten = style.replace(CSS_URL_RE, (full, quote, rawUrl) => {
8453
+ const rewritten = replaceMatches(style, cssUrlMatches(style), (full, quote, rawUrl) => {
8417
8454
  const result = processPath((rawUrl || "").trim());
8418
8455
  if (!result) return full;
8419
8456
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -8516,13 +8553,10 @@ async function localizeRemoteImageSources(html, downloadDir) {
8516
8553
  "Localized remote image source(s)"
8517
8554
  );
8518
8555
  }
8519
- var REMOTE_BG_URL_RE = /background(?:-image)?\s*:\s*[^;}"']*?url\(\s*["']?(https?:\/\/[^"')]+)["']?\s*\)/gi;
8520
8556
  async function localizeRemoteBackgroundImages(html, downloadDir) {
8521
8557
  const urlSet = /* @__PURE__ */ new Set();
8522
- const re = new RegExp(REMOTE_BG_URL_RE.source, REMOTE_BG_URL_RE.flags);
8523
- let m;
8524
- while ((m = re.exec(html)) !== null) {
8525
- if (m[1] && !isGoogleFontsUrl(m[1])) urlSet.add(m[1]);
8558
+ for (const { parts } of remoteBackgroundUrlMatches(html)) {
8559
+ if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
8526
8560
  }
8527
8561
  return downloadAndRewriteUrls(
8528
8562
  urlSet,
@@ -8535,7 +8569,6 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
8535
8569
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
8536
8570
  );
8537
8571
  }
8538
- var REMOTE_FONTFACE_URL_RE = /url\(["']?(https?:\/\/[^"')]+)["']?\)/gi;
8539
8572
  function isGoogleFontsUrl(href) {
8540
8573
  try {
8541
8574
  const host = new URL(href).hostname.toLowerCase();
@@ -8563,31 +8596,33 @@ async function fetchExternalStylesheetCss(href) {
8563
8596
  }
8564
8597
  function extractFontFaceBlocks(css) {
8565
8598
  const blocks = [];
8599
+ const closes = matchingBraces(css);
8566
8600
  const atRule = /@font-face\s*/gi;
8567
- let m;
8568
- while ((m = atRule.exec(css)) !== null) {
8569
- const openIdx = css.indexOf("{", m.index + m[0].length);
8570
- if (openIdx === -1) break;
8571
- let depth = 1;
8572
- let i = openIdx + 1;
8573
- for (; i < css.length && depth > 0; i++) {
8574
- if (css[i] === "{") depth++;
8575
- else if (css[i] === "}") depth--;
8576
- }
8577
- if (depth === 0) {
8578
- blocks.push(css.slice(m.index, i));
8579
- atRule.lastIndex = i;
8580
- }
8601
+ let open2 = -1;
8602
+ for (let m = atRule.exec(css); m; m = atRule.exec(css)) {
8603
+ if (open2 < atRule.lastIndex) open2 = css.indexOf("{", atRule.lastIndex);
8604
+ if (open2 === -1) break;
8605
+ const close = closes.get(open2);
8606
+ if (close === void 0) continue;
8607
+ blocks.push(css.slice(m.index, close + 1));
8608
+ atRule.lastIndex = close + 1;
8581
8609
  }
8582
8610
  return blocks;
8583
8611
  }
8612
+ function matchingBraces(css) {
8613
+ const closes = /* @__PURE__ */ new Map();
8614
+ const unclosed = [];
8615
+ for (let i = 0; i < css.length; i++) {
8616
+ if (css[i] === "{") unclosed.push(i);
8617
+ else if (css[i] === "}" && unclosed.length > 0) closes.set(unclosed.pop(), i);
8618
+ }
8619
+ return closes;
8620
+ }
8584
8621
  async function inlineExternalFontStylesheets(html) {
8585
- const linkRe = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
8586
8622
  const hrefRe = /\bhref=["']([^"']+)["']/i;
8587
8623
  const linkMatches = [];
8588
- let linkMatch;
8589
- while ((linkMatch = linkRe.exec(html)) !== null) {
8590
- const tag = linkMatch[0];
8624
+ for (const { parts } of stylesheetLinkMatches(html)) {
8625
+ const tag = parts[0];
8591
8626
  const hrefMatch = hrefRe.exec(tag);
8592
8627
  if (!hrefMatch?.[1]) continue;
8593
8628
  const href = hrefMatch[1];
@@ -8628,16 +8663,18 @@ ${fontFaceBlocks.join("\n")}
8628
8663
  }
8629
8664
  function projectStylesheetFontFamilies(html, projectDir) {
8630
8665
  const families = [];
8631
- for (const [tag] of html.matchAll(/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi)) {
8666
+ for (const {
8667
+ parts: [tag]
8668
+ } of stylesheetLinkMatches(html)) {
8632
8669
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
8633
8670
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
8634
8671
  const sheet = resolve7(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
8635
8672
  if (!isPathInside(sheet, projectDir) || !existsSync11(sheet)) continue;
8636
8673
  for (const face of extractFontFaceBlocks(readFileSync8(sheet, "utf8"))) {
8637
8674
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
8638
- const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
8675
+ const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
8639
8676
  const path = decodedUrlPath(url);
8640
- const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname8(sheet), path);
8677
+ const file = path.startsWith("/") ? resolve7(projectDir, `.${path}`) : resolve7(dirname9(sheet), path);
8641
8678
  return isPathInside(file, projectDir) && existsSync11(file);
8642
8679
  });
8643
8680
  if (family && shipsFile) families.push(family);
@@ -8646,11 +8683,9 @@ function projectStylesheetFontFamilies(html, projectDir) {
8646
8683
  return families;
8647
8684
  }
8648
8685
  function collectFontFaceUrls(html) {
8649
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
8650
8686
  const urlSet = /* @__PURE__ */ new Set();
8651
- let styleMatch;
8652
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
8653
- const cssText = styleMatch[1] ?? "";
8687
+ for (const { parts } of styleBlockMatches(html)) {
8688
+ const cssText = parts[1];
8654
8689
  let i = 0;
8655
8690
  while (i < cssText.length) {
8656
8691
  const atIdx = cssText.indexOf("@font-face", i);
@@ -8665,10 +8700,8 @@ function collectFontFaceUrls(html) {
8665
8700
  j++;
8666
8701
  }
8667
8702
  const block = cssText.slice(braceStart + 1, j - 1);
8668
- const urlRe = new RegExp(REMOTE_FONTFACE_URL_RE.source, REMOTE_FONTFACE_URL_RE.flags);
8669
- let urlMatch;
8670
- while ((urlMatch = urlRe.exec(block)) !== null) {
8671
- if (urlMatch[1]) urlSet.add(urlMatch[1]);
8703
+ for (const { parts: parts2 } of remoteFontFaceUrlMatches(block)) {
8704
+ if (parts2[1]) urlSet.add(parts2[1]);
8672
8705
  }
8673
8706
  i = j;
8674
8707
  }
@@ -8688,7 +8721,6 @@ function localizeFontFaceUrls(html, downloadDir) {
8688
8721
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
8689
8722
  );
8690
8723
  }
8691
- var LOCAL_FONTFACE_URL_RE = /url\(["']?(?!data:|file:|https?:\/\/)([^"')]+)["']?\)/gi;
8692
8724
  function urlOccurrenceRe(localPath) {
8693
8725
  const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8694
8726
  return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
@@ -8709,23 +8741,15 @@ async function readLocalFont(absPath) {
8709
8741
  }
8710
8742
  async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
8711
8743
  const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
8712
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
8713
- const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;
8714
8744
  let result = html;
8715
8745
  const embeddedPaths = /* @__PURE__ */ new Set();
8716
8746
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
8717
8747
  const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
8718
- let styleMatch;
8719
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
8720
- const cssText = styleMatch[1] ?? "";
8721
- const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);
8722
- let ffMatch;
8723
- while ((ffMatch = ffRe.exec(cssText)) !== null) {
8724
- const block = ffMatch[1] ?? "";
8725
- const urlRe = new RegExp(LOCAL_FONTFACE_URL_RE.source, LOCAL_FONTFACE_URL_RE.flags);
8726
- let urlMatch;
8727
- while ((urlMatch = urlRe.exec(block)) !== null) {
8728
- const localPath = urlMatch[1];
8748
+ for (const { parts: style } of styleBlockMatches(html)) {
8749
+ for (const { parts: face } of fontFaceBlockMatches(style[1])) {
8750
+ const block = face[1];
8751
+ for (const { parts } of localFontFaceUrlMatches(block)) {
8752
+ const localPath = parts[1];
8729
8753
  if (!localPath || embeddedPaths.has(localPath)) continue;
8730
8754
  const absPath = localPath.startsWith("/") ? localPath : resolve7(projectDir, localPath);
8731
8755
  if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
@@ -8844,6 +8868,9 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
8844
8868
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
8845
8869
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
8846
8870
  }
8871
+ if (!COMPOSITION_FILE.test(htmlPath)) {
8872
+ throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
8873
+ }
8847
8874
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
8848
8875
  const rawHtml = bindVariableMediaSources(
8849
8876
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
@@ -9399,6 +9426,14 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9399
9426
  }
9400
9427
 
9401
9428
  // src/services/render/stages/compileStage.ts
9429
+ function animatedGifCacheDir(extractCacheDir) {
9430
+ try {
9431
+ const root = extractCacheDir && privateCacheRoot(extractCacheDir);
9432
+ return root ? join20(root, "animated-gif") : void 0;
9433
+ } catch {
9434
+ return void 0;
9435
+ }
9436
+ }
9402
9437
  function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height, log) {
9403
9438
  if (!requested || !aspectAgnostic) return requested;
9404
9439
  const flipped = suggestMatchingPreset(width, height, requested);
@@ -9478,7 +9513,7 @@ async function runCompileStage(input) {
9478
9513
  variables: input.variables,
9479
9514
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
9480
9515
  pageMotionBlur: input.pageMotionBlur,
9481
- animatedGifCacheDir: cfg.extractCacheDir ? join20(cfg.extractCacheDir, "animated-gif") : void 0,
9516
+ animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
9482
9517
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
9483
9518
  allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
9484
9519
  });
@@ -10356,8 +10391,13 @@ import {
10356
10391
  rebaseVideoToWindow,
10357
10392
  resolveFinalFrameExtractionWindow as resolveFinalFrameExtractionWindow2,
10358
10393
  resolveVideoExtractionWindow as resolveVideoExtractionWindow2,
10359
- isHttpUrl as isHttpUrl2,
10394
+ isHttpUrl as isHttpUrl3,
10395
+ isInsideAssetRoots as isInsideAssetRoots2,
10360
10396
  assertPublicHttpsUrl,
10397
+ downloadToTemp as downloadToTemp2,
10398
+ resolveRestrictPageNetwork,
10399
+ isUrlNotPermittedError,
10400
+ writeUrlDownloadTelemetry as writeUrlDownloadTelemetry2,
10361
10401
  resolveProjectRelativeSrc as resolveProjectRelativeSrc4,
10362
10402
  runVideoExtractionWithRetry as runVideoExtractionWithRetry2,
10363
10403
  safeVideoExtractionSourceIdentity,
@@ -10598,9 +10638,11 @@ async function runExtractVideosStage(input) {
10598
10638
  deferRangeExtraction,
10599
10639
  shownBoxes,
10600
10640
  urlByAbsentLocalPath,
10641
+ audioDownloadDir,
10601
10642
  skipFrameExtractionIds = []
10602
10643
  } = input;
10603
10644
  const stage2Start = Date.now();
10645
+ const assetRoots = job.config.allowOutsideProjectAssets ? void 0 : mediaAssetRoots(projectDir, compiledDir);
10604
10646
  const extractionPolicy = resolveVideoExtractionPolicy();
10605
10647
  composition.videos = composition.videos.filter(
10606
10648
  (video) => !isVideoPastTimelineEnd(video, composition.duration)
@@ -10619,7 +10661,7 @@ async function runExtractVideosStage(input) {
10619
10661
  const probeFailures = await Promise.all(
10620
10662
  composition.videos.map(async (v) => {
10621
10663
  const videoPath = resolveProjectRelativeSrc4(v.src, projectDir, compiledDir);
10622
- if (!existsSync13(videoPath)) return null;
10664
+ if (!opensLocally(videoPath, assetRoots)) return null;
10623
10665
  try {
10624
10666
  const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata4(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata4(videoPath), {
10625
10667
  signal: abortSignal,
@@ -10657,7 +10699,7 @@ async function runExtractVideosStage(input) {
10657
10699
  const probed = await Promise.all(
10658
10700
  composition.images.map(async (img) => {
10659
10701
  const imgPath = resolveProjectRelativeSrc4(img.src, projectDir, compiledDir);
10660
- if (!existsSync13(imgPath)) return null;
10702
+ if (!opensLocally(imgPath, assetRoots)) return null;
10661
10703
  const colorSpace = await probeColorSpaceSafely(imgPath, log);
10662
10704
  if (isHdrColorSpace2(colorSpace)) {
10663
10705
  nativeHdrImageIds.add(img.id);
@@ -10670,7 +10712,16 @@ async function runExtractVideosStage(input) {
10670
10712
  imageColorSpaces.push(...probed);
10671
10713
  }
10672
10714
  if (skipFrameExtractionIds.length > 0) {
10673
- await appendVideoAudioFromProbe({ projectDir, compiledDir, composition, urlByAbsentLocalPath });
10715
+ await appendVideoAudioFromProbe({
10716
+ projectDir,
10717
+ compiledDir,
10718
+ composition,
10719
+ urlByAbsentLocalPath,
10720
+ downloadDir: audioDownloadDir,
10721
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10722
+ signal: abortSignal,
10723
+ log
10724
+ });
10674
10725
  videoReadinessSkipIds = [...skipFrameExtractionIds];
10675
10726
  } else if (composition.videos.length > 0) {
10676
10727
  const totalVideos = composition.videos.length;
@@ -10701,6 +10752,7 @@ async function runExtractVideosStage(input) {
10701
10752
  shownBoxes,
10702
10753
  contentKeyedDirs: [join22(compiledDir, REMOTE_MEDIA_SUBDIR)],
10703
10754
  urlByAbsentLocalPath,
10755
+ assetRoots,
10704
10756
  onProgress: ({ planned = 0, done = 0 }) => {
10705
10757
  framesPlanned += planned;
10706
10758
  framesDone += done;
@@ -10777,17 +10829,41 @@ function isPublicHttpsUrl(url) {
10777
10829
  return false;
10778
10830
  }
10779
10831
  }
10832
+ function opensLocally(path, assetRoots) {
10833
+ return existsSync13(path) && (!assetRoots || isInsideAssetRoots2(path, assetRoots));
10834
+ }
10835
+ function localProbeSource(src, input) {
10836
+ const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
10837
+ const readFrom = input.urlByAbsentLocalPath?.get(path) ?? path;
10838
+ const roots = input.allowOutsideProjectAssets ? void 0 : mediaAssetRoots(input.projectDir, input.compiledDir);
10839
+ return isHttpUrl3(readFrom) || opensLocally(readFrom, roots) ? readFrom : null;
10840
+ }
10841
+ async function remoteProbeSource(video, input) {
10842
+ if (!isPublicHttpsUrl(video.src)) return null;
10843
+ if (!resolveRestrictPageNetwork()) return video.src;
10844
+ if (!video.hasAudio || video.hidden) return null;
10845
+ const downloadDir = input.downloadDir ?? join22(input.compiledDir, REMOTE_MEDIA_SUBDIR);
10846
+ try {
10847
+ return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
10848
+ onTelemetry: writeUrlDownloadTelemetry2
10849
+ });
10850
+ } catch (error) {
10851
+ if (!isUrlNotPermittedError(error)) throw error;
10852
+ input.log?.warn("Video sound skipped: its URL is outside the download address rules", {
10853
+ videoId: video.id
10854
+ });
10855
+ return null;
10856
+ }
10857
+ }
10780
10858
  async function appendVideoAudioFromProbe(input) {
10781
- const { projectDir, compiledDir, composition, urlByAbsentLocalPath } = input;
10859
+ const { composition } = input;
10782
10860
  const videos = composition.videos.filter(
10783
10861
  (video) => !isVideoPastTimelineEnd(video, composition.duration)
10784
10862
  );
10785
10863
  const probed = await Promise.all(
10786
10864
  videos.map(async (video) => {
10787
- if (isHttpUrl2(video.src) && !isPublicHttpsUrl(video.src)) return null;
10788
- const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc4(video.src, projectDir, compiledDir);
10789
- const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
10790
- if (!isHttpUrl2(readFrom) && !existsSync13(readFrom)) return null;
10865
+ const readFrom = isHttpUrl3(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
10866
+ if (readFrom === null) return null;
10791
10867
  const metadata = await extractMediaMetadata4(readFrom);
10792
10868
  const window2 = await resolveFinalFrameExtractionWindow2(
10793
10869
  readFrom,
@@ -10810,7 +10886,7 @@ async function appendVideoAudioFromProbe(input) {
10810
10886
  import { existsSync as existsSync14 } from "node:fs";
10811
10887
  import {
10812
10888
  buildVideoLayerInput,
10813
- isHttpUrl as isHttpUrl3,
10889
+ isHttpUrl as isHttpUrl4,
10814
10890
  qualifyVideoLayer,
10815
10891
  resolveProjectRelativeSrc as resolveProjectRelativeSrc5
10816
10892
  } from "@hyperframes/engine";
@@ -10873,7 +10949,7 @@ async function planVideoLayerPassthrough(input) {
10873
10949
  const q = qualifyVideoLayer(input.videos, input.duration);
10874
10950
  if (!q.qualifies) return { reason: q.reason };
10875
10951
  const { video } = q;
10876
- if (isHttpUrl3(video.src)) return { reason: "remote_source" };
10952
+ if (isHttpUrl4(video.src)) return { reason: "remote_source" };
10877
10953
  const path = resolveProjectRelativeSrc5(video.src, input.projectDir, input.compiledDir);
10878
10954
  if (!existsSync14(path)) return { reason: "source_missing" };
10879
10955
  const layout = await probeVideoLayout(input.page, video.id, input.canvas, input.duration);
@@ -10902,7 +10978,7 @@ import {
10902
10978
 
10903
10979
  // src/services/render/audioDeliveryLimit.ts
10904
10980
  import { existsSync as existsSync15 } from "node:fs";
10905
- import { dirname as dirname10, join as join24 } from "node:path";
10981
+ import { dirname as dirname11, join as join24 } from "node:path";
10906
10982
  import {
10907
10983
  applyAudioFxChain,
10908
10984
  describeFfmpegFailure as describeFfmpegFailure3,
@@ -10912,7 +10988,7 @@ import {
10912
10988
 
10913
10989
  // src/services/render/audioPadTrim.ts
10914
10990
  import { spawn } from "node:child_process";
10915
- import { dirname as dirname9, join as join23 } from "node:path";
10991
+ import { dirname as dirname10, join as join23 } from "node:path";
10916
10992
  import {
10917
10993
  DEFAULT_CONFIG,
10918
10994
  describeFfmpegFailure as describeFfmpegFailure2,
@@ -11206,7 +11282,7 @@ async function cutSource(input, scratchDir, attenuationDb) {
11206
11282
  async function enforceAacTruePeak(input) {
11207
11283
  let scratchDir;
11208
11284
  try {
11209
- scratchDir = createStagingDir3(dirname9(input.audioPath), ".true-peak-");
11285
+ scratchDir = createStagingDir3(dirname10(input.audioPath), ".true-peak-");
11210
11286
  const correctedPath = join23(scratchDir, "audio.m4a");
11211
11287
  const measurements = [];
11212
11288
  let attenuationDb = 0;
@@ -11417,7 +11493,7 @@ async function limitDeliveryPeaks(input, deps = {
11417
11493
  const peak = await deps.measure(audioPath, { timeoutMs, signal });
11418
11494
  if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
11419
11495
  const alternating = ["a", "b"].map(
11420
- (k) => join24(dirname10(sourcePath), `audio-source-limited-${k}.wav`)
11496
+ (k) => join24(dirname11(sourcePath), `audio-source-limited-${k}.wav`)
11421
11497
  );
11422
11498
  let encodedFrom;
11423
11499
  let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
@@ -11565,7 +11641,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11565
11641
  audioResult = await processCompositionAudio(
11566
11642
  audios,
11567
11643
  projectDir,
11568
- join25(workDir, "audio-work"),
11644
+ audioWorkDir(workDir),
11569
11645
  audioOutputPath,
11570
11646
  duration,
11571
11647
  abortSignal,
@@ -11575,7 +11651,8 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
11575
11651
  masterFxChain,
11576
11652
  urlByAbsentLocalPath,
11577
11653
  audioSidecarUrlByLocalPath,
11578
- keepEncoderInputAt: pcmSourcePath
11654
+ keepEncoderInputAt: pcmSourcePath,
11655
+ assetRoots: input.allowOutsideProjectAssets ? void 0 : mediaAssetRoots(projectDir, compiledDir)
11579
11656
  },
11580
11657
  compiledDir
11581
11658
  );
@@ -12255,7 +12332,7 @@ import {
12255
12332
  // src/services/shaderTransitionWorkerPool.ts
12256
12333
  import { Worker } from "node:worker_threads";
12257
12334
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
12258
- import { dirname as dirname11, join as join28 } from "node:path";
12335
+ import { dirname as dirname12, join as join28 } from "node:path";
12259
12336
  import { createRequire } from "node:module";
12260
12337
  import { usableCpuCount } from "@hyperframes/engine";
12261
12338
  import { existsSync as existsSync18 } from "node:fs";
@@ -12268,7 +12345,7 @@ function resolveWorkerEntry(explicit) {
12268
12345
  const isTs = override.endsWith(".ts");
12269
12346
  return { path: override, isTs };
12270
12347
  }
12271
- const moduleDir = dirname11(fileURLToPath3(import.meta.url));
12348
+ const moduleDir = dirname12(fileURLToPath3(import.meta.url));
12272
12349
  const jsPath = join28(moduleDir, "shaderTransitionWorker.js");
12273
12350
  if (existsSync18(jsPath)) return { path: jsPath, isTs: false };
12274
12351
  const tsPath = join28(moduleDir, "shaderTransitionWorker.ts");
@@ -12997,7 +13074,7 @@ import {
12997
13074
  writeFileSync as writeFileSync6
12998
13075
  } from "node:fs";
12999
13076
  import { readFile as readFile2 } from "node:fs/promises";
13000
- import { dirname as dirname12, join as join31 } from "node:path";
13077
+ import { dirname as dirname13, join as join31 } from "node:path";
13001
13078
  import {
13002
13079
  encodeFramesChunkedConcat,
13003
13080
  encodeFramesFromDir,
@@ -13315,7 +13392,7 @@ async function runEncodeStage(input) {
13315
13392
  const encodeResult2 = await encodeGifFromDir(framesDir, framePattern2, outputPath, {
13316
13393
  fps: job.config.fps,
13317
13394
  loop,
13318
- palettePath: join31(dirname12(videoOnlyPath), "gif-palette.png"),
13395
+ palettePath: join31(dirname13(videoOnlyPath), "gif-palette.png"),
13319
13396
  preserveAlpha: needsAlpha,
13320
13397
  signal: abortSignal,
13321
13398
  timeout: engineCfg.ffmpegEncodeTimeout
@@ -13760,7 +13837,7 @@ function getNextRetryWorkerCount(currentWorkers) {
13760
13837
  }
13761
13838
  function resolveRenderWorkDirPrefix(outputPath, jobId, platform2 = process.platform, systemTempDir = tmpdir2()) {
13762
13839
  if (platform2 === "win32" || platform2 === "darwin") return join32(systemTempDir, "hf-render-");
13763
- return join32(dirname13(outputPath), `work-${jobId}-`);
13840
+ return join32(dirname14(outputPath), `work-${jobId}-`);
13764
13841
  }
13765
13842
  var MAX_TRANSIENT_CAPTURE_RETRIES = 1;
13766
13843
  function isTransientCaptureRetryEligible(failureKind, missing, retriesUsed) {
@@ -14463,6 +14540,19 @@ function resolveCaptureForceScreenshotForPageSideCompositing(args) {
14463
14540
  function shouldDiscardProbeSessionForPageSideCompositing(args) {
14464
14541
  return args.hasProbeSession && args.usePageSideCompositing;
14465
14542
  }
14543
+ var PAGE_SIDE_COMPOSITOR_CANVAS_ID = "__hf-page-side-compositor";
14544
+ async function pageInstallsShaderCompositor(open2, session = { initializeSession: initializeSession8, closeCaptureSession: closeCaptureSession8 }) {
14545
+ const probe = await open2();
14546
+ try {
14547
+ await session.initializeSession(probe);
14548
+ return await probe.page.evaluate(
14549
+ (id) => document.getElementById(id) !== null,
14550
+ PAGE_SIDE_COMPOSITOR_CANVAS_ID
14551
+ );
14552
+ } finally {
14553
+ await session.closeCaptureSession(probe);
14554
+ }
14555
+ }
14466
14556
  function deVerifyFallbackTelemetry(err) {
14467
14557
  const details = getDrawElementVerificationDetails(err);
14468
14558
  return {
@@ -14473,7 +14563,7 @@ function deVerifyFallbackTelemetry(err) {
14473
14563
  };
14474
14564
  }
14475
14565
  function resolveRenderDebugDir() {
14476
- const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname13(fileURLToPath4(import.meta.url)), "../..");
14566
+ const producerRoot = process.env.PRODUCER_RENDERS_DIR ? resolve8(process.env.PRODUCER_RENDERS_DIR, "..") : resolve8(dirname14(fileURLToPath4(import.meta.url)), "../..");
14477
14567
  return join32(producerRoot, ".debug");
14478
14568
  }
14479
14569
  async function executeRenderJob(job, projectDir, outputPath, progressSink, abortSignal, assertRenderActive) {
@@ -14481,7 +14571,7 @@ async function executeRenderJob(job, projectDir, outputPath, progressSink, abort
14481
14571
  validateDeliveryEncoderConfig(job.config);
14482
14572
  validateChromaSubsamplingConfig(job.config);
14483
14573
  const debugDir = resolveRenderDebugDir();
14484
- const outputDir = dirname13(outputPath);
14574
+ const outputDir = dirname14(outputPath);
14485
14575
  if (!existsSync21(outputDir)) mkdirSync12(outputDir, { recursive: true });
14486
14576
  const workDir = job.config.debug ? join32(debugDir, job.id) : createRenderWorkDir(resolveRenderWorkDirPrefix(outputPath, job.id), outputDir);
14487
14577
  const pipelineStart = Date.now();
@@ -14893,6 +14983,7 @@ async function executeRenderPipeline(input) {
14893
14983
  log,
14894
14984
  composition,
14895
14985
  skipFrameExtractionIds: videoLayer ? [videoLayer.videoId] : [],
14986
+ audioDownloadDir: audioWorkDir(workDir),
14896
14987
  abortSignal: executionSignal,
14897
14988
  assertNotAborted,
14898
14989
  // Local staging can use links; distributed plan() alone requires real copies.
@@ -14979,6 +15070,7 @@ async function executeRenderPipeline(input) {
14979
15070
  audioGain: cfg.audioGain,
14980
15071
  audios: composition.audios,
14981
15072
  masterFxChain: composition.masterFxChain,
15073
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
14982
15074
  abortSignal: executionSignal,
14983
15075
  assertNotAborted,
14984
15076
  log,
@@ -15598,7 +15690,7 @@ async function executeRenderPipeline(input) {
15598
15690
  };
15599
15691
  const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
15600
15692
  const videoOnlyPath = join32(workDir, `video-only${videoExt}`);
15601
- const usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15693
+ let usePageSideCompositingForTransitions = (cfg.enablePageSideCompositing || isGif) && compiled.hasShaderTransitions && !hasHdrContent && outputSupportsPageSideShaderCompositing(outputFormat);
15602
15694
  if (usePageSideCompositingForTransitions) {
15603
15695
  activeFileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
15604
15696
  if (shouldDiscardProbeSessionForPageSideCompositing({
@@ -15612,6 +15704,26 @@ async function executeRenderPipeline(input) {
15612
15704
  "[Render] Recreating capture session so page-side compositing pre-head script is loaded."
15613
15705
  );
15614
15706
  }
15707
+ try {
15708
+ usePageSideCompositingForTransitions = await pageInstallsShaderCompositor(
15709
+ () => createCaptureSession8(activeFileServer.url, framesDir, buildPrepCaptureOptions(), null, {
15710
+ ...cfg,
15711
+ forceScreenshot: true
15712
+ })
15713
+ );
15714
+ } catch (error) {
15715
+ assertNotAborted();
15716
+ log.warn("[Render] Shader compositor check failed; keeping page-side compositing.", {
15717
+ error: error instanceof Error ? error.message : String(error)
15718
+ });
15719
+ }
15720
+ if (!usePageSideCompositingForTransitions) {
15721
+ log.warn(
15722
+ "[Render] The page's shader-transitions build cannot composite in this browser; shader transitions blend on the Node-side layered path."
15723
+ );
15724
+ }
15725
+ }
15726
+ if (usePageSideCompositingForTransitions) {
15615
15727
  captureForceScreenshot = resolveCaptureForceScreenshotForPageSideCompositing({
15616
15728
  forceScreenshot: captureForceScreenshot,
15617
15729
  usePageSideCompositing: true
@@ -16631,7 +16743,7 @@ import { tmpdir as tmpdir4 } from "node:os";
16631
16743
  import { createReadStream as createReadStream3, createWriteStream, mkdirSync as mkdirSync13, rmSync as rmSync13 } from "node:fs";
16632
16744
  import { open } from "node:fs/promises";
16633
16745
  import { renameWithRetry as renameWithRetry7 } from "@hyperframes/engine";
16634
- import { basename as basename7, dirname as dirname14, join as join33 } from "node:path";
16746
+ import { basename as basename7, dirname as dirname15, join as join33 } from "node:path";
16635
16747
  import { finished, pipeline } from "node:stream/promises";
16636
16748
  import { createStagingDir as createStagingDir4 } from "@hyperframes/core/atomic-file";
16637
16749
  function boxAt(src, off, at, limit) {
@@ -16996,8 +17108,8 @@ async function writeStitchedMp4(chunkPaths, outputPath, audioPath) {
16996
17108
  const sourcePaths = audioPath ? [audioPath, ...chunkPaths] : chunkPaths;
16997
17109
  const layouts = await Promise.all(sourcePaths.map((path) => readMp4Layout(fileRange(path))));
16998
17110
  const header = audioPath ? buildStitchedHeader(layouts.slice(1), layouts[0]) : buildStitchedHeader(layouts);
16999
- mkdirSync13(dirname14(outputPath), { recursive: true });
17000
- const workDir = createStagingDir4(dirname14(outputPath), `${basename7(outputPath)}.stitch-`);
17111
+ mkdirSync13(dirname15(outputPath), { recursive: true });
17112
+ const workDir = createStagingDir4(dirname15(outputPath), `${basename7(outputPath)}.stitch-`);
17001
17113
  const out = createWriteStream(join33(workDir, "out.mp4"));
17002
17114
  try {
17003
17115
  out.write(header);
@@ -17063,7 +17175,7 @@ import {
17063
17175
 
17064
17176
  // src/services/distributed/shared.ts
17065
17177
  import { execFile as execFileCallback } from "node:child_process";
17066
- import { dirname as dirname15, join as join34 } from "node:path";
17178
+ import { dirname as dirname16, join as join34 } from "node:path";
17067
17179
  import { existsSync as existsSync22, readFileSync as readFileSync10 } from "node:fs";
17068
17180
  import { fileURLToPath as fileURLToPath5 } from "node:url";
17069
17181
  import { promisify as promisify2 } from "node:util";
@@ -17339,7 +17451,7 @@ function buildSyntheticRenderJob(input) {
17339
17451
  var cachedProducerVersion = null;
17340
17452
  function readProducerVersion() {
17341
17453
  if (cachedProducerVersion !== null) return cachedProducerVersion;
17342
- const startDir = dirname15(fileURLToPath5(import.meta.url));
17454
+ const startDir = dirname16(fileURLToPath5(import.meta.url));
17343
17455
  let current = startDir;
17344
17456
  for (let i = 0; i < 10; i++) {
17345
17457
  const candidate = join34(current, "package.json");
@@ -17353,7 +17465,7 @@ function readProducerVersion() {
17353
17465
  } catch {
17354
17466
  }
17355
17467
  }
17356
- const parent = dirname15(current);
17468
+ const parent = dirname16(current);
17357
17469
  if (parent === current) break;
17358
17470
  current = parent;
17359
17471
  }
@@ -18974,6 +19086,7 @@ function mixPlanAudio(c, compiledDir) {
18974
19086
  compiledDir,
18975
19087
  urlByAbsentLocalPath: c.urlByAbsentLocalPath,
18976
19088
  audioSidecarUrlByLocalPath: c.audioSidecarUrlByLocalPath,
19089
+ allowOutsideProjectAssets: c.job.config.allowOutsideProjectAssets,
18977
19090
  totalFrames: c.totalFrames,
18978
19091
  fps: c.job.config.fps,
18979
19092
  ffmpegProcessTimeout: c.cfg.ffmpegProcessTimeout,
@@ -19332,7 +19445,7 @@ import {
19332
19445
  writeFileSync as writeFileSync12
19333
19446
  } from "node:fs";
19334
19447
  import { tmpdir as tmpdir3 } from "node:os";
19335
- import { dirname as dirname17, isAbsolute as isAbsolute4, join as join44, relative as relative7, resolve as resolve10, sep as sep5 } from "node:path";
19448
+ import { dirname as dirname18, isAbsolute as isAbsolute4, join as join44, relative as relative7, resolve as resolve10, sep as sep5 } from "node:path";
19336
19449
  import { DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core";
19337
19450
  import {
19338
19451
  createFrameLookupTable as createFrameLookupTable5,
@@ -19351,7 +19464,7 @@ import {
19351
19464
  writeFileSync as writeFileSync11
19352
19465
  } from "node:fs";
19353
19466
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
19354
- import { dirname as dirname16, join as join43 } from "node:path";
19467
+ import { dirname as dirname17, join as join43 } from "node:path";
19355
19468
 
19356
19469
  // src/services/distributed/planV2Errors.ts
19357
19470
  var PLAN_V2_INTEGRITY_UNRECOVERABLE = "PLAN_V2_INTEGRITY_UNRECOVERABLE";
@@ -19412,8 +19525,8 @@ var LocalPlanV2ArtifactPublisher = class {
19412
19525
  }
19413
19526
  this.destinationDir = destinationDir;
19414
19527
  this.#linkFile = options.linkFile ?? linkSync2;
19415
- mkdirSync17(dirname16(destinationDir), { recursive: true });
19416
- this.temporaryDir = createStagingDir5(dirname16(destinationDir), ".plan-v2-publish-");
19528
+ mkdirSync17(dirname17(destinationDir), { recursive: true });
19529
+ this.temporaryDir = createStagingDir5(dirname17(destinationDir), ".plan-v2-publish-");
19417
19530
  }
19418
19531
  async putBlob(blob) {
19419
19532
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
@@ -19425,8 +19538,8 @@ var LocalPlanV2ArtifactPublisher = class {
19425
19538
  }
19426
19539
  const destinationPath = planV2BlobPath(this.temporaryDir, digest);
19427
19540
  if (existsSync27(destinationPath)) return;
19428
- mkdirSync17(dirname16(destinationPath), { recursive: true });
19429
- const stagingDir = createStagingDir5(dirname16(destinationPath), ".plan-v2-blob-");
19541
+ mkdirSync17(dirname17(destinationPath), { recursive: true });
19542
+ const stagingDir = createStagingDir5(dirname17(destinationPath), ".plan-v2-blob-");
19430
19543
  const temporaryPath = join43(stagingDir, "blob");
19431
19544
  try {
19432
19545
  try {
@@ -19717,8 +19830,8 @@ function computeManifestHash(manifest) {
19717
19830
  }
19718
19831
  function writeBlob(sourcePath, destinationPath) {
19719
19832
  if (existsSync28(destinationPath)) return;
19720
- mkdirSync18(dirname17(destinationPath), { recursive: true });
19721
- const temporaryDir = createStagingDir6(dirname17(destinationPath), ".plan-v2-blob-");
19833
+ mkdirSync18(dirname18(destinationPath), { recursive: true });
19834
+ const temporaryDir = createStagingDir6(dirname18(destinationPath), ".plan-v2-blob-");
19722
19835
  const temporaryPath = join44(temporaryDir, "blob");
19723
19836
  try {
19724
19837
  copyFileSync8(sourcePath, temporaryPath);
@@ -19843,8 +19956,8 @@ function createPlanV2FromExecutionPlan(executionPlanDir, planV2Dir) {
19843
19956
  if (publication.storedBlobs.length > 0) {
19844
19957
  throw new PlanV2IntegrityError("a local plan v2 directory cannot reference remote files");
19845
19958
  }
19846
- mkdirSync18(dirname17(planV2Dir), { recursive: true });
19847
- const tempDir = createStagingDir6(dirname17(planV2Dir), ".plan-v2-build-");
19959
+ mkdirSync18(dirname18(planV2Dir), { recursive: true });
19960
+ const tempDir = createStagingDir6(dirname18(planV2Dir), ".plan-v2-build-");
19848
19961
  try {
19849
19962
  for (const blob of publication.blobs) {
19850
19963
  writeBlob(blob.sourcePath, planV2BlobPath(tempDir, blob.sha256));
@@ -19928,7 +20041,7 @@ async function planV2(projectDir, config, planV2Dir) {
19928
20041
  }
19929
20042
  const publisher = new LocalPlanV2ArtifactPublisher(planV2Dir);
19930
20043
  const manifest = await planV2WithPublisher(projectDir, config, publisher, {
19931
- stagingParentDir: dirname17(planV2Dir)
20044
+ stagingParentDir: dirname18(planV2Dir)
19932
20045
  });
19933
20046
  return resultFromManifest(planV2Dir, manifest);
19934
20047
  }
@@ -20121,12 +20234,12 @@ function materializePlanV2Target(planV2Dir, target, destinationDir, options = {}
20121
20234
  artifact,
20122
20235
  sourcePath: verifyBlob(planV2Dir, artifact)
20123
20236
  }));
20124
- mkdirSync18(dirname17(destinationDir), { recursive: true });
20125
- const tempDir = createStagingDir6(dirname17(destinationDir), ".plan-v2-materialize-");
20237
+ mkdirSync18(dirname18(destinationDir), { recursive: true });
20238
+ const tempDir = createStagingDir6(dirname18(destinationDir), ".plan-v2-materialize-");
20126
20239
  try {
20127
20240
  for (const { artifact, sourcePath } of verified) {
20128
20241
  const destinationPath = join44(tempDir, ...artifact.path.split("/"));
20129
- mkdirSync18(dirname17(destinationPath), { recursive: true });
20242
+ mkdirSync18(dirname18(destinationPath), { recursive: true });
20130
20243
  copyFileSync8(sourcePath, destinationPath);
20131
20244
  }
20132
20245
  if (target.role === "chunk") materializeExtractedVideoDirectories(tempDir);
@@ -21605,9 +21718,10 @@ import {
21605
21718
  rmSync as rmSync19,
21606
21719
  createReadStream as createReadStream5
21607
21720
  } from "node:fs";
21608
- import { resolve as resolve12, dirname as dirname19, join as join49 } from "node:path";
21721
+ import { resolve as resolve12, dirname as dirname20, join as join49 } from "node:path";
21609
21722
  import { tmpdir as tmpdir5 } from "node:os";
21610
21723
  import { parseArgs } from "node:util";
21724
+ import { isIP } from "node:net";
21611
21725
  import crypto from "node:crypto";
21612
21726
  import { Hono as Hono2 } from "hono";
21613
21727
  import { streamSSE } from "hono/streaming";
@@ -21617,6 +21731,7 @@ import {
21617
21731
  REFERENCE_BACKGROUND_FIELD as REFERENCE_BACKGROUND_FIELD5,
21618
21732
  referenceBackgroundResult as referenceBackgroundResult7
21619
21733
  } from "@hyperframes/engine";
21734
+ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
21620
21735
 
21621
21736
  // src/services/hyperframeLint.ts
21622
21737
  import {
@@ -21672,7 +21787,11 @@ function readEntryHtml(filePath) {
21672
21787
  closeSync7(fd);
21673
21788
  }
21674
21789
  }
21675
- function readProjectEntryFile(projectDir, preferredEntryFile) {
21790
+ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
21791
+ const entryRelativePath = relative8(absProjectDir, absoluteEntryPath);
21792
+ return entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep6}`) || isAbsolute5(entryRelativePath) || isAllowedEntry !== void 0 && !isAllowedEntry(absoluteEntryPath);
21793
+ }
21794
+ function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
21676
21795
  const absProjectDir = resolve11(projectDir);
21677
21796
  if (!existsSync30(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
21678
21797
  return { error: `Project directory not found: ${absProjectDir}` };
@@ -21682,8 +21801,7 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
21682
21801
  );
21683
21802
  for (const entryFile of entryCandidates) {
21684
21803
  const absoluteEntryPath = resolve11(absProjectDir, entryFile);
21685
- const entryRelativePath = relative8(absProjectDir, absoluteEntryPath);
21686
- if (entryRelativePath === ".." || entryRelativePath.startsWith(`..${sep6}`) || isAbsolute5(entryRelativePath)) {
21804
+ if (leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry)) {
21687
21805
  return { error: `Entry file must stay inside project directory: ${entryFile}` };
21688
21806
  }
21689
21807
  const html = readEntryHtml(absoluteEntryPath);
@@ -21699,10 +21817,10 @@ function readProjectEntryFile(projectDir, preferredEntryFile) {
21699
21817
  error: `No HTML entry file found in project directory: ${join47(absProjectDir, preferredEntryFile || "index.html")}`
21700
21818
  };
21701
21819
  }
21702
- function prepareHyperframeLintBody(body) {
21820
+ function prepareHyperframeLintBody(body, isAllowedEntry) {
21703
21821
  const requestedEntryFile = typeof body.entryFile === "string" && body.entryFile.trim().length > 0 ? body.entryFile.trim() : void 0;
21704
21822
  if (typeof body.projectDir === "string" && body.projectDir.trim().length > 0) {
21705
- const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile);
21823
+ const prepared = readProjectEntryFile(body.projectDir, requestedEntryFile, isAllowedEntry);
21706
21824
  if ("error" in prepared) {
21707
21825
  return prepared;
21708
21826
  }
@@ -21742,7 +21860,7 @@ async function runHyperframeLint(prepared) {
21742
21860
  // src/services/healthWorker.ts
21743
21861
  import { Worker as Worker2 } from "node:worker_threads";
21744
21862
  import { fileURLToPath as fileURLToPath6 } from "node:url";
21745
- import { dirname as dirname18, join as join48 } from "node:path";
21863
+ import { dirname as dirname19, join as join48 } from "node:path";
21746
21864
  import { existsSync as existsSync31 } from "node:fs";
21747
21865
  var DEFAULT_HEALTH_PORT = 9848;
21748
21866
  async function startHealthWorker(options = {}) {
@@ -21817,7 +21935,7 @@ function defaultLogger2() {
21817
21935
  };
21818
21936
  }
21819
21937
  function resolveWorkerEntry2() {
21820
- const here = dirname18(fileURLToPath6(import.meta.url));
21938
+ const here = dirname19(fileURLToPath6(import.meta.url));
21821
21939
  const candidates = [join48(here, "healthWorkerThread.js"), join48(here, "healthWorkerThread.ts")];
21822
21940
  for (const candidate of candidates) {
21823
21941
  if (existsSync31(candidate)) return candidate;
@@ -21978,16 +22096,22 @@ function buildRenderJobConfig(input, outputPath, log) {
21978
22096
  });
21979
22097
  return renderConfigFromRequest(request, { logger: log });
21980
22098
  }
21981
- function resolvePreparedRenderOutput(prepared, rendersDir, log) {
22099
+ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
21982
22100
  const { input, cleanupProjectDir } = prepared;
21983
22101
  const absoluteOutputPath = resolveOutputPath(input.projectDir, input.outputPath, rendersDir, log);
21984
- const outputDir = dirname19(absoluteOutputPath);
22102
+ if (confineOutput) {
22103
+ mkdirSync21(rendersDir, { recursive: true });
22104
+ if (!isSafePath3(rendersDir, absoluteOutputPath)) {
22105
+ throw new Error("outputPath must be inside the renders directory");
22106
+ }
22107
+ }
22108
+ const outputDir = dirname20(absoluteOutputPath);
21985
22109
  if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
21986
22110
  return { input, cleanupProjectDir, absoluteOutputPath };
21987
22111
  }
21988
- function prepareRenderJob(prepared, rendersDir, log) {
22112
+ function prepareRenderJob(prepared, rendersDir, log, confineOutput) {
21989
22113
  try {
21990
- const output = resolvePreparedRenderOutput(prepared, rendersDir, log);
22114
+ const output = resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput);
21991
22115
  const job = createRenderJob(buildRenderJobConfig(output.input, output.absoluteOutputPath, log));
21992
22116
  return { ...output, job };
21993
22117
  } catch (error) {
@@ -22038,16 +22162,32 @@ function validateOutputResolutionOverride(body) {
22038
22162
  return void 0;
22039
22163
  }
22040
22164
  var MAX_PREVIEW_HTML_BYTES = 20 * 1024 * 1024;
22041
- function prepareProjectDirectory(projectDir, options) {
22165
+ function resolveRenderRequestPolicy(options) {
22166
+ return {
22167
+ projectsDir: resolve12(
22168
+ options.projectsDir ?? (process.env.PRODUCER_PROJECTS_DIR || process.cwd())
22169
+ ),
22170
+ allowDebug: options.allowDebug ?? process.env.PRODUCER_ALLOW_DEBUG === "1"
22171
+ };
22172
+ }
22173
+ function isAllowedProjectPath(projectsDir, path) {
22174
+ return isSafePath3(projectsDir, path) && !isSafePath3(resolveRenderDebugDir(), path);
22175
+ }
22176
+ function isAllowedEntryPath(policy, projectDir, path) {
22177
+ return isSafePath3(projectDir, path) && isAllowedProjectPath(policy.projectsDir, path);
22178
+ }
22179
+ function prepareProjectDirectory(projectDir, options, policy) {
22042
22180
  const candidate = nonEmptyString(projectDir);
22043
22181
  if (!candidate) return null;
22044
- const absProjectDir = resolve12(candidate);
22045
- if (!existsSync32(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22046
- return { error: `Project directory not found: ${absProjectDir}` };
22182
+ const absProjectDir = policy ? resolve12(policy.projectsDir, candidate) : resolve12(candidate);
22183
+ const shown = policy ? candidate : absProjectDir;
22184
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22185
+ return { error: `Project directory not found: ${shown}` };
22047
22186
  }
22048
22187
  const entry = options.entryFile || "index.html";
22049
- if (!existsSync32(resolve12(absProjectDir, entry))) {
22050
- return { error: `Entry file "${entry}" not found in project directory: ${absProjectDir}` };
22188
+ const entryPath = resolve12(absProjectDir, entry);
22189
+ if (policy && !isAllowedEntryPath(policy, absProjectDir, entryPath) || !existsSync32(entryPath)) {
22190
+ return { error: `Entry file "${entry}" not found in project directory: ${shown}` };
22051
22191
  }
22052
22192
  return { prepared: { input: { projectDir: absProjectDir, ...options } } };
22053
22193
  }
@@ -22076,15 +22216,18 @@ function materializeInlineProject(html, options) {
22076
22216
  }
22077
22217
  };
22078
22218
  }
22079
- async function prepareRenderBody(body) {
22219
+ async function prepareRenderBody(body, policy) {
22080
22220
  const overrideError = validateRenderOverrides(body);
22081
22221
  if (overrideError) return { error: overrideError };
22222
+ if (policy && body.debug === true && !policy.allowDebug) {
22223
+ return { error: "debug is disabled on this server (set allowDebug or PRODUCER_ALLOW_DEBUG=1)" };
22224
+ }
22082
22225
  const pageMotionBlur = body.pageMotionBlur;
22083
22226
  if (pageMotionBlur !== void 0 && pageMotionBlur !== "off") {
22084
22227
  return { error: "pageMotionBlur must be off when supplied" };
22085
22228
  }
22086
22229
  const options = { ...parseRenderOptions(body), pageMotionBlur };
22087
- const project = prepareProjectDirectory(body.projectDir, options);
22230
+ const project = prepareProjectDirectory(body.projectDir, options, policy);
22088
22231
  if (project) return project;
22089
22232
  const source = await resolveInlineRenderHtml(body);
22090
22233
  return "error" in source ? source : materializeInlineProject(source.html, options);
@@ -22137,6 +22280,9 @@ function cleanupTempDir(dir, log) {
22137
22280
  });
22138
22281
  }
22139
22282
  }
22283
+ function publicPerfSummary(job) {
22284
+ return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
22285
+ }
22140
22286
  function outputFileSize(path) {
22141
22287
  return existsSync32(path) ? statSync14(path).size : 0;
22142
22288
  }
@@ -22149,7 +22295,7 @@ function createBlockingProgressReporter(log, requestId) {
22149
22295
  log.info(`render progress ${pct}%`, { requestId, stage: job.currentStage, message });
22150
22296
  };
22151
22297
  }
22152
- async function prepareSseRenderRequest(c, stream, requestId) {
22298
+ async function prepareSseRenderRequest(c, stream, requestId, policy) {
22153
22299
  let body;
22154
22300
  try {
22155
22301
  body = await c.req.json();
@@ -22164,7 +22310,7 @@ async function prepareSseRenderRequest(c, stream, requestId) {
22164
22310
  });
22165
22311
  return null;
22166
22312
  }
22167
- const prepared = await prepareRenderBody(body);
22313
+ const prepared = await prepareRenderBody(body, policy);
22168
22314
  if (!("error" in prepared)) return prepared.prepared;
22169
22315
  await stream.writeSSE({
22170
22316
  data: JSON.stringify({
@@ -22236,6 +22382,7 @@ function createRenderHandlers(options = {}) {
22236
22382
  const getRequestId = options.getRequestId ?? ((c) => c.req.header("x-request-id") || crypto.randomUUID());
22237
22383
  const outputUrlPrefix = options.outputUrlPrefix ?? "/outputs";
22238
22384
  const rendersDir = options.rendersDir ?? process.env.PRODUCER_RENDERS_DIR ?? "/tmp";
22385
+ const policy = options.confineRequests ? resolveRenderRequestPolicy(options) : void 0;
22239
22386
  const artifactTtlMs = options.artifactTtlMs ?? Number(process.env.PRODUCER_OUTPUT_ARTIFACT_TTL_MS || 15 * 60 * 1e3);
22240
22387
  const store = createArtifactStore(artifactTtlMs);
22241
22388
  const maxConcurrentRenders = options.maxConcurrentRenders ?? Number(process.env.PRODUCER_MAX_CONCURRENT_RENDERS || 2);
@@ -22254,7 +22401,18 @@ function createRenderHandlers(options = {}) {
22254
22401
  } catch {
22255
22402
  return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
22256
22403
  }
22257
- const preparedResult = prepareHyperframeLintBody(body);
22404
+ const lintProjectDir = nonEmptyString(body.projectDir);
22405
+ let isAllowedEntry;
22406
+ if (policy && lintProjectDir) {
22407
+ const absProjectDir = resolve12(policy.projectsDir, lintProjectDir);
22408
+ if (!isAllowedProjectPath(policy.projectsDir, absProjectDir)) {
22409
+ const error = `Project directory not found: ${lintProjectDir}`;
22410
+ return c.json({ success: false, requestId, error }, 400);
22411
+ }
22412
+ body = { ...body, projectDir: absProjectDir };
22413
+ isAllowedEntry = (path) => isAllowedEntryPath(policy, absProjectDir, path);
22414
+ }
22415
+ const preparedResult = prepareHyperframeLintBody(body, isAllowedEntry);
22258
22416
  if ("error" in preparedResult) {
22259
22417
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
22260
22418
  }
@@ -22283,11 +22441,11 @@ function createRenderHandlers(options = {}) {
22283
22441
  } catch {
22284
22442
  return c.json({ success: false, requestId, error: "Invalid JSON body" }, 400);
22285
22443
  }
22286
- const preparedResult = await prepareRenderBody(body);
22444
+ const preparedResult = await prepareRenderBody(body, policy);
22287
22445
  if ("error" in preparedResult) {
22288
22446
  return c.json({ success: false, requestId, error: preparedResult.error }, 400);
22289
22447
  }
22290
- const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log);
22448
+ const preparedJob = prepareRenderJob(preparedResult.prepared, rendersDir, log, !!policy);
22291
22449
  if ("error" in preparedJob) {
22292
22450
  return c.json({ success: false, requestId, error: preparedJob.error }, 400);
22293
22451
  }
@@ -22328,7 +22486,7 @@ function createRenderHandlers(options = {}) {
22328
22486
  videoDurationSeconds: job.duration ?? null,
22329
22487
  outcome: job.outcome ?? "completed",
22330
22488
  warnings: job.warnings,
22331
- perf: job.perfSummary ?? null,
22489
+ perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
22332
22490
  ...strictVariablesResult(job)
22333
22491
  });
22334
22492
  } catch (error) {
@@ -22365,9 +22523,9 @@ function createRenderHandlers(options = {}) {
22365
22523
  return streamSSE(c, async (stream) => {
22366
22524
  const requestId = getRequestId(c);
22367
22525
  const t0 = Date.now();
22368
- const prepared = await prepareSseRenderRequest(c, stream, requestId);
22526
+ const prepared = await prepareSseRenderRequest(c, stream, requestId, policy);
22369
22527
  if (!prepared) return;
22370
- const preparedJob = prepareRenderJob(prepared, rendersDir, log);
22528
+ const preparedJob = prepareRenderJob(prepared, rendersDir, log, !!policy);
22371
22529
  if ("error" in preparedJob) {
22372
22530
  await stream.writeSSE({
22373
22531
  data: JSON.stringify({
@@ -22424,7 +22582,7 @@ function createRenderHandlers(options = {}) {
22424
22582
  videoDurationSeconds: job.duration ?? null,
22425
22583
  outcome: job.outcome ?? "completed",
22426
22584
  warnings: job.warnings,
22427
- perf: job.perfSummary ?? null,
22585
+ perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
22428
22586
  producerVersion: readProducerVersion(),
22429
22587
  ...strictVariablesResult(job)
22430
22588
  })
@@ -22482,9 +22640,79 @@ function isCrossOriginBrowserRequest(c) {
22482
22640
  return true;
22483
22641
  }
22484
22642
  }
22643
+ function hostnameOf(host) {
22644
+ try {
22645
+ return new URL(`http://${host}`).hostname.toLowerCase();
22646
+ } catch {
22647
+ return null;
22648
+ }
22649
+ }
22650
+ function isAllowedBrowserHostname(hostname2, allowed) {
22651
+ if (!hostname2) return false;
22652
+ if (hostname2 === "localhost" || hostname2.endsWith(".localhost")) return true;
22653
+ if (isIP(hostname2.replace(/^\[|\]$/g, "")) !== 0) return true;
22654
+ return allowed.has(hostname2);
22655
+ }
22656
+ function allowedHostnames(options) {
22657
+ const fromEnv = (process.env.PRODUCER_ALLOWED_HOSTS ?? "").split(",");
22658
+ const names = /* @__PURE__ */ new Set();
22659
+ for (const entry of [...options.allowedHosts ?? [], ...fromEnv]) {
22660
+ const hostname2 = entry.trim() ? hostnameOf(entry.trim()) : null;
22661
+ if (hostname2) names.add(hostname2);
22662
+ }
22663
+ return names;
22664
+ }
22665
+ function resolveAuthToken(options) {
22666
+ return options.authToken?.trim() || process.env.PRODUCER_AUTH_TOKEN?.trim() || "";
22667
+ }
22668
+ function hasBearerToken(c, token) {
22669
+ const digest = (value) => crypto.createHash("sha256").update(value).digest();
22670
+ return crypto.timingSafeEqual(
22671
+ digest(c.req.header("authorization") ?? ""),
22672
+ digest(`Bearer ${token}`)
22673
+ );
22674
+ }
22675
+ function isLoopbackHostname(hostname2) {
22676
+ const host = hostname2.replace(/^\[|\]$/g, "").toLowerCase();
22677
+ return host === "localhost" || host === "::1" || isIP(host) === 4 && host.startsWith("127.");
22678
+ }
22679
+ function isDisallowedBrowserHost(c, allowed) {
22680
+ const origin = c.req.header("origin");
22681
+ if (!origin && !c.req.header("sec-fetch-site")) return false;
22682
+ if (!isAllowedBrowserHostname(hostnameOf(c.req.header("host") ?? ""), allowed)) return true;
22683
+ if (!origin) return false;
22684
+ try {
22685
+ return !isAllowedBrowserHostname(new URL(origin).hostname.toLowerCase(), allowed);
22686
+ } catch {
22687
+ return true;
22688
+ }
22689
+ }
22485
22690
  function createProducerApp(options = {}) {
22486
22691
  const app = new Hono2();
22487
- const handlers = createRenderHandlers(options);
22692
+ const handlers = createRenderHandlers({
22693
+ ...options,
22694
+ confineRequests: options.confineRequests ?? true
22695
+ });
22696
+ const allowed = allowedHostnames(options);
22697
+ const authToken = resolveAuthToken(options);
22698
+ app.use("*", async (c, next) => {
22699
+ if (authToken && c.req.path !== "/health" && !hasBearerToken(c, authToken)) {
22700
+ return c.json({ success: false, error: "Unauthorized" }, 401);
22701
+ }
22702
+ await next();
22703
+ });
22704
+ app.use("*", async (c, next) => {
22705
+ if (isDisallowedBrowserHost(c, allowed)) {
22706
+ return c.json(
22707
+ {
22708
+ success: false,
22709
+ error: "Host not allowed. Add it to allowedHosts or PRODUCER_ALLOWED_HOSTS."
22710
+ },
22711
+ 403
22712
+ );
22713
+ }
22714
+ await next();
22715
+ });
22488
22716
  app.post("*", async (c, next) => {
22489
22717
  if (isCrossOriginBrowserRequest(c)) {
22490
22718
  return c.json({ success: false, error: "Cross-origin requests are not allowed" }, 403);
@@ -22501,10 +22729,17 @@ function createProducerApp(options = {}) {
22501
22729
  }
22502
22730
  function startServer(options = {}) {
22503
22731
  const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
22732
+ const hostname2 = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
22504
22733
  const log = options.logger ?? defaultLogger;
22734
+ if (!isLoopbackHostname(hostname2) && !resolveAuthToken(options)) {
22735
+ throw new Error(
22736
+ `Refusing to listen on ${hostname2} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`
22737
+ );
22738
+ }
22505
22739
  const app = createProducerApp(options);
22506
- const server = serve2({ fetch: app.fetch, port }, () => {
22507
- log.info(`Listening on http://localhost:${port}`);
22740
+ const server = serve2({ fetch: app.fetch, port, hostname: hostname2 }, (info) => {
22741
+ const address = info.family === "IPv6" ? `[${info.address}]` : info.address;
22742
+ log.info(`Listening on http://${address}:${info.port}`);
22508
22743
  });
22509
22744
  server.setTimeout(0);
22510
22745
  server.requestTimeout = 0;
@@ -22582,7 +22817,7 @@ import {
22582
22817
  statSync as statSync15,
22583
22818
  writeFileSync as writeFileSync15
22584
22819
  } from "node:fs";
22585
- import { basename as basename8, dirname as dirname20, join as join50 } from "node:path";
22820
+ import { basename as basename8, dirname as dirname21, join as join50 } from "node:path";
22586
22821
  import {
22587
22822
  appendRateCapArgs as appendRateCapArgs2,
22588
22823
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
@@ -22629,10 +22864,10 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
22629
22864
  }
22630
22865
  const format = plan2.dimensions.format;
22631
22866
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
22632
- if (!existsSync33(dirname20(outputPath))) {
22633
- mkdirSync22(dirname20(outputPath), { recursive: true });
22867
+ if (!existsSync33(dirname21(outputPath))) {
22868
+ mkdirSync22(dirname21(outputPath), { recursive: true });
22634
22869
  }
22635
- const workDir = createStagingDir7(dirname20(outputPath), `${basename8(outputPath)}.assemble-work-`);
22870
+ const workDir = createStagingDir7(dirname21(outputPath), `${basename8(outputPath)}.assemble-work-`);
22636
22871
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
22637
22872
  const stageMs = {};
22638
22873
  const ctx = {