@hyperframes/producer 0.9.58 → 0.9.61

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.
Files changed (31) hide show
  1. package/dist/distributed.js +408 -153
  2. package/dist/hyperframe.manifest.json +1 -1
  3. package/dist/hyperframe.runtime.iife.js +64 -64
  4. package/dist/hyperframeLintWorker.js +9 -0
  5. package/dist/index.js +576 -185
  6. package/dist/public-server.js +531 -166
  7. package/dist/renderRequest.d.ts +3 -0
  8. package/dist/server.d.ts +2 -0
  9. package/dist/services/animatedGifPrep.d.ts +2 -2
  10. package/dist/services/compositionSizeLimit.d.ts +22 -0
  11. package/dist/services/distributed/plan.d.ts +6 -1
  12. package/dist/services/distributed/planV2.d.ts +1 -0
  13. package/dist/services/distributed/projectHash.d.ts +9 -4
  14. package/dist/services/distributed/renderConfigValidation.d.ts +0 -18
  15. package/dist/services/distributed/renderSpan.d.ts +1 -0
  16. package/dist/services/distributed/shared.d.ts +2 -0
  17. package/dist/services/fileServer.d.ts +1 -0
  18. package/dist/services/heifImagePrep.d.ts +1 -1
  19. package/dist/services/htmlCompiler.d.ts +5 -2
  20. package/dist/services/htmlTagScans.d.ts +1 -0
  21. package/dist/services/hyperframeLint.d.ts +8 -2
  22. package/dist/services/hyperframeLintWorker.d.ts +1 -0
  23. package/dist/services/render/outputDimensions.d.ts +6 -0
  24. package/dist/services/render/shared.d.ts +7 -0
  25. package/dist/services/render/stages/audioStage.d.ts +1 -0
  26. package/dist/services/render/stages/encodeStage.d.ts +26 -1
  27. package/dist/services/render/stages/probeStage.d.ts +11 -2
  28. package/dist/services/renderOrchestrator.d.ts +5 -0
  29. package/dist/utils/paths.d.ts +6 -2
  30. package/dist/verifyStaticPage.d.ts +1 -1
  31. package/package.json +7 -7
@@ -1,16 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/services/render/outputDimensions.ts
4
+ function isExpectedOutputDimensions(value) {
5
+ return typeof value === "object" && value !== null && "width" in value && "height" in value && typeof value.width === "number" && typeof value.height === "number" && Number.isSafeInteger(value.width) && Number.isSafeInteger(value.height) && value.width > 0 && value.height > 0;
6
+ }
7
+ var OutputDimensionsMismatchError = class extends Error {
8
+ code = "OUTPUT_DIMENSIONS_MISMATCH";
9
+ constructor() {
10
+ super("Compiled output dimensions do not match the requested render dimensions.");
11
+ }
12
+ };
13
+ function requireOutputDimensions(expected, width, height) {
14
+ if (expected !== void 0 && (!isExpectedOutputDimensions(expected) || expected.width !== width || expected.height !== height)) {
15
+ throw new OutputDimensionsMismatchError();
16
+ }
17
+ }
18
+
3
19
  // src/server.ts
4
20
  import {
5
21
  existsSync as existsSync25,
6
22
  mkdirSync as mkdirSync13,
7
- statSync as statSync12,
23
+ statSync as statSync13,
8
24
  mkdtempSync,
9
25
  writeFileSync as writeFileSync8,
10
26
  rmSync as rmSync13,
11
27
  createReadStream as createReadStream3
12
28
  } from "node:fs";
13
- import { resolve as resolve10, dirname as dirname17, join as join37 } from "node:path";
29
+ import { resolve as resolve10, dirname as dirname18, join as join37 } from "node:path";
14
30
  import { tmpdir as tmpdir3 } from "node:os";
15
31
  import { parseArgs } from "node:util";
16
32
  import { isIP } from "node:net";
@@ -32,7 +48,7 @@ import {
32
48
  mkdirSync as mkdirSync12,
33
49
  readdirSync as readdirSync6,
34
50
  rmSync as rmSync12,
35
- statSync as statSync10,
51
+ statSync as statSync11,
36
52
  writeFileSync as writeFileSync7,
37
53
  copyFileSync as copyFileSync5,
38
54
  appendFileSync
@@ -200,6 +216,10 @@ function stripPreloadNone(html) {
200
216
  return attr && attr.index < tagEnd ? [attr.index, attr.index + attr[0].length] : void 0;
201
217
  });
202
218
  }
219
+ function hasClosedMediaTag(text) {
220
+ const open = /<(?:video|audio)\b/i.exec(text);
221
+ return open !== null && text.includes(">", open.index + open[0].length);
222
+ }
203
223
  var REMOTE_SRC_TAGS = {
204
224
  media: { opener: "<(?:video|audio)\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
205
225
  source: { opener: "<source\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
@@ -548,6 +568,7 @@ import { isSafePath } from "@hyperframes/core/safe-path";
548
568
  import {
549
569
  isCopiedOutsideFileType,
550
570
  isPrivateOutsideFile,
571
+ isUploadedOutsideFileType,
551
572
  leftOutWarning,
552
573
  linksOutside
553
574
  } from "@hyperframes/studio-server/outside-file";
@@ -569,15 +590,17 @@ function isPathInside(childPath, parentPath, options = {}) {
569
590
  function escapesAssetRoot(path, assetRoot) {
570
591
  return assetRoot !== void 0 && !isSafePath(assetRoot, path);
571
592
  }
572
- function outsideAssetRefusal(projectDir, path) {
593
+ function outsideAssetRefusal(projectDir, path, policy = {}) {
573
594
  if (!linksOutside(projectDir, path)) return null;
574
595
  if (isPrivateOutsideFile(projectDir, path)) return "blocklisted";
575
596
  const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
576
- return folder || isCopiedOutsideFileType(path) ? null : "file_type";
597
+ if (folder || isUploadedOutsideFileType(path)) return null;
598
+ if (!isCopiedOutsideFileType(path)) return "file_type";
599
+ return policy.includeScripts ? null : "script";
577
600
  }
578
601
  var leftOutOfRender = (file, reference, reason) => leftOutWarning(file, reference, reason, "render");
579
- function refusesOutsideLink(projectDir, path, warn) {
580
- const refusal = outsideAssetRefusal(projectDir, path);
602
+ function refusesOutsideLink(projectDir, path, warn, policy = {}) {
603
+ const refusal = outsideAssetRefusal(projectDir, path, policy);
581
604
  if (!refusal) return false;
582
605
  const file = nodeRelative(projectDir, path).split(sep).join("/");
583
606
  warn(leftOutOfRender(file, realFilePath(path), refusal));
@@ -1160,7 +1183,8 @@ function createFileServer(options) {
1160
1183
  compiledDir,
1161
1184
  port = 0,
1162
1185
  stripEmbeddedRuntime = true,
1163
- allowOutsideProjectAssets = false
1186
+ allowOutsideProjectAssets = false,
1187
+ includeOutsideScripts = false
1164
1188
  } = options;
1165
1189
  const preHeadScripts = [
1166
1190
  HF_EARLY_STUB,
@@ -1171,6 +1195,7 @@ function createFileServer(options) {
1171
1195
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
1172
1196
  const app = new Hono();
1173
1197
  const warnLeftOut = (line) => console.warn(`[FileServer] ${terminalText2(line)}`);
1198
+ const outsidePolicy = { includeScripts: includeOutsideScripts };
1174
1199
  let listeningPort = -1;
1175
1200
  app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
1176
1201
  await next();
@@ -1188,7 +1213,7 @@ function createFileServer(options) {
1188
1213
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
1189
1214
  if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
1190
1215
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
1191
- if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut)) continue;
1216
+ if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut, outsidePolicy)) continue;
1192
1217
  file = openRegularFile(candidate);
1193
1218
  if (file) break;
1194
1219
  }
@@ -1596,6 +1621,30 @@ function reportEncodeProgress(job, done, total, onProgress, from) {
1596
1621
  "encoding"
1597
1622
  );
1598
1623
  }
1624
+ var AUDIO_STAGE = "Processing audio tracks";
1625
+ var AUDIO_WAIT_REPORT_MS = 5e3;
1626
+ function audioWaitReporter(job, onProgress) {
1627
+ let waiting2 = false;
1628
+ let reportedAt = -Infinity;
1629
+ return {
1630
+ progressed() {
1631
+ const now = Date.now();
1632
+ if (!waiting2 || now - reportedAt < AUDIO_WAIT_REPORT_MS) return;
1633
+ reportedAt = now;
1634
+ updateJobStatus(job, job.status, AUDIO_STAGE, job.progress, onProgress, {
1635
+ code: "process_audio"
1636
+ });
1637
+ },
1638
+ async wait(audio) {
1639
+ waiting2 = true;
1640
+ try {
1641
+ return await audio;
1642
+ } finally {
1643
+ waiting2 = false;
1644
+ }
1645
+ }
1646
+ };
1647
+ }
1599
1648
  var lastAssembleReportAt = /* @__PURE__ */ new WeakMap();
1600
1649
  function reportAssembleProgress(job, done, total, onProgress) {
1601
1650
  if (total <= 0) return;
@@ -2724,9 +2773,10 @@ function frameWeightedAvgMs(perfs, avgOf) {
2724
2773
  function aggregateDedup(perfs) {
2725
2774
  if (perfs.length === 0) return void 0;
2726
2775
  const armed = perfs.some((p) => p.staticDedupArmed);
2727
- const skipReasons = armed ? [] : [
2728
- ...new Set(perfs.map((p) => p.staticDedupSkipReason).filter((r) => !!r))
2729
- ].sort();
2776
+ const distinctUnarmed = (values) => {
2777
+ const distinct = armed ? [] : [...new Set(values.filter((v) => !!v))].sort();
2778
+ return distinct.length > 0 ? distinct.join("|") : void 0;
2779
+ };
2730
2780
  const verificationPerfs = perfs.filter((perf) => perf.staticDedupVerificationOutcome);
2731
2781
  const verificationOutcomes = [
2732
2782
  ...new Set(
@@ -2738,7 +2788,8 @@ function aggregateDedup(perfs) {
2738
2788
  armed,
2739
2789
  predictedFrames: perfs.reduce((sum, p) => sum + (p.staticDedupPredicted ?? 0), 0),
2740
2790
  reusedFrames: perfs.reduce((sum, p) => sum + (p.staticDedupReused ?? 0), 0),
2741
- skipReason: skipReasons.length > 0 ? skipReasons.join("|") : void 0,
2791
+ skipReason: distinctUnarmed(perfs.map((p) => p.staticDedupSkipReason)),
2792
+ ineligibleCause: distinctUnarmed(perfs.map((p) => p.staticDedupIneligibleCause)),
2742
2793
  ...verificationPerfs.length === 0 ? {} : {
2743
2794
  verifiedFrames: verificationPerfs.reduce(
2744
2795
  (sum, perf) => sum + (perf.staticDedupVerified ?? 0),
@@ -6876,6 +6927,61 @@ import { suggestMatchingPreset } from "@hyperframes/core";
6876
6927
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6877
6928
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6878
6929
 
6930
+ // src/services/compositionSizeLimit.ts
6931
+ import { statSync as statSync7 } from "node:fs";
6932
+ var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
6933
+ var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
6934
+ var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
6935
+ var MAX_EXPANDED_COMPOSITION_BYTES = 2 * MAX_COMPOSITION_HTML_BYTES;
6936
+ var MAX_COMPOSITION_MOUNTS = 1e4;
6937
+ var CompositionTooLargeError = class extends Error {
6938
+ constructor(message, publicMetadata) {
6939
+ super(message);
6940
+ this.publicMetadata = publicMetadata;
6941
+ this.name = "CompositionTooLargeError";
6942
+ }
6943
+ publicMetadata;
6944
+ code = COMPOSITION_TOO_LARGE;
6945
+ // The producer server reads these off the error for the wire envelope.
6946
+ owner = "user";
6947
+ retryable = false;
6948
+ };
6949
+ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6950
+ `Composition file "${file}" is ${megabytes(bytes)}, over the ${megabytes(MAX_COMPOSITION_HTML_BYTES)} limit for one composition HTML file. Keep large data such as images, fonts and JSON in separate asset files and reference them by path instead of inlining them.`,
6951
+ { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6952
+ );
6953
+ var CompositionExpansionBudget = class {
6954
+ bytes = 0;
6955
+ mounts = 0;
6956
+ charge(file, bytes) {
6957
+ this.bytes += bytes;
6958
+ this.mounts += 1;
6959
+ if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
6960
+ return;
6961
+ }
6962
+ throw new CompositionTooLargeError(
6963
+ `Sub-composition mounts, ending at "${file}", add up to ${megabytes(this.bytes)} across ${this.mounts} mounts. One render inlines at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} of composition HTML in at most ${MAX_COMPOSITION_MOUNTS} mounts. Mount large or repeated scenes fewer times.`,
6964
+ {
6965
+ bytes: this.bytes,
6966
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
6967
+ mounts: this.mounts,
6968
+ exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
6969
+ }
6970
+ );
6971
+ }
6972
+ };
6973
+ function assertCompositionFileSize(path, file) {
6974
+ let bytes;
6975
+ try {
6976
+ const stats = statSync7(path);
6977
+ if (!stats.isFile()) return;
6978
+ bytes = stats.size;
6979
+ } catch {
6980
+ return;
6981
+ }
6982
+ if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
6983
+ }
6984
+
6879
6985
  // src/services/htmlCompiler.ts
6880
6986
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6881
6987
  import {
@@ -6962,11 +7068,13 @@ import {
6962
7068
  import {
6963
7069
  isUnresolvedAssetPlaceholder,
6964
7070
  namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
7071
+ projectAssetExists,
6965
7072
  readProjectFile,
6966
7073
  readTextFile,
6967
7074
  resolveCompositionSrc
6968
7075
  } from "@hyperframes/parsers/asset-resolution";
6969
7076
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7077
+ import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
6970
7078
 
6971
7079
  // src/services/renderMediaCollector.ts
6972
7080
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7160,7 +7268,7 @@ import {
7160
7268
 
7161
7269
  // src/services/animatedGifPrep.ts
7162
7270
  import { createHash as createHash4 } from "node:crypto";
7163
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7271
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7164
7272
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7165
7273
  import { parseHTML as parseHTML3 } from "linkedom";
7166
7274
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7213,12 +7321,13 @@ function resolveLocalImageSourcePath(src, options) {
7213
7321
  isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7214
7322
  resolve5(options.downloadDir, normalizedBase)
7215
7323
  ];
7216
- const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, options.assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7324
+ const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7325
+ const allowed = (candidate) => !namesAnotherNetworkRoot(options.projectDir, candidate) && !isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) && (!escapesAssetRoot(candidate, assetRoot) && outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted" || !escapesAssetRoot(candidate, options.downloadDir));
7217
7326
  return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7218
7327
  }
7219
7328
  function isUsableFile(path) {
7220
7329
  try {
7221
- const stat = statSync7(path);
7330
+ const stat = statSync8(path);
7222
7331
  return stat.isFile() && stat.size > 0;
7223
7332
  } catch {
7224
7333
  return false;
@@ -7483,7 +7592,7 @@ import {
7483
7592
  readFileSync as readFileSync7,
7484
7593
  readSync as readSync3,
7485
7594
  rmSync as rmSync10,
7486
- statSync as statSync8,
7595
+ statSync as statSync9,
7487
7596
  writeFileSync as writeFileSync4
7488
7597
  } from "node:fs";
7489
7598
  import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
@@ -7727,7 +7836,7 @@ function resolveImageSource(src, options) {
7727
7836
  }
7728
7837
  function isUsableFile2(path) {
7729
7838
  try {
7730
- return statSync8(path).size > 0;
7839
+ return statSync9(path).size > 0;
7731
7840
  } catch {
7732
7841
  return false;
7733
7842
  }
@@ -8006,7 +8115,7 @@ Check that each file referenced by data-composition-src contains valid HTML with
8006
8115
  };
8007
8116
  function normalizeCompositionSrcs(html, projectDir) {
8008
8117
  return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
8009
- if (!value.includes("%") && !value.startsWith("/")) return whole;
8118
+ if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
8010
8119
  const file = resolveCompositionSrc(projectDir, value);
8011
8120
  if (file === null) return whole;
8012
8121
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
@@ -8022,68 +8131,94 @@ function resolveCompositionFile(projectDir, src, assetRoot) {
8022
8131
  const file = resolveCompositionPath(projectDir, src, assetRoot);
8023
8132
  return file !== null && COMPOSITION_FILE.test(file) ? file : null;
8024
8133
  }
8134
+ var OUTSIDE_COMPOSITION_NEEDS_FLAG = "it is outside the project, and any scripts in it would run; move it into the project, or pass --include-outside-files to hyperframes render, to include it";
8135
+ var runsOutsideMarkupUnasked = (projectDir, filePath, assetRoot, outsideFiles) => assetRoot === void 0 && !outsideFiles.includeScripts && linksOutside2(projectDir, filePath);
8136
+ function assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles) {
8137
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8138
+ throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
8139
+ }
8140
+ }
8025
8141
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
8026
- function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
8142
+ var mountSrcsUnder = (root) => [...root.querySelectorAll("[data-composition-src]")].map((el) => el.getAttribute("data-composition-src")).filter((srcPath) => !!srcPath && !isUnresolvedAssetPlaceholder(srcPath));
8143
+ function compositionSrcsIn(html) {
8027
8144
  const { document: document2 } = parseHTML5(html);
8028
- const hosts = [...document2.querySelectorAll("[data-composition-src]")];
8029
- const problems = [];
8030
- for (const el of hosts) {
8031
- const srcPath = el.getAttribute("data-composition-src");
8032
- if (!srcPath) continue;
8033
- if (isUnresolvedAssetPlaceholder(srcPath)) continue;
8145
+ const templated = [];
8146
+ const templates = [...document2.querySelectorAll("template")];
8147
+ for (let template = templates.pop(); template; template = templates.pop()) {
8148
+ templated.push(...mountSrcsUnder(template.content));
8149
+ templates.push(...template.content.querySelectorAll("template"));
8150
+ }
8151
+ return { mounts: mountSrcsUnder(document2), templated };
8152
+ }
8153
+ function compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles) {
8154
+ if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8155
+ return "it is outside the project in a private location";
8156
+ }
8157
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8158
+ return OUTSIDE_COMPOSITION_NEEDS_FLAG;
8159
+ }
8160
+ if (isPrivateCompositionFile(projectDir, filePath)) {
8161
+ return "it is git metadata, an env file or a private tool record";
8162
+ }
8163
+ return COMPOSITION_FILE.test(filePath) ? null : NOT_A_COMPOSITION_FILE;
8164
+ }
8165
+ function readSubCompositionFile(filePath, srcPath) {
8166
+ assertCompositionFileSize(filePath, srcPath);
8167
+ const read = readProjectFile(filePath);
8168
+ if (read.kind === "missing") return { detail: "the file does not exist" };
8169
+ if (read.kind === "folder") return { detail: "it is a folder, not an HTML file" };
8170
+ const validity = checkSubCompositionUsability(read.text, parseSubCompHtmlForValidity);
8171
+ if (!validity.ok)
8172
+ return { detail: validity.detail ?? "the file is empty or could not be parsed" };
8173
+ return { bytes: Buffer.byteLength(read.text), ...compositionSrcsIn(read.text) };
8174
+ }
8175
+ function assertSubCompositionsUsable(html, projectDir, assetRoot, outsideFiles) {
8176
+ const budget = new CompositionExpansionBudget();
8177
+ const files = /* @__PURE__ */ new Map();
8178
+ const problems = /* @__PURE__ */ new Map();
8179
+ const report = (srcPath, detail) => problems.set(`${srcPath}\0${detail}`, { srcPath, detail });
8180
+ const chain = /* @__PURE__ */ new Set();
8181
+ const paths = /* @__PURE__ */ new Map();
8182
+ const resolveMount = (srcPath) => {
8034
8183
  const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
8035
- if (filePath === null) {
8036
- problems.push({ srcPath, detail: "it is outside the project folder" });
8037
- continue;
8038
- }
8039
- if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8040
- problems.push({ srcPath, detail: "it is outside the project in a private location" });
8041
- continue;
8042
- }
8043
- if (isPrivateCompositionFile(projectDir, filePath)) {
8044
- problems.push({
8045
- srcPath,
8046
- detail: "it is git metadata, an env file or a private tool record"
8047
- });
8048
- continue;
8049
- }
8050
- if (!COMPOSITION_FILE.test(filePath)) {
8051
- problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
8052
- continue;
8053
- }
8054
- if (visited.has(filePath)) continue;
8055
- const read = readProjectFile(filePath);
8056
- if (read.kind === "missing") {
8057
- problems.push({ srcPath, detail: "the file does not exist" });
8058
- continue;
8059
- }
8060
- if (read.kind === "folder") {
8061
- problems.push({ srcPath, detail: "it is a folder, not an HTML file" });
8062
- continue;
8063
- }
8064
- const fileHtml = read.text;
8065
- const validity = checkSubCompositionUsability(fileHtml, parseSubCompHtmlForValidity);
8066
- if (!validity.ok) {
8067
- problems.push({
8068
- srcPath,
8069
- detail: validity.detail ?? "the file is empty or could not be parsed"
8070
- });
8071
- continue;
8072
- }
8073
- const nestedVisited = new Set(visited);
8074
- nestedVisited.add(filePath);
8075
- try {
8076
- assertSubCompositionsUsable(fileHtml, projectDir, assetRoot, nestedVisited);
8077
- } catch (err) {
8078
- if (err instanceof EmptyCompositionError) {
8079
- problems.push(...err.problems);
8080
- } else {
8081
- throw err;
8184
+ if (filePath === null) return { detail: "it is outside the project folder" };
8185
+ const detail = compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles);
8186
+ return detail ? { detail } : { filePath };
8187
+ };
8188
+ const walk = (srcPaths, quiet) => {
8189
+ for (const srcPath of srcPaths) {
8190
+ let resolved = paths.get(srcPath);
8191
+ if (!resolved) {
8192
+ resolved = resolveMount(srcPath);
8193
+ paths.set(srcPath, resolved);
8194
+ }
8195
+ if ("detail" in resolved) {
8196
+ if (!quiet) report(srcPath, resolved.detail);
8197
+ continue;
8198
+ }
8199
+ const { filePath } = resolved;
8200
+ if (chain.has(filePath)) continue;
8201
+ let file = files.get(filePath);
8202
+ if (!file) {
8203
+ file = readSubCompositionFile(filePath, srcPath);
8204
+ files.set(filePath, file);
8082
8205
  }
8206
+ if ("detail" in file) {
8207
+ if (!quiet) report(srcPath, file.detail);
8208
+ continue;
8209
+ }
8210
+ budget.charge(srcPath, file.bytes);
8211
+ chain.add(filePath);
8212
+ walk(file.mounts, quiet);
8213
+ walk(file.templated, true);
8214
+ chain.delete(filePath);
8083
8215
  }
8084
- }
8085
- if (problems.length > 0) {
8086
- throw new EmptyCompositionError(problems);
8216
+ };
8217
+ const entry = compositionSrcsIn(html);
8218
+ walk(entry.mounts, false);
8219
+ walk(entry.templated, true);
8220
+ if (problems.size > 0) {
8221
+ throw new EmptyCompositionError([...problems.values()]);
8087
8222
  }
8088
8223
  }
8089
8224
  var COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
@@ -8338,7 +8473,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8338
8473
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
8339
8474
  return { html: compiledHtml, unresolvedCompositions };
8340
8475
  }
8341
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot) {
8476
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8342
8477
  const subCompositions = /* @__PURE__ */ new Map();
8343
8478
  const { document: document2 } = parseHTML5(html);
8344
8479
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -8351,6 +8486,10 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8351
8486
  if (visited.has(filePath)) {
8352
8487
  continue;
8353
8488
  }
8489
+ if (compiledSrcs.has(srcPath)) continue;
8490
+ compiledSrcs.add(srcPath);
8491
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8492
+ assertCompositionFileSize(filePath, srcPath);
8354
8493
  const read = readProjectFile(filePath);
8355
8494
  if (read.kind !== "file") {
8356
8495
  continue;
@@ -8379,7 +8518,9 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8379
8518
  item.nestedVisited,
8380
8519
  urlByAbsentLocalPath,
8381
8520
  probes,
8382
- assetRoot
8521
+ assetRoot,
8522
+ outsideFiles,
8523
+ compiledSrcs
8383
8524
  );
8384
8525
  return {
8385
8526
  srcPath: item.srcPath,
@@ -8515,7 +8656,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8515
8656
  }
8516
8657
  return document2.toString();
8517
8658
  }
8518
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot) {
8659
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8519
8660
  const { document: document2 } = parseHTML5(html);
8520
8661
  const head = document2.querySelector("head");
8521
8662
  const body = document2.querySelector("body");
@@ -8526,8 +8667,29 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8526
8667
  {},
8527
8668
  variableOverrides
8528
8669
  );
8529
- return emitted ? document2.toString() : html;
8670
+ return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8530
8671
  }
8672
+ const budget = new CompositionExpansionBudget();
8673
+ const readOnce = /* @__PURE__ */ new Map();
8674
+ const readMountHtml = (srcPath) => {
8675
+ const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8676
+ if (filePath) {
8677
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8678
+ assertCompositionFileSize(filePath, srcPath);
8679
+ }
8680
+ const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8681
+ return read?.kind === "file" ? rewriteUnresolvableGsapToCdn(
8682
+ normalizeCompositionSrcs(read.text, projectDir),
8683
+ projectDir,
8684
+ srcPath
8685
+ ) : null;
8686
+ };
8687
+ const resolveMountHtml = (srcPath) => {
8688
+ const compiled = subCompositions.get(srcPath);
8689
+ if (compiled) return compiled;
8690
+ if (!readOnce.has(srcPath)) readOnce.set(srcPath, readMountHtml(srcPath));
8691
+ return readOnce.get(srcPath) ?? null;
8692
+ };
8531
8693
  const hostIdentityByElement = new ProducerHostIdentityMap(
8532
8694
  document2,
8533
8695
  hosts
@@ -8543,20 +8705,14 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8543
8705
  readVariableDefaults: readDeclaredDefaults,
8544
8706
  parseHostVariables: parseHostVariableValues,
8545
8707
  resolveHtml: (srcPath) => {
8546
- let compHtml = subCompositions.get(srcPath) || null;
8547
- if (!compHtml) {
8548
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8549
- const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8550
- if (read?.kind === "file") {
8551
- compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
8552
- }
8553
- }
8708
+ const compHtml = resolveMountHtml(srcPath);
8709
+ if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
8554
8710
  return compHtml;
8555
8711
  },
8556
8712
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
8557
8713
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
8558
8714
  // against its own directory, project-root refs stay as authored.
8559
- assetExists: (path) => existsSync11(resolve7(projectDir, path)),
8715
+ assetExists: projectAssetExists(projectDir),
8560
8716
  // Preserve the authored root wrapper as a child of the host, matching
8561
8717
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
8562
8718
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8640,7 +8796,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8640
8796
  variableOverrides
8641
8797
  );
8642
8798
  assignMediaRenderIds(document2);
8643
- return document2.toString();
8799
+ return { html: document2.toString(), variablesByComp: result.variablesByComp };
8644
8800
  }
8645
8801
  function ensureFullDocument(html) {
8646
8802
  const trimmed = html.trim();
@@ -8761,7 +8917,7 @@ ${safeText}
8761
8917
  }
8762
8918
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8763
8919
  }
8764
- function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html") {
8920
+ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8765
8921
  const absProjectDir = resolve7(projectDir);
8766
8922
  const externalAssets = /* @__PURE__ */ new Map();
8767
8923
  const leftOut = /* @__PURE__ */ new Set();
@@ -8774,7 +8930,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8774
8930
  }
8775
8931
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8776
8932
  if (!onShare && !existsSync11(absPath)) return null;
8777
- const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath);
8933
+ const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8778
8934
  if (refusal) {
8779
8935
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
8780
8936
  leftOut.add(trimmed);
@@ -9160,7 +9316,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9160
9316
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9161
9317
  if (!entryPath.includes("/")) return html;
9162
9318
  const { document: document2 } = parseHTML5(html);
9163
- const assetExists = (path) => existsSync11(resolve7(projectDir, path));
9319
+ const assetExists = projectAssetExists(projectDir);
9164
9320
  rewriteAssetPaths(
9165
9321
  document2.querySelectorAll("[src], [href], [srcset]"),
9166
9322
  entryPath,
@@ -9201,18 +9357,23 @@ function bindVariableMediaSources(html, variables) {
9201
9357
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9202
9358
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9203
9359
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9360
+ const outsideFiles = { includeScripts: options.includeOutsideScripts };
9204
9361
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
9205
9362
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
9206
9363
  }
9364
+ if (isPathInside(htmlPath, projectDir) && runsOutsideMarkupUnasked(projectDir, htmlPath, assetRoot, outsideFiles)) {
9365
+ throw new Error(`Entry file ${htmlPath} ${OUTSIDE_COMPOSITION_NEEDS_FLAG}`);
9366
+ }
9207
9367
  if (!COMPOSITION_FILE.test(htmlPath)) {
9208
9368
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9209
9369
  }
9370
+ assertCompositionFileSize(htmlPath, basename5(htmlPath));
9210
9371
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9211
9372
  const rawHtml = bindVariableMediaSources(
9212
9373
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9213
9374
  options.variables ?? {}
9214
9375
  );
9215
- assertSubCompositionsUsable(rawHtml, projectDir, assetRoot);
9376
+ assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9216
9377
  const probes = /* @__PURE__ */ new Map();
9217
9378
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
9218
9379
  rawHtml,
@@ -9231,15 +9392,17 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9231
9392
  void 0,
9232
9393
  options.urlByAbsentLocalPath,
9233
9394
  probes,
9234
- assetRoot
9395
+ assetRoot,
9396
+ outsideFiles
9235
9397
  );
9236
9398
  const fullHtml = ensureFullDocument(compiledHtml);
9237
- const inlinedHtml = inlineSubCompositions(
9399
+ const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
9238
9400
  fullHtml,
9239
9401
  subCompositions,
9240
9402
  projectDir,
9241
9403
  options.variables ?? {},
9242
- assetRoot
9404
+ assetRoot,
9405
+ outsideFiles
9243
9406
  );
9244
9407
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9245
9408
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9293,7 +9456,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9293
9456
  cacheDir: options.animatedGifCacheDir,
9294
9457
  sourceAssets: remoteImageAssets,
9295
9458
  timeoutMs: options.ffmpegProcessTimeout,
9296
- assetRoot
9459
+ allowOutsideFiles: assetRoot === void 0
9297
9460
  });
9298
9461
  if (preparedHeifImages.length > 0) {
9299
9462
  defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
@@ -9309,7 +9472,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9309
9472
  cacheDir: options.animatedGifCacheDir,
9310
9473
  sourceAssets: gifSourceAssets,
9311
9474
  timeoutMs: options.ffmpegProcessTimeout,
9312
- assetRoot
9475
+ allowOutsideFiles: assetRoot === void 0
9313
9476
  });
9314
9477
  if (preparedGifs.length > 0) {
9315
9478
  defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
@@ -9324,7 +9487,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9324
9487
  embeddedHtml,
9325
9488
  projectDir,
9326
9489
  options.log,
9327
- entryFileName(projectDir, htmlPath)
9490
+ entryFileName(projectDir, htmlPath),
9491
+ { includeScripts: options.includeOutsideScripts }
9328
9492
  ) : { html: embeddedHtml, externalAssets: /* @__PURE__ */ new Map() };
9329
9493
  for (const [relPath, absPath] of remoteMediaAssets) {
9330
9494
  externalAssets.set(relPath, absPath);
@@ -9387,6 +9551,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9387
9551
  gradedCanvas,
9388
9552
  ...masterFxChain ? { masterFxChain } : {},
9389
9553
  unresolvedCompositions,
9554
+ variablesByComp,
9390
9555
  externalAssets,
9391
9556
  width,
9392
9557
  height,
@@ -9730,7 +9895,7 @@ async function resolveCompositionDurations(page, unresolved) {
9730
9895
  }
9731
9896
  return resolutions;
9732
9897
  }
9733
- async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot) {
9898
+ async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot, outsideFiles = {}) {
9734
9899
  if (resolutions.length === 0) return compiled;
9735
9900
  const html = injectDurations(compiled.html, resolutions);
9736
9901
  const { subCompositions } = await parseSubCompositions(
@@ -9740,7 +9905,8 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9740
9905
  void 0,
9741
9906
  void 0,
9742
9907
  void 0,
9743
- assetRoot
9908
+ assetRoot,
9909
+ outsideFiles
9744
9910
  );
9745
9911
  const { videos, audios, images } = compiled;
9746
9912
  const remaining = compiled.unresolvedCompositions.filter(
@@ -9788,6 +9954,7 @@ function resolveEntryHtmlPath(input) {
9788
9954
  `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
9789
9955
  );
9790
9956
  }
9957
+ assertCompositionFileSize(path, relative3(projectDir, path));
9791
9958
  return readTextFile2(path);
9792
9959
  };
9793
9960
  const htmlPath = join20(projectDir, entryFile);
@@ -9849,7 +10016,8 @@ async function runCompileStage(input) {
9849
10016
  pageMotionBlur: input.pageMotionBlur,
9850
10017
  animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
9851
10018
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
9852
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10019
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10020
+ includeOutsideScripts: job.config.includeOutsideScripts
9853
10021
  });
9854
10022
  assertNotAborted();
9855
10023
  const compileOnlyMs = Date.now() - compileStart;
@@ -9935,6 +10103,8 @@ async function runCompileStage(input) {
9935
10103
  });
9936
10104
  const outputWidth = Math.round(width * deviceScaleFactor);
9937
10105
  const outputHeight = Math.round(height * deviceScaleFactor);
10106
+ requireOutputDimensions(job.config.expectedOutputDimensions, outputWidth, outputHeight);
10107
+ if (job.config.expectedOutputDimensions !== void 0) job.outputDimensionsChecked = true;
9938
10108
  if (deviceScaleFactor !== 1) {
9939
10109
  log.info("Scaling composition via deviceScaleFactor", {
9940
10110
  compositionWidth: width,
@@ -10029,23 +10199,50 @@ function hasAutoStartVideos(html) {
10029
10199
  const { document: document2 } = parseHTML6(html);
10030
10200
  return document2.querySelector("video[data-hf-auto-start]") !== null;
10031
10201
  }
10032
- function variableHasValue(element, variableId, variables) {
10202
+ var MAX_VARIABLE_SCOPE_STEPS = 1e6;
10203
+ function variableIdsOn(scan, element) {
10204
+ let ids = scan.ids.get(element);
10205
+ if (!ids) {
10206
+ ids = /* @__PURE__ */ new Set([
10207
+ ...Object.keys(parseHostVariableValues2(element)),
10208
+ ...Object.keys(readDeclaredDefaults2(element))
10209
+ ]);
10210
+ scan.ids.set(element, ids);
10211
+ }
10212
+ return ids;
10213
+ }
10214
+ function scopedVariablesFor(scan, element, variablesByComp) {
10215
+ for (let node = element; node; node = node.parentElement) {
10216
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return null;
10217
+ if (!node.hasAttribute("data-composition-id")) continue;
10218
+ const compId = node.getAttribute("data-composition-id")?.trim() ?? "";
10219
+ return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : void 0;
10220
+ }
10221
+ return void 0;
10222
+ }
10223
+ function variableHasValue(scan, element, variableId, variables, variablesByComp) {
10033
10224
  if (variables && Object.hasOwn(variables, variableId)) return true;
10225
+ const scoped = scopedVariablesFor(scan, element, variablesByComp);
10226
+ if (scoped === null) return true;
10227
+ if (scoped) return Object.hasOwn(scoped, variableId);
10034
10228
  for (let scope = element.parentElement; scope; scope = scope.parentElement) {
10035
- if (Object.hasOwn(parseHostVariableValues2(scope), variableId)) return true;
10036
- if (Object.hasOwn(readDeclaredDefaults2(scope), variableId)) return true;
10229
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return true;
10230
+ if (variableIdsOn(scan, scope).has(variableId)) return true;
10037
10231
  }
10038
- return Object.hasOwn(readDeclaredDefaults2(element.ownerDocument.documentElement), variableId);
10232
+ return variableIdsOn(scan, element.ownerDocument.documentElement).has(variableId);
10039
10233
  }
10040
- function hasVariableBoundMedia(html, variables) {
10234
+ function hasVariableBoundMedia(html, variables, variablesByComp = {}) {
10041
10235
  const { document: document2 } = parseHTML6(html);
10236
+ const scan = { ids: /* @__PURE__ */ new Map(), steps: 0 };
10042
10237
  return Array.from(
10043
10238
  document2.querySelectorAll(
10044
10239
  "img[data-var-src], audio[data-var-src], video[data-var-src], source[data-var-src]"
10045
10240
  )
10046
10241
  ).some((element) => {
10047
10242
  const variableId = element.getAttribute("data-var-src")?.trim();
10048
- return Boolean(variableId && variableHasValue(element, variableId, variables));
10243
+ return Boolean(
10244
+ variableId && variableHasValue(scan, element, variableId, variables, variablesByComp)
10245
+ );
10049
10246
  });
10050
10247
  }
10051
10248
  function authoredMediaStarts(html) {
@@ -10085,29 +10282,54 @@ function reconcileBrowserMediaEnd(existingEnd, projectedEnd, sourceChanged, dura
10085
10282
  if (sourceChanged && durationInferred) return projectedEnd;
10086
10283
  return existingEnd <= 0 ? projectedEnd : Math.min(existingEnd, projectedEnd);
10087
10284
  }
10285
+ var MAX_MEDIA_SELECTOR_WORK = 1e6;
10286
+ var SIBLING_COMBINATOR = /[~+]/;
10287
+ function managedMediaElements(document2) {
10288
+ const managed = [];
10289
+ const pending = [];
10290
+ for (const element of Array.from(document2.children)) pending.push({ element, inMedia: false });
10291
+ for (let next = pending.pop(); next; next = pending.pop()) {
10292
+ const name = next.element.tagName.toLowerCase();
10293
+ const isMedia = name === "video" || name === "audio";
10294
+ if (isMedia || next.inMedia && name === "source") managed.push(next.element);
10295
+ for (const child2 of Array.from(next.element.children)) {
10296
+ pending.push({ element: child2, inMedia: next.inMedia || isMedia });
10297
+ }
10298
+ }
10299
+ return managed;
10300
+ }
10088
10301
  function hasRuntimeMediaChanges(html) {
10089
10302
  const { document: document2 } = parseHTML6(html);
10090
10303
  const scriptBodies = [...document2.querySelectorAll("script")].map(
10091
10304
  (script) => script.textContent ?? ""
10092
10305
  );
10093
10306
  const insertedMedia = scriptBodies.some(
10094
- (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || /<(?:video|audio)\b[^>]*>/i.test(script)
10307
+ (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || hasClosedMediaTag(script)
10095
10308
  );
10096
10309
  if (insertedMedia) return true;
10097
- const isManagedMedia = (element) => {
10098
- const name = element.tagName.toLowerCase();
10099
- if (name === "video" || name === "audio") return true;
10100
- return name === "source" && element.closest("video, audio") !== null;
10101
- };
10310
+ const managed = managedMediaElements(document2);
10311
+ if (managed.length === 0) return false;
10312
+ const managedIds = new Set(managed.map((element) => element.getAttribute("id")).filter(Boolean));
10313
+ const selectors = /* @__PURE__ */ new Set();
10314
+ let selectorChars = 0;
10102
10315
  for (const script of scriptBodies) {
10103
10316
  for (const mutation of extractMediaSrcMutations(script)) {
10104
- try {
10105
- const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10106
- const idTarget = id ? document2.getElementById(id) : null;
10107
- const targets = id ? idTarget ? [idTarget] : [] : [...document2.querySelectorAll(mutation.selector)];
10108
- if (targets.some(isManagedMedia)) return true;
10109
- } catch {
10317
+ const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10318
+ if (id) {
10319
+ if (managedIds.has(id)) return true;
10320
+ continue;
10110
10321
  }
10322
+ if (selectors.has(mutation.selector)) continue;
10323
+ if (SIBLING_COMBINATOR.test(mutation.selector)) return true;
10324
+ selectors.add(mutation.selector);
10325
+ selectorChars += mutation.selector.length;
10326
+ if (selectorChars * managed.length > MAX_MEDIA_SELECTOR_WORK) return true;
10327
+ }
10328
+ }
10329
+ for (const selector of selectors) {
10330
+ try {
10331
+ if (managed.some((element) => element.matches(selector))) return true;
10332
+ } catch {
10111
10333
  }
10112
10334
  }
10113
10335
  return false;
@@ -10160,7 +10382,11 @@ async function runProbeStage(input) {
10160
10382
  compiled.html,
10161
10383
  composition.audios.length
10162
10384
  );
10163
- const hasVariableMedia = hasVariableBoundMedia(compiled.html, job.config.variables);
10385
+ const hasVariableMedia = hasVariableBoundMedia(
10386
+ compiled.html,
10387
+ job.config.variables,
10388
+ compiled.variablesByComp
10389
+ );
10164
10390
  const hasInsertedMedia = hasRuntimeMediaChanges(compiled.html);
10165
10391
  const needsBrowser = cfg.videoLayerPassthrough || input.measuresShownBoxes === true || probeRequiresBrowser({
10166
10392
  durationSeconds: composition.duration,
@@ -10191,7 +10417,8 @@ async function runProbeStage(input) {
10191
10417
  port: 0,
10192
10418
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10193
10419
  fps: job.config.fps,
10194
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10420
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10421
+ includeOutsideScripts: job.config.includeOutsideScripts
10195
10422
  });
10196
10423
  assertNotAborted();
10197
10424
  const motionBlur = job.config.motionBlur;
@@ -10347,7 +10574,8 @@ async function runProbeStage(input) {
10347
10574
  resolutions,
10348
10575
  projectDir,
10349
10576
  join21(workDir, "downloads"),
10350
- job.config.allowOutsideProjectAssets ? void 0 : projectDir
10577
+ job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10578
+ { includeScripts: job.config.includeOutsideScripts }
10351
10579
  );
10352
10580
  assertNotAborted();
10353
10581
  composition.videos = compiled.videos;
@@ -11271,7 +11499,8 @@ import {
11271
11499
  audioFailureDiagnostics,
11272
11500
  processCompositionAudio,
11273
11501
  removeScratch as removeScratch2,
11274
- collectScratchLeftovers
11502
+ collectScratchLeftovers,
11503
+ withFfmpegProgress
11275
11504
  } from "@hyperframes/engine";
11276
11505
 
11277
11506
  // src/services/render/audioDeliveryLimit.ts
@@ -11297,7 +11526,8 @@ import {
11297
11526
  removeScratch,
11298
11527
  renameWithRetry as renameWithRetry5,
11299
11528
  runFfmpeg as runFfmpeg5,
11300
- trackChildProcess
11529
+ trackChildProcess,
11530
+ withPublicOnlyProxy
11301
11531
  } from "@hyperframes/engine";
11302
11532
  import { redactKnownPaths, redactTelemetryString as redactTelemetryString3 } from "@hyperframes/core";
11303
11533
 
@@ -11739,7 +11969,17 @@ async function runFfprobeJson(args, signal) {
11739
11969
  if (!args.includes("--")) {
11740
11970
  throw new Error('[audioPadTrim] ffprobe args must terminate options with "--".');
11741
11971
  }
11972
+ const proxying = withPublicOnlyProxy(args, [args.indexOf("--") + 1]);
11973
+ const routed = proxying && await proxying;
11974
+ try {
11975
+ return await spawnFfprobeJson(routed?.args ?? args, routed?.env, signal);
11976
+ } finally {
11977
+ await routed?.close();
11978
+ }
11979
+ }
11980
+ async function spawnFfprobeJson(args, env, signal) {
11742
11981
  const proc = spawn(getFfprobeBinary(), args, {
11982
+ ...env && { env },
11743
11983
  stdio: ["ignore", "pipe", "pipe"],
11744
11984
  windowsHide: true
11745
11985
  });
@@ -11855,7 +12095,8 @@ function assertAudioNotInterrupted(failures) {
11855
12095
  }
11856
12096
  function runAudioStage(input) {
11857
12097
  return collectScratchLeftovers(
11858
- () => runAudioStageScoped(input),
12098
+ () => withFfmpegProgress(input.onFfmpegProgress ?? (() => {
12099
+ }), () => runAudioStageScoped(input)),
11859
12100
  (left) => {
11860
12101
  if (left.length > 0) input.log?.warn("[audio] scratch left behind", { count: left.length });
11861
12102
  }
@@ -13375,7 +13616,7 @@ import {
13375
13616
  readdirSync as readdirSync5,
13376
13617
  readFileSync as readFileSync9,
13377
13618
  rmSync as rmSync11,
13378
- statSync as statSync9,
13619
+ statSync as statSync10,
13379
13620
  writeFileSync as writeFileSync6
13380
13621
  } from "node:fs";
13381
13622
  import { readFile as readFile2 } from "node:fs/promises";
@@ -13504,7 +13745,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13504
13745
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13505
13746
  if (failure) return failure;
13506
13747
  }
13507
- const fileSize = existsSync20(outputPath) ? statSync9(outputPath).size : 0;
13748
+ const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
13508
13749
  return {
13509
13750
  success: true,
13510
13751
  outputPath,
@@ -13527,7 +13768,10 @@ function startEncodeProgress(job, stage, onProgress) {
13527
13768
  function resolveEngineConfig(input) {
13528
13769
  return input.engineConfig ?? input.job.config.producerConfig ?? resolveConfig();
13529
13770
  }
13530
- function videoEncoderOptions(input, engineCfg) {
13771
+ function overlapEncoderThreads(workerCount, cpuCount) {
13772
+ return Math.max(1, Math.floor(cpuCount) - Math.floor(workerCount));
13773
+ }
13774
+ function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
13531
13775
  const { job, preset } = input;
13532
13776
  return {
13533
13777
  fps: job.config.fps,
@@ -13547,7 +13791,8 @@ function videoEncoderOptions(input, engineCfg) {
13547
13791
  // keyframes that survive `-f concat -c copy` at assemble time. In-process
13548
13792
  // renders leave both undefined → preserves the existing open-GOP output.
13549
13793
  lockGopForChunkConcat: input.lockGopForChunkConcat === true,
13550
- gopSize: input.gopSize
13794
+ gopSize: input.gopSize,
13795
+ softwareEncoderThreads
13551
13796
  };
13552
13797
  }
13553
13798
  function canEncodeWhileCapturing(input, workerCount, cpuCount) {
@@ -13563,8 +13808,9 @@ async function readLandedFrame(workerPath, mergedPath) {
13563
13808
  }
13564
13809
  return readFile2(mergedPath);
13565
13810
  }
13566
- function encodeWhileCapturing(input, totalFrames) {
13811
+ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13567
13812
  const engineCfg = resolveEngineConfig(input);
13813
+ const softwareEncoderThreads = captureBudget ? overlapEncoderThreads(captureBudget.workerCount, captureBudget.cpuCount) : void 0;
13568
13814
  const stop = new AbortController();
13569
13815
  const signal = input.abortSignal ? AbortSignal.any([input.abortSignal, stop.signal]) : stop.signal;
13570
13816
  const landed = /* @__PURE__ */ new Map();
@@ -13579,7 +13825,10 @@ function encodeWhileCapturing(input, totalFrames) {
13579
13825
  let reportFed = null;
13580
13826
  const encoder = spawnStreamingEncoder4(
13581
13827
  input.videoOnlyPath,
13582
- { ...videoEncoderOptions(input, engineCfg), imageFormat: "jpeg" },
13828
+ {
13829
+ ...videoEncoderOptions(input, engineCfg, softwareEncoderThreads),
13830
+ imageFormat: "jpeg"
13831
+ },
13583
13832
  signal,
13584
13833
  engineCfg
13585
13834
  );
@@ -13910,7 +14159,7 @@ function sampleDirectoryBytes(dir) {
13910
14159
  for (const name of entries) {
13911
14160
  const full = join32(current, name);
13912
14161
  try {
13913
- const st = statSync10(full);
14162
+ const st = statSync11(full);
13914
14163
  if (st.isDirectory()) {
13915
14164
  stack.push(full);
13916
14165
  } else if (st.isFile()) {
@@ -14065,7 +14314,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14065
14314
  let rangeStart = null;
14066
14315
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14067
14316
  const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14068
- const missing = !existsSync21(framePath) || statSync10(framePath).size <= 8;
14317
+ const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14069
14318
  if (missing && rangeStart === null) {
14070
14319
  rangeStart = frameIndex;
14071
14320
  } else if (!missing && rangeStart !== null) {
@@ -15360,9 +15609,10 @@ async function executeRenderPipeline(input) {
15360
15609
  nativeHdrVideoCount: nativeHdrVideoIds.size,
15361
15610
  nativeHdrImageCount: nativeHdrImageIds.size
15362
15611
  });
15363
- updateJobStatus(job, "preprocessing", "Processing audio tracks", 20, onProgress, {
15612
+ updateJobStatus(job, "preprocessing", AUDIO_STAGE, 20, onProgress, {
15364
15613
  code: "process_audio"
15365
15614
  });
15615
+ const audioWait = audioWaitReporter(job, onProgress);
15366
15616
  const audioStage = observeRenderStage(
15367
15617
  observability,
15368
15618
  "audio_process",
@@ -15381,7 +15631,8 @@ async function executeRenderPipeline(input) {
15381
15631
  abortSignal: executionSignal,
15382
15632
  assertNotAborted,
15383
15633
  log,
15384
- keepDeliverySource: true
15634
+ keepDeliverySource: true,
15635
+ onFfmpegProgress: audioWait.progressed
15385
15636
  })
15386
15637
  );
15387
15638
  pendingAudio = audioStage.catch(() => void 0);
@@ -15400,7 +15651,8 @@ async function executeRenderPipeline(input) {
15400
15651
  port: 0,
15401
15652
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15402
15653
  fps: job.config.fps,
15403
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
15654
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
15655
+ includeOutsideScripts: job.config.includeOutsideScripts
15404
15656
  });
15405
15657
  assertNotAborted();
15406
15658
  observability.stageEnd("file_server", fileServerStart);
@@ -16191,7 +16443,7 @@ async function executeRenderPipeline(input) {
16191
16443
  }
16192
16444
  const effectiveQuality = job.config.crf ?? preset.quality;
16193
16445
  const effectiveBitrate = job.config.crf != null ? void 0 : job.config.videoBitrate;
16194
- const audioResult = await audioStage;
16446
+ const audioResult = await audioWait.wait(audioStage);
16195
16447
  const { audioOutputPath, deliverySourcePath, hasAudio } = audioResult;
16196
16448
  perfStages.audioProcessMs = audioResult.audioProcessMs;
16197
16449
  recordLimiterAttenuation(job, audioResult.audioLoweredDb);
@@ -16689,7 +16941,10 @@ async function executeRenderPipeline(input) {
16689
16941
  assertNotAborted,
16690
16942
  onProgress
16691
16943
  };
16692
- const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames) : null;
16944
+ const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames, {
16945
+ workerCount: capturePlan.workerCount,
16946
+ cpuCount: workerSizing.cpuCount
16947
+ }) : null;
16693
16948
  const captureFrameStart = Date.now();
16694
16949
  const invokeDiskCapture = (diskPlan) => observeRenderStage(
16695
16950
  observability,
@@ -17041,14 +17296,15 @@ async function executeRenderPipeline(input) {
17041
17296
  import {
17042
17297
  existsSync as existsSync22,
17043
17298
  readFileSync as readFileSync10,
17044
- statSync as statSync11,
17299
+ statSync as statSync12,
17045
17300
  openSync as openSync5,
17046
17301
  fstatSync as fstatSync3,
17047
17302
  closeSync as closeSync5,
17048
17303
  constants as constants3
17049
17304
  } from "node:fs";
17050
- import { resolve as resolve9, join as join33, relative as relative4, isAbsolute as isAbsolute3, sep as sep4 } from "node:path";
17051
- import { lintHyperframeHtml } from "@hyperframes/lint";
17305
+ import { resolve as resolve9, join as join33, relative as relative4, isAbsolute as isAbsolute3, sep as sep4, dirname as dirname15 } from "node:path";
17306
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
17307
+ import { Worker as Worker2 } from "node:worker_threads";
17052
17308
  function isStringRecord(value) {
17053
17309
  if (!value || typeof value !== "object" || Array.isArray(value)) {
17054
17310
  return false;
@@ -17081,7 +17337,7 @@ function readEntryHtml(filePath) {
17081
17337
  } catch (error) {
17082
17338
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
17083
17339
  return null;
17084
- if (!statSync11(filePath, { throwIfNoEntry: false })?.isFile()) return null;
17340
+ if (!statSync12(filePath, { throwIfNoEntry: false })?.isFile()) return null;
17085
17341
  throw error;
17086
17342
  }
17087
17343
  try {
@@ -17097,7 +17353,7 @@ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
17097
17353
  }
17098
17354
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
17099
17355
  const absProjectDir = resolve9(projectDir);
17100
- if (!existsSync22(absProjectDir) || !statSync11(absProjectDir).isDirectory()) {
17356
+ if (!existsSync22(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
17101
17357
  return { error: `Project directory not found: ${absProjectDir}` };
17102
17358
  }
17103
17359
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -17154,17 +17410,111 @@ function prepareHyperframeLintBody(body, isAllowedEntry) {
17154
17410
  }
17155
17411
  return { error: "Missing lint source: provide projectDir, files, or html" };
17156
17412
  }
17157
- async function runHyperframeLint(prepared) {
17158
- return lintHyperframeHtml(prepared.html, {
17159
- filePath: prepared.entryFile,
17160
- compSrcPath: prepared.entryFile
17413
+ var LINT_HEAP_MB = 512;
17414
+ var LINT_TIMEOUT_MS = 15e3;
17415
+ var LINT_MAX_WORKERS = 2;
17416
+ var waiting = [];
17417
+ var running = 0;
17418
+ function takeLintSlot(limit, waitMs) {
17419
+ if (running < limit) {
17420
+ running++;
17421
+ return Promise.resolve(true);
17422
+ }
17423
+ return new Promise((resolve11) => {
17424
+ const entry = () => {
17425
+ clearTimeout(timer);
17426
+ running++;
17427
+ resolve11(true);
17428
+ };
17429
+ const timer = setTimeout(
17430
+ () => {
17431
+ waiting.splice(waiting.indexOf(entry), 1);
17432
+ resolve11(false);
17433
+ },
17434
+ Math.max(0, waitMs)
17435
+ );
17436
+ waiting.push(entry);
17437
+ });
17438
+ }
17439
+ function freeLintSlot() {
17440
+ running--;
17441
+ waiting.shift()?.();
17442
+ }
17443
+ function resolveLintWorkerEntry() {
17444
+ const here = dirname15(fileURLToPath5(import.meta.url));
17445
+ for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
17446
+ const candidate = join33(here, name);
17447
+ if (existsSync22(candidate)) return candidate;
17448
+ }
17449
+ return void 0;
17450
+ }
17451
+ function abortedLintResult(filePath, afterMs) {
17452
+ return {
17453
+ ok: false,
17454
+ errorCount: 1,
17455
+ warningCount: 0,
17456
+ infoCount: 0,
17457
+ findings: [
17458
+ {
17459
+ code: "lint_aborted",
17460
+ severity: "error",
17461
+ message: "This composition's script could not be checked: linting it ran too long or out of memory, so it was stopped. A very large or deeply nested script is the usual cause.",
17462
+ file: filePath
17463
+ }
17464
+ ],
17465
+ timings: { totalMs: afterMs, groupMs: {}, slowestRule: "", slowestRuleMs: 0 }
17466
+ };
17467
+ }
17468
+ async function runHyperframeLint(prepared, options = {}) {
17469
+ const began = performance.now();
17470
+ const aborted = () => abortedLintResult(prepared.entryFile, Math.round(performance.now() - began));
17471
+ const entry = options.workerEntry ?? resolveLintWorkerEntry();
17472
+ if (!entry) return aborted();
17473
+ const timeoutMs = options.timeoutMs ?? LINT_TIMEOUT_MS;
17474
+ const gotSlot = await takeLintSlot(options.maxWorkers ?? LINT_MAX_WORKERS, timeoutMs);
17475
+ if (!gotSlot) return aborted();
17476
+ const remainingMs = Math.max(0, timeoutMs - (performance.now() - began));
17477
+ return new Promise((resolvePromise, reject) => {
17478
+ let worker;
17479
+ try {
17480
+ worker = new Worker2(entry, {
17481
+ workerData: {
17482
+ html: prepared.html,
17483
+ opts: { filePath: prepared.entryFile, compSrcPath: prepared.entryFile }
17484
+ },
17485
+ resourceLimits: { maxOldGenerationSizeMb: options.heapMb ?? LINT_HEAP_MB },
17486
+ stdout: false,
17487
+ stderr: false
17488
+ });
17489
+ } catch {
17490
+ freeLintSlot();
17491
+ resolvePromise(aborted());
17492
+ return;
17493
+ }
17494
+ let settled = false;
17495
+ const settle = (finish) => {
17496
+ if (settled) return;
17497
+ settled = true;
17498
+ clearTimeout(timer);
17499
+ void worker.terminate().finally(freeLintSlot);
17500
+ finish();
17501
+ };
17502
+ const timer = setTimeout(() => settle(() => resolvePromise(aborted())), remainingMs);
17503
+ worker.on(
17504
+ "message",
17505
+ (message) => settle(
17506
+ () => message.result ? resolvePromise(message.result) : reject(new Error(message.error))
17507
+ )
17508
+ );
17509
+ worker.on("error", () => settle(() => resolvePromise(aborted())));
17510
+ worker.on("exit", () => settle(() => resolvePromise(aborted())));
17161
17511
  });
17162
17512
  }
17163
17513
 
17164
17514
  // src/services/healthWorker.ts
17165
- import { Worker as Worker2 } from "node:worker_threads";
17166
- import { fileURLToPath as fileURLToPath5 } from "node:url";
17167
- import { dirname as dirname15, join as join34 } from "node:path";
17515
+ import { Worker as Worker3 } from "node:worker_threads";
17516
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
17517
+ import { dirname as dirname16, join as join34 } from "node:path";
17168
17518
  import { existsSync as existsSync23 } from "node:fs";
17169
17519
  var DEFAULT_HEALTH_PORT = 9848;
17170
17520
  async function startHealthWorker(options = {}) {
@@ -17176,7 +17526,7 @@ async function startHealthWorker(options = {}) {
17176
17526
  "[healthWorker] could not resolve worker entry. Pass options.workerEntry or ensure healthWorkerThread.{js,ts} is co-located."
17177
17527
  );
17178
17528
  }
17179
- const worker = new Worker2(entry, {
17529
+ const worker = new Worker3(entry, {
17180
17530
  workerData: { port },
17181
17531
  // Keep stdio inherited so the worker's console logs land in the pod logs
17182
17532
  // alongside the main thread's.
@@ -17239,7 +17589,7 @@ function defaultLogger2() {
17239
17589
  };
17240
17590
  }
17241
17591
  function resolveWorkerEntry2() {
17242
- const here = dirname15(fileURLToPath5(import.meta.url));
17592
+ const here = dirname16(fileURLToPath6(import.meta.url));
17243
17593
  const candidates = [join34(here, "healthWorkerThread.js"), join34(here, "healthWorkerThread.ts")];
17244
17594
  for (const candidate of candidates) {
17245
17595
  if (existsSync23(candidate)) return candidate;
@@ -17315,9 +17665,9 @@ import {
17315
17665
 
17316
17666
  // src/services/distributed/shared.ts
17317
17667
  import { execFile as execFileCallback } from "node:child_process";
17318
- import { dirname as dirname16, join as join35 } from "node:path";
17668
+ import { dirname as dirname17, join as join35 } from "node:path";
17319
17669
  import { existsSync as existsSync24, readFileSync as readFileSync11 } from "node:fs";
17320
- import { fileURLToPath as fileURLToPath6 } from "node:url";
17670
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
17321
17671
  import { promisify as promisify2 } from "node:util";
17322
17672
  import {
17323
17673
  getFfmpegBinary,
@@ -17328,7 +17678,7 @@ var execFile = promisify2(execFileCallback);
17328
17678
  var cachedProducerVersion = null;
17329
17679
  function readProducerVersion() {
17330
17680
  if (cachedProducerVersion !== null) return cachedProducerVersion;
17331
- const startDir = dirname16(fileURLToPath6(import.meta.url));
17681
+ const startDir = dirname17(fileURLToPath7(import.meta.url));
17332
17682
  let current = startDir;
17333
17683
  for (let i = 0; i < 10; i++) {
17334
17684
  const candidate = join35(current, "package.json");
@@ -17342,7 +17692,7 @@ function readProducerVersion() {
17342
17692
  } catch {
17343
17693
  }
17344
17694
  }
17345
- const parent = dirname16(current);
17695
+ const parent = dirname17(current);
17346
17696
  if (parent === current) break;
17347
17697
  current = parent;
17348
17698
  }
@@ -17602,6 +17952,11 @@ function assertRequestOptionScalars(options) {
17602
17952
  }
17603
17953
  function assertRequestOptionObjects(options) {
17604
17954
  validateEngineConfigSnapshot2(options.engineConfig);
17955
+ if (options.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(options.expectedOutputDimensions)) {
17956
+ throw new Error(
17957
+ "Render request expectedOutputDimensions must contain positive integer width and height"
17958
+ );
17959
+ }
17605
17960
  if (options.variables !== void 0 && !isPlainObject(options.variables)) {
17606
17961
  throw new Error("Render request variables must be a JSON object");
17607
17962
  }
@@ -17667,7 +18022,8 @@ function renderConfigFromRequest(request, runtime = {}) {
17667
18022
  ...options,
17668
18023
  producerConfig: engineConfig,
17669
18024
  logger: runtime.logger,
17670
- allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true
18025
+ allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true,
18026
+ includeOutsideScripts: runtime.includeOutsideScripts === true
17671
18027
  };
17672
18028
  }
17673
18029
 
@@ -17684,7 +18040,9 @@ var SAFE_RENDER_ERROR_CODES = /* @__PURE__ */ new Set([
17684
18040
  "RENDER_TOO_SLOW",
17685
18041
  "RENDER_STAGE_STALLED",
17686
18042
  "PAGE_NEVER_READY",
17687
- "VARIABLES_INVALID"
18043
+ "VARIABLES_INVALID",
18044
+ "OUTPUT_DIMENSIONS_MISMATCH",
18045
+ "COMPOSITION_TOO_LARGE"
17688
18046
  ]);
17689
18047
  function extractSafeRenderErrorCode(error) {
17690
18048
  if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
@@ -17791,6 +18149,7 @@ function parseRenderOptions(body) {
17791
18149
  outputDynamicRange,
17792
18150
  variables,
17793
18151
  strictVariables,
18152
+ expectedOutputDimensions: isExpectedOutputDimensions(body.expectedOutputDimensions) ? body.expectedOutputDimensions : void 0,
17794
18153
  outputResolution,
17795
18154
  outputResolutionAspectAgnostic,
17796
18155
  videoFrameFormat
@@ -17830,6 +18189,7 @@ function buildRenderJobConfig(input, outputPath, log) {
17830
18189
  entryFile: input.entryFile,
17831
18190
  variables: input.variables,
17832
18191
  strictVariables: input.strictVariables,
18192
+ expectedOutputDimensions: input.expectedOutputDimensions,
17833
18193
  outputResolution: input.outputResolution,
17834
18194
  outputResolutionAspectAgnostic: input.outputResolutionAspectAgnostic,
17835
18195
  videoFrameFormat: input.videoFrameFormat,
@@ -17848,7 +18208,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
17848
18208
  throw new Error("outputPath must be inside the renders directory");
17849
18209
  }
17850
18210
  }
17851
- const outputDir = dirname17(absoluteOutputPath);
18211
+ const outputDir = dirname18(absoluteOutputPath);
17852
18212
  if (!existsSync25(outputDir)) mkdirSync13(outputDir, { recursive: true });
17853
18213
  return { input, cleanupProjectDir, absoluteOutputPath };
17854
18214
  }
@@ -17874,6 +18234,9 @@ function validateRenderOverrides(body) {
17874
18234
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
17875
18235
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
17876
18236
  }
18237
+ if (body.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(body.expectedOutputDimensions)) {
18238
+ return "expectedOutputDimensions must contain positive integer width and height";
18239
+ }
17877
18240
  if (body.strictVariables !== void 0 && typeof body.strictVariables !== "boolean") {
17878
18241
  return "strictVariables must be a boolean";
17879
18242
  }
@@ -17924,7 +18287,7 @@ function prepareProjectDirectory(projectDir, options, policy) {
17924
18287
  if (!candidate) return null;
17925
18288
  const absProjectDir = policy ? resolve10(policy.projectsDir, candidate) : resolve10(candidate);
17926
18289
  const shown = policy ? candidate : absProjectDir;
17927
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync25(absProjectDir) || !statSync12(absProjectDir).isDirectory()) {
18290
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync25(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
17928
18291
  return { error: `Project directory not found: ${shown}` };
17929
18292
  }
17930
18293
  const entry = options.entryFile || "index.html";
@@ -18027,7 +18390,7 @@ function publicPerfSummary(job) {
18027
18390
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
18028
18391
  }
18029
18392
  function outputFileSize(path) {
18030
- return existsSync25(path) ? statSync12(path).size : 0;
18393
+ return existsSync25(path) ? statSync13(path).size : 0;
18031
18394
  }
18032
18395
  function createBlockingProgressReporter(log, requestId) {
18033
18396
  let lastLoggedPct = -10;
@@ -18230,7 +18593,8 @@ function createRenderHandlers(options = {}) {
18230
18593
  outcome: job.outcome ?? "completed",
18231
18594
  warnings: job.warnings,
18232
18595
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
18233
- ...strictVariablesResult(job)
18596
+ ...strictVariablesResult(job),
18597
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
18234
18598
  });
18235
18599
  } catch (error) {
18236
18600
  const durationMs = Date.now() - t0;
@@ -18327,7 +18691,8 @@ function createRenderHandlers(options = {}) {
18327
18691
  warnings: job.warnings,
18328
18692
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
18329
18693
  producerVersion: readProducerVersion(),
18330
- ...strictVariablesResult(job)
18694
+ ...strictVariablesResult(job),
18695
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
18331
18696
  })
18332
18697
  });
18333
18698
  } catch (error) {
@@ -18356,7 +18721,7 @@ function createRenderHandlers(options = {}) {
18356
18721
  store.delete(token);
18357
18722
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
18358
18723
  }
18359
- const stats = statSync12(artifact.path);
18724
+ const stats = statSync13(artifact.path);
18360
18725
  return new Response(createReadStream3(artifact.path), {
18361
18726
  headers: {
18362
18727
  "content-type": "video/mp4",