@hyperframes/producer 0.9.72 → 0.9.74

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.
@@ -7114,92 +7114,7 @@ import { privateCacheRoot } from "@hyperframes/engine";
7114
7114
  import { suggestMatchingPreset } from "@hyperframes/core";
7115
7115
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
7116
7116
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
7117
-
7118
- // src/services/compositionSizeLimit.ts
7119
- import { statSync as statSync6 } from "node:fs";
7120
- var MAX_COMPOSITION_HTML_BYTES = 16 * 1024 * 1024;
7121
- var COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE";
7122
- var megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
7123
- var MAX_EXPANDED_COMPOSITION_BYTES = 4 * MAX_COMPOSITION_HTML_BYTES;
7124
- var MAX_COMPOSITION_MOUNTS = 1e4;
7125
- var CompositionTooLargeError = class extends Error {
7126
- constructor(message, publicMetadata) {
7127
- super(message);
7128
- this.publicMetadata = publicMetadata;
7129
- this.name = "CompositionTooLargeError";
7130
- }
7131
- publicMetadata;
7132
- code = COMPOSITION_TOO_LARGE;
7133
- // The producer server reads these off the error for the wire envelope.
7134
- owner = "user";
7135
- retryable = false;
7136
- };
7137
- var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
7138
- `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.`,
7139
- { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
7140
- );
7141
- var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
7142
- var REMOTE_SCRIPTS = "remote scripts";
7143
- var REMOTE_STYLESHEETS = "remote stylesheets";
7144
- function generatedTooLarge(file, bytes) {
7145
- if (file === "composition variables") {
7146
- return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
7147
- }
7148
- if (file === "variable media sources") {
7149
- return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
7150
- }
7151
- if (file === REMOTE_SCRIPTS || file === REMOTE_STYLESHEETS) {
7152
- return `Inlined ${file} add up to ${megabytes(bytes)}. ${limitText}. Bundle scripts and fonts with the project, or link each one once.`;
7153
- }
7154
- return `Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ${megabytes(bytes)}. One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts and style rules, keep data-composition-id values short, or mount scenes fewer times.`;
7155
- }
7156
- var CompositionExpansionBudget = class {
7157
- bytes = 0;
7158
- mounts = 0;
7159
- generated = 0;
7160
- /** `bytes` may be negative when a reserved upper bound is settled to the real size. */
7161
- chargeGenerated(file, bytes) {
7162
- this.generated += bytes;
7163
- if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
7164
- throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
7165
- bytes: this.generated,
7166
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
7167
- exceeded: "generated"
7168
- });
7169
- }
7170
- chargeGeneratedIfItFits(bytes) {
7171
- if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
7172
- this.generated += bytes;
7173
- return true;
7174
- }
7175
- charge(file, bytes) {
7176
- this.bytes += bytes;
7177
- this.mounts += 1;
7178
- if (this.bytes <= MAX_EXPANDED_COMPOSITION_BYTES && this.mounts <= MAX_COMPOSITION_MOUNTS) {
7179
- return;
7180
- }
7181
- throw new CompositionTooLargeError(
7182
- `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.`,
7183
- {
7184
- bytes: this.bytes,
7185
- limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
7186
- mounts: this.mounts,
7187
- exceeded: this.mounts > MAX_COMPOSITION_MOUNTS ? "mounts" : "bytes"
7188
- }
7189
- );
7190
- }
7191
- };
7192
- function assertCompositionFileSize(path, file) {
7193
- let bytes;
7194
- try {
7195
- const stats = statSync6(path);
7196
- if (!stats.isFile()) return;
7197
- bytes = stats.size;
7198
- } catch {
7199
- return;
7200
- }
7201
- if (bytes > MAX_COMPOSITION_HTML_BYTES) throw fileTooLarge(file, bytes);
7202
- }
7117
+ import { assertCompositionFileSize as assertCompositionFileSize2 } from "@hyperframes/core/compiler";
7203
7118
 
7204
7119
  // src/services/htmlCompiler.ts
7205
7120
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
@@ -7217,7 +7132,7 @@ import {
7217
7132
  stylesheetLinkMatches
7218
7133
  } from "@hyperframes/parsers/css-url-scans";
7219
7134
  import { createHash as createHash6 } from "node:crypto";
7220
- import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8 } from "fs";
7135
+ import { createReadStream as createReadStream3, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync8, statSync as statSync8 } from "fs";
7221
7136
  import { join as join21, dirname as dirname9, resolve as resolve8, basename as basename6, relative as relative3, sep as sep4 } from "path";
7222
7137
  import { parseHTML as parseHTML5 } from "linkedom";
7223
7138
 
@@ -7295,6 +7210,13 @@ import {
7295
7210
  } from "@hyperframes/parsers/asset-resolution";
7296
7211
  import { isPrivateFileUnder as isPrivateFileUnder2, isStudioPrivatePath as isStudioPrivatePath2 } from "@hyperframes/core/safe-path";
7297
7212
  import { linksOutside as linksOutside2 } from "@hyperframes/studio-server/outside-file";
7213
+ import {
7214
+ assertCompositionFileSize,
7215
+ CompositionExpansionBudget,
7216
+ ENTRY_PAGE,
7217
+ REMOTE_SCRIPTS,
7218
+ REMOTE_STYLESHEETS
7219
+ } from "@hyperframes/core/compiler";
7298
7220
 
7299
7221
  // src/services/renderMediaCollector.ts
7300
7222
  import { parseHTML as parseHTML2 } from "linkedom";
@@ -7489,7 +7411,7 @@ import {
7489
7411
 
7490
7412
  // src/services/animatedGifPrep.ts
7491
7413
  import { createHash as createHash4 } from "node:crypto";
7492
- import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync7 } from "node:fs";
7414
+ import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync6, rmSync as rmSync9, statSync as statSync6 } from "node:fs";
7493
7415
  import { dirname as dirname6, isAbsolute as isAbsolute3, join as join18, resolve as resolve6 } from "node:path";
7494
7416
  import { parseHTML as parseHTML3 } from "linkedom";
7495
7417
  import { parseAnimatedGifMetadata } from "@hyperframes/core";
@@ -7548,7 +7470,7 @@ function resolveLocalImageSourcePath(src, options) {
7548
7470
  }
7549
7471
  function isUsableFile(path) {
7550
7472
  try {
7551
- const stat = statSync7(path);
7473
+ const stat = statSync6(path);
7552
7474
  return stat.isFile() && stat.size > 0;
7553
7475
  } catch {
7554
7476
  return false;
@@ -7813,7 +7735,7 @@ import {
7813
7735
  readFileSync as readFileSync7,
7814
7736
  readSync as readSync3,
7815
7737
  rmSync as rmSync10,
7816
- statSync as statSync8,
7738
+ statSync as statSync7,
7817
7739
  writeFileSync as writeFileSync3
7818
7740
  } from "node:fs";
7819
7741
  import { dirname as dirname7, join as join19, resolve as resolve7 } from "node:path";
@@ -8057,7 +7979,7 @@ function resolveImageSource(src, options) {
8057
7979
  }
8058
7980
  function isUsableFile2(path) {
8059
7981
  try {
8060
- return statSync8(path).size > 0;
7982
+ return statSync7(path).size > 0;
8061
7983
  } catch {
8062
7984
  return false;
8063
7985
  }
@@ -8544,16 +8466,64 @@ function detectShaderTransitionUsage(html) {
8544
8466
  }
8545
8467
  return false;
8546
8468
  }
8547
- async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, probes, assetRoot) {
8469
+ var MAX_REMOTE_ASSETS = 1e3;
8470
+ var ASSET_DOWNLOADS_AT_ONCE = 8;
8471
+ var AssetDownloads = class {
8472
+ reserved = /* @__PURE__ */ new Set();
8473
+ running = 0;
8474
+ queued = [];
8475
+ ended = new AbortController();
8476
+ signal;
8477
+ constructor(cancel) {
8478
+ this.signal = cancel ? AbortSignal.any([cancel, this.ended.signal]) : this.ended.signal;
8479
+ }
8480
+ /** Stops every download still running or queued: the compile that owns them has returned. */
8481
+ end() {
8482
+ this.ended.abort(new Error("The compile that started this download has ended"));
8483
+ }
8484
+ /** Throws before any of `urls` downloads when they would take the compile past the cap. */
8485
+ reserve(urls) {
8486
+ this.signal?.throwIfAborted();
8487
+ const fresh = new Set([...urls].filter((url) => !this.reserved.has(url)));
8488
+ if (this.reserved.size + fresh.size > MAX_REMOTE_ASSETS) {
8489
+ throw new Error(
8490
+ `The composition links more than ${MAX_REMOTE_ASSETS} remote media, image and font files; at most ${MAX_REMOTE_ASSETS} are downloaded at compile time`
8491
+ );
8492
+ }
8493
+ for (const url of fresh) this.reserved.add(url);
8494
+ }
8495
+ async download(url, destDir) {
8496
+ while (this.running >= ASSET_DOWNLOADS_AT_ONCE) {
8497
+ await new Promise((resolve12) => this.queued.push(resolve12));
8498
+ }
8499
+ if (this.signal?.aborted) {
8500
+ this.queued.shift()?.();
8501
+ this.signal.throwIfAborted();
8502
+ }
8503
+ this.running += 1;
8504
+ try {
8505
+ return await downloadToTemp(url, destDir, void 0, this.signal, void 0, {
8506
+ onTelemetry: logRemoteDownloadTelemetry
8507
+ });
8508
+ } finally {
8509
+ this.running -= 1;
8510
+ this.queued.shift()?.();
8511
+ }
8512
+ }
8513
+ };
8514
+ var downloadAsset = (url, destDir, assets) => assets ? assets.download(url, destDir) : downloadToTemp(url, destDir, void 0, void 0, void 0, {
8515
+ onTelemetry: logRemoteDownloadTelemetry
8516
+ });
8517
+ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, baseDir, downloadDir, tagName, elementIdentity, log, urlByAbsentLocalPath, run, assetRoot) {
8548
8518
  let filePath = src;
8549
8519
  if (isHttpUrl(src)) {
8550
8520
  const remoteDir = join21(downloadDir, REMOTE_MEDIA_SUBDIR);
8551
8521
  if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
8522
+ run?.assets.reserve([src]);
8552
8523
  try {
8553
- filePath = await downloadToTemp(src, remoteDir, void 0, void 0, void 0, {
8554
- onTelemetry: logRemoteDownloadTelemetry
8555
- });
8556
- } catch {
8524
+ filePath = await downloadAsset(src, remoteDir, run?.assets);
8525
+ } catch (err) {
8526
+ if (run?.assets.signal?.aborted) throw err;
8557
8527
  return { duration: null, resolvedPath: src };
8558
8528
  }
8559
8529
  } else {
@@ -8581,13 +8551,17 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8581
8551
  const probe = () => withMediaProbeSlot(async () => {
8582
8552
  try {
8583
8553
  await assertMediaPayload(filePath, elementIdentity);
8584
- const profile = await probeMediaProfile2(filePath);
8554
+ const signal = run?.assets.signal;
8555
+ const profile = await probeMediaProfile2(filePath, { signal });
8585
8556
  if (tagName === "video") {
8586
- return { profile, fileDuration: (await extractMediaMetadata(filePath)).durationSeconds };
8557
+ const { durationSeconds } = await extractMediaMetadata(filePath, { signal });
8558
+ return { profile, fileDuration: durationSeconds };
8587
8559
  }
8588
8560
  try {
8589
- return { profile, fileDuration: (await extractAudioMetadata(filePath)).durationSeconds };
8561
+ const { durationSeconds } = await extractAudioMetadata(filePath, { signal });
8562
+ return { profile, fileDuration: durationSeconds };
8590
8563
  } catch {
8564
+ if (signal?.aborted) throw signal.reason;
8591
8565
  return { profile, fileDuration: null };
8592
8566
  }
8593
8567
  } catch (error) {
@@ -8595,10 +8569,10 @@ async function resolveMediaDuration(src, mediaStart, playbackRate, projectDir, b
8595
8569
  }
8596
8570
  });
8597
8571
  const key = `${tagName}\0${filePath}`;
8598
- let probed = probes?.get(key);
8572
+ let probed = run?.probes.get(key);
8599
8573
  if (!probed) {
8600
8574
  probed = probe();
8601
- probes?.set(key, probed);
8575
+ run?.probes.set(key, probed);
8602
8576
  }
8603
8577
  const outcome = await probed;
8604
8578
  if ("error" in outcome) {
@@ -8637,12 +8611,13 @@ function markInferredVariableMediaDurations(html, unresolvedMedia) {
8637
8611
  }
8638
8612
  return changed ? document2.toString() : html;
8639
8613
  }
8640
- async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, probes, assetRoot) {
8614
+ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlByAbsentLocalPath, run, assetRoot) {
8641
8615
  const { html: staticCompiled, unresolved } = compileTimingAttrs(html);
8642
8616
  const mediaUnresolved = unresolved.filter(
8643
8617
  (el) => (el.tagName === "video" || el.tagName === "audio") && el.src
8644
8618
  );
8645
8619
  const unresolvedCompositions = unresolved.filter((el) => el.tagName === "div");
8620
+ run?.assets.reserve(mediaUnresolved.map((el) => el.src).filter(isHttpUrl));
8646
8621
  const resolvedResults = await Promise.all(
8647
8622
  mediaUnresolved.map(
8648
8623
  (el) => resolveMediaDuration(
@@ -8656,7 +8631,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8656
8631
  el.id,
8657
8632
  log,
8658
8633
  urlByAbsentLocalPath,
8659
- probes,
8634
+ run,
8660
8635
  assetRoot
8661
8636
  ).then(({ duration }) => ({ id: el.id, duration }))
8662
8637
  )
@@ -8668,8 +8643,10 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8668
8643
  let compiledHtml = resolutions.length > 0 ? injectDurations(markedStaticHtml, resolutions) : markedStaticHtml;
8669
8644
  const preResolved = extractResolvedMedia(compiledHtml);
8670
8645
  const hiddenVideoIds = collectHiddenVideoIds(compiledHtml);
8646
+ const clampable = preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id));
8647
+ run?.assets.reserve(clampable.map((el) => el.src).filter(isHttpUrl));
8671
8648
  const clampResults = await Promise.all(
8672
- preResolved.filter((el) => !!el.src && !el.loop && !hiddenVideoIds.has(el.id)).map(async (el) => {
8649
+ clampable.map(async (el) => {
8673
8650
  const { duration: maxDuration } = await resolveMediaDuration(
8674
8651
  el.src,
8675
8652
  el.mediaStart,
@@ -8681,7 +8658,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8681
8658
  el.id,
8682
8659
  log,
8683
8660
  void 0,
8684
- probes,
8661
+ run,
8685
8662
  assetRoot
8686
8663
  );
8687
8664
  return { id: el.id, tagName: el.tagName, duration: el.duration, maxDuration, src: el.src };
@@ -8704,7 +8681,7 @@ async function compileHtmlFile(html, projectDir, baseDir, downloadDir, log, urlB
8704
8681
  compiledHtml = stripCrossoriginAttr(compiledHtml, "audio");
8705
8682
  return { html: compiledHtml, unresolvedCompositions };
8706
8683
  }
8707
- async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, probes, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8684
+ async function parseSubCompositions(html, projectDir, downloadDir, visited = /* @__PURE__ */ new Set(), urlByAbsentLocalPath, run, assetRoot, outsideFiles = {}, compiledSrcs = /* @__PURE__ */ new Set()) {
8708
8685
  const subCompositions = /* @__PURE__ */ new Map();
8709
8686
  const { document: document2 } = parseHTML5(html);
8710
8687
  const compEls = document2.querySelectorAll("[data-composition-src]");
@@ -8739,7 +8716,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8739
8716
  downloadDir,
8740
8717
  void 0,
8741
8718
  urlByAbsentLocalPath,
8742
- probes,
8719
+ run,
8743
8720
  assetRoot
8744
8721
  );
8745
8722
  const nested = await parseSubCompositions(
@@ -8748,7 +8725,7 @@ async function parseSubCompositions(html, projectDir, downloadDir, visited = /*
8748
8725
  downloadDir,
8749
8726
  item.nestedVisited,
8750
8727
  urlByAbsentLocalPath,
8751
- probes,
8728
+ run,
8752
8729
  assetRoot,
8753
8730
  outsideFiles,
8754
8731
  compiledSrcs
@@ -8806,13 +8783,28 @@ function promoteCssImportsToLinkTags(html) {
8806
8783
  return document2.toString();
8807
8784
  }
8808
8785
  var ProducerHostIdentityMap = class extends Map {
8809
- #document;
8810
8786
  #lateInstanceByCompositionId = /* @__PURE__ */ new Map();
8787
+ /** How many elements carry each composition id: the page once, then each mount's copy once. */
8788
+ #idCounts = /* @__PURE__ */ new Map();
8789
+ /** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */
8790
+ #uncounted;
8811
8791
  constructor(document2, initialHosts) {
8812
8792
  super(assignBundledRuntimeCompositionIds(initialHosts));
8813
- this.#document = document2;
8793
+ this.#uncounted = [document2];
8794
+ }
8795
+ #countUncopied() {
8796
+ for (const root of this.#uncounted.splice(0)) {
8797
+ for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) {
8798
+ this.#adjust(element.getAttribute("data-composition-id"), 1);
8799
+ }
8800
+ }
8801
+ }
8802
+ #adjust(id, by) {
8803
+ if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by);
8814
8804
  }
8815
8805
  get(host) {
8806
+ this.#countUncopied();
8807
+ this.#uncounted.push(host);
8816
8808
  const existing = super.get(host);
8817
8809
  if (existing) return existing;
8818
8810
  const authoredCompositionId = (host.getAttribute("data-hf-original-composition-id") || host.getAttribute("data-composition-id") || "").trim() || null;
@@ -8821,17 +8813,19 @@ var ProducerHostIdentityMap = class extends Map {
8821
8813
  this.set(host, identity2);
8822
8814
  return identity2;
8823
8815
  }
8816
+ const ownId = host.getAttribute("data-composition-id");
8817
+ const heldByOthers = (id) => (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0;
8824
8818
  let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
8825
8819
  let runtimeCompositionId;
8826
8820
  do {
8827
8821
  instanceIndex += 1;
8828
8822
  runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
8829
- } while (Array.from(this.#document.querySelectorAll("[data-composition-id]")).some(
8830
- (element) => element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId
8831
- ));
8823
+ } while (heldByOthers(runtimeCompositionId));
8832
8824
  this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
8833
8825
  host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
8834
8826
  host.setAttribute("data-composition-id", runtimeCompositionId);
8827
+ this.#adjust(ownId, -1);
8828
+ this.#adjust(runtimeCompositionId, 1);
8835
8829
  const identity = { authoredCompositionId, runtimeCompositionId };
8836
8830
  this.set(host, identity);
8837
8831
  return identity;
@@ -8889,6 +8883,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
8889
8883
  }
8890
8884
  function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
8891
8885
  const { document: document2 } = parseHTML5(html);
8886
+ budget.chargeElements(ENTRY_PAGE, document2.querySelectorAll("*").length);
8892
8887
  const head = document2.querySelector("head");
8893
8888
  const body = document2.querySelector("body");
8894
8889
  const hosts = Array.from(document2.querySelectorAll("[data-composition-src]"));
@@ -8946,6 +8941,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8946
8941
  return compHtml;
8947
8942
  },
8948
8943
  chargeEmitted: (srcPath, bytes) => budget.chargeGenerated(srcPath, bytes),
8944
+ chargeElements: (srcPath, count) => budget.chargeElements(srcPath, count),
8949
8945
  parseHtml: (htmlStr) => parseHTML5(htmlStr).document,
8950
8946
  // Mirrors the preview bundler: a sub-composition's SIBLING assets resolve
8951
8947
  // against its own directory, project-root refs stay as authored.
@@ -9274,18 +9270,18 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
9274
9270
  };
9275
9271
  }
9276
9272
  var REMOTE_MEDIA_SUBDIR = "_remote_media";
9277
- async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, extraRewrite) {
9273
+ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLabel, assets, extraRewrite) {
9274
+ assets?.reserve(urlSet);
9278
9275
  if (urlSet.size === 0) return { html, remoteMediaAssets: /* @__PURE__ */ new Map() };
9279
9276
  if (!existsSync11(remoteDir)) mkdirSync9(remoteDir, { recursive: true });
9280
9277
  const urlToLocal = /* @__PURE__ */ new Map();
9281
9278
  await Promise.all(
9282
9279
  [...urlSet].map(async (url) => {
9283
9280
  try {
9284
- const localPath = await downloadToTemp(url, remoteDir, void 0, void 0, void 0, {
9285
- onTelemetry: logRemoteDownloadTelemetry
9286
- });
9281
+ const localPath = await downloadAsset(url, remoteDir, assets);
9287
9282
  urlToLocal.set(url, localPath);
9288
9283
  } catch (err) {
9284
+ if (assets?.signal?.aborted) throw err;
9289
9285
  const identity = safeDownloadUrlIdentity(url);
9290
9286
  defaultLogger.warn(`[Compiler] ${warnLabel}, using original URL as fallback.`, {
9291
9287
  urlFingerprint: identity.urlFingerprint,
@@ -9311,14 +9307,15 @@ async function downloadAndRewriteUrls(urlSet, html, remoteDir, warnLabel, logLab
9311
9307
  defaultLogger.debug(`[Compiler] ${logLabel} ${urlToLocal.size} to ${REMOTE_MEDIA_SUBDIR}/`);
9312
9308
  return { html: result, remoteMediaAssets };
9313
9309
  }
9314
- async function localizeRemoteMediaSources(html, downloadDir) {
9310
+ async function localizeRemoteMediaSources(html, downloadDir, assets) {
9315
9311
  const urlSet = /* @__PURE__ */ new Set([...remoteSrcUrls(html, "media"), ...remoteSrcUrls(html, "source")]);
9316
9312
  const localized = await downloadAndRewriteUrls(
9317
9313
  urlSet,
9318
9314
  html,
9319
9315
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9320
9316
  "Remote media download failed",
9321
- "Localized remote media source(s)"
9317
+ "Localized remote media source(s)",
9318
+ assets
9322
9319
  );
9323
9320
  return { ...localized, html: dropBindingOnLocalizedMedia(localized.html) };
9324
9321
  }
@@ -9334,17 +9331,18 @@ function dropBindingOnLocalizedMedia(html) {
9334
9331
  }
9335
9332
  return changed ? document2.toString() : html;
9336
9333
  }
9337
- async function localizeRemoteImageSources(html, downloadDir) {
9334
+ async function localizeRemoteImageSources(html, downloadDir, assets) {
9338
9335
  const urlSet = new Set(remoteSrcUrls(html, "img"));
9339
9336
  return downloadAndRewriteUrls(
9340
9337
  urlSet,
9341
9338
  html,
9342
9339
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9343
9340
  "Remote image download failed",
9344
- "Localized remote image source(s)"
9341
+ "Localized remote image source(s)",
9342
+ assets
9345
9343
  );
9346
9344
  }
9347
- async function localizeRemoteBackgroundImages(html, downloadDir) {
9345
+ async function localizeRemoteBackgroundImages(html, downloadDir, assets) {
9348
9346
  const urlSet = /* @__PURE__ */ new Set();
9349
9347
  for (const { parts } of remoteBackgroundUrlMatches(html)) {
9350
9348
  if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
@@ -9355,6 +9353,7 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
9355
9353
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9356
9354
  "Remote background-image download failed",
9357
9355
  "Localized remote background-image(s)",
9356
+ assets,
9358
9357
  // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default
9359
9358
  // replaceAll; this handles the unquoted url(https://..) form.
9360
9359
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
@@ -9508,13 +9507,14 @@ function collectFontFaceUrls(html) {
9508
9507
  }
9509
9508
  return urlSet;
9510
9509
  }
9511
- function localizeFontFaceUrls(html, downloadDir) {
9510
+ function localizeFontFaceUrls(html, downloadDir, assets) {
9512
9511
  return downloadAndRewriteUrls(
9513
9512
  collectFontFaceUrls(html),
9514
9513
  html,
9515
9514
  join21(downloadDir, REMOTE_MEDIA_SUBDIR),
9516
9515
  "Remote font download failed",
9517
9516
  "Localized remote font face(s)",
9517
+ assets,
9518
9518
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
9519
9519
  );
9520
9520
  }
@@ -9532,16 +9532,24 @@ async function readLocalFont(absPath) {
9532
9532
  }
9533
9533
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
9534
9534
  }
9535
- async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
9536
- const absPath = localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath);
9537
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
9538
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9539
- return void 0;
9535
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log, downloadedPath, reserve) {
9536
+ const absPath = downloadedPath ?? (localPath.startsWith("/") ? localPath : resolve8(projectDir, localPath));
9537
+ if (downloadedPath === void 0) {
9538
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) {
9539
+ return void 0;
9540
+ }
9541
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
9542
+ return void 0;
9543
+ }
9544
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9540
9545
  }
9541
- if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
9542
9546
  if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
9543
9547
  const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
9544
9548
  try {
9549
+ if (!reserve(Math.ceil(statSync8(absPath).size / 3) * 4 + 64)) {
9550
+ dataUriByAbsolutePath.set(absPath, void 0);
9551
+ return void 0;
9552
+ }
9545
9553
  const font = await readLocalFont(absPath);
9546
9554
  if (font.kind === "file-backed") {
9547
9555
  dataUriByAbsolutePath.set(absPath, void 0);
@@ -9565,9 +9573,26 @@ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsol
9565
9573
  }
9566
9574
  }
9567
9575
  var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
9568
- async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
9576
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger, downloadedFonts = /* @__PURE__ */ new Map()) {
9569
9577
  const dataUriByPath = /* @__PURE__ */ new Map();
9570
9578
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
9579
+ let warned = false;
9580
+ const keptFileBacked = (localPath) => {
9581
+ if (warned) return;
9582
+ warned = true;
9583
+ log.warn(
9584
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9585
+ );
9586
+ };
9587
+ let reserved = 0;
9588
+ const reserveFor = (localPath) => (bytes) => {
9589
+ if (reserved + bytes > budget.generatedRoom) {
9590
+ keptFileBacked(localPath);
9591
+ return false;
9592
+ }
9593
+ reserved += bytes;
9594
+ return true;
9595
+ };
9571
9596
  for (const { parts: style } of styleBlockMatches(html)) {
9572
9597
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
9573
9598
  for (const { parts } of localFontFaceUrlMatches(face[1])) {
@@ -9575,24 +9600,26 @@ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = de
9575
9600
  if (!localPath || dataUriByPath.has(localPath)) continue;
9576
9601
  dataUriByPath.set(
9577
9602
  localPath,
9578
- await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
9603
+ await localFontDataUri(
9604
+ localPath,
9605
+ projectDir,
9606
+ assetRoot,
9607
+ dataUriByAbsolutePath,
9608
+ log,
9609
+ downloadedFonts.get(localPath),
9610
+ reserveFor(localPath)
9611
+ )
9579
9612
  );
9580
9613
  }
9581
9614
  }
9582
9615
  }
9583
9616
  if (![...dataUriByPath.values()].some(Boolean)) return html;
9584
- let warned = false;
9585
9617
  const embed = (source, localPath) => {
9586
9618
  const dataUri = dataUriByPath.get(localPath);
9587
9619
  if (!dataUri) return source;
9588
9620
  const inlined = `url("${dataUri}")`;
9589
9621
  if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
9590
- if (!warned) {
9591
- warned = true;
9592
- log.warn(
9593
- `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
9594
- );
9595
- }
9622
+ keptFileBacked(localPath);
9596
9623
  return source;
9597
9624
  };
9598
9625
  return replaceMatches(
@@ -9698,6 +9725,14 @@ function bindVariableMediaSources(html, variables, budget, log) {
9698
9725
  }
9699
9726
  var entryFileName = (projectDir, htmlPath) => isPathInside(htmlPath, projectDir) ? relative3(projectDir, htmlPath).split(sep4).join("/") : basename6(htmlPath);
9700
9727
  async function compileForRender(projectDir, htmlPath, downloadDir, options = {}) {
9728
+ const assets = new AssetDownloads(options.abortSignal);
9729
+ try {
9730
+ return await compileWithAssets(projectDir, htmlPath, downloadDir, options, assets);
9731
+ } finally {
9732
+ assets.end();
9733
+ }
9734
+ }
9735
+ async function compileWithAssets(projectDir, htmlPath, downloadDir, options, assets) {
9701
9736
  const assetRoot = options.allowOutsideProjectAssets ? void 0 : projectDir;
9702
9737
  const outsideFiles = { includeScripts: options.includeOutsideScripts };
9703
9738
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
@@ -9724,7 +9759,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9724
9759
  options.log
9725
9760
  );
9726
9761
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
9727
- const probes = /* @__PURE__ */ new Map();
9762
+ const run = { probes: /* @__PURE__ */ new Map(), assets };
9728
9763
  const { html: compiledHtml, unresolvedCompositions } = await compileHtmlFile(
9729
9764
  rawHtml,
9730
9765
  projectDir,
@@ -9732,7 +9767,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9732
9767
  downloadDir,
9733
9768
  options.log,
9734
9769
  options.urlByAbsentLocalPath,
9735
- probes,
9770
+ run,
9736
9771
  assetRoot
9737
9772
  );
9738
9773
  const { subCompositions } = await parseSubCompositions(
@@ -9741,7 +9776,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9741
9776
  downloadDir,
9742
9777
  void 0,
9743
9778
  options.urlByAbsentLocalPath,
9744
- probes,
9779
+ run,
9745
9780
  assetRoot,
9746
9781
  outsideFiles
9747
9782
  );
@@ -9794,11 +9829,12 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9794
9829
  );
9795
9830
  const { html: htmlWithLocalMedia, remoteMediaAssets } = await localizeRemoteMediaSources(
9796
9831
  htmlWithDeferredScripts,
9797
- downloadDir
9832
+ downloadDir,
9833
+ run.assets
9798
9834
  );
9799
- const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir);
9800
- const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir);
9801
- const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir);
9835
+ const { html: htmlWithLocalImages, remoteMediaAssets: remoteImageAssets } = await localizeRemoteImageSources(htmlWithLocalMedia, downloadDir, run.assets);
9836
+ const { html: htmlWithLocalBg, remoteMediaAssets: remoteBgAssets } = await localizeRemoteBackgroundImages(htmlWithLocalImages, downloadDir, run.assets);
9837
+ const { html: htmlWithLocalizedFonts, remoteMediaAssets: remoteFontAssets } = await localizeFontFaceUrls(htmlWithLocalBg, downloadDir, run.assets);
9802
9838
  const {
9803
9839
  html: htmlWithJpegs,
9804
9840
  preparedAssets: preparedHeifAssets,
@@ -9835,7 +9871,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9835
9871
  projectDir,
9836
9872
  assetRoot,
9837
9873
  budget,
9838
- options.log
9874
+ options.log,
9875
+ remoteFontAssets
9839
9876
  );
9840
9877
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
9841
9878
  embeddedHtml,
@@ -10308,7 +10345,7 @@ function resolveEntryHtmlPath(input) {
10308
10345
  `Entry file "${relative4(projectDir, path)}" leads outside the project folder`
10309
10346
  );
10310
10347
  }
10311
- assertCompositionFileSize(path, relative4(projectDir, path));
10348
+ assertCompositionFileSize2(path, relative4(projectDir, path));
10312
10349
  return readTextFile2(path);
10313
10350
  };
10314
10351
  const htmlPath = join22(projectDir, entryFile);
@@ -11573,13 +11610,19 @@ async function runExtractVideosStage(input) {
11573
11610
  const videoPath = resolveProjectRelativeSrc4(v.src, projectDir, compiledDir);
11574
11611
  if (!opensLocally(videoPath, assetRoots)) return null;
11575
11612
  try {
11576
- const attempted = extractionPolicy.maxTransientRetries === 0 ? { result: await extractMediaMetadata4(videoPath), retries: 0 } : await runVideoExtractionWithRetry2(() => extractMediaMetadata4(videoPath), {
11577
- signal: abortSignal,
11578
- maxTransientRetries: extractionPolicy.maxTransientRetries,
11579
- onRetry: () => {
11580
- hdrProbeTransientRetries += 1;
11613
+ const attempted = extractionPolicy.maxTransientRetries === 0 ? {
11614
+ result: await extractMediaMetadata4(videoPath, { signal: abortSignal }),
11615
+ retries: 0
11616
+ } : await runVideoExtractionWithRetry2(
11617
+ () => extractMediaMetadata4(videoPath, { signal: abortSignal }),
11618
+ {
11619
+ signal: abortSignal,
11620
+ maxTransientRetries: extractionPolicy.maxTransientRetries,
11621
+ onRetry: () => {
11622
+ hdrProbeTransientRetries += 1;
11623
+ }
11581
11624
  }
11582
- });
11625
+ );
11583
11626
  const meta = attempted.result;
11584
11627
  if (isHdrColorSpace2(meta.colorSpace)) {
11585
11628
  nativeHdrVideoIds.add(v.id);
@@ -11774,7 +11817,7 @@ async function appendVideoAudioFromProbe(input) {
11774
11817
  videos.map(async (video) => {
11775
11818
  const readFrom = isHttpUrl3(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
11776
11819
  if (readFrom === null) return null;
11777
- const metadata = await extractMediaMetadata4(readFrom);
11820
+ const metadata = await extractMediaMetadata4(readFrom, { signal: input.signal });
11778
11821
  const window2 = await resolveFinalFrameExtractionWindow2(
11779
11822
  readFrom,
11780
11823
  video,