@hyperframes/producer 0.9.59 → 0.9.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,13 +7,13 @@ import {
7
7
  } from "@hyperframes/engine";
8
8
 
9
9
  // src/services/renderOrchestrator.ts
10
- import { audioFailureDiagnostics as audioFailureDiagnostics2 } from "@hyperframes/engine";
10
+ import { audioFailureDiagnostics as audioFailureDiagnostics2, usableCpuCount as usableCpuCount2 } from "@hyperframes/engine";
11
11
  import {
12
12
  existsSync as existsSync21,
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 },
@@ -381,7 +385,10 @@ import { Readable } from "node:stream";
381
385
  import { join as join2, extname, resolve as resolve2, sep as sep2 } from "node:path";
382
386
  import { injectScriptsAtHeadStart, injectScriptsIntoHtml } from "@hyperframes/core/compiler";
383
387
  import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
384
- import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-mark";
388
+ import {
389
+ PREVIEW_FOR_ANOTHER_SITE_META,
390
+ serviceWorkerScriptFetch
391
+ } from "@hyperframes/core/studio-preview-mark";
385
392
  import { fpsToNumber, terminalText as terminalText2 } from "@hyperframes/core";
386
393
  import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
387
394
  import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
@@ -529,6 +536,7 @@ import { isSafePath } from "@hyperframes/core/safe-path";
529
536
  import {
530
537
  isCopiedOutsideFileType,
531
538
  isPrivateOutsideFile,
539
+ isUploadedOutsideFileType,
532
540
  leftOutWarning,
533
541
  linksOutside
534
542
  } from "@hyperframes/studio-server/outside-file";
@@ -550,15 +558,17 @@ function isPathInside(childPath, parentPath, options = {}) {
550
558
  function escapesAssetRoot(path, assetRoot) {
551
559
  return assetRoot !== void 0 && !isSafePath(assetRoot, path);
552
560
  }
553
- function outsideAssetRefusal(projectDir, path) {
561
+ function outsideAssetRefusal(projectDir, path, policy = {}) {
554
562
  if (!linksOutside(projectDir, path)) return null;
555
563
  if (isPrivateOutsideFile(projectDir, path)) return "blocklisted";
556
564
  const folder = statSync(path, { throwIfNoEntry: false })?.isDirectory();
557
- return folder || isCopiedOutsideFileType(path) ? null : "file_type";
565
+ if (folder || isUploadedOutsideFileType(path)) return null;
566
+ if (!isCopiedOutsideFileType(path)) return "file_type";
567
+ return policy.includeScripts ? null : "script";
558
568
  }
559
569
  var leftOutOfRender = (file, reference, reason) => leftOutWarning(file, reference, reason, "render");
560
- function refusesOutsideLink(projectDir, path, warn) {
561
- const refusal = outsideAssetRefusal(projectDir, path);
570
+ function refusesOutsideLink(projectDir, path, warn, policy = {}) {
571
+ const refusal = outsideAssetRefusal(projectDir, path, policy);
562
572
  if (!refusal) return false;
563
573
  const file = nodeRelative(projectDir, path).split(sep).join("/");
564
574
  warn(leftOutOfRender(file, realFilePath(path), refusal));
@@ -1141,7 +1151,8 @@ function createFileServer(options) {
1141
1151
  compiledDir,
1142
1152
  port = 0,
1143
1153
  stripEmbeddedRuntime = true,
1144
- allowOutsideProjectAssets = false
1154
+ allowOutsideProjectAssets = false,
1155
+ includeOutsideScripts = false
1145
1156
  } = options;
1146
1157
  const preHeadScripts = [
1147
1158
  HF_EARLY_STUB,
@@ -1152,12 +1163,19 @@ function createFileServer(options) {
1152
1163
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
1153
1164
  const app = new Hono();
1154
1165
  const warnLeftOut = (line) => console.warn(`[FileServer] ${terminalText2(line)}`);
1166
+ const outsidePolicy = { includeScripts: includeOutsideScripts };
1155
1167
  let listeningPort = -1;
1156
1168
  app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
1157
1169
  await next();
1158
1170
  c.res.headers.set("X-Content-Type-Options", "nosniff");
1159
1171
  });
1160
1172
  answerOwnLoopbackHostOnly(app, () => listeningPort);
1173
+ app.use(async function refuseServiceWorkerScripts(c, next) {
1174
+ const serviceWorker = c.req.header("service-worker");
1175
+ if (!serviceWorkerScriptFetch({ serviceWorker, fetchDest: c.req.header("sec-fetch-dest") }))
1176
+ return next();
1177
+ return c.text("Forbidden", 403);
1178
+ });
1161
1179
  app.get("/*", async (c) => {
1162
1180
  let requestPath = c.req.path;
1163
1181
  if (requestPath === "/") requestPath = "/index.html";
@@ -1169,7 +1187,7 @@ function createFileServer(options) {
1169
1187
  if (!isPathInside2(candidate, root, { resolveSymlinks })) continue;
1170
1188
  if (isPrivateFileUnder(root, candidate, isStudioPrivatePath)) continue;
1171
1189
  const checksLinks = allowOutsideProjectAssets && root !== compiledDir;
1172
- if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut)) continue;
1190
+ if (checksLinks && refusesOutsideLink(root, candidate, warnLeftOut, outsidePolicy)) continue;
1173
1191
  file = openRegularFile(candidate);
1174
1192
  if (file) break;
1175
1193
  }
@@ -2733,9 +2751,10 @@ function frameWeightedAvgMs(perfs, avgOf) {
2733
2751
  function aggregateDedup(perfs) {
2734
2752
  if (perfs.length === 0) return void 0;
2735
2753
  const armed = perfs.some((p) => p.staticDedupArmed);
2736
- const skipReasons = armed ? [] : [
2737
- ...new Set(perfs.map((p) => p.staticDedupSkipReason).filter((r) => !!r))
2738
- ].sort();
2754
+ const distinctUnarmed = (values) => {
2755
+ const distinct = armed ? [] : [...new Set(values.filter((v) => !!v))].sort();
2756
+ return distinct.length > 0 ? distinct.join("|") : void 0;
2757
+ };
2739
2758
  const verificationPerfs = perfs.filter((perf) => perf.staticDedupVerificationOutcome);
2740
2759
  const verificationOutcomes = [
2741
2760
  ...new Set(
@@ -2747,7 +2766,8 @@ function aggregateDedup(perfs) {
2747
2766
  armed,
2748
2767
  predictedFrames: perfs.reduce((sum2, p) => sum2 + (p.staticDedupPredicted ?? 0), 0),
2749
2768
  reusedFrames: perfs.reduce((sum2, p) => sum2 + (p.staticDedupReused ?? 0), 0),
2750
- skipReason: skipReasons.length > 0 ? skipReasons.join("|") : void 0,
2769
+ skipReason: distinctUnarmed(perfs.map((p) => p.staticDedupSkipReason)),
2770
+ ineligibleCause: distinctUnarmed(perfs.map((p) => p.staticDedupIneligibleCause)),
2751
2771
  ...verificationPerfs.length === 0 ? {} : {
2752
2772
  verifiedFrames: verificationPerfs.reduce(
2753
2773
  (sum2, perf) => sum2 + (perf.staticDedupVerified ?? 0),
@@ -6877,6 +6897,22 @@ function countAuthoredTimedClips(html) {
6877
6897
  return document2.querySelectorAll("[data-start]").length;
6878
6898
  }
6879
6899
 
6900
+ // src/services/render/outputDimensions.ts
6901
+ function isExpectedOutputDimensions(value) {
6902
+ 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;
6903
+ }
6904
+ var OutputDimensionsMismatchError = class extends Error {
6905
+ code = "OUTPUT_DIMENSIONS_MISMATCH";
6906
+ constructor() {
6907
+ super("Compiled output dimensions do not match the requested render dimensions.");
6908
+ }
6909
+ };
6910
+ function requireOutputDimensions(expected, width, height) {
6911
+ if (expected !== void 0 && (!isExpectedOutputDimensions(expected) || expected.width !== width || expected.height !== height)) {
6912
+ throw new OutputDimensionsMismatchError();
6913
+ }
6914
+ }
6915
+
6880
6916
  // src/services/render/stages/compileStage.ts
6881
6917
  import { existsSync as existsSync12, writeFileSync as writeFileSync5 } from "node:fs";
6882
6918
  import { join as join20, relative as relative3 } from "node:path";
@@ -6885,6 +6921,61 @@ import { suggestMatchingPreset } from "@hyperframes/core";
6885
6921
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
6886
6922
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
6887
6923
 
6924
+ // src/services/compositionSizeLimit.ts
6925
+ import { statSync as statSync7 } from "node:fs";
6926
+ var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
6927
+ var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
6928
+ var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
6929
+ var MAX_EXPANDED_COMPOSITION_BYTES = 2 * MAX_COMPOSITION_HTML_BYTES;
6930
+ var MAX_COMPOSITION_MOUNTS = 1e4;
6931
+ var CompositionTooLargeError = class extends Error {
6932
+ constructor(message, publicMetadata) {
6933
+ super(message);
6934
+ this.publicMetadata = publicMetadata;
6935
+ this.name = "CompositionTooLargeError";
6936
+ }
6937
+ publicMetadata;
6938
+ code = COMPOSITION_TOO_LARGE;
6939
+ // The producer server reads these off the error for the wire envelope.
6940
+ owner = "user";
6941
+ retryable = false;
6942
+ };
6943
+ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
6944
+ `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.`,
6945
+ { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
6946
+ );
6947
+ var CompositionExpansionBudget = class {
6948
+ bytes = 0;
6949
+ mounts = 0;
6950
+ charge(file, bytes) {
6951
+ this.bytes += bytes;
6952
+ this.mounts += 1;
6953
+ if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
6954
+ return;
6955
+ }
6956
+ throw new CompositionTooLargeError(
6957
+ `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.`,
6958
+ {
6959
+ bytes: this.bytes,
6960
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
6961
+ mounts: this.mounts,
6962
+ exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
6963
+ }
6964
+ );
6965
+ }
6966
+ };
6967
+ function assertCompositionFileSize(path, file) {
6968
+ let bytes;
6969
+ try {
6970
+ const stats = statSync7(path);
6971
+ if (!stats.isFile()) return;
6972
+ bytes = stats.size;
6973
+ } catch {
6974
+ return;
6975
+ }
6976
+ if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
6977
+ }
6978
+
6888
6979
  // src/services/htmlCompiler.ts
6889
6980
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
6890
6981
  import {
@@ -6971,11 +7062,13 @@ import {
6971
7062
  import {
6972
7063
  isUnresolvedAssetPlaceholder,
6973
7064
  namesAnotherNetworkRoot as namesAnotherNetworkRoot2,
7065
+ projectAssetExists,
6974
7066
  readProjectFile,
6975
7067
  readTextFile,
6976
7068
  resolveCompositionSrc
6977
7069
  } from "@hyperframes/parsers/asset-resolution";
6978
7070
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7071
+ import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
6979
7072
 
6980
7073
  // src/services/renderMediaCollector.ts
6981
7074
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7169,7 +7262,7 @@ import {
7169
7262
 
7170
7263
  // src/services/animatedGifPrep.ts
7171
7264
  import { createHash as createHash4 } from "node:crypto";
7172
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7265
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync8 } from "node:fs";
7173
7266
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join16, resolve as resolve5 } from "node:path";
7174
7267
  import { parseHTML as parseHTML3 } from "linkedom";
7175
7268
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7222,12 +7315,13 @@ function resolveLocalImageSourcePath(src, options) {
7222
7315
  isAbsolute2(basePath) ? basePath : resolve5(options.projectDir, projectRelative),
7223
7316
  resolve5(options.downloadDir, normalizedBase)
7224
7317
  ];
7225
- 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));
7318
+ const assetRoot = options.allowOutsideFiles ? void 0 : options.projectDir;
7319
+ 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));
7226
7320
  return candidates.find((candidate) => allowed(candidate) && existsSync9(candidate)) ?? null;
7227
7321
  }
7228
7322
  function isUsableFile(path) {
7229
7323
  try {
7230
- const stat = statSync7(path);
7324
+ const stat = statSync8(path);
7231
7325
  return stat.isFile() && stat.size > 0;
7232
7326
  } catch {
7233
7327
  return false;
@@ -7492,7 +7586,7 @@ import {
7492
7586
  readFileSync as readFileSync7,
7493
7587
  readSync as readSync3,
7494
7588
  rmSync as rmSync10,
7495
- statSync as statSync8,
7589
+ statSync as statSync9,
7496
7590
  writeFileSync as writeFileSync4
7497
7591
  } from "node:fs";
7498
7592
  import { dirname as dirname7, join as join17, resolve as resolve6 } from "node:path";
@@ -7736,7 +7830,7 @@ function resolveImageSource(src, options) {
7736
7830
  }
7737
7831
  function isUsableFile2(path) {
7738
7832
  try {
7739
- return statSync8(path).size > 0;
7833
+ return statSync9(path).size > 0;
7740
7834
  } catch {
7741
7835
  return false;
7742
7836
  }
@@ -8015,7 +8109,7 @@ Check that each file referenced by data-composition-src contains valid HTML with
8015
8109
  };
8016
8110
  function normalizeCompositionSrcs(html, projectDir) {
8017
8111
  return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
8018
- if (!value.includes("%") && !value.startsWith("/")) return whole;
8112
+ if (!value.includes("%") && !/^\.?[\\/]/.test(value)) return whole;
8019
8113
  const file = resolveCompositionSrc(projectDir, value);
8020
8114
  if (file === null) return whole;
8021
8115
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
@@ -8031,68 +8125,94 @@ function resolveCompositionFile(projectDir, src, assetRoot) {
8031
8125
  const file = resolveCompositionPath(projectDir, src, assetRoot);
8032
8126
  return file !== null && COMPOSITION_FILE.test(file) ? file : null;
8033
8127
  }
8128
+ 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";
8129
+ var runsOutsideMarkupUnasked = (projectDir, filePath, assetRoot, outsideFiles) => assetRoot === void 0 && !outsideFiles.includeScripts && linksOutside2(projectDir, filePath);
8130
+ function assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles) {
8131
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8132
+ throw new EmptyCompositionError([{ srcPath, detail: OUTSIDE_COMPOSITION_NEEDS_FLAG }]);
8133
+ }
8134
+ }
8034
8135
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isStudioPrivatePath2);
8035
- function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
8136
+ var mountSrcsUnder = (root) => [...root.querySelectorAll("[data-composition-src]")].map((el) => el.getAttribute("data-composition-src")).filter((srcPath) => !!srcPath && !isUnresolvedAssetPlaceholder(srcPath));
8137
+ function compositionSrcsIn(html) {
8036
8138
  const { document: document2 } = parseHTML5(html);
8037
- const hosts = [...document2.querySelectorAll("[data-composition-src]")];
8038
- const problems = [];
8039
- for (const el of hosts) {
8040
- const srcPath = el.getAttribute("data-composition-src");
8041
- if (!srcPath) continue;
8042
- if (isUnresolvedAssetPlaceholder(srcPath)) continue;
8139
+ const templated = [];
8140
+ const templates = [...document2.querySelectorAll("template")];
8141
+ for (let template = templates.pop(); template; template = templates.pop()) {
8142
+ templated.push(...mountSrcsUnder(template.content));
8143
+ templates.push(...template.content.querySelectorAll("template"));
8144
+ }
8145
+ return { mounts: mountSrcsUnder(document2), templated };
8146
+ }
8147
+ function compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles) {
8148
+ if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8149
+ return "it is outside the project in a private location";
8150
+ }
8151
+ if (runsOutsideMarkupUnasked(projectDir, filePath, assetRoot, outsideFiles)) {
8152
+ return OUTSIDE_COMPOSITION_NEEDS_FLAG;
8153
+ }
8154
+ if (isPrivateCompositionFile(projectDir, filePath)) {
8155
+ return "it is git metadata, an env file or a private tool record";
8156
+ }
8157
+ return COMPOSITION_FILE.test(filePath) ? null : NOT_A_COMPOSITION_FILE;
8158
+ }
8159
+ function readSubCompositionFile(filePath, srcPath) {
8160
+ assertCompositionFileSize(filePath, srcPath);
8161
+ const read = readProjectFile(filePath);
8162
+ if (read.kind === "missing") return { detail: "the file does not exist" };
8163
+ if (read.kind === "folder") return { detail: "it is a folder, not an HTML file" };
8164
+ const validity = checkSubCompositionUsability(read.text, parseSubCompHtmlForValidity);
8165
+ if (!validity.ok)
8166
+ return { detail: validity.detail ?? "the file is empty or could not be parsed" };
8167
+ return { bytes: Buffer.byteLength(read.text), ...compositionSrcsIn(read.text) };
8168
+ }
8169
+ function assertSubCompositionsUsable(html, projectDir, assetRoot, outsideFiles) {
8170
+ const budget = new CompositionExpansionBudget();
8171
+ const files = /* @__PURE__ */ new Map();
8172
+ const problems = /* @__PURE__ */ new Map();
8173
+ const report = (srcPath, detail) => problems.set(`${srcPath}\0${detail}`, { srcPath, detail });
8174
+ const chain = /* @__PURE__ */ new Set();
8175
+ const paths = /* @__PURE__ */ new Map();
8176
+ const resolveMount = (srcPath) => {
8043
8177
  const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
8044
- if (filePath === null) {
8045
- problems.push({ srcPath, detail: "it is outside the project folder" });
8046
- continue;
8047
- }
8048
- if (outsideAssetRefusal(projectDir, filePath) === "blocklisted") {
8049
- problems.push({ srcPath, detail: "it is outside the project in a private location" });
8050
- continue;
8051
- }
8052
- if (isPrivateCompositionFile(projectDir, filePath)) {
8053
- problems.push({
8054
- srcPath,
8055
- detail: "it is git metadata, an env file or a private tool record"
8056
- });
8057
- continue;
8058
- }
8059
- if (!COMPOSITION_FILE.test(filePath)) {
8060
- problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
8061
- continue;
8062
- }
8063
- if (visited.has(filePath)) continue;
8064
- const read = readProjectFile(filePath);
8065
- if (read.kind === "missing") {
8066
- problems.push({ srcPath, detail: "the file does not exist" });
8067
- continue;
8068
- }
8069
- if (read.kind === "folder") {
8070
- problems.push({ srcPath, detail: "it is a folder, not an HTML file" });
8071
- continue;
8072
- }
8073
- const fileHtml = read.text;
8074
- const validity = checkSubCompositionUsability(fileHtml, parseSubCompHtmlForValidity);
8075
- if (!validity.ok) {
8076
- problems.push({
8077
- srcPath,
8078
- detail: validity.detail ?? "the file is empty or could not be parsed"
8079
- });
8080
- continue;
8081
- }
8082
- const nestedVisited = new Set(visited);
8083
- nestedVisited.add(filePath);
8084
- try {
8085
- assertSubCompositionsUsable(fileHtml, projectDir, assetRoot, nestedVisited);
8086
- } catch (err) {
8087
- if (err instanceof EmptyCompositionError) {
8088
- problems.push(...err.problems);
8089
- } else {
8090
- throw err;
8178
+ if (filePath === null) return { detail: "it is outside the project folder" };
8179
+ const detail = compositionPathProblem(projectDir, filePath, assetRoot, outsideFiles);
8180
+ return detail ? { detail } : { filePath };
8181
+ };
8182
+ const walk = (srcPaths, quiet) => {
8183
+ for (const srcPath of srcPaths) {
8184
+ let resolved = paths.get(srcPath);
8185
+ if (!resolved) {
8186
+ resolved = resolveMount(srcPath);
8187
+ paths.set(srcPath, resolved);
8188
+ }
8189
+ if ("detail" in resolved) {
8190
+ if (!quiet) report(srcPath, resolved.detail);
8191
+ continue;
8091
8192
  }
8193
+ const { filePath } = resolved;
8194
+ if (chain.has(filePath)) continue;
8195
+ let file = files.get(filePath);
8196
+ if (!file) {
8197
+ file = readSubCompositionFile(filePath, srcPath);
8198
+ files.set(filePath, file);
8199
+ }
8200
+ if ("detail" in file) {
8201
+ if (!quiet) report(srcPath, file.detail);
8202
+ continue;
8203
+ }
8204
+ budget.charge(srcPath, file.bytes);
8205
+ chain.add(filePath);
8206
+ walk(file.mounts, quiet);
8207
+ walk(file.templated, true);
8208
+ chain.delete(filePath);
8092
8209
  }
8093
- }
8094
- if (problems.length > 0) {
8095
- throw new EmptyCompositionError(problems);
8210
+ };
8211
+ const entry = compositionSrcsIn(html);
8212
+ walk(entry.mounts, false);
8213
+ walk(entry.templated, true);
8214
+ if (problems.size > 0) {
8215
+ throw new EmptyCompositionError([...problems.values()]);
8096
8216
  }
8097
8217
  }
8098
8218
  var COMPILER_MOUNT_BLOCK_START = "/* __HF_COMPILER_MOUNT_START__ */";
@@ -8347,7 +8467,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8347
8467
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
8348
8468
  return { html: compiledHtml, unresolvedCompositions };
8349
8469
  }
8350
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot) {
8470
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8351
8471
  const subCompositions = /* @__PURE__ */ new Map();
8352
8472
  const { document: document2 } = parseHTML5(html);
8353
8473
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -8360,6 +8480,10 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8360
8480
  if (visited.has(filePath)) {
8361
8481
  continue;
8362
8482
  }
8483
+ if (compiledSrcs.has(srcPath)) continue;
8484
+ compiledSrcs.add(srcPath);
8485
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8486
+ assertCompositionFileSize(filePath, srcPath);
8363
8487
  const read = readProjectFile(filePath);
8364
8488
  if (read.kind !== "file") {
8365
8489
  continue;
@@ -8388,7 +8512,9 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8388
8512
  item.nestedVisited,
8389
8513
  urlByAbsentLocalPath,
8390
8514
  probes,
8391
- assetRoot
8515
+ assetRoot,
8516
+ outsideFiles,
8517
+ compiledSrcs
8392
8518
  );
8393
8519
  return {
8394
8520
  srcPath: item.srcPath,
@@ -8524,7 +8650,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8524
8650
  }
8525
8651
  return document2.toString();
8526
8652
  }
8527
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot) {
8653
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
8528
8654
  const { document: document2 } = parseHTML5(html);
8529
8655
  const head = document2.querySelector("head");
8530
8656
  const body = document2.querySelector("body");
@@ -8537,6 +8663,27 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8537
8663
  );
8538
8664
  return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8539
8665
  }
8666
+ const budget = new CompositionExpansionBudget();
8667
+ const readOnce = /* @__PURE__ */ new Map();
8668
+ const readMountHtml = (srcPath) => {
8669
+ const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8670
+ if (filePath) {
8671
+ assertOutsideMarkupAsked(projectDir, filePath, srcPath, assetRoot, outsideFiles);
8672
+ assertCompositionFileSize(filePath, srcPath);
8673
+ }
8674
+ const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8675
+ return read?.kind === "file" ? rewriteUnresolvableGsapToCdn(
8676
+ normalizeCompositionSrcs(read.text, projectDir),
8677
+ projectDir,
8678
+ srcPath
8679
+ ) : null;
8680
+ };
8681
+ const resolveMountHtml = (srcPath) => {
8682
+ const compiled = subCompositions.get(srcPath);
8683
+ if (compiled) return compiled;
8684
+ if (!readOnce.has(srcPath)) readOnce.set(srcPath, readMountHtml(srcPath));
8685
+ return readOnce.get(srcPath) ?? null;
8686
+ };
8540
8687
  const hostIdentityByElement = new ProducerHostIdentityMap(
8541
8688
  document2,
8542
8689
  hosts
@@ -8552,20 +8699,14 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8552
8699
  readVariableDefaults: readDeclaredDefaults,
8553
8700
  parseHostVariables: parseHostVariableValues,
8554
8701
  resolveHtml: (srcPath) => {
8555
- let compHtml = subCompositions.get(srcPath) || null;
8556
- if (!compHtml) {
8557
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
8558
- const read = filePath && !isPrivateCompositionFile(projectDir, filePath) ? readProjectFile(filePath) : null;
8559
- if (read?.kind === "file") {
8560
- compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
8561
- }
8562
- }
8702
+ const compHtml = resolveMountHtml(srcPath);
8703
+ if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
8563
8704
  return compHtml;
8564
8705
  },
8565
8706
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
8566
8707
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
8567
8708
  // against its own directory, project-root refs stay as authored.
8568
- assetExists: (path) => existsSync11(resolve7(projectDir, path)),
8709
+ assetExists: projectAssetExists(projectDir),
8569
8710
  // Preserve the authored root wrapper as a child of the host, matching
8570
8711
  // the preview bundler's shape (htmlBundler.ts's prepareFlattenedInnerRoot,
8571
8712
  // which the runtime compositionLoader mirrors with its own copy for the
@@ -8770,7 +8911,7 @@ ${safeText}
8770
8911
  }
8771
8912
  return wrappedFragment ? document2.body.innerHTML || "" : document2.toString();
8772
8913
  }
8773
- function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html") {
8914
+ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "index.html", policy = {}) {
8774
8915
  const absProjectDir = resolve7(projectDir);
8775
8916
  const externalAssets = /* @__PURE__ */ new Map();
8776
8917
  const leftOut = /* @__PURE__ */ new Set();
@@ -8783,7 +8924,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
8783
8924
  }
8784
8925
  const onShare = namesAnotherNetworkRoot2(absProjectDir, absPath);
8785
8926
  if (!onShare && !existsSync11(absPath)) return null;
8786
- const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath);
8927
+ const refusal = onShare ? "network_share" : outsideAssetRefusal(absProjectDir, absPath, policy);
8787
8928
  if (refusal) {
8788
8929
  if (!leftOut.has(trimmed)) log.warn(`[Compiler] ${leftOutOfRender(file, trimmed, refusal)}`);
8789
8930
  leftOut.add(trimmed);
@@ -9172,7 +9313,7 @@ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
9172
9313
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
9173
9314
  if (!entryPath.includes("/")) return html;
9174
9315
  const { document: document2 } = parseHTML5(html);
9175
- const assetExists = (path) => existsSync11(resolve7(projectDir, path));
9316
+ const assetExists = projectAssetExists(projectDir);
9176
9317
  rewriteAssetPaths(
9177
9318
  document2.querySelectorAll("[src], [href], [srcset]"),
9178
9319
  entryPath,
@@ -9213,18 +9354,23 @@ function bindVariableMediaSources(html, variables) {
9213
9354
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative2(projectDir, htmlPath).split(sep3).join("/") : basename5(htmlPath);
9214
9355
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9215
9356
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9357
+ const outsideFiles = { includeScripts: options.includeOutsideScripts };
9216
9358
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
9217
9359
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
9218
9360
  }
9361
+ if (isPathInside(htmlPath, projectDir) && runsOutsideMarkupUnasked(projectDir, htmlPath, assetRoot, outsideFiles)) {
9362
+ throw new Error(`Entry file ${htmlPath} ${OUTSIDE_COMPOSITION_NEEDS_FLAG}`);
9363
+ }
9219
9364
  if (!COMPOSITION_FILE.test(htmlPath)) {
9220
9365
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
9221
9366
  }
9367
+ assertCompositionFileSize(htmlPath, basename5(htmlPath));
9222
9368
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
9223
9369
  const rawHtml = bindVariableMediaSources(
9224
9370
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
9225
9371
  options.variables ?? {}
9226
9372
  );
9227
- assertSubCompositionsUsable(rawHtml, projectDir, assetRoot);
9373
+ assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9228
9374
  const probes = /* @__PURE__ */ new Map();
9229
9375
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
9230
9376
  rawHtml,
@@ -9243,7 +9389,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9243
9389
  void 0,
9244
9390
  options.urlByAbsentLocalPath,
9245
9391
  probes,
9246
- assetRoot
9392
+ assetRoot,
9393
+ outsideFiles
9247
9394
  );
9248
9395
  const fullHtml = ensureFullDocument(compiledHtml);
9249
9396
  const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
@@ -9251,7 +9398,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9251
9398
  subCompositions,
9252
9399
  projectDir,
9253
9400
  options.variables ?? {},
9254
- assetRoot
9401
+ assetRoot,
9402
+ outsideFiles
9255
9403
  );
9256
9404
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
9257
9405
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -9305,7 +9453,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9305
9453
  cacheDir: options.animatedGifCacheDir,
9306
9454
  sourceAssets: remoteImageAssets,
9307
9455
  timeoutMs: options.ffmpegProcessTimeout,
9308
- assetRoot
9456
+ allowOutsideFiles: assetRoot === void 0
9309
9457
  });
9310
9458
  if (preparedHeifImages.length > 0) {
9311
9459
  defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
@@ -9321,7 +9469,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9321
9469
  cacheDir: options.animatedGifCacheDir,
9322
9470
  sourceAssets: gifSourceAssets,
9323
9471
  timeoutMs: options.ffmpegProcessTimeout,
9324
- assetRoot
9472
+ allowOutsideFiles: assetRoot === void 0
9325
9473
  });
9326
9474
  if (preparedGifs.length > 0) {
9327
9475
  defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
@@ -9336,7 +9484,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9336
9484
  embeddedHtml,
9337
9485
  projectDir,
9338
9486
  options.log,
9339
- entryFileName(projectDir, htmlPath)
9487
+ entryFileName(projectDir, htmlPath),
9488
+ { includeScripts: options.includeOutsideScripts }
9340
9489
  ) : { html: embeddedHtml, externalAssets: /* @__PURE__ */ new Map() };
9341
9490
  for (const [relPath, absPath] of remoteMediaAssets) {
9342
9491
  externalAssets.set(relPath, absPath);
@@ -9743,7 +9892,7 @@ async function resolveCompositionDurations(page, unresolved) {
9743
9892
  }
9744
9893
  return resolutions;
9745
9894
  }
9746
- async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot) {
9895
+ async function recompileWithResolutions(compiled, resolutions, projectDir, downloadDir, assetRoot, outsideFiles = {}) {
9747
9896
  if (resolutions.length === 0) return compiled;
9748
9897
  const html = injectDurations(compiled.html, resolutions);
9749
9898
  const { subCompositions } = await parseSubCompositions(
@@ -9753,7 +9902,8 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
9753
9902
  void 0,
9754
9903
  void 0,
9755
9904
  void 0,
9756
- assetRoot
9905
+ assetRoot,
9906
+ outsideFiles
9757
9907
  );
9758
9908
  const { videos, audios, images } = compiled;
9759
9909
  const remaining = compiled.unresolvedCompositions.filter(
@@ -9801,6 +9951,7 @@ function resolveEntryHtmlPath(input) {
9801
9951
  `Entry file "${relative3(projectDir, path)}" leads outside the project folder`
9802
9952
  );
9803
9953
  }
9954
+ assertCompositionFileSize(path, relative3(projectDir, path));
9804
9955
  return readTextFile2(path);
9805
9956
  };
9806
9957
  const htmlPath = join20(projectDir, entryFile);
@@ -9862,7 +10013,8 @@ async function runCompileStage(input) {
9862
10013
  pageMotionBlur: input.pageMotionBlur,
9863
10014
  animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
9864
10015
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
9865
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10016
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10017
+ includeOutsideScripts: job.config.includeOutsideScripts
9866
10018
  });
9867
10019
  assertNotAborted();
9868
10020
  const compileOnlyMs = Date.now() - compileStart;
@@ -9948,6 +10100,8 @@ async function runCompileStage(input) {
9948
10100
  });
9949
10101
  const outputWidth = Math.round(width * deviceScaleFactor);
9950
10102
  const outputHeight = Math.round(height * deviceScaleFactor);
10103
+ requireOutputDimensions(job.config.expectedOutputDimensions, outputWidth, outputHeight);
10104
+ if (job.config.expectedOutputDimensions !== void 0) job.outputDimensionsChecked = true;
9951
10105
  if (deviceScaleFactor !== 1) {
9952
10106
  log.info("Scaling composition via deviceScaleFactor", {
9953
10107
  compositionWidth: width,
@@ -10042,30 +10196,50 @@ function hasAutoStartVideos(html) {
10042
10196
  const { document: document2 } = parseHTML6(html);
10043
10197
  return document2.querySelector("video[data-hf-auto-start]") !== null;
10044
10198
  }
10045
- function scopedVariablesFor(element, variablesByComp) {
10046
- const scope = element.closest("[data-composition-id]");
10047
- const compId = scope?.getAttribute("data-composition-id")?.trim() ?? "";
10048
- return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : void 0;
10199
+ var MAX_VARIABLE_SCOPE_STEPS = 1e6;
10200
+ function variableIdsOn(scan, element) {
10201
+ let ids = scan.ids.get(element);
10202
+ if (!ids) {
10203
+ ids = /* @__PURE__ */ new Set([
10204
+ ...Object.keys(parseHostVariableValues2(element)),
10205
+ ...Object.keys(readDeclaredDefaults2(element))
10206
+ ]);
10207
+ scan.ids.set(element, ids);
10208
+ }
10209
+ return ids;
10049
10210
  }
10050
- function variableHasValue(element, variableId, variables, variablesByComp) {
10211
+ function scopedVariablesFor(scan, element, variablesByComp) {
10212
+ for (let node = element; node; node = node.parentElement) {
10213
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return null;
10214
+ if (!node.hasAttribute("data-composition-id")) continue;
10215
+ const compId = node.getAttribute("data-composition-id")?.trim() ?? "";
10216
+ return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : void 0;
10217
+ }
10218
+ return void 0;
10219
+ }
10220
+ function variableHasValue(scan, element, variableId, variables, variablesByComp) {
10051
10221
  if (variables && Object.hasOwn(variables, variableId)) return true;
10052
- const scoped = scopedVariablesFor(element, variablesByComp);
10222
+ const scoped = scopedVariablesFor(scan, element, variablesByComp);
10223
+ if (scoped === null) return true;
10053
10224
  if (scoped) return Object.hasOwn(scoped, variableId);
10054
10225
  for (let scope = element.parentElement; scope; scope = scope.parentElement) {
10055
- if (Object.hasOwn(parseHostVariableValues2(scope), variableId)) return true;
10056
- if (Object.hasOwn(readDeclaredDefaults2(scope), variableId)) return true;
10226
+ if (++scan.steps > MAX_VARIABLE_SCOPE_STEPS) return true;
10227
+ if (variableIdsOn(scan, scope).has(variableId)) return true;
10057
10228
  }
10058
- return Object.hasOwn(readDeclaredDefaults2(element.ownerDocument.documentElement), variableId);
10229
+ return variableIdsOn(scan, element.ownerDocument.documentElement).has(variableId);
10059
10230
  }
10060
10231
  function hasVariableBoundMedia(html, variables, variablesByComp = {}) {
10061
10232
  const { document: document2 } = parseHTML6(html);
10233
+ const scan = { ids: /* @__PURE__ */ new Map(), steps: 0 };
10062
10234
  return Array.from(
10063
10235
  document2.querySelectorAll(
10064
10236
  "img[data-var-src], audio[data-var-src], video[data-var-src], source[data-var-src]"
10065
10237
  )
10066
10238
  ).some((element) => {
10067
10239
  const variableId = element.getAttribute("data-var-src")?.trim();
10068
- return Boolean(variableId && variableHasValue(element, variableId, variables, variablesByComp));
10240
+ return Boolean(
10241
+ variableId && variableHasValue(scan, element, variableId, variables, variablesByComp)
10242
+ );
10069
10243
  });
10070
10244
  }
10071
10245
  function authoredMediaStarts(html) {
@@ -10105,29 +10279,54 @@ function reconcileBrowserMediaEnd(existingEnd, projectedEnd, sourceChanged, dura
10105
10279
  if (sourceChanged && durationInferred) return projectedEnd;
10106
10280
  return existingEnd <= 0 ? projectedEnd : Math.min(existingEnd, projectedEnd);
10107
10281
  }
10282
+ var MAX_MEDIA_SELECTOR_WORK = 1e6;
10283
+ var SIBLING_COMBINATOR = /[~+]/;
10284
+ function managedMediaElements(document2) {
10285
+ const managed = [];
10286
+ const pending = [];
10287
+ for (const element of Array.from(document2.children)) pending.push({ element, inMedia: false });
10288
+ for (let next = pending.pop(); next; next = pending.pop()) {
10289
+ const name = next.element.tagName.toLowerCase();
10290
+ const isMedia = name === "video" || name === "audio";
10291
+ if (isMedia || next.inMedia && name === "source") managed.push(next.element);
10292
+ for (const child3 of Array.from(next.element.children)) {
10293
+ pending.push({ element: child3, inMedia: next.inMedia || isMedia });
10294
+ }
10295
+ }
10296
+ return managed;
10297
+ }
10108
10298
  function hasRuntimeMediaChanges(html) {
10109
10299
  const { document: document2 } = parseHTML6(html);
10110
10300
  const scriptBodies = [...document2.querySelectorAll("script")].map(
10111
10301
  (script) => script.textContent ?? ""
10112
10302
  );
10113
10303
  const insertedMedia = scriptBodies.some(
10114
- (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || /<(?:video|audio)\b[^>]*>/i.test(script)
10304
+ (script) => /\bcreateElement\s*\(\s*["'`](?:video|audio)["'`]\s*\)/i.test(script) || /\bnew\s+(?:Audio|Video)\s*\(/i.test(script) || hasClosedMediaTag(script)
10115
10305
  );
10116
10306
  if (insertedMedia) return true;
10117
- const isManagedMedia = (element) => {
10118
- const name = element.tagName.toLowerCase();
10119
- if (name === "video" || name === "audio") return true;
10120
- return name === "source" && element.closest("video, audio") !== null;
10121
- };
10307
+ const managed = managedMediaElements(document2);
10308
+ if (managed.length === 0) return false;
10309
+ const managedIds = new Set(managed.map((element) => element.getAttribute("id")).filter(Boolean));
10310
+ const selectors = /* @__PURE__ */ new Set();
10311
+ let selectorChars = 0;
10122
10312
  for (const script of scriptBodies) {
10123
10313
  for (const mutation of extractMediaSrcMutations(script)) {
10124
- try {
10125
- const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10126
- const idTarget = id ? document2.getElementById(id) : null;
10127
- const targets = id ? idTarget ? [idTarget] : [] : [...document2.querySelectorAll(mutation.selector)];
10128
- if (targets.some(isManagedMedia)) return true;
10129
- } catch {
10314
+ const id = /^#[A-Za-z_][\w-]*$/.test(mutation.selector) ? mutation.selector.slice(1) : null;
10315
+ if (id) {
10316
+ if (managedIds.has(id)) return true;
10317
+ continue;
10130
10318
  }
10319
+ if (selectors.has(mutation.selector)) continue;
10320
+ if (SIBLING_COMBINATOR.test(mutation.selector)) return true;
10321
+ selectors.add(mutation.selector);
10322
+ selectorChars += mutation.selector.length;
10323
+ if (selectorChars * managed.length > MAX_MEDIA_SELECTOR_WORK) return true;
10324
+ }
10325
+ }
10326
+ for (const selector of selectors) {
10327
+ try {
10328
+ if (managed.some((element) => element.matches(selector))) return true;
10329
+ } catch {
10131
10330
  }
10132
10331
  }
10133
10332
  return false;
@@ -10215,7 +10414,8 @@ async function runProbeStage(input) {
10215
10414
  port: 0,
10216
10415
  preHeadScripts: [VIRTUAL_TIME_SHIM],
10217
10416
  fps: job.config.fps,
10218
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
10417
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
10418
+ includeOutsideScripts: job.config.includeOutsideScripts
10219
10419
  });
10220
10420
  assertNotAborted();
10221
10421
  const motionBlur = job.config.motionBlur;
@@ -10371,7 +10571,8 @@ async function runProbeStage(input) {
10371
10571
  resolutions,
10372
10572
  projectDir,
10373
10573
  join21(workDir, "downloads"),
10374
- job.config.allowOutsideProjectAssets ? void 0 : projectDir
10574
+ job.config.allowOutsideProjectAssets ? void 0 : projectDir,
10575
+ { includeScripts: job.config.includeOutsideScripts }
10375
10576
  );
10376
10577
  assertNotAborted();
10377
10578
  composition.videos = compiled.videos;
@@ -13449,7 +13650,7 @@ import {
13449
13650
  readdirSync as readdirSync5,
13450
13651
  readFileSync as readFileSync9,
13451
13652
  rmSync as rmSync11,
13452
- statSync as statSync9,
13653
+ statSync as statSync10,
13453
13654
  writeFileSync as writeFileSync6
13454
13655
  } from "node:fs";
13455
13656
  import { readFile as readFile2 } from "node:fs/promises";
@@ -13578,7 +13779,7 @@ async function encodeGifFromDir(framesDir, framePattern, outputPath, input) {
13578
13779
  const failure = await reencodeWithClearedWholeFrames(argsInput, run, startTime);
13579
13780
  if (failure) return failure;
13580
13781
  }
13581
- const fileSize = existsSync20(outputPath) ? statSync9(outputPath).size : 0;
13782
+ const fileSize = existsSync20(outputPath) ? statSync10(outputPath).size : 0;
13582
13783
  return {
13583
13784
  success: true,
13584
13785
  outputPath,
@@ -13601,7 +13802,10 @@ function startEncodeProgress(job, stage, onProgress) {
13601
13802
  function resolveEngineConfig(input) {
13602
13803
  return input.engineConfig ?? input.job.config.producerConfig ?? resolveConfig();
13603
13804
  }
13604
- function videoEncoderOptions(input, engineCfg) {
13805
+ function overlapEncoderThreads(workerCount, cpuCount) {
13806
+ return Math.max(1, Math.floor(cpuCount) - Math.floor(workerCount));
13807
+ }
13808
+ function videoEncoderOptions(input, engineCfg, softwareEncoderThreads) {
13605
13809
  const { job, preset } = input;
13606
13810
  return {
13607
13811
  fps: job.config.fps,
@@ -13621,7 +13825,8 @@ function videoEncoderOptions(input, engineCfg) {
13621
13825
  // keyframes that survive `-f concat -c copy` at assemble time. In-process
13622
13826
  // renders leave both undefined → preserves the existing open-GOP output.
13623
13827
  lockGopForChunkConcat: input.lockGopForChunkConcat === true,
13624
- gopSize: input.gopSize
13828
+ gopSize: input.gopSize,
13829
+ softwareEncoderThreads
13625
13830
  };
13626
13831
  }
13627
13832
  function canEncodeWhileCapturing(input, workerCount, cpuCount) {
@@ -13637,8 +13842,9 @@ async function readLandedFrame(workerPath, mergedPath) {
13637
13842
  }
13638
13843
  return readFile2(mergedPath);
13639
13844
  }
13640
- function encodeWhileCapturing(input, totalFrames) {
13845
+ function encodeWhileCapturing(input, totalFrames, captureBudget) {
13641
13846
  const engineCfg = resolveEngineConfig(input);
13847
+ const softwareEncoderThreads = captureBudget ? overlapEncoderThreads(captureBudget.workerCount, captureBudget.cpuCount) : void 0;
13642
13848
  const stop = new AbortController();
13643
13849
  const signal = input.abortSignal ? AbortSignal.any([input.abortSignal, stop.signal]) : stop.signal;
13644
13850
  const landed = /* @__PURE__ */ new Map();
@@ -13653,7 +13859,10 @@ function encodeWhileCapturing(input, totalFrames) {
13653
13859
  let reportFed = null;
13654
13860
  const encoder = spawnStreamingEncoder4(
13655
13861
  input.videoOnlyPath,
13656
- { ...videoEncoderOptions(input, engineCfg), imageFormat: "jpeg" },
13862
+ {
13863
+ ...videoEncoderOptions(input, engineCfg, softwareEncoderThreads),
13864
+ imageFormat: "jpeg"
13865
+ },
13657
13866
  signal,
13658
13867
  engineCfg
13659
13868
  );
@@ -13706,7 +13915,7 @@ function encodeWhileCapturing(input, totalFrames) {
13706
13915
  error: String(failure ?? result?.error)
13707
13916
  }
13708
13917
  );
13709
- return runEncodeStage(input);
13918
+ return runEncodeStage({ ...input, hasAudio: false });
13710
13919
  },
13711
13920
  abort: async () => {
13712
13921
  stop.abort();
@@ -13984,7 +14193,7 @@ function sampleDirectoryBytes(dir) {
13984
14193
  for (const name of entries) {
13985
14194
  const full = join32(current, name);
13986
14195
  try {
13987
- const st = statSync10(full);
14196
+ const st = statSync11(full);
13988
14197
  if (st.isDirectory()) {
13989
14198
  stack.push(full);
13990
14199
  } else if (st.isFile()) {
@@ -14034,6 +14243,7 @@ var RenderQualityError = class extends Error {
14034
14243
  }
14035
14244
  warnings;
14036
14245
  };
14246
+ var MIN_CPUS_TO_CAPTURE_DURING_MIX = 4;
14037
14247
  function applyRenderWarningPolicy(job, captureWarnings, log = defaultLogger) {
14038
14248
  job.warnings ??= [];
14039
14249
  const existing = new Set(
@@ -14139,7 +14349,7 @@ function findMissingFrameRanges(totalFrames, framesDir, frameExt) {
14139
14349
  let rangeStart = null;
14140
14350
  for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
14141
14351
  const framePath = join32(framesDir, formatCaptureFrameName(frameIndex, frameExt));
14142
- const missing = !existsSync21(framePath) || statSync10(framePath).size <= 8;
14352
+ const missing = !existsSync21(framePath) || statSync11(framePath).size <= 8;
14143
14353
  if (missing && rangeStart === null) {
14144
14354
  rangeStart = frameIndex;
14145
14355
  } else if (!missing && rangeStart !== null) {
@@ -15004,8 +15214,14 @@ async function executeRenderPipeline(input) {
15004
15214
  const onProgress = execution.onProgress;
15005
15215
  const tooSlow = new AbortController();
15006
15216
  let tooSlowError;
15217
+ const audioFailed = new AbortController();
15218
+ let audioFailure;
15007
15219
  let calibrationEvaluateTimedOut = false;
15008
- const executionSignal = job.config.maxRenderMs ? AbortSignal.any([tooSlow.signal, ...execution.signal ? [execution.signal] : []]) : execution.signal;
15220
+ const executionSignal = AbortSignal.any([
15221
+ audioFailed.signal,
15222
+ ...job.config.maxRenderMs ? [tooSlow.signal] : [],
15223
+ ...execution.signal ? [execution.signal] : []
15224
+ ]);
15009
15225
  let fileServer = null;
15010
15226
  let probeSession = null;
15011
15227
  let lastBrowserConsole = [];
@@ -15476,7 +15692,8 @@ async function executeRenderPipeline(input) {
15476
15692
  port: 0,
15477
15693
  preHeadScripts: [VIRTUAL_TIME_SHIM],
15478
15694
  fps: job.config.fps,
15479
- allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
15695
+ allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
15696
+ includeOutsideScripts: job.config.includeOutsideScripts
15480
15697
  });
15481
15698
  assertNotAborted();
15482
15699
  observability.stageEnd("file_server", fileServerStart);
@@ -16267,33 +16484,41 @@ async function executeRenderPipeline(input) {
16267
16484
  }
16268
16485
  const effectiveQuality = job.config.crf ?? preset.quality;
16269
16486
  const effectiveBitrate = job.config.crf != null ? void 0 : job.config.videoBitrate;
16270
- const audioResult = await audioWait.wait(audioStage);
16271
- const { audioOutputPath, deliverySourcePath, hasAudio } = audioResult;
16272
- perfStages.audioProcessMs = audioResult.audioProcessMs;
16273
- recordLimiterAttenuation(job, audioResult.audioLoweredDb);
16274
- if (audioResult.audioError) {
16275
- const audioFailures = audioResult.audioFailures ?? [];
16276
- const failureOwner = audioFailures.length === 0 ? void 0 : audioFailures.some((failure) => failure.owner === "system") ? "system" : "user";
16277
- const retryable = audioFailures.length === 0 ? void 0 : audioFailures.every((failure) => failure.retryable);
16278
- applyRenderWarningPolicy(
16279
- job,
16280
- [
16281
- {
16282
- code: "audio_processing_failed",
16283
- message: `Audio mix failed; output would be video-only: ${audioResult.audioError}`,
16284
- details: {
16285
- mediaType: "audio",
16286
- audioFailures: audioFailureDiagnostics2(audioFailures),
16287
- failureReasons: [...new Set(audioFailures.map((failure) => failure.reason))],
16288
- failureStages: [...new Set(audioFailures.map((failure) => failure.stage))],
16289
- failureOwner,
16290
- retryable
16487
+ const audioReady = audioStage.then((audioResult) => {
16488
+ perfStages.audioProcessMs = audioResult.audioProcessMs;
16489
+ recordLimiterAttenuation(job, audioResult.audioLoweredDb);
16490
+ if (audioResult.audioError) {
16491
+ const audioFailures = audioResult.audioFailures ?? [];
16492
+ const failureOwner = audioFailures.length === 0 ? void 0 : audioFailures.some((failure) => failure.owner === "system") ? "system" : "user";
16493
+ const retryable = audioFailures.length === 0 ? void 0 : audioFailures.every((failure) => failure.retryable);
16494
+ applyRenderWarningPolicy(
16495
+ job,
16496
+ [
16497
+ {
16498
+ code: "audio_processing_failed",
16499
+ message: `Audio mix failed; output would be video-only: ${audioResult.audioError}`,
16500
+ details: {
16501
+ mediaType: "audio",
16502
+ audioFailures: audioFailureDiagnostics2(audioFailures),
16503
+ failureReasons: [...new Set(audioFailures.map((failure) => failure.reason))],
16504
+ failureStages: [...new Set(audioFailures.map((failure) => failure.stage))],
16505
+ failureOwner,
16506
+ retryable
16507
+ }
16291
16508
  }
16292
- }
16293
- ],
16294
- log
16295
- );
16296
- }
16509
+ ],
16510
+ log
16511
+ );
16512
+ }
16513
+ return audioResult;
16514
+ });
16515
+ audioReady.catch((error) => {
16516
+ if (executionSignal.aborted) return;
16517
+ audioFailure = error;
16518
+ audioFailed.abort(error);
16519
+ });
16520
+ const mixedAudio = () => audioWait.wait(audioReady);
16521
+ if (usableCpuCount2() < MIN_CPUS_TO_CAPTURE_DURING_MIX) await mixedAudio();
16297
16522
  resetCaptureAttemptProgress(job);
16298
16523
  if (capturePlan.kind === "hdr_layered") {
16299
16524
  const layeredPlan = capturePlan;
@@ -16476,7 +16701,7 @@ async function executeRenderPipeline(input) {
16476
16701
  } catch (err) {
16477
16702
  const isVerifyError = isDrawElementVerificationError(err);
16478
16703
  const isDeStall = isDeRendererStallError(err);
16479
- if (!isVerifyError && !isDrawElementCaptureError(err) && !isDeStall || err instanceof RenderCancelledError || executionSignal?.aborted === true) {
16704
+ if (!isVerifyError && !isDrawElementCaptureError(err) && !isDeStall || err instanceof RenderCancelledError || executionSignal.aborted === true) {
16480
16705
  throw err;
16481
16706
  }
16482
16707
  deSelfVerifyFallback = isVerifyError;
@@ -16619,7 +16844,7 @@ async function executeRenderPipeline(input) {
16619
16844
  const isSequentialStall = isSequentialCaptureStallError(err);
16620
16845
  const isParallelStall = isParallelCaptureStallError(err);
16621
16846
  const isEncoderDeath = isRetryableEncoderDeath(err);
16622
- const isCancellation = err instanceof RenderCancelledError || executionSignal?.aborted === true;
16847
+ const isCancellation = err instanceof RenderCancelledError || executionSignal.aborted === true;
16623
16848
  if (!shouldRetryViaPinnedFallback({
16624
16849
  isVerifyError,
16625
16850
  isDeCaptureError,
@@ -16748,8 +16973,6 @@ async function executeRenderPipeline(input) {
16748
16973
  height,
16749
16974
  needsAlpha,
16750
16975
  captureImageFormat: captureOptions.format ?? "jpeg",
16751
- hasAudio,
16752
- audioOutputPath,
16753
16976
  isPngSequence,
16754
16977
  isGif,
16755
16978
  preset,
@@ -16765,7 +16988,10 @@ async function executeRenderPipeline(input) {
16765
16988
  assertNotAborted,
16766
16989
  onProgress
16767
16990
  };
16768
- const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames) : null;
16991
+ const overlap = !cfg.useDrawElement && workerSizing !== void 0 && canEncodeWhileCapturing(encodeInput, capturePlan.workerCount, workerSizing.cpuCount) ? encodeWhileCapturing(encodeInput, totalFrames, {
16992
+ workerCount: capturePlan.workerCount,
16993
+ cpuCount: workerSizing.cpuCount
16994
+ }) : null;
16769
16995
  const captureFrameStart = Date.now();
16770
16996
  const invokeDiskCapture = (diskPlan) => observeRenderStage(
16771
16997
  observability,
@@ -16799,7 +17025,7 @@ async function executeRenderPipeline(input) {
16799
17025
  captureRes = await invokeDiskCapture(capturePlan);
16800
17026
  } catch (err) {
16801
17027
  await overlap?.abort();
16802
- if (!isDrawElementVerificationError(err) && !isDrawElementCaptureError(err) || err instanceof RenderCancelledError || executionSignal?.aborted === true) {
17028
+ if (!isDrawElementVerificationError(err) && !isDrawElementCaptureError(err) || err instanceof RenderCancelledError || executionSignal.aborted === true) {
16803
17029
  throw err;
16804
17030
  }
16805
17031
  deSelfVerifyFallback = isDrawElementVerificationError(err);
@@ -16858,16 +17084,17 @@ async function executeRenderPipeline(input) {
16858
17084
  perfStages.captureMs = Date.now() - stage4Start;
16859
17085
  perfStages.captureFrameMs = captureFrameMs;
16860
17086
  perfStages.captureSetupMs = Math.max(0, perfStages.captureMs - captureFrameMs);
17087
+ const { hasAudio: hasAudio2, audioOutputPath: audioOutputPath2 } = await mixedAudio();
16861
17088
  const encodeRes = await observeRenderStage(
16862
17089
  observability,
16863
17090
  "encode",
16864
17091
  captureStageObservationData({
16865
- hasAudio,
17092
+ hasAudio: hasAudio2,
16866
17093
  isPngSequence,
16867
17094
  isGif,
16868
17095
  chunkedEncode: enableChunkedEncode
16869
17096
  }),
16870
- () => overlap ? overlap.finish() : runEncodeStage(encodeInput)
17097
+ () => overlap ? overlap.finish() : runEncodeStage({ ...encodeInput, hasAudio: hasAudio2, audioOutputPath: audioOutputPath2 })
16871
17098
  );
16872
17099
  perfStages.encodeMs = encodeRes.encodeMs;
16873
17100
  }
@@ -16887,6 +17114,7 @@ async function executeRenderPipeline(input) {
16887
17114
  if (frameLookup) frameLookup.cleanup();
16888
17115
  closeFileServerSafely(fileServer, "renderOrchestrator", log);
16889
17116
  fileServer = null;
17117
+ const { audioOutputPath, deliverySourcePath, hasAudio } = await mixedAudio();
16890
17118
  if (!isPngSequence && !isGif) {
16891
17119
  const assembleRes = await observeRenderStage(
16892
17120
  observability,
@@ -17022,8 +17250,11 @@ async function executeRenderPipeline(input) {
17022
17250
  framesRendered: job.framesRendered ?? 0,
17023
17251
  error: caught
17024
17252
  });
17025
- const error = surfaceScriptFailure(tooSlowError ?? pageNeverReady ?? caught, job);
17026
- if (!tooSlowError && (error instanceof RenderCancelledError || executionSignal?.aborted)) {
17253
+ const error = surfaceScriptFailure(
17254
+ tooSlowError ?? audioFailure ?? pageNeverReady ?? caught,
17255
+ job
17256
+ );
17257
+ if (!tooSlowError && !audioFailure && (error instanceof RenderCancelledError || executionSignal.aborted)) {
17027
17258
  job.error = error instanceof Error ? error.message : "render_cancelled";
17028
17259
  updateJobStatus(job, "cancelled", "Render cancelled", job.progress, onProgress);
17029
17260
  await eventPublisher.flush();
@@ -17065,7 +17296,7 @@ async function executeRenderPipeline(input) {
17065
17296
  `Parallel capture timed out with ${captureObservability.workerCount ?? "auto"} workers. Video-heavy compositions often need sequential capture. Retry with --workers 1`
17066
17297
  );
17067
17298
  }
17068
- const failedStage = job.currentStage || "pipeline";
17299
+ const failedStage = audioFailure === void 0 ? job.currentStage || "pipeline" : AUDIO_STAGE;
17069
17300
  const observabilitySummary = observability.summary({
17070
17301
  lastBrowserConsole,
17071
17302
  capture: withCapturedBeyondViewport(captureObservability, dedupPerfs),
@@ -17826,8 +18057,10 @@ function buildSyntheticRenderJob(input) {
17826
18057
  producerConfig: input.producerConfig,
17827
18058
  variables: input.variables,
17828
18059
  strictVariables: input.strictVariables,
18060
+ expectedOutputDimensions: input.expectedOutputDimensions,
17829
18061
  pageMotionBlur: input.pageMotionBlur,
17830
- allowOutsideProjectAssets: input.allowOutsideProjectAssets
18062
+ allowOutsideProjectAssets: input.allowOutsideProjectAssets,
18063
+ includeOutsideScripts: input.includeOutsideScripts
17831
18064
  };
17832
18065
  return createRenderJob(renderConfig);
17833
18066
  }
@@ -19304,8 +19537,10 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19304
19537
  producerConfig: cfg,
19305
19538
  variables: config.variables,
19306
19539
  strictVariables: config.strictVariables,
19540
+ expectedOutputDimensions: config.expectedOutputDimensions,
19307
19541
  pageMotionBlur: config.pageMotionBlur,
19308
- allowOutsideProjectAssets: options.allowOutsideProjectAssets === true
19542
+ allowOutsideProjectAssets: options.allowOutsideProjectAssets === true,
19543
+ includeOutsideScripts: options.includeOutsideScripts === true
19309
19544
  });
19310
19545
  const entryFile = config.entryFile ?? "index.html";
19311
19546
  const htmlPath = join41(projectDir, entryFile);
@@ -19326,7 +19561,9 @@ async function compilePlanComposition(projectDir, config, planDir, options) {
19326
19561
  if (rel === "") return true;
19327
19562
  if (leavesRoot(rel)) return false;
19328
19563
  if (job.config.allowOutsideProjectAssets) {
19329
- if (refusesOutsideLink(projectDir, src, (line) => log.warn(`[Plan] ${line}`))) return false;
19564
+ const warn = (line) => log.warn(`[Plan] ${line}`);
19565
+ const policy = { includeScripts: job.config.includeOutsideScripts };
19566
+ if (refusesOutsideLink(projectDir, src, warn, policy)) return false;
19330
19567
  } else if (!isSafePath2(projectDir, src)) return false;
19331
19568
  const firstSegment = rel.split(sep4, 1)[0];
19332
19569
  return firstSegment === void 0 || !PLAN_PROJECT_DIR_SKIP_SEGMENTS.has(firstSegment);
@@ -19771,6 +20008,7 @@ async function buildLocalExecutionPlan(projectDir, config, executionPlanDir, opt
19771
20008
  format: config.format,
19772
20009
  ffmpegVersion,
19773
20010
  producerVersion,
20011
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked },
19774
20012
  ...job.strictVariablesChecked === void 0 ? {} : { strictVariablesChecked: job.strictVariablesChecked }
19775
20013
  };
19776
20014
  }
@@ -19789,6 +20027,7 @@ async function plan(projectDir, config, planDir, options = {}) {
19789
20027
  format: executionPlan.format,
19790
20028
  ffmpegVersion: executionPlan.ffmpegVersion,
19791
20029
  producerVersion: executionPlan.producerVersion,
20030
+ ...executionPlan.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: executionPlan.outputDimensionsChecked },
19792
20031
  ...executionPlan.strictVariablesChecked === void 0 ? {} : { strictVariablesChecked: executionPlan.strictVariablesChecked }
19793
20032
  };
19794
20033
  }
@@ -19812,7 +20051,7 @@ import {
19812
20051
  probeBeginFrameLiveness as probeBeginFrameLiveness2,
19813
20052
  readWebGlVendorInfoFromCanvas,
19814
20053
  resolveConfig as resolveConfig4,
19815
- usableCpuCount as usableCpuCount2
20054
+ usableCpuCount as usableCpuCount3
19816
20055
  } from "@hyperframes/engine";
19817
20056
 
19818
20057
  // src/services/distributed/planV2.ts
@@ -19828,7 +20067,7 @@ import {
19828
20067
  readFileSync as readFileSync13,
19829
20068
  readdirSync as readdirSync10,
19830
20069
  rmSync as rmSync16,
19831
- statSync as statSync12,
20070
+ statSync as statSync13,
19832
20071
  writeFileSync as writeFileSync12
19833
20072
  } from "node:fs";
19834
20073
  import { tmpdir as tmpdir3 } from "node:os";
@@ -19847,7 +20086,7 @@ import {
19847
20086
  linkSync as linkSync2,
19848
20087
  mkdirSync as mkdirSync17,
19849
20088
  rmSync as rmSync15,
19850
- statSync as statSync11,
20089
+ statSync as statSync12,
19851
20090
  writeFileSync as writeFileSync11
19852
20091
  } from "node:fs";
19853
20092
  import { renameWithRetry as renameWithRetry9 } from "@hyperframes/engine";
@@ -19917,7 +20156,7 @@ var LocalPlanV2ArtifactPublisher = class {
19917
20156
  }
19918
20157
  async putBlob(blob) {
19919
20158
  const digest = assertPlanV2Sha256(blob.sha256, "published blob sha256");
19920
- const sourceSize = statSync11(blob.sourcePath).size;
20159
+ const sourceSize = statSync12(blob.sourcePath).size;
19921
20160
  if (sourceSize !== blob.sizeBytes) {
19922
20161
  throw new PlanV2IntegrityError(
19923
20162
  `published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`
@@ -20231,7 +20470,7 @@ function publishBlobFor(absolutePath, digests) {
20231
20470
  return {
20232
20471
  sourcePath: absolutePath,
20233
20472
  sha256: planFileSha256(absolutePath, digests),
20234
- sizeBytes: statSync12(absolutePath).size
20473
+ sizeBytes: statSync13(absolutePath).size
20235
20474
  };
20236
20475
  }
20237
20476
  async function putBlobs(publisher, blobs) {
@@ -20410,7 +20649,10 @@ async function planV2WithPublisher(projectDir, config, publisher, options = {})
20410
20649
  sliceChunkAudio: true,
20411
20650
  deferAudio: options.deferAudio
20412
20651
  });
20413
- options.onPlanned?.({ strictVariablesChecked: planned.strictVariablesChecked });
20652
+ options.onPlanned?.({
20653
+ strictVariablesChecked: planned.strictVariablesChecked,
20654
+ outputDimensionsChecked: planned.outputDimensionsChecked
20655
+ });
20414
20656
  return await publishExecutionPlan(stagingRoot, publisher, { digests, log: config.logger });
20415
20657
  } catch (error) {
20416
20658
  try {
@@ -20599,7 +20841,7 @@ function verifyBlob(planV2Dir, artifact) {
20599
20841
  if (!existsSync28(sourcePath)) {
20600
20842
  throw new PlanV2IntegrityError(`missing content-addressed artifact ${artifact.sha256}`);
20601
20843
  }
20602
- const stats = statSync12(sourcePath);
20844
+ const stats = statSync13(sourcePath);
20603
20845
  if (!stats.isFile() || stats.size !== artifact.sizeBytes) {
20604
20846
  throw new PlanV2IntegrityError(`artifact size mismatch for ${artifact.path}`);
20605
20847
  }
@@ -20692,7 +20934,7 @@ function readValidatedPlanV2Materialization(planDir, expectedTarget) {
20692
20934
  for (const artifact of required) {
20693
20935
  if (Object.hasOwn(remoteSources, artifact.path)) continue;
20694
20936
  const path = join44(planDir, ...artifact.path.split("/"));
20695
- if (!existsSync28(path) || statSync12(path).size !== artifact.sizeBytes) {
20937
+ if (!existsSync28(path) || statSync13(path).size !== artifact.sizeBytes) {
20696
20938
  throw new PlanV2IntegrityError(
20697
20939
  `materialized artifact missing or truncated: ${artifact.path}`
20698
20940
  );
@@ -21233,7 +21475,10 @@ async function renderChunk(planDir, chunkIndex, outputChunkPath, options) {
21233
21475
  const captureSession = session;
21234
21476
  session = null;
21235
21477
  verifyStarted = Date.now();
21236
- overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount2()) ? encodeWhileCapturing(encodeInput, framesInChunk) : null;
21478
+ overlap.current = canEncodeWhileCapturing(encodeInput, chunkWorkerCount, usableCpuCount3()) ? encodeWhileCapturing(encodeInput, framesInChunk, {
21479
+ workerCount: chunkWorkerCount,
21480
+ cpuCount: usableCpuCount3()
21481
+ }) : null;
21237
21482
  await observeRenderStage(
21238
21483
  new RenderObservabilityRecorder({ pipelineStartMs: start, log }),
21239
21484
  "capture_chunk",
@@ -21438,7 +21683,11 @@ async function renderSpan(projectDir, config, span, outputPath, options = {}) {
21438
21683
  projectDir,
21439
21684
  { ...config, rejectOnSystemFonts: false, failClosedFontFetch: false },
21440
21685
  planDir,
21441
- { chunksCarryAudio: true, allowOutsideProjectAssets: options.allowOutsideProjectAssets }
21686
+ {
21687
+ chunksCarryAudio: true,
21688
+ allowOutsideProjectAssets: options.allowOutsideProjectAssets,
21689
+ includeOutsideScripts: options.includeOutsideScripts
21690
+ }
21442
21691
  );
21443
21692
  const { startFrame, endFrame } = spanFrameRange(
21444
21693
  span.startSeconds,
@@ -21487,7 +21736,9 @@ var SAFE_RENDER_ERROR_CODES = /* @__PURE__ */ new Set([
21487
21736
  "RENDER_TOO_SLOW",
21488
21737
  "RENDER_STAGE_STALLED",
21489
21738
  "PAGE_NEVER_READY",
21490
- "VARIABLES_INVALID"
21739
+ "VARIABLES_INVALID",
21740
+ "OUTPUT_DIMENSIONS_MISMATCH",
21741
+ "COMPOSITION_TOO_LARGE"
21491
21742
  ]);
21492
21743
  function extractSafeRenderErrorCode(error) {
21493
21744
  if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
@@ -21547,6 +21798,12 @@ function validateDistributedRenderConfig(config) {
21547
21798
  `must be one of ${DISTRIBUTED_FPS2.join(", ")}; got ${String(config.fps)}`
21548
21799
  );
21549
21800
  }
21801
+ if (config.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(config.expectedOutputDimensions)) {
21802
+ throw new InvalidConfigError(
21803
+ "config.expectedOutputDimensions",
21804
+ "must contain positive integer width and height"
21805
+ );
21806
+ }
21550
21807
  validateIntDimension("config.width", config.width);
21551
21808
  validateIntDimension("config.height", config.height);
21552
21809
  if (config.pageMotionBlur !== void 0 && config.pageMotionBlur !== "off") {
@@ -21900,6 +22157,11 @@ function assertRequestOptionScalars(options) {
21900
22157
  }
21901
22158
  function assertRequestOptionObjects(options) {
21902
22159
  validateEngineConfigSnapshot2(options.engineConfig);
22160
+ if (options.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(options.expectedOutputDimensions)) {
22161
+ throw new Error(
22162
+ "Render request expectedOutputDimensions must contain positive integer width and height"
22163
+ );
22164
+ }
21903
22165
  if (options.variables !== void 0 && !isPlainObject(options.variables)) {
21904
22166
  throw new Error("Render request variables must be a JSON object");
21905
22167
  }
@@ -21965,7 +22227,8 @@ function renderConfigFromRequest(request, runtime = {}) {
21965
22227
  ...options,
21966
22228
  producerConfig: engineConfig,
21967
22229
  logger: runtime.logger,
21968
- allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true
22230
+ allowOutsideProjectAssets: runtime.allowOutsideProjectAssets === true,
22231
+ includeOutsideScripts: runtime.includeOutsideScripts === true
21969
22232
  };
21970
22233
  }
21971
22234
  function distributedFps(fps) {
@@ -22020,7 +22283,8 @@ function distributedConfigFromRequest(request, runtime = {}) {
22020
22283
  abortSignal: runtime.abortSignal,
22021
22284
  planDirSizeLimitBytes: distributed.planDirSizeLimitBytes,
22022
22285
  variables: options.variables,
22023
- strictVariables: options.strictVariables
22286
+ strictVariables: options.strictVariables,
22287
+ expectedOutputDimensions: options.expectedOutputDimensions
22024
22288
  };
22025
22289
  }
22026
22290
  function optionalProperty(key, value) {
@@ -22062,7 +22326,8 @@ function renderRequestFromDistributedConfig(input) {
22062
22326
  ...optionalProperty("strictness", config.strictness),
22063
22327
  ...optionalProperty("entryFile", config.entryFile),
22064
22328
  ...optionalProperty("variables", config.variables),
22065
- ...optionalProperty("strictVariables", config.strictVariables)
22329
+ ...optionalProperty("strictVariables", config.strictVariables),
22330
+ ...optionalProperty("expectedOutputDimensions", config.expectedOutputDimensions)
22066
22331
  };
22067
22332
  return createRenderRequest({
22068
22333
  projectDir: input.projectDir,
@@ -22099,7 +22364,7 @@ import {
22099
22364
  import {
22100
22365
  existsSync as existsSync32,
22101
22366
  mkdirSync as mkdirSync21,
22102
- statSync as statSync14,
22367
+ statSync as statSync15,
22103
22368
  mkdtempSync as mkdtempSync2,
22104
22369
  writeFileSync as writeFileSync14,
22105
22370
  rmSync as rmSync19,
@@ -22124,7 +22389,7 @@ import { isSafePath as isSafePath3 } from "@hyperframes/core/safe-path";
22124
22389
  import {
22125
22390
  existsSync as existsSync30,
22126
22391
  readFileSync as readFileSync16,
22127
- statSync as statSync13,
22392
+ statSync as statSync14,
22128
22393
  openSync as openSync7,
22129
22394
  fstatSync as fstatSync3,
22130
22395
  closeSync as closeSync7,
@@ -22165,7 +22430,7 @@ function readEntryHtml(filePath) {
22165
22430
  } catch (error) {
22166
22431
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
22167
22432
  return null;
22168
- if (!statSync13(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22433
+ if (!statSync14(filePath, { throwIfNoEntry: false })?.isFile()) return null;
22169
22434
  throw error;
22170
22435
  }
22171
22436
  try {
@@ -22181,7 +22446,7 @@ function leavesProject(absProjectDir, absoluteEntryPath, isAllowedEntry) {
22181
22446
  }
22182
22447
  function readProjectEntryFile(projectDir, preferredEntryFile, isAllowedEntry) {
22183
22448
  const absProjectDir = resolve11(projectDir);
22184
- if (!existsSync30(absProjectDir) || !statSync13(absProjectDir).isDirectory()) {
22449
+ if (!existsSync30(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22185
22450
  return { error: `Project directory not found: ${absProjectDir}` };
22186
22451
  }
22187
22452
  const entryCandidates = [preferredEntryFile, "index.html", "src/index.html"].filter(
@@ -22530,6 +22795,7 @@ function parseRenderOptions(body) {
22530
22795
  outputDynamicRange,
22531
22796
  variables,
22532
22797
  strictVariables,
22798
+ expectedOutputDimensions: isExpectedOutputDimensions(body.expectedOutputDimensions) ? body.expectedOutputDimensions : void 0,
22533
22799
  outputResolution,
22534
22800
  outputResolutionAspectAgnostic,
22535
22801
  videoFrameFormat
@@ -22569,6 +22835,7 @@ function buildRenderJobConfig(input, outputPath, log) {
22569
22835
  entryFile: input.entryFile,
22570
22836
  variables: input.variables,
22571
22837
  strictVariables: input.strictVariables,
22838
+ expectedOutputDimensions: input.expectedOutputDimensions,
22572
22839
  outputResolution: input.outputResolution,
22573
22840
  outputResolutionAspectAgnostic: input.outputResolutionAspectAgnostic,
22574
22841
  videoFrameFormat: input.videoFrameFormat,
@@ -22613,6 +22880,9 @@ function validateRenderOverrides(body) {
22613
22880
  if (body.variables !== void 0 && !isPlainObject2(body.variables)) {
22614
22881
  return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
22615
22882
  }
22883
+ if (body.expectedOutputDimensions !== void 0 && !isExpectedOutputDimensions(body.expectedOutputDimensions)) {
22884
+ return "expectedOutputDimensions must contain positive integer width and height";
22885
+ }
22616
22886
  if (body.strictVariables !== void 0 && typeof body.strictVariables !== "boolean") {
22617
22887
  return "strictVariables must be a boolean";
22618
22888
  }
@@ -22663,7 +22933,7 @@ function prepareProjectDirectory(projectDir, options, policy) {
22663
22933
  if (!candidate) return null;
22664
22934
  const absProjectDir = policy ? resolve12(policy.projectsDir, candidate) : resolve12(candidate);
22665
22935
  const shown = policy ? candidate : absProjectDir;
22666
- if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync14(absProjectDir).isDirectory()) {
22936
+ if (policy && !isAllowedProjectPath(policy.projectsDir, absProjectDir) || !existsSync32(absProjectDir) || !statSync15(absProjectDir).isDirectory()) {
22667
22937
  return { error: `Project directory not found: ${shown}` };
22668
22938
  }
22669
22939
  const entry = options.entryFile || "index.html";
@@ -22766,7 +23036,7 @@ function publicPerfSummary(job) {
22766
23036
  return job.perfSummary ? { ...job.perfSummary, renderId: void 0 } : null;
22767
23037
  }
22768
23038
  function outputFileSize(path) {
22769
- return existsSync32(path) ? statSync14(path).size : 0;
23039
+ return existsSync32(path) ? statSync15(path).size : 0;
22770
23040
  }
22771
23041
  function createBlockingProgressReporter(log, requestId) {
22772
23042
  let lastLoggedPct = -10;
@@ -22969,7 +23239,8 @@ function createRenderHandlers(options = {}) {
22969
23239
  outcome: job.outcome ?? "completed",
22970
23240
  warnings: job.warnings,
22971
23241
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
22972
- ...strictVariablesResult(job)
23242
+ ...strictVariablesResult(job),
23243
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
22973
23244
  });
22974
23245
  } catch (error) {
22975
23246
  const durationMs = Date.now() - t0;
@@ -23066,7 +23337,8 @@ function createRenderHandlers(options = {}) {
23066
23337
  warnings: job.warnings,
23067
23338
  perf: policy ? publicPerfSummary(job) : job.perfSummary ?? null,
23068
23339
  producerVersion: readProducerVersion(),
23069
- ...strictVariablesResult(job)
23340
+ ...strictVariablesResult(job),
23341
+ ...job.outputDimensionsChecked === void 0 ? {} : { outputDimensionsChecked: job.outputDimensionsChecked }
23070
23342
  })
23071
23343
  });
23072
23344
  } catch (error) {
@@ -23095,7 +23367,7 @@ function createRenderHandlers(options = {}) {
23095
23367
  store.delete(token);
23096
23368
  return c.json({ success: false, error: "Output artifact file missing" }, 404);
23097
23369
  }
23098
- const stats = statSync14(artifact.path);
23370
+ const stats = statSync15(artifact.path);
23099
23371
  return new Response(createReadStream5(artifact.path), {
23100
23372
  headers: {
23101
23373
  "content-type": "video/mp4",
@@ -23296,7 +23568,7 @@ import {
23296
23568
  readFileSync as readFileSync17,
23297
23569
  readdirSync as readdirSync12,
23298
23570
  rmSync as rmSync20,
23299
- statSync as statSync15,
23571
+ statSync as statSync16,
23300
23572
  writeFileSync as writeFileSync15
23301
23573
  } from "node:fs";
23302
23574
  import { basename as basename8, dirname as dirname22, join as join50 } from "node:path";
@@ -23341,7 +23613,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23341
23613
  outputPath,
23342
23614
  durationMs: Date.now() - start,
23343
23615
  framesEncoded: plan2.totalFrames,
23344
- fileSize: statSync15(outputPath).size
23616
+ fileSize: statSync16(outputPath).size
23345
23617
  };
23346
23618
  }
23347
23619
  const format = plan2.dimensions.format;
@@ -23388,7 +23660,7 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23388
23660
  });
23389
23661
  }
23390
23662
  }
23391
- const fileSize = existsSync33(outputPath) ? statSync15(outputPath).size : 0;
23663
+ const fileSize = existsSync33(outputPath) ? statSync16(outputPath).size : 0;
23392
23664
  return {
23393
23665
  ...referenceBackgroundResult8(plan2[REFERENCE_BACKGROUND_FIELD6]),
23394
23666
  outputPath,
@@ -23586,7 +23858,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23586
23858
  mkdirSync22(outputPath, { recursive: true });
23587
23859
  let globalIdx = 0;
23588
23860
  for (const chunkDir of chunkPaths) {
23589
- if (!statSync15(chunkDir).isDirectory()) {
23861
+ if (!statSync16(chunkDir).isDirectory()) {
23590
23862
  throw new Error(
23591
23863
  `[assemble] png-sequence chunk must be a directory: ${chunkDir} (got a file)`
23592
23864
  );
@@ -23613,7 +23885,7 @@ function mergePngFrameDirs(chunkPaths, outputPath, totalFrames, audioPath, start
23613
23885
  let fileSize = 0;
23614
23886
  for (const name of readdirSync12(outputPath)) {
23615
23887
  try {
23616
- fileSize += statSync15(join50(outputPath, name)).size;
23888
+ fileSize += statSync16(join50(outputPath, name)).size;
23617
23889
  } catch {
23618
23890
  }
23619
23891
  }