@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
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  mkdirSync as mkdirSync12,
14
14
  readdirSync as readdirSync6,
15
15
  rmSync as rmSync12,
16
- statSync as statSync10,
16
+ statSync as statSync11,
17
17
  writeFileSync as writeFileSync7,
18
18
  copyFileSync as copyFileSync5,
19
19
  appendFileSync
@@ -181,6 +181,10 @@ function stripPreloadNone(html) {
181
181
  return attr && attr.index < tagEnd ? [attr.index, attr.index + attr[0].length] : void 0;
182
182
  });
183
183
  }
184
+ function hasClosedMediaTag(text) {
185
+ const open2 = /<(?:video|audio)\b/i.exec(text);
186
+ return open2 !== null && text.includes(">", open2.index + open2[0].length);
187
+ }
184
188
  var REMOTE_SRC_TAGS = {
185
189
  media: { opener: "<(?:video|audio)\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
186
190
  source: { opener: "<source\\b", attr: /\bsrc\s*=\s*["'](https?:\/\/)/gi },
@@ -529,6 +533,7 @@ import { isSafePath } from "@hyperframes/core/safe-path";
529
533
  import {
530
534
  isCopiedOutsideFileType,
531
535
  isPrivateOutsideFile,
536
+ isUploadedOutsideFileType,
532
537
  leftOutWarning,
533
538
  linksOutside
534
539
  } from "@hyperframes/studio-server/outside-file";
@@ -550,15 +555,17 @@ function isPathInside(childPath, parentPath, options = {}) {
550
555
  function escapesAssetRoot(path, assetRoot) {
551
556
  return assetRoot !== void 0 && !isSafePath(assetRoot, path);
552
557
  }
553
- function outsideAssetRefusal(projectDir, path) {
558
+ function outsideAssetRefusal(projectDir, path, policy = {}) {
554
559
  if (!linksOutside(projectDir, path)) return null;
555
560
  if (isPrivateOutsideFile(projectDir, path)) return "blocklisted";
556
561
  const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
557
- return folder || isCopiedOutsideFileType(path) ? null : "file_type";
562
+ if (folder || isUploadedOutsideFileType(path)) return null;
563
+ if (!isCopiedOutsideFileType(path)) return "file_type";
564
+ return policy.includeScripts ? null : "script";
558
565
  }
559
566
  var leftOutOfRender = (file, reference, reason) => leftOutWarning(file, reference, reason, "render");
560
- function refusesOutsideLink(projectDir, path, warn) {
561
- const refusal = outsideAssetRefusal(projectDir, path);
567
+ function refusesOutsideLink(projectDir, path, warn, policy = {}) {
568
+ const refusal = outsideAssetRefusal(projectDir, path, policy);
562
569
  if (!refusal) return false;
563
570
  const file = nodeRelative(projectDir, path).split(sep).join("/");
564
571
  warn(leftOutOfRender(file, realFilePath(path), refusal));
@@ -1141,7 +1148,8 @@ function createFileServer(options) {
1141
1148
  compiledDir,
1142
1149
  port = 0,
1143
1150
  stripEmbeddedRuntime = true,
1144
- allowOutsideProjectAssets = false
1151
+ allowOutsideProjectAssets = false,
1152
+ includeOutsideScripts = false
1145
1153
  } = options;
1146
1154
  const preHeadScripts = [
1147
1155
  HF_EARLY_STUB,
@@ -1152,6 +1160,7 @@ function createFileServer(options) {
1152
1160
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
1153
1161
  const app = new Hono();
1154
1162
  const warnLeftOut = (line) => console.warn(`[FileServer] ${terminalText2(line)}`);
1163
+ const outsidePolicy = { includeScripts: includeOutsideScripts };
1155
1164
  let listeningPort = -1;
1156
1165
  app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
1157
1166
  await next();
@@ -1169,7 +1178,7 @@ function createFileServer(options) {
1169
1178
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
1170
1179
  if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
1171
1180
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
1172
- if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut)) continue;
1181
+ if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut, outsidePolicy)) continue;
1173
1182
  file = openRegularFile(candidate);
1174
1183
  if (file) break;
1175
1184
  }
@@ -1580,6 +1589,30 @@ function reportEncodeProgress(job, done, total, onProgress, from) {
1580
1589
  "encoding"
1581
1590
  );
1582
1591
  }
1592
+ var AUDIO_STAGE = "Processing audio tracks";
1593
+ var AUDIO_WAIT_REPORT_MS = 5e3;
1594
+ function audioWaitReporter(job, onProgress) {
1595
+ let waiting2 = false;
1596
+ let reportedAt = -Infinity;
1597
+ return {
1598
+ progressed() {
1599
+ const now = Date.now();
1600
+ if (!waiting2 || now - reportedAt < AUDIO_WAIT_REPORT_MS) return;
1601
+ reportedAt = now;
1602
+ updateJobStatus(job, job.status, AUDIO_STAGE, job.progress, onProgress, {
1603
+ code: "process_audio"
1604
+ });
1605
+ },
1606
+ async wait(audio) {
1607
+ waiting2 = true;
1608
+ try {
1609
+ return await audio;
1610
+ } finally {
1611
+ waiting2 = false;
1612
+ }
1613
+ }
1614
+ };
1615
+ }
1583
1616
  var lastAssembleReportAt = /* @__PURE__ */ new WeakMap();
1584
1617
  function reportAssembleProgress(job, done, total, onProgress) {
1585
1618
  if (total <= 0) return;
@@ -2709,9 +2742,10 @@ function frameWeightedAvgMs(perfs, avgOf) {
2709
2742
  function aggregateDedup(perfs) {
2710
2743
  if (perfs.length === 0) return void 0;
2711
2744
  const armed = perfs.some((p) => p.staticDedupArmed);
2712
- const skipReasons = armed ? [] : [
2713
- ...new Set(perfs.map((p) => p.staticDedupSkipReason).filter((r) => !!r))
2714
- ].sort();
2745
+ const distinctUnarmed = (values) => {
2746
+ const distinct = armed ? [] : [...new Set(values.filter((v) => !!v))].sort();
2747
+ return distinct.length > 0 ? distinct.join("|") : void 0;
2748
+ };
2715
2749
  const verificationPerfs = perfs.filter((perf) => perf.staticDedupVerificationOutcome);
2716
2750
  const verificationOutcomes = [
2717
2751
  ...new Set(
@@ -2723,7 +2757,8 @@ function aggregateDedup(perfs) {
2723
2757
  armed,
2724
2758
  predictedFrames: perfs.reduce((sum2, p) => sum2 + (p.staticDedupPredicted ?? 0), 0),
2725
2759
  reusedFrames: perfs.reduce((sum2, p) => sum2 + (p.staticDedupReused ?? 0), 0),
2726
- skipReason: skipReasons.length > 0 ? skipReasons.join("|") : void 0,
2760
+ skipReason: distinctUnarmed(perfs.map((p) => p.staticDedupSkipReason)),
2761
+ ineligibleCause: distinctUnarmed(perfs.map((p) => p.staticDedupIneligibleCause)),
2727
2762
  ...verificationPerfs.length === 0 ? {} : {
2728
2763
  verifiedFrames: verificationPerfs.reduce(
2729
2764
  (sum2, perf) => sum2 + (perf.staticDedupVerified ?? 0),
@@ -6853,6 +6888,22 @@ function countAuthoredTimedClips(html) {
6853
6888
  return document2.querySelectorAll("[data-start]").length;
6854
6889
  }
6855
6890
 
6891
+ // src/services/render/outputDimensions.ts
6892
+ function isExpectedOutputDimensions(value) {
6893
+ 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;
6894
+ }
6895
+ var OutputDimensionsMismatchError = class extends Error {
6896
+ code = "OUTPUT_DIMENSIONS_MISMATCH";
6897
+ constructor() {
6898
+ super("Compiled output dimensions do not match the requested render dimensions.");
6899
+ }
6900
+ };
6901
+ function requireOutputDimensions(expected, width, height) {
6902
+ if (expected !== void 0 && (!isExpectedOutputDimensions(expected) || expected.width !== width || expected.height !== height)) {
6903
+ throw new OutputDimensionsMismatchError();
6904
+ }
6905
+ }
6906
+
6856
6907
  // src/services/render/stages/compileStage.ts
6857
6908
  import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6858
6909
  import { join as join20, relative as relative3 } from "node:path";
@@ -6861,6 +6912,61 @@ import { suggestMatchingPreset } from "@hyperframes/core";
6861
6912
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6862
6913
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6863
6914
 
6915
+ // src/services/compositionSizeLimit.ts
6916
+ import { statSync as statSync7 } from "node:fs";
6917
+ var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
6918
+ var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
6919
+ var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
6920
+ var MAX_EXPANDED_COMPOSITION_BYTES = 2 * MAX_COMPOSITION_HTML_BYTES;
6921
+ var MAX_COMPOSITION_MOUNTS = 1e4;
6922
+ var CompositionTooLargeError = class extends Error {
6923
+ constructor(message, publicMetadata) {
6924
+ super(message);
6925
+ this.publicMetadata = publicMetadata;
6926
+ this.name = "CompositionTooLargeError";
6927
+ }
6928
+ publicMetadata;
6929
+ code = COMPOSITION_TOO_LARGE;
6930
+ // The producer server reads these off the error for the wire envelope.
6931
+ owner = "user";
6932
+ retryable = false;
6933
+ };
6934
+ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6935
+ `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.`,
6936
+ { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6937
+ );
6938
+ var CompositionExpansionBudget = class {
6939
+ bytes = 0;
6940
+ mounts = 0;
6941
+ charge(file, bytes) {
6942
+ this.bytes += bytes;
6943
+ this.mounts += 1;
6944
+ if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
6945
+ return;
6946
+ }
6947
+ throw new CompositionTooLargeError(
6948
+ `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.`,
6949
+ {
6950
+ bytes: this.bytes,
6951
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
6952
+ mounts: this.mounts,
6953
+ exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
6954
+ }
6955
+ );
6956
+ }
6957
+ };
6958
+ function assertCompositionFileSize(path, file) {
6959
+ let bytes;
6960
+ try {
6961
+ const stats = statSync7(path);
6962
+ if (!stats.isFile()) return;
6963
+ bytes = stats.size;
6964
+ } catch {
6965
+ return;
6966
+ }
6967
+ if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
6968
+ }
6969
+
6864
6970
  // src/services/htmlCompiler.ts
6865
6971
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6866
6972
  import {
@@ -6947,11 +7053,13 @@ import {
6947
7053
  import {
6948
7054
  isUnresolvedAssetPlaceholder,
6949
7055
  namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
7056
+ projectAssetExists,
6950
7057
  readProjectFile,
6951
7058
  readTextFile,
6952
7059
  resolveCompositionSrc
6953
7060
  } from "@hyperframes/parsers/asset-resolution";
6954
7061
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7062
+ import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
6955
7063
 
6956
7064
  // src/services/renderMediaCollector.ts
6957
7065
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7145,7 +7253,7 @@ import {
7145
7253
 
7146
7254
  // src/services/animatedGifPrep.ts
7147
7255
  import { createHash as createHash4 } from "node:crypto";
7148
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7256
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7149
7257
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7150
7258
  import { parseHTML as parseHTML3 } from "linkedom";
7151
7259
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7198,12 +7306,13 @@ function resolveLocalImageSourcePath(src, options) {
7198
7306
  isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7199
7307
  resolve5(options.downloadDir, normalizedBase)
7200
7308
  ];
7201
- 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));
7309
+ const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7310
+ 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));
7202
7311
  return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7203
7312
  }
7204
7313
  function isUsableFile(path) {
7205
7314
  try {
7206
- const stat = statSync7(path);
7315
+ const stat = statSync8(path);
7207
7316
  return stat.isFile() && stat.size > 0;
7208
7317
  } catch {
7209
7318
  return false;
@@ -7468,7 +7577,7 @@ import {
7468
7577
  readFileSync as readFileSync7,
7469
7578
  readSync as readSync3,
7470
7579
  rmSync as rmSync10,
7471
- statSync as statSync8,
7580
+ statSync as statSync9,
7472
7581
  writeFileSync as writeFileSync4
7473
7582
  } from "node:fs";
7474
7583
  import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
@@ -7712,7 +7821,7 @@ function resolveImageSource(src, options) {
7712
7821
  }
7713
7822
  function isUsableFile2(path) {
7714
7823
  try {
7715
- return statSync8(path).size > 0;
7824
+ return statSync9(path).size > 0;
7716
7825
  } catch {
7717
7826
  return false;
7718
7827
  }
@@ -7991,7 +8100,7 @@ Check that each file referenced by data-composition-src contains valid HTML with
7991
8100
  };
7992
8101
  function normalizeCompositionSrcs(html, projectDir) {
7993
8102
  return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
7994
- if (!value.includes("%") && !value.startsWith("/")) return whole;
8103
+ if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
7995
8104
  const file = resolveCompositionSrc(projectDir, value);
7996
8105
  if (file === null) return whole;
7997
8106
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
@@ -8007,68 +8116,94 @@ function resolveCompositionFile(projectDir, src, assetRoot) {
8007
8116
  const file = resolveCompositionPath(projectDir, src, assetRoot);
8008
8117
  return file !== null && COMPOSITION_FILE.test(file) ? file : null;
8009
8118
  }
8119
+ 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";
8120
+ var runsOutsideMarkupUnasked = (projectDir, filePath, assetRoot, outsideFiles) => assetRoot === void 0 && !outsideFiles.includeScripts && linksOutside2(projectDir, filePath);
8121
+ function assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles) {
8122
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8123
+ throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
8124
+ }
8125
+ }
8010
8126
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
8011
- function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
8127
+ var mountSrcsUnder = (root) => [...root.querySelectorAll("[data-composition-src]")].map((el) => el.getAttribute("data-composition-src")).filter((srcPath) => !!srcPath && !isUnresolvedAssetPlaceholder(srcPath));
8128
+ function compositionSrcsIn(html) {
8012
8129
  const { document: document2 } = parseHTML5(html);
8013
- const hosts = [...document2.querySelectorAll("[data-composition-src]")];
8014
- const problems = [];
8015
- for (const el of hosts) {
8016
- const srcPath = el.getAttribute("data-composition-src");
8017
- if (!srcPath) continue;
8018
- if (isUnresolvedAssetPlaceholder(srcPath)) continue;
8130
+ const templated = [];
8131
+ const templates = [...document2.querySelectorAll("template")];
8132
+ for (let template = templates.pop(); template; template = templates.pop()) {
8133
+ templated.push(...mountSrcsUnder(template.content));
8134
+ templates.push(...template.content.querySelectorAll("template"));
8135
+ }
8136
+ return { mounts: mountSrcsUnder(document2), templated };
8137
+ }
8138
+ function compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles) {
8139
+ if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8140
+ return "it is outside the project in a private location";
8141
+ }
8142
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8143
+ return OUTSIDE_COMPOSITION_NEEDS_FLAG;
8144
+ }
8145
+ if (isPrivateCompositionFile(projectDir, filePath)) {
8146
+ return "it is git metadata, an env file or a private tool record";
8147
+ }
8148
+ return COMPOSITION_FILE.test(filePath) ? null : NOT_A_COMPOSITION_FILE;
8149
+ }
8150
+ function readSubCompositionFile(filePath, srcPath) {
8151
+ assertCompositionFileSize(filePath, srcPath);
8152
+ const read = readProjectFile(filePath);
8153
+ if (read.kind === "missing") return { detail: "the file does not exist" };
8154
+ if (read.kind === "folder") return { detail: "it is a folder, not an HTML file" };
8155
+ const validity = checkSubCompositionUsability(read.text, parseSubCompHtmlForValidity);
8156
+ if (!validity.ok)
8157
+ return { detail: validity.detail ?? "the file is empty or could not be parsed" };
8158
+ return { bytes: Buffer.byteLength(read.text), ...compositionSrcsIn(read.text) };
8159
+ }
8160
+ function assertSubCompositionsUsable(html, projectDir, assetRoot, outsideFiles) {
8161
+ const budget = new CompositionExpansionBudget();
8162
+ const files = /* @__PURE__ */ new Map();
8163
+ const problems = /* @__PURE__ */ new Map();
8164
+ const report = (srcPath, detail) => problems.set(`${srcPath}\0${detail}`, { srcPath, detail });
8165
+ const chain = /* @__PURE__ */ new Set();
8166
+ const paths = /* @__PURE__ */ new Map();
8167
+ const resolveMount = (srcPath) => {
8019
8168
  const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
8020
- if (filePath === null) {
8021
- problems.push({ srcPath, detail: "it is outside the project folder" });
8022
- continue;
8023
- }
8024
- if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8025
- problems.push({ srcPath, detail: "it is outside the project in a private location" });
8026
- continue;
8027
- }
8028
- if (isPrivateCompositionFile(projectDir, filePath)) {
8029
- problems.push({
8030
- srcPath,
8031
- detail: "it is git metadata, an env file or a private tool record"
8032
- });
8033
- continue;
8034
- }
8035
- if (!COMPOSITION_FILE.test(filePath)) {
8036
- problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
8037
- continue;
8038
- }
8039
- if (visited.has(filePath)) continue;
8040
- const read = readProjectFile(filePath);
8041
- if (read.kind === "missing") {
8042
- problems.push({ srcPath, detail: "the file does not exist" });
8043
- continue;
8044
- }
8045
- if (read.kind === "folder") {
8046
- problems.push({ srcPath, detail: "it is a folder, not an HTML file" });
8047
- continue;
8048
- }
8049
- const fileHtml = read.text;
8050
- const validity = checkSubCompositionUsability(fileHtml, parseSubCompHtmlForValidity);
8051
- if (!validity.ok) {
8052
- problems.push({
8053
- srcPath,
8054
- detail: validity.detail ?? "the file is empty or could not be parsed"
8055
- });
8056
- continue;
8057
- }
8058
- const nestedVisited = new Set(visited);
8059
- nestedVisited.add(filePath);
8060
- try {
8061
- assertSubCompositionsUsable(fileHtml, projectDir, assetRoot, nestedVisited);
8062
- } catch (err) {
8063
- if (err instanceof EmptyCompositionError) {
8064
- problems.push(...err.problems);
8065
- } else {
8066
- throw err;
8169
+ if (filePath === null) return { detail: "it is outside the project folder" };
8170
+ const detail = compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles);
8171
+ return detail ? { detail } : { filePath };
8172
+ };
8173
+ const walk = (srcPaths, quiet) => {
8174
+ for (const srcPath of srcPaths) {
8175
+ let resolved = paths.get(srcPath);
8176
+ if (!resolved) {
8177
+ resolved = resolveMount(srcPath);
8178
+ paths.set(srcPath, resolved);
8179
+ }
8180
+ if ("detail" in resolved) {
8181
+ if (!quiet) report(srcPath, resolved.detail);
8182
+ continue;
8067
8183
  }
8184
+ const { filePath } = resolved;
8185
+ if (chain.has(filePath)) continue;
8186
+ let file = files.get(filePath);
8187
+ if (!file) {
8188
+ file = readSubCompositionFile(filePath, srcPath);
8189
+ files.set(filePath, file);
8190
+ }
8191
+ if ("detail" in file) {
8192
+ if (!quiet) report(srcPath, file.detail);
8193
+ continue;
8194
+ }
8195
+ budget.charge(srcPath, file.bytes);
8196
+ chain.add(filePath);
8197
+ walk(file.mounts, quiet);
8198
+ walk(file.templated, true);
8199
+ chain.delete(filePath);
8068
8200
  }
8069
- }
8070
- if (problems.length > 0) {
8071
- throw new EmptyCompositionError(problems);
8201
+ };
8202
+ const entry = compositionSrcsIn(html);
8203
+ walk(entry.mounts, false);
8204
+ walk(entry.templated, true);
8205
+ if (problems.size > 0) {
8206
+ throw new EmptyCompositionError([...problems.values()]);
8072
8207
  }
8073
8208
  }
8074
8209
  var COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
@@ -8323,7 +8458,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8323
8458
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
8324
8459
  return { html: compiledHtml, unresolvedCompositions };
8325
8460
  }
8326
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot) {
8461
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8327
8462
  const subCompositions = /* @__PURE__ */ new Map();
8328
8463
  const { document: document2 } = parseHTML5(html);
8329
8464
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -8336,6 +8471,10 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8336
8471
  if (visited.has(filePath)) {
8337
8472
  continue;
8338
8473
  }
8474
+ if (compiledSrcs.has(srcPath)) continue;
8475
+ compiledSrcs.add(srcPath);
8476
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8477
+ assertCompositionFileSize(filePath, srcPath);
8339
8478
  const read = readProjectFile(filePath);
8340
8479
  if (read.kind !== "file") {
8341
8480
  continue;
@@ -8364,7 +8503,9 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8364
8503
  item.nestedVisited,
8365
8504
  urlByAbsentLocalPath,
8366
8505
  probes,
8367
- assetRoot
8506
+ assetRoot,
8507
+ outsideFiles,
8508
+ compiledSrcs
8368
8509
  );
8369
8510
  return {
8370
8511
  srcPath: item.srcPath,
@@ -8500,7 +8641,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8500
8641
  }
8501
8642
  return document2.toString();
8502
8643
  }
8503
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot) {
8644
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8504
8645
  const { document: document2 } = parseHTML5(html);
8505
8646
  const head = document2.querySelector("head");
8506
8647
  const body = document2.querySelector("body");
@@ -8511,8 +8652,29 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8511
8652
  {},
8512
8653
  variableOverrides
8513
8654
  );
8514
- return emitted ? document2.toString() : html;
8655
+ return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8515
8656
  }
8657
+ const budget = new CompositionExpansionBudget();
8658
+ const readOnce = /* @__PURE__ */ new Map();
8659
+ const readMountHtml = (srcPath) => {
8660
+ const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8661
+ if (filePath) {
8662
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8663
+ assertCompositionFileSize(filePath, srcPath);
8664
+ }
8665
+ const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8666
+ return read?.kind === "file" ? rewriteUnresolvableGsapToCdn(
8667
+ normalizeCompositionSrcs(read.text, projectDir),
8668
+ projectDir,
8669
+ srcPath
8670
+ ) : null;
8671
+ };
8672
+ const resolveMountHtml = (srcPath) => {
8673
+ const compiled = subCompositions.get(srcPath);
8674
+ if (compiled) return compiled;
8675
+ if (!readOnce.has(srcPath)) readOnce.set(srcPath, readMountHtml(srcPath));
8676
+ return readOnce.get(srcPath) ?? null;
8677
+ };
8516
8678
  const hostIdentityByElement = new ProducerHostIdentityMap(
8517
8679
  document2,
8518
8680
  hosts
@@ -8528,20 +8690,14 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8528
8690
  readVariableDefaults: readDeclaredDefaults,
8529
8691
  parseHostVariables: parseHostVariableValues,
8530
8692
  resolveHtml: (srcPath) => {
8531
- let compHtml = subCompositions.get(srcPath) || null;
8532
- if (!compHtml) {
8533
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8534
- const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8535
- if (read?.kind === "file") {
8536
- compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
8537
- }
8538
- }
8693
+ const compHtml = resolveMountHtml(srcPath);
8694
+ if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
8539
8695
  return compHtml;
8540
8696
  },
8541
8697
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
8542
8698
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
8543
8699
  // against its own directory, project-root refs stay as authored.
8544
- assetExists: (path) => existsSync11(resolve7(projectDir, path)),
8700
+ assetExists: projectAssetExists(projectDir),
8545
8701
  // Preserve the authored root wrapper as a child of the host, matching
8546
8702
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
8547
8703
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8625,7 +8781,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8625
8781
  variableOverrides
8626
8782
  );
8627
8783
  assignMediaRenderIds(document2);
8628
- return document2.toString();
8784
+ return { html: document2.toString(), variablesByComp: result.variablesByComp };
8629
8785
  }
8630
8786
  function ensureFullDocument(html) {
8631
8787
  const trimmed = html.trim();
@@ -8746,7 +8902,7 @@ ${safeText}
8746
8902
  }
8747
8903
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8748
8904
  }
8749
- function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html") {
8905
+ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8750
8906
  const absProjectDir = resolve7(projectDir);
8751
8907
  const externalAssets = /* @__PURE__ */ new Map();
8752
8908
  const leftOut = /* @__PURE__ */ new Set();
@@ -8759,7 +8915,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8759
8915
  }
8760
8916
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8761
8917
  if (!onShare && !existsSync11(absPath)) return null;
8762
- const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath);
8918
+ const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8763
8919
  if (refusal) {
8764
8920
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
8765
8921
  leftOut.add(trimmed);
@@ -9148,7 +9304,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9148
9304
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9149
9305
  if (!entryPath.includes("/")) return html;
9150
9306
  const { document: document2 } = parseHTML5(html);
9151
- const assetExists = (path) => existsSync11(resolve7(projectDir, path));
9307
+ const assetExists = projectAssetExists(projectDir);
9152
9308
  rewriteAssetPaths(
9153
9309
  document2.querySelectorAll("[src], [href], [srcset]"),
9154
9310
  entryPath,
@@ -9189,18 +9345,23 @@ function bindVariableMediaSources(html, variables) {
9189
9345
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9190
9346
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9191
9347
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9348
+ const outsideFiles = { includeScripts: options.includeOutsideScripts };
9192
9349
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
9193
9350
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
9194
9351
  }
9352
+ if (isPathInside(htmlPath, projectDir) && runsOutsideMarkupUnasked(projectDir, htmlPath, assetRoot, outsideFiles)) {
9353
+ throw new Error(`Entry file ${htmlPath} ${OUTSIDE_COMPOSITION_NEEDS_FLAG}`);
9354
+ }
9195
9355
  if (!COMPOSITION_FILE.test(htmlPath)) {
9196
9356
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9197
9357
  }
9358
+ assertCompositionFileSize(htmlPath, basename5(htmlPath));
9198
9359
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9199
9360
  const rawHtml = bindVariableMediaSources(
9200
9361
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9201
9362
  options.variables ?? {}
9202
9363
  );
9203
- assertSubCompositionsUsable(rawHtml, projectDir, assetRoot);
9364
+ assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9204
9365
  const probes = /* @__PURE__ */ new Map();
9205
9366
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
9206
9367
  rawHtml,
@@ -9219,15 +9380,17 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9219
9380
  void 0,
9220
9381
  options.urlByAbsentLocalPath,
9221
9382
  probes,
9222
- assetRoot
9383
+ assetRoot,
9384
+ outsideFiles
9223
9385
  );
9224
9386
  const fullHtml = ensureFullDocument(compiledHtml);
9225
- const inlinedHtml = inlineSubCompositions(
9387
+ const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
9226
9388
  fullHtml,
9227
9389
  subCompositions,
9228
9390
  projectDir,
9229
9391
  options.variables ?? {},
9230
- assetRoot
9392
+ assetRoot,
9393
+ outsideFiles
9231
9394
  );
9232
9395
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9233
9396
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9281,7 +9444,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9281
9444
  cacheDir: options.animatedGifCacheDir,
9282
9445
  sourceAssets: remoteImageAssets,
9283
9446
  timeoutMs: options.ffmpegProcessTimeout,
9284
- assetRoot
9447
+ allowOutsideFiles: assetRoot === void 0
9285
9448
  });
9286
9449
  if (preparedHeifImages.length > 0) {
9287
9450
  defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
@@ -9297,7 +9460,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9297
9460
  cacheDir: options.animatedGifCacheDir,
9298
9461
  sourceAssets: gifSourceAssets,
9299
9462
  timeoutMs: options.ffmpegProcessTimeout,
9300
- assetRoot
9463
+ allowOutsideFiles: assetRoot === void 0
9301
9464
  });
9302
9465
  if (preparedGifs.length > 0) {
9303
9466
  defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
@@ -9312,7 +9475,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9312
9475
  embeddedHtml,
9313
9476
  projectDir,
9314
9477
  options.log,
9315
- entryFileName(projectDir, htmlPath)
9478
+ entryFileName(projectDir, htmlPath),
9479
+ { includeScripts: options.includeOutsideScripts }
9316
9480
  ) : { html: embeddedHtml, externalAssets: /* @__PURE__ */ new Map() };
9317
9481
  for (const [relPath, absPath] of remoteMediaAssets) {
9318
9482
  externalAssets.set(relPath, absPath);
@@ -9375,6 +9539,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9375
9539
  gradedCanvas,
9376
9540
  ...masterFxChain ? { masterFxChain } : {},
9377
9541
  unresolvedCompositions,
9542
+ variablesByComp,
9378
9543
  externalAssets,
9379
9544
  width,
9380
9545
  height,
@@ -9718,7 +9883,7 @@ async function resolveCompositionDurations(page, unresolved) {
9718
9883
  }
9719
9884
  return resolutions;
9720
9885
  }
9721
- async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot) {
9886
+ async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot, outsideFiles = {}) {
9722
9887
  if (resolutions.length === 0) return compiled;
9723
9888
  const html = injectDurations(compiled.html, resolutions);
9724
9889
  const { subCompositions } = await parseSubCompositions(
@@ -9728,7 +9893,8 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9728
9893
  void 0,
9729
9894
  void 0,
9730
9895
  void 0,
9731
- assetRoot
9896
+ assetRoot,
9897
+ outsideFiles
9732
9898
  );
9733
9899
  const { videos, audios, images } = compiled;
9734
9900
  const remaining = compiled.unresolvedCompositions.filter(
@@ -9776,6 +9942,7 @@ function resolveEntryHtmlPath(input) {
9776
9942
  `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
9777
9943
  );
9778
9944
  }
9945
+ assertCompositionFileSize(path, relative3(projectDir, path));
9779
9946
  return readTextFile2(path);
9780
9947
  };
9781
9948
  const htmlPath = join20(projectDir, entryFile);
@@ -9837,7 +10004,8 @@ async function runCompileStage(input) {
9837
10004
  pageMotionBlur: input.pageMotionBlur,
9838
10005
  animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
9839
10006
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
9840
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10007
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10008
+ includeOutsideScripts: job.config.includeOutsideScripts
9841
10009
  });
9842
10010
  assertNotAborted();
9843
10011
  const compileOnlyMs = Date.now() - compileStart;
@@ -9923,6 +10091,8 @@ async function runCompileStage(input) {
9923
10091
  });
9924
10092
  const outputWidth = Math.round(width * deviceScaleFactor);
9925
10093
  const outputHeight = Math.round(height * deviceScaleFactor);
10094
+ requireOutputDimensions(job.config.expectedOutputDimensions, outputWidth, outputHeight);
10095
+ if (job.config.expectedOutputDimensions !== void 0) job.outputDimensionsChecked = true;
9926
10096
  if (deviceScaleFactor !== 1) {
9927
10097
  log.info("Scaling composition via deviceScaleFactor", {
9928
10098
  compositionWidth: width,
@@ -10017,23 +10187,50 @@ function hasAutoStartVideos(html) {
10017
10187
  const { document: document2 } = parseHTML6(html);
10018
10188
  return document2.querySelector("video[data-hf-auto-start]") !== null;
10019
10189
  }
10020
- function variableHasValue(element, variableId, variables) {
10190
+ var MAX_VARIABLE_SCOPE_STEPS = 1e6;
10191
+ function variableIdsOn(scan, element) {
10192
+ let ids = scan.ids.get(element);
10193
+ if (!ids) {
10194
+ ids = /* @__PURE__ */ new Set([
10195
+ ...Object.keys(parseHostVariableValues2(element)),
10196
+ ...Object.keys(readDeclaredDefaults2(element))
10197
+ ]);
10198
+ scan.ids.set(element, ids);
10199
+ }
10200
+ return ids;
10201
+ }
10202
+ function scopedVariablesFor(scan, element, variablesByComp) {
10203
+ for (let node = element; node; node = node.parentElement) {
10204
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return null;
10205
+ if (!node.hasAttribute("data-composition-id")) continue;
10206
+ const compId = node.getAttribute("data-composition-id")?.trim() ?? "";
10207
+ return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : void 0;
10208
+ }
10209
+ return void 0;
10210
+ }
10211
+ function variableHasValue(scan, element, variableId, variables, variablesByComp) {
10021
10212
  if (variables && Object.hasOwn(variables, variableId)) return true;
10213
+ const scoped = scopedVariablesFor(scan, element, variablesByComp);
10214
+ if (scoped === null) return true;
10215
+ if (scoped) return Object.hasOwn(scoped, variableId);
10022
10216
  for (let scope = element.parentElement; scope; scope = scope.parentElement) {
10023
- if (Object.hasOwn(parseHostVariableValues2(scope), variableId)) return true;
10024
- if (Object.hasOwn(readDeclaredDefaults2(scope), variableId)) return true;
10217
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return true;
10218
+ if (variableIdsOn(scan, scope).has(variableId)) return true;
10025
10219
  }
10026
- return Object.hasOwn(readDeclaredDefaults2(element.ownerDocument.documentElement), variableId);
10220
+ return variableIdsOn(scan, element.ownerDocument.documentElement).has(variableId);
10027
10221
  }
10028
- function hasVariableBoundMedia(html, variables) {
10222
+ function hasVariableBoundMedia(html, variables, variablesByComp = {}) {
10029
10223
  const { document: document2 } = parseHTML6(html);
10224
+ const scan = { ids: /* @__PURE__ */ new Map(), steps: 0 };
10030
10225
  return Array.from(
10031
10226
  document2.querySelectorAll(
10032
10227
  "img[data-var-src], audio[data-var-src], video[data-var-src], source[data-var-src]"
10033
10228
  )
10034
10229
  ).some((element) => {
10035
10230
  const variableId = element.getAttribute("data-var-src")?.trim();
10036
- return Boolean(variableId && variableHasValue(element, variableId, variables));
10231
+ return Boolean(
10232
+ variableId && variableHasValue(scan, element, variableId, variables, variablesByComp)
10233
+ );
10037
10234
  });
10038
10235
  }
10039
10236
  function authoredMediaStarts(html) {
@@ -10073,29 +10270,54 @@ function reconcileBrowserMediaEnd(existingEnd, projectedEnd, sourceChanged, dura
10073
10270
  if (sourceChanged && durationInferred) return projectedEnd;
10074
10271
  return existingEnd <= 0 ? projectedEnd : Math.min(existingEnd, projectedEnd);
10075
10272
  }
10273
+ var MAX_MEDIA_SELECTOR_WORK = 1e6;
10274
+ var SIBLING_COMBINATOR = /[~+]/;
10275
+ function managedMediaElements(document2) {
10276
+ const managed = [];
10277
+ const pending = [];
10278
+ for (const element of Array.from(document2.children)) pending.push({ element, inMedia: false });
10279
+ for (let next = pending.pop(); next; next = pending.pop()) {
10280
+ const name = next.element.tagName.toLowerCase();
10281
+ const isMedia = name === "video" || name === "audio";
10282
+ if (isMedia || next.inMedia && name === "source") managed.push(next.element);
10283
+ for (const child3 of Array.from(next.element.children)) {
10284
+ pending.push({ element: child3, inMedia: next.inMedia || isMedia });
10285
+ }
10286
+ }
10287
+ return managed;
10288
+ }
10076
10289
  function hasRuntimeMediaChanges(html) {
10077
10290
  const { document: document2 } = parseHTML6(html);
10078
10291
  const scriptBodies = [...document2.querySelectorAll("script")].map(
10079
10292
  (script) => script.textContent ?? ""
10080
10293
  );
10081
10294
  const insertedMedia = scriptBodies.some(
10082
- (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || /<(?:video|audio)\b[^>]*>/i.test(script)
10295
+ (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || hasClosedMediaTag(script)
10083
10296
  );
10084
10297
  if (insertedMedia) return true;
10085
- const isManagedMedia = (element) => {
10086
- const name = element.tagName.toLowerCase();
10087
- if (name === "video" || name === "audio") return true;
10088
- return name === "source" && element.closest("video, audio") !== null;
10089
- };
10298
+ const managed = managedMediaElements(document2);
10299
+ if (managed.length === 0) return false;
10300
+ const managedIds = new Set(managed.map((element) => element.getAttribute("id")).filter(Boolean));
10301
+ const selectors = /* @__PURE__ */ new Set();
10302
+ let selectorChars = 0;
10090
10303
  for (const script of scriptBodies) {
10091
10304
  for (const mutation of extractMediaSrcMutations(script)) {
10092
- try {
10093
- const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10094
- const idTarget = id ? document2.getElementById(id) : null;
10095
- const targets = id ? idTarget ? [idTarget] : [] : [...document2.querySelectorAll(mutation.selector)];
10096
- if (targets.some(isManagedMedia)) return true;
10097
- } catch {
10305
+ const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10306
+ if (id) {
10307
+ if (managedIds.has(id)) return true;
10308
+ continue;
10098
10309
  }
10310
+ if (selectors.has(mutation.selector)) continue;
10311
+ if (SIBLING_COMBINATOR.test(mutation.selector)) return true;
10312
+ selectors.add(mutation.selector);
10313
+ selectorChars += mutation.selector.length;
10314
+ if (selectorChars * managed.length > MAX_MEDIA_SELECTOR_WORK) return true;
10315
+ }
10316
+ }
10317
+ for (const selector of selectors) {
10318
+ try {
10319
+ if (managed.some((element) => element.matches(selector))) return true;
10320
+ } catch {
10099
10321
  }
10100
10322
  }
10101
10323
  return false;
@@ -10148,7 +10370,11 @@ async function runProbeStage(input) {
10148
10370
  compiled.html,
10149
10371
  composition.audios.length
10150
10372
  );
10151
- const hasVariableMedia = hasVariableBoundMedia(compiled.html, job.config.variables);
10373
+ const hasVariableMedia = hasVariableBoundMedia(
10374
+ compiled.html,
10375
+ job.config.variables,
10376
+ compiled.variablesByComp
10377
+ );
10152
10378
  const hasInsertedMedia = hasRuntimeMediaChanges(compiled.html);
10153
10379
  const needsBrowser = cfg.videoLayerPassthrough || input.measuresShownBoxes === true || probeRequiresBrowser({
10154
10380
  durationSeconds: composition.duration,
@@ -10179,7 +10405,8 @@ async function runProbeStage(input) {
10179
10405
  port: 0,
10180
10406
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10181
10407
  fps: job.config.fps,
10182
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10408
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10409
+ includeOutsideScripts: job.config.includeOutsideScripts
10183
10410
  });
10184
10411
  assertNotAborted();
10185
10412
  const motionBlur = job.config.motionBlur;
@@ -10335,7 +10562,8 @@ async function runProbeStage(input) {
10335
10562
  resolutions,
10336
10563
  projectDir,
10337
10564
  join21(workDir, "downloads"),
10338
- job.config.allowOutsideProjectAssets ? void 0 : projectDir
10565
+ job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10566
+ { includeScripts: job.config.includeOutsideScripts }
10339
10567
  );
10340
10568
  assertNotAborted();
10341
10569
  composition.videos = compiled.videos;
@@ -11296,7 +11524,8 @@ import {
11296
11524
  audioFailureDiagnostics,
11297
11525
  processCompositionAudio,
11298
11526
  removeScratch as removeScratch2,
11299
- collectScratchLeftovers
11527
+ collectScratchLeftovers,
11528
+ withFfmpegProgress
11300
11529
  } from "@hyperframes/engine";
11301
11530
 
11302
11531
  // src/services/render/audioDeliveryLimit.ts
@@ -11322,7 +11551,8 @@ import {
11322
11551
  removeScratch,
11323
11552
  renameWithRetry as renameWithRetry5,
11324
11553
  runFfmpeg as runFfmpeg5,
11325
- trackChildProcess
11554
+ trackChildProcess,
11555
+ withPublicOnlyProxy
11326
11556
  } from "@hyperframes/engine";
11327
11557
  import { redactKnownPaths, redactTelemetryString as redactTelemetryString3 } from "@hyperframes/core";
11328
11558
 
@@ -11764,7 +11994,17 @@ async function runFfprobeJson(args, signal) {
11764
11994
  if (!args.includes("--")) {
11765
11995
  throw new Error('[audioPadTrim] ffprobe args must terminate options with "--".');
11766
11996
  }
11997
+ const proxying = withPublicOnlyProxy(args, [args.indexOf("--") + 1]);
11998
+ const routed = proxying && await proxying;
11999
+ try {
12000
+ return await spawnFfprobeJson(routed?.args ?? args, routed?.env, signal);
12001
+ } finally {
12002
+ await routed?.close();
12003
+ }
12004
+ }
12005
+ async function spawnFfprobeJson(args, env, signal) {
11767
12006
  const proc = spawn(getFfprobeBinary(), args, {
12007
+ ...env && { env },
11768
12008
  stdio: ["ignore", "pipe", "pipe"],
11769
12009
  windowsHide: true
11770
12010
  });
@@ -11880,7 +12120,8 @@ function assertAudioNotInterrupted(failures) {
11880
12120
  }
11881
12121
  function runAudioStage(input) {
11882
12122
  return collectScratchLeftovers(
11883
- () => runAudioStageScoped(input),
12123
+ () => withFfmpegProgress(input.onFfmpegProgress ?? (() => {
12124
+ }), () => runAudioStageScoped(input)),
11884
12125
  (left) => {
11885
12126
  if (left.length > 0) input.log?.warn("[audio] scratch left behind", { count: left.length });
11886
12127
  }
@@ -13400,7 +13641,7 @@ import {
13400
13641
  readdirSync as readdirSync5,
13401
13642
  readFileSync as readFileSync9,
13402
13643
  rmSync as rmSync11,
13403
- statSync as statSync9,
13644
+ statSync as statSync10,
13404
13645
  writeFileSync as writeFileSync6
13405
13646
  } from "node:fs";
13406
13647
  import { readFile as readFile2 } from "node:fs/promises";
@@ -13529,7 +13770,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13529
13770
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13530
13771
  if (failure) return failure;
13531
13772
  }
13532
- const fileSize = existsSync20(outputPath) ? statSync9(outputPath).size : 0;
13773
+ const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
13533
13774
  return {
13534
13775
  success: true,
13535
13776
  outputPath,
@@ -13552,7 +13793,10 @@ function startEncodeProgress(job, stage, onProgress) {
13552
13793
  function resolveEngineConfig(input) {
13553
13794
  return input.engineConfig ?? input.job.config.producerConfig ?? resolveConfig();
13554
13795
  }
13555
- function videoEncoderOptions(input, engineCfg) {
13796
+ function overlapEncoderThreads(workerCount, cpuCount) {
13797
+ return Math.max(1, Math.floor(cpuCount) - Math.floor(workerCount));
13798
+ }
13799
+ function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
13556
13800
  const { job, preset } = input;
13557
13801
  return {
13558
13802
  fps: job.config.fps,
@@ -13572,7 +13816,8 @@ function videoEncoderOptions(input, engineCfg) {
13572
13816
  // keyframes that survive `-f concat -c copy` at assemble time. In-process
13573
13817
  // renders leave both undefined → preserves the existing open-GOP output.
13574
13818
  lockGopForChunkConcat: input.lockGopForChunkConcat === true,
13575
- gopSize: input.gopSize
13819
+ gopSize: input.gopSize,
13820
+ softwareEncoderThreads
13576
13821
  };
13577
13822
  }
13578
13823
  function canEncodeWhileCapturing(input, workerCount, cpuCount) {
@@ -13588,8 +13833,9 @@ async function readLandedFrame(workerPath, mergedPath) {
13588
13833
  }
13589
13834
  return readFile2(mergedPath);
13590
13835
  }
13591
- function encodeWhileCapturing(input, totalFrames) {
13836
+ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13592
13837
  const engineCfg = resolveEngineConfig(input);
13838
+ const softwareEncoderThreads = captureBudget ? overlapEncoderThreads(captureBudget.workerCount, captureBudget.cpuCount) : void 0;
13593
13839
  const stop = new AbortController();
13594
13840
  const signal = input.abortSignal ? AbortSignal.any([input.abortSignal, stop.signal]) : stop.signal;
13595
13841
  const landed = /* @__PURE__ */ new Map();
@@ -13604,7 +13850,10 @@ function encodeWhileCapturing(input, totalFrames) {
13604
13850
  let reportFed = null;
13605
13851
  const encoder = spawnStreamingEncoder4(
13606
13852
  input.videoOnlyPath,
13607
- { ...videoEncoderOptions(input, engineCfg), imageFormat: "jpeg" },
13853
+ {
13854
+ ...videoEncoderOptions(input, engineCfg, softwareEncoderThreads),
13855
+ imageFormat: "jpeg"
13856
+ },
13608
13857
  signal,
13609
13858
  engineCfg
13610
13859
  );
@@ -13935,7 +14184,7 @@ function sampleDirectoryBytes(dir) {
13935
14184
  for (const name of entries) {
13936
14185
  const full = join32(current, name);
13937
14186
  try {
13938
- const st = statSync10(full);
14187
+ const st = statSync11(full);
13939
14188
  if (st.isDirectory()) {
13940
14189
  stack.push(full);
13941
14190
  } else if (st.isFile()) {
@@ -14090,7 +14339,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14090
14339
  let rangeStart = null;
14091
14340
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14092
14341
  const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14093
- const missing = !existsSync21(framePath) || statSync10(framePath).size <= 8;
14342
+ const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14094
14343
  if (missing && rangeStart === null) {
14095
14344
  rangeStart = frameIndex;
14096
14345
  } else if (!missing && rangeStart !== null) {
@@ -15385,9 +15634,10 @@ async function executeRenderPipeline(input) {
15385
15634
  nativeHdrVideoCount: nativeHdrVideoIds.size,
15386
15635
  nativeHdrImageCount: nativeHdrImageIds.size
15387
15636
  });
15388
- updateJobStatus(job, "preprocessing", "Processing audio tracks", 20, onProgress, {
15637
+ updateJobStatus(job, "preprocessing", AUDIO_STAGE, 20, onProgress, {
15389
15638
  code: "process_audio"
15390
15639
  });
15640
+ const audioWait = audioWaitReporter(job, onProgress);
15391
15641
  const audioStage = observeRenderStage(
15392
15642
  observability,
15393
15643
  "audio_process",
@@ -15406,7 +15656,8 @@ async function executeRenderPipeline(input) {
15406
15656
  abortSignal: executionSignal,
15407
15657
  assertNotAborted,
15408
15658
  log,
15409
- keepDeliverySource: true
15659
+ keepDeliverySource: true,
15660
+ onFfmpegProgress: audioWait.progressed
15410
15661
  })
15411
15662
  );
15412
15663
  pendingAudio = audioStage.catch(() => void 0);
@@ -15425,7 +15676,8 @@ async function executeRenderPipeline(input) {
15425
15676
  port: 0,
15426
15677
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15427
15678
  fps: job.config.fps,
15428
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
15679
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
15680
+ includeOutsideScripts: job.config.includeOutsideScripts
15429
15681
  });
15430
15682
  assertNotAborted();
15431
15683
  observability.stageEnd("file_server", fileServerStart);
@@ -16216,7 +16468,7 @@ async function executeRenderPipeline(input) {
16216
16468
  }
16217
16469
  const effectiveQuality = job.config.crf ?? preset.quality;
16218
16470
  const effectiveBitrate = job.config.crf != null ? void 0 : job.config.videoBitrate;
16219
- const audioResult = await audioStage;
16471
+ const audioResult = await audioWait.wait(audioStage);
16220
16472
  const { audioOutputPath, deliverySourcePath, hasAudio } = audioResult;
16221
16473
  perfStages.audioProcessMs = audioResult.audioProcessMs;
16222
16474
  recordLimiterAttenuation(job, audioResult.audioLoweredDb);
@@ -16714,7 +16966,10 @@ async function executeRenderPipeline(input) {
16714
16966
  assertNotAborted,
16715
16967
  onProgress
16716
16968
  };
16717
- const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames) : null;
16969
+ const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames, {
16970
+ workerCount: capturePlan.workerCount,
16971
+ cpuCount: workerSizing.cpuCount
16972
+ }) : null;
16718
16973
  const captureFrameStart = Date.now();
16719
16974
  const invokeDiskCapture = (diskPlan) => observeRenderStage(
16720
16975
  observability,
@@ -17775,8 +18030,10 @@ function buildSyntheticRenderJob(input) {
17775
18030
  producerConfig: input.producerConfig,
17776
18031
  variables: input.variables,
17777
18032
  strictVariables: input.strictVariables,
18033
+ expectedOutputDimensions: input.expectedOutputDimensions,
17778
18034
  pageMotionBlur: input.pageMotionBlur,
17779
- allowOutsideProjectAssets: input.allowOutsideProjectAssets
18035
+ allowOutsideProjectAssets: input.allowOutsideProjectAssets,
18036
+ includeOutsideScripts: input.includeOutsideScripts
17780
18037
  };
17781
18038
  return createRenderJob(renderConfig);
17782
18039
  }
@@ -19253,8 +19510,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19253
19510
  producerConfig: cfg,
19254
19511
  variables: config.variables,
19255
19512
  strictVariables: config.strictVariables,
19513
+ expectedOutputDimensions: config.expectedOutputDimensions,
19256
19514
  pageMotionBlur: config.pageMotionBlur,
19257
- allowOutsideProjectAssets: options.allowOutsideProjectAssets === true
19515
+ allowOutsideProjectAssets: options.allowOutsideProjectAssets === true,
19516
+ includeOutsideScripts: options.includeOutsideScripts === true
19258
19517
  });
19259
19518
  const entryFile = config.entryFile ?? "index.html";
19260
19519
  const htmlPath = join41(projectDir, entryFile);
@@ -19275,7 +19534,9 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19275
19534
  if (rel === "") return true;
19276
19535
  if (leavesRoot(rel)) return false;
19277
19536
  if (job.config.allowOutsideProjectAssets) {
19278
- if (refusesOutsideLink(projectDir, src, (line) => log.warn(`[Plan] ${line}`))) return false;
19537
+ const warn = (line) => log.warn(`[Plan] ${line}`);
19538
+ const policy = { includeScripts: job.config.includeOutsideScripts };
19539
+ if (refusesOutsideLink(projectDir, src, warn, policy)) return false;
19279
19540
  } else if (!isSafePath2(projectDir, src)) return false;
19280
19541
  const firstSegment = rel.split(sep4, 1)[0];
19281
19542
  return firstSegment === void 0 || !PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(firstSegment);
@@ -19720,6 +19981,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
19720
19981
  format: config.format,
19721
19982
  ffmpegVersion,
19722
19983
  producerVersion,
19984
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked },
19723
19985
  ...job.strictVariablesChecked === void 0 ? {} : { strictVariablesChecked: job.strictVariablesChecked }
19724
19986
  };
19725
19987
  }
@@ -19738,6 +20000,7 @@ async function plan(projectDir, config, planDir, options = {}) {
19738
20000
  format: executionPlan.format,
19739
20001
  ffmpegVersion: executionPlan.ffmpegVersion,
19740
20002
  producerVersion: executionPlan.producerVersion,
20003
+ ...executionPlan.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: executionPlan.outputDimensionsChecked },
19741
20004
  ...executionPlan.strictVariablesChecked === void 0 ? {} : { strictVariablesChecked: executionPlan.strictVariablesChecked }
19742
20005
  };
19743
20006
  }
@@ -19777,7 +20040,7 @@ import {
19777
20040
  readFileSync as readFileSync13,
19778
20041
  readdirSync as readdirSync10,
19779
20042
  rmSync as rmSync16,
19780
- statSync as statSync12,
20043
+ statSync as statSync13,
19781
20044
  writeFileSync as writeFileSync12
19782
20045
  } from "node:fs";
19783
20046
  import { tmpdir as tmpdir3 } from "node:os";
@@ -19796,7 +20059,7 @@ import {
19796
20059
  linkSync as linkSync2,
19797
20060
  mkdirSync as mkdirSync17,
19798
20061
  rmSync as rmSync15,
19799
- statSync as statSync11,
20062
+ statSync as statSync12,
19800
20063
  writeFileSync as writeFileSync11
19801
20064
  } from "node:fs";
19802
20065
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
@@ -19866,7 +20129,7 @@ var LocalPlanV2ArtifactPublisher = class {
19866
20129
  }
19867
20130
  async putBlob(blob) {
19868
20131
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
19869
- const sourceSize = statSync11(blob.sourcePath).size;
20132
+ const sourceSize = statSync12(blob.sourcePath).size;
19870
20133
  if (sourceSize !== blob.sizeBytes) {
19871
20134
  throw new PlanV2IntegrityError(
19872
20135
  `published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`
@@ -20180,7 +20443,7 @@ function publishBlobFor(absolutePath, digests) {
20180
20443
  return {
20181
20444
  sourcePath: absolutePath,
20182
20445
  sha256: planFileSha256(absolutePath, digests),
20183
- sizeBytes: statSync12(absolutePath).size
20446
+ sizeBytes: statSync13(absolutePath).size
20184
20447
  };
20185
20448
  }
20186
20449
  async function putBlobs(publisher, blobs) {
@@ -20359,7 +20622,10 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
20359
20622
  sliceChunkAudio: true,
20360
20623
  deferAudio: options.deferAudio
20361
20624
  });
20362
- options.onPlanned?.({ strictVariablesChecked: planned.strictVariablesChecked });
20625
+ options.onPlanned?.({
20626
+ strictVariablesChecked: planned.strictVariablesChecked,
20627
+ outputDimensionsChecked: planned.outputDimensionsChecked
20628
+ });
20363
20629
  return await publishExecutionPlan(stagingRoot, publisher, { digests, log: config.logger });
20364
20630
  } catch (error) {
20365
20631
  try {
@@ -20548,7 +20814,7 @@ function verifyBlob(planV2Dir, artifact) {
20548
20814
  if (!existsSync28(sourcePath)) {
20549
20815
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
20550
20816
  }
20551
- const stats = statSync12(sourcePath);
20817
+ const stats = statSync13(sourcePath);
20552
20818
  if (!stats.isFile() || stats.size !== artifact.sizeBytes) {
20553
20819
  throw new PlanV2IntegrityError(`artifact size mismatch for ${artifact.path}`);
20554
20820
  }
@@ -20641,7 +20907,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
20641
20907
  for (const artifact of required) {
20642
20908
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
20643
20909
  const path = join44(planDir, ...artifact.path.split("/"));
20644
- if (!existsSync28(path) || statSync12(path).size !== artifact.sizeBytes) {
20910
+ if (!existsSync28(path) || statSync13(path).size !== artifact.sizeBytes) {
20645
20911
  throw new PlanV2IntegrityError(
20646
20912
  `materialized artifact missing or truncated: ${artifact.path}`
20647
20913
  );
@@ -21182,7 +21448,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21182
21448
  const captureSession = session;
21183
21449
  session = null;
21184
21450
  verifyStarted = Date.now();
21185
- overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount2()) ? encodeWhileCapturing(encodeInput, framesInChunk) : null;
21451
+ overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount2()) ? encodeWhileCapturing(encodeInput, framesInChunk, {
21452
+ workerCount: chunkWorkerCount,
21453
+ cpuCount: usableCpuCount2()
21454
+ }) : null;
21186
21455
  await observeRenderStage(
21187
21456
  new RenderObservabilityRecorder({ pipelineStartMs: start, log }),
21188
21457
  "capture_chunk",
@@ -21387,7 +21656,11 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
21387
21656
  projectDir,
21388
21657
  { ...config, rejectOnSystemFonts: false, failClosedFontFetch: false },
21389
21658
  planDir,
21390
- { chunksCarryAudio: true, allowOutsideProjectAssets: options.allowOutsideProjectAssets }
21659
+ {
21660
+ chunksCarryAudio: true,
21661
+ allowOutsideProjectAssets: options.allowOutsideProjectAssets,
21662
+ includeOutsideScripts: options.includeOutsideScripts
21663
+ }
21391
21664
  );
21392
21665
  const { startFrame, endFrame } = spanFrameRange(
21393
21666
  span.startSeconds,
@@ -21436,7 +21709,9 @@ var SAFE_RENDER_ERROR_CODES = /* @__PURE__ */ new Set([
21436
21709
  "RENDER_TOO_SLOW",
21437
21710
  "RENDER_STAGE_STALLED",
21438
21711
  "PAGE_NEVER_READY",
21439
- "VARIABLES_INVALID"
21712
+ "VARIABLES_INVALID",
21713
+ "OUTPUT_DIMENSIONS_MISMATCH",
21714
+ "COMPOSITION_TOO_LARGE"
21440
21715
  ]);
21441
21716
  function extractSafeRenderErrorCode(error) {
21442
21717
  if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
@@ -21496,6 +21771,12 @@ function validateDistributedRenderConfig(config) {
21496
21771
  `must be one of ${DISTRIBUTED_FPS2.join(", ")}; got ${String(config.fps)}`
21497
21772
  );
21498
21773
  }
21774
+ if (config.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(config.expectedOutputDimensions)) {
21775
+ throw new InvalidConfigError(
21776
+ "config.expectedOutputDimensions",
21777
+ "must contain positive integer width and height"
21778
+ );
21779
+ }
21499
21780
  validateIntDimension("config.width", config.width);
21500
21781
  validateIntDimension("config.height", config.height);
21501
21782
  if (config.pageMotionBlur !== void 0 && config.pageMotionBlur !== "off") {
@@ -21849,6 +22130,11 @@ function assertRequestOptionScalars(options) {
21849
22130
  }
21850
22131
  function assertRequestOptionObjects(options) {
21851
22132
  validateEngineConfigSnapshot2(options.engineConfig);
22133
+ if (options.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(options.expectedOutputDimensions)) {
22134
+ throw new Error(
22135
+ "Render request expectedOutputDimensions must contain positive integer width and height"
22136
+ );
22137
+ }
21852
22138
  if (options.variables !== void 0 && !isPlainObject(options.variables)) {
21853
22139
  throw new Error("Render request variables must be a JSON object");
21854
22140
  }
@@ -21914,7 +22200,8 @@ function renderConfigFromRequest(request, runtime = {}) {
21914
22200
  ...options,
21915
22201
  producerConfig: engineConfig,
21916
22202
  logger: runtime.logger,
21917
- allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true
22203
+ allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true,
22204
+ includeOutsideScripts: runtime.includeOutsideScripts === true
21918
22205
  };
21919
22206
  }
21920
22207
  function distributedFps(fps) {
@@ -21969,7 +22256,8 @@ function distributedConfigFromRequest(request, runtime = {}) {
21969
22256
  abortSignal: runtime.abortSignal,
21970
22257
  planDirSizeLimitBytes: distributed.planDirSizeLimitBytes,
21971
22258
  variables: options.variables,
21972
- strictVariables: options.strictVariables
22259
+ strictVariables: options.strictVariables,
22260
+ expectedOutputDimensions: options.expectedOutputDimensions
21973
22261
  };
21974
22262
  }
21975
22263
  function optionalProperty(key, value) {
@@ -22011,7 +22299,8 @@ function renderRequestFromDistributedConfig(input) {
22011
22299
  ...optionalProperty("strictness", config.strictness),
22012
22300
  ...optionalProperty("entryFile", config.entryFile),
22013
22301
  ...optionalProperty("variables", config.variables),
22014
- ...optionalProperty("strictVariables", config.strictVariables)
22302
+ ...optionalProperty("strictVariables", config.strictVariables),
22303
+ ...optionalProperty("expectedOutputDimensions", config.expectedOutputDimensions)
22015
22304
  };
22016
22305
  return createRenderRequest({
22017
22306
  projectDir: input.projectDir,
@@ -22048,13 +22337,13 @@ import {
22048
22337
  import {
22049
22338
  existsSync as existsSync32,
22050
22339
  mkdirSync as mkdirSync21,
22051
- statSync as statSync14,
22340
+ statSync as statSync15,
22052
22341
  mkdtempSync as mkdtempSync2,
22053
22342
  writeFileSync as writeFileSync14,
22054
22343
  rmSync as rmSync19,
22055
22344
  createReadStream as createReadStream5
22056
22345
  } from "node:fs";
22057
- import { resolve as resolve12, dirname as dirname20, join as join49 } from "node:path";
22346
+ import { resolve as resolve12, dirname as dirname21, join as join49 } from "node:path";
22058
22347
  import { tmpdir as tmpdir5 } from "node:os";
22059
22348
  import { parseArgs } from "node:util";
22060
22349
  import { isIP } from "node:net";
@@ -22073,14 +22362,15 @@ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
22073
22362
  import {
22074
22363
  existsSync as existsSync30,
22075
22364
  readFileSync as readFileSync16,
22076
- statSync as statSync13,
22365
+ statSync as statSync14,
22077
22366
  openSync as openSync7,
22078
22367
  fstatSync as fstatSync3,
22079
22368
  closeSync as closeSync7,
22080
22369
  constants as constants3
22081
22370
  } from "node:fs";
22082
- import { resolve as resolve11, join as join47, relative as relative8, isAbsolute as isAbsolute5, sep as sep6 } from "node:path";
22083
- import { lintHyperframeHtml } from "@hyperframes/lint";
22371
+ import { resolve as resolve11, join as join47, relative as relative8, isAbsolute as isAbsolute5, sep as sep6, dirname as dirname19 } from "node:path";
22372
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
22373
+ import { Worker as Worker2 } from "node:worker_threads";
22084
22374
  function isStringRecord(value) {
22085
22375
  if (!value || typeof value !== "object" || Array.isArray(value)) {
22086
22376
  return false;
@@ -22113,7 +22403,7 @@ function readEntryHtml(filePath) {
22113
22403
  } catch (error) {
22114
22404
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
22115
22405
  return null;
22116
- if (!statSync13(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22406
+ if (!statSync14(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22117
22407
  throw error;
22118
22408
  }
22119
22409
  try {
@@ -22129,7 +22419,7 @@ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
22129
22419
  }
22130
22420
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
22131
22421
  const absProjectDir = resolve11(projectDir);
22132
- if (!existsSync30(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
22422
+ if (!existsSync30(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22133
22423
  return { error: `Project directory not found: ${absProjectDir}` };
22134
22424
  }
22135
22425
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -22186,17 +22476,111 @@ function prepareHyperframeLintBody(body, isAllowedEntry) {
22186
22476
  }
22187
22477
  return { error: "Missing lint source: provide projectDir, files, or html" };
22188
22478
  }
22189
- async function runHyperframeLint(prepared) {
22190
- return lintHyperframeHtml(prepared.html, {
22191
- filePath: prepared.entryFile,
22192
- compSrcPath: prepared.entryFile
22479
+ var LINT_HEAP_MB = 512;
22480
+ var LINT_TIMEOUT_MS = 15e3;
22481
+ var LINT_MAX_WORKERS = 2;
22482
+ var waiting = [];
22483
+ var running = 0;
22484
+ function takeLintSlot(limit, waitMs) {
22485
+ if (running < limit) {
22486
+ running++;
22487
+ return Promise.resolve(true);
22488
+ }
22489
+ return new Promise((resolve13) => {
22490
+ const entry = () => {
22491
+ clearTimeout(timer);
22492
+ running++;
22493
+ resolve13(true);
22494
+ };
22495
+ const timer = setTimeout(
22496
+ () => {
22497
+ waiting.splice(waiting.indexOf(entry), 1);
22498
+ resolve13(false);
22499
+ },
22500
+ Math.max(0, waitMs)
22501
+ );
22502
+ waiting.push(entry);
22503
+ });
22504
+ }
22505
+ function freeLintSlot() {
22506
+ running--;
22507
+ waiting.shift()?.();
22508
+ }
22509
+ function resolveLintWorkerEntry() {
22510
+ const here = dirname19(fileURLToPath6(import.meta.url));
22511
+ for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
22512
+ const candidate = join47(here, name);
22513
+ if (existsSync30(candidate)) return candidate;
22514
+ }
22515
+ return void 0;
22516
+ }
22517
+ function abortedLintResult(filePath, afterMs) {
22518
+ return {
22519
+ ok: false,
22520
+ errorCount: 1,
22521
+ warningCount: 0,
22522
+ infoCount: 0,
22523
+ findings: [
22524
+ {
22525
+ code: "lint_aborted",
22526
+ severity: "error",
22527
+ 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.",
22528
+ file: filePath
22529
+ }
22530
+ ],
22531
+ timings: { totalMs: afterMs, groupMs: {}, slowestRule: "", slowestRuleMs: 0 }
22532
+ };
22533
+ }
22534
+ async function runHyperframeLint(prepared, options = {}) {
22535
+ const began = performance.now();
22536
+ const aborted = () => abortedLintResult(prepared.entryFile, Math.round(performance.now() - began));
22537
+ const entry = options.workerEntry ?? resolveLintWorkerEntry();
22538
+ if (!entry) return aborted();
22539
+ const timeoutMs = options.timeoutMs ?? LINT_TIMEOUT_MS;
22540
+ const gotSlot = await takeLintSlot(options.maxWorkers ?? LINT_MAX_WORKERS, timeoutMs);
22541
+ if (!gotSlot) return aborted();
22542
+ const remainingMs = Math.max(0, timeoutMs - (performance.now() - began));
22543
+ return new Promise((resolvePromise, reject) => {
22544
+ let worker;
22545
+ try {
22546
+ worker = new Worker2(entry, {
22547
+ workerData: {
22548
+ html: prepared.html,
22549
+ opts: { filePath: prepared.entryFile, compSrcPath: prepared.entryFile }
22550
+ },
22551
+ resourceLimits: { maxOldGenerationSizeMb: options.heapMb ?? LINT_HEAP_MB },
22552
+ stdout: false,
22553
+ stderr: false
22554
+ });
22555
+ } catch {
22556
+ freeLintSlot();
22557
+ resolvePromise(aborted());
22558
+ return;
22559
+ }
22560
+ let settled = false;
22561
+ const settle = (finish) => {
22562
+ if (settled) return;
22563
+ settled = true;
22564
+ clearTimeout(timer);
22565
+ void worker.terminate().finally(freeLintSlot);
22566
+ finish();
22567
+ };
22568
+ const timer = setTimeout(() => settle(() => resolvePromise(aborted())), remainingMs);
22569
+ worker.on(
22570
+ "message",
22571
+ (message) => settle(
22572
+ () => message.result ? resolvePromise(message.result) : reject(new Error(message.error))
22573
+ )
22574
+ );
22575
+ worker.on("error", () => settle(() => resolvePromise(aborted())));
22576
+ worker.on("exit", () => settle(() => resolvePromise(aborted())));
22193
22577
  });
22194
22578
  }
22195
22579
 
22196
22580
  // src/services/healthWorker.ts
22197
- import { Worker as Worker2 } from "node:worker_threads";
22198
- import { fileURLToPath as fileURLToPath6 } from "node:url";
22199
- import { dirname as dirname19, join as join48 } from "node:path";
22581
+ import { Worker as Worker3 } from "node:worker_threads";
22582
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
22583
+ import { dirname as dirname20, join as join48 } from "node:path";
22200
22584
  import { existsSync as existsSync31 } from "node:fs";
22201
22585
  var DEFAULT_HEALTH_PORT = 9848;
22202
22586
  async function startHealthWorker(options = {}) {
@@ -22208,7 +22592,7 @@ async function startHealthWorker(options = {}) {
22208
22592
  "[healthWorker] could not resolve worker entry. Pass options.workerEntry or ensure healthWorkerThread.{js,ts} is co-located."
22209
22593
  );
22210
22594
  }
22211
- const worker = new Worker2(entry, {
22595
+ const worker = new Worker3(entry, {
22212
22596
  workerData: { port },
22213
22597
  // Keep stdio inherited so the worker's console logs land in the pod logs
22214
22598
  // alongside the main thread's.
@@ -22271,7 +22655,7 @@ function defaultLogger2() {
22271
22655
  };
22272
22656
  }
22273
22657
  function resolveWorkerEntry2() {
22274
- const here = dirname19(fileURLToPath6(import.meta.url));
22658
+ const here = dirname20(fileURLToPath7(import.meta.url));
22275
22659
  const candidates = [join48(here, "healthWorkerThread.js"), join48(here, "healthWorkerThread.ts")];
22276
22660
  for (const candidate of candidates) {
22277
22661
  if (existsSync31(candidate)) return candidate;
@@ -22384,6 +22768,7 @@ function parseRenderOptions(body) {
22384
22768
  outputDynamicRange,
22385
22769
  variables,
22386
22770
  strictVariables,
22771
+ expectedOutputDimensions: isExpectedOutputDimensions(body.expectedOutputDimensions) ? body.expectedOutputDimensions : void 0,
22387
22772
  outputResolution,
22388
22773
  outputResolutionAspectAgnostic,
22389
22774
  videoFrameFormat
@@ -22423,6 +22808,7 @@ function buildRenderJobConfig(input, outputPath, log) {
22423
22808
  entryFile: input.entryFile,
22424
22809
  variables: input.variables,
22425
22810
  strictVariables: input.strictVariables,
22811
+ expectedOutputDimensions: input.expectedOutputDimensions,
22426
22812
  outputResolution: input.outputResolution,
22427
22813
  outputResolutionAspectAgnostic: input.outputResolutionAspectAgnostic,
22428
22814
  videoFrameFormat: input.videoFrameFormat,
@@ -22441,7 +22827,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
22441
22827
  throw new Error("outputPath must be inside the renders directory");
22442
22828
  }
22443
22829
  }
22444
- const outputDir = dirname20(absoluteOutputPath);
22830
+ const outputDir = dirname21(absoluteOutputPath);
22445
22831
  if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
22446
22832
  return { input, cleanupProjectDir, absoluteOutputPath };
22447
22833
  }
@@ -22467,6 +22853,9 @@ function validateRenderOverrides(body) {
22467
22853
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
22468
22854
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
22469
22855
  }
22856
+ if (body.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(body.expectedOutputDimensions)) {
22857
+ return "expectedOutputDimensions must contain positive integer width and height";
22858
+ }
22470
22859
  if (body.strictVariables !== void 0 && typeof body.strictVariables !== "boolean") {
22471
22860
  return "strictVariables must be a boolean";
22472
22861
  }
@@ -22517,7 +22906,7 @@ function prepareProjectDirectory(projectDir, options, policy) {
22517
22906
  if (!candidate) return null;
22518
22907
  const absProjectDir = policy ? resolve12(policy.projectsDir, candidate) : resolve12(candidate);
22519
22908
  const shown = policy ? candidate : absProjectDir;
22520
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22909
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync15(absProjectDir).isDirectory()) {
22521
22910
  return { error: `Project directory not found: ${shown}` };
22522
22911
  }
22523
22912
  const entry = options.entryFile || "index.html";
@@ -22620,7 +23009,7 @@ function publicPerfSummary(job) {
22620
23009
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
22621
23010
  }
22622
23011
  function outputFileSize(path) {
22623
- return existsSync32(path) ? statSync14(path).size : 0;
23012
+ return existsSync32(path) ? statSync15(path).size : 0;
22624
23013
  }
22625
23014
  function createBlockingProgressReporter(log, requestId) {
22626
23015
  let lastLoggedPct = -10;
@@ -22823,7 +23212,8 @@ function createRenderHandlers(options = {}) {
22823
23212
  outcome: job.outcome ?? "completed",
22824
23213
  warnings: job.warnings,
22825
23214
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
22826
- ...strictVariablesResult(job)
23215
+ ...strictVariablesResult(job),
23216
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
22827
23217
  });
22828
23218
  } catch (error) {
22829
23219
  const durationMs = Date.now() - t0;
@@ -22920,7 +23310,8 @@ function createRenderHandlers(options = {}) {
22920
23310
  warnings: job.warnings,
22921
23311
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
22922
23312
  producerVersion: readProducerVersion(),
22923
- ...strictVariablesResult(job)
23313
+ ...strictVariablesResult(job),
23314
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
22924
23315
  })
22925
23316
  });
22926
23317
  } catch (error) {
@@ -22949,7 +23340,7 @@ function createRenderHandlers(options = {}) {
22949
23340
  store.delete(token);
22950
23341
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
22951
23342
  }
22952
- const stats = statSync14(artifact.path);
23343
+ const stats = statSync15(artifact.path);
22953
23344
  return new Response(createReadStream5(artifact.path), {
22954
23345
  headers: {
22955
23346
  "content-type": "video/mp4",
@@ -23150,10 +23541,10 @@ import {
23150
23541
  readFileSync as readFileSync17,
23151
23542
  readdirSync as readdirSync12,
23152
23543
  rmSync as rmSync20,
23153
- statSync as statSync15,
23544
+ statSync as statSync16,
23154
23545
  writeFileSync as writeFileSync15
23155
23546
  } from "node:fs";
23156
- import { basename as basename8, dirname as dirname21, join as join50 } from "node:path";
23547
+ import { basename as basename8, dirname as dirname22, join as join50 } from "node:path";
23157
23548
  import {
23158
23549
  appendRateCapArgs as appendRateCapArgs2,
23159
23550
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
@@ -23195,15 +23586,15 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23195
23586
  outputPath,
23196
23587
  durationMs: Date.now() - start,
23197
23588
  framesEncoded: plan2.totalFrames,
23198
- fileSize: statSync15(outputPath).size
23589
+ fileSize: statSync16(outputPath).size
23199
23590
  };
23200
23591
  }
23201
23592
  const format = plan2.dimensions.format;
23202
23593
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
23203
- if (!existsSync33(dirname21(outputPath))) {
23204
- mkdirSync22(dirname21(outputPath), { recursive: true });
23594
+ if (!existsSync33(dirname22(outputPath))) {
23595
+ mkdirSync22(dirname22(outputPath), { recursive: true });
23205
23596
  }
23206
- const workDir = createStagingDir7(dirname21(outputPath), `${basename8(outputPath)}.assemble-work-`);
23597
+ const workDir = createStagingDir7(dirname22(outputPath), `${basename8(outputPath)}.assemble-work-`);
23207
23598
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
23208
23599
  const stageMs = {};
23209
23600
  const ctx = {
@@ -23242,7 +23633,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23242
23633
  });
23243
23634
  }
23244
23635
  }
23245
- const fileSize = existsSync33(outputPath) ? statSync15(outputPath).size : 0;
23636
+ const fileSize = existsSync33(outputPath) ? statSync16(outputPath).size : 0;
23246
23637
  return {
23247
23638
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
23248
23639
  outputPath,
@@ -23440,7 +23831,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23440
23831
  mkdirSync22(outputPath, { recursive: true });
23441
23832
  let globalIdx = 0;
23442
23833
  for (const chunkDir of chunkPaths) {
23443
- if (!statSync15(chunkDir).isDirectory()) {
23834
+ if (!statSync16(chunkDir).isDirectory()) {
23444
23835
  throw new Error(
23445
23836
  `[assemble] png-sequence chunk must be a directory: ${chunkDir} (got a file)`
23446
23837
  );
@@ -23467,7 +23858,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23467
23858
  let fileSize = 0;
23468
23859
  for (const name of readdirSync12(outputPath)) {
23469
23860
  try {
23470
- fileSize += statSync15(join50(outputPath, name)).size;
23861
+ fileSize += statSync16(join50(outputPath, name)).size;
23471
23862
  } catch {
23472
23863
  }
23473
23864
  }