@hyperframes/producer 0.9.65 → 0.9.66

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.
@@ -2472,6 +2472,16 @@ var fileTooLarge = (file, bytes) => new CompositionTooLargeError(
2472
2472
  `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.`,
2473
2473
  { bytes, limitBytes: MAX_COMPOSITION_HTML_BYTES }
2474
2474
  );
2475
+ var limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)}`;
2476
+ function generatedTooLarge(file, bytes) {
2477
+ if (file === "composition variables") {
2478
+ return `Composition variable styles add up to ${megabytes(bytes)}. ${limitText}. Shorten the variable values or declare them on fewer elements.`;
2479
+ }
2480
+ if (file === "variable media sources") {
2481
+ return `Variable-bound media sources add up to ${megabytes(bytes)}. ${limitText}. Use shorter URLs or bind fewer elements.`;
2482
+ }
2483
+ 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.`;
2484
+ }
2475
2485
  var CompositionExpansionBudget = class {
2476
2486
  bytes = 0;
2477
2487
  mounts = 0;
@@ -2480,10 +2490,16 @@ var CompositionExpansionBudget = class {
2480
2490
  chargeGenerated(file, bytes) {
2481
2491
  this.generated += bytes;
2482
2492
  if (this.generated <= MAX_EXPANDED_COMPOSITION_BYTES) return;
2483
- throw new CompositionTooLargeError(
2484
- `Scripts and styles generated for sub-composition mounts, ending at "${file}", add up to ${megabytes(this.generated)}. 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.`,
2485
- { bytes: this.generated, limitBytes: MAX_EXPANDED_COMPOSITION_BYTES, exceeded: "generated" }
2486
- );
2493
+ throw new CompositionTooLargeError(generatedTooLarge(file, this.generated), {
2494
+ bytes: this.generated,
2495
+ limitBytes: MAX_EXPANDED_COMPOSITION_BYTES,
2496
+ exceeded: "generated"
2497
+ });
2498
+ }
2499
+ chargeGeneratedIfItFits(bytes) {
2500
+ if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
2501
+ this.generated += bytes;
2502
+ return true;
2487
2503
  }
2488
2504
  charge(file, bytes) {
2489
2505
  this.bytes += bytes;
@@ -4195,7 +4211,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
4195
4211
  }
4196
4212
  return document2.toString();
4197
4213
  }
4198
- function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles) {
4214
+ function inlineSubCompositions(html, subCompositions, projectDir, variableOverrides, assetRoot, outsideFiles, budget) {
4199
4215
  const { document: document2 } = parseHTML5(html);
4200
4216
  const head = document2.querySelector("head");
4201
4217
  const body = document2.querySelector("body");
@@ -4204,11 +4220,11 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4204
4220
  const emitted = emitRootCompositionVariableStyles(
4205
4221
  document2,
4206
4222
  {},
4207
- variableOverrides
4223
+ variableOverrides,
4224
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
4208
4225
  );
4209
4226
  return { html: emitted ? document2.toString() : html, variablesByComp: {} };
4210
4227
  }
4211
- const budget = new CompositionExpansionBudget();
4212
4228
  const readOnce = /* @__PURE__ */ new Map();
4213
4229
  const readMountHtml = (srcPath) => {
4214
4230
  const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
@@ -4243,6 +4259,10 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4243
4259
  hostIdentityMap: hostIdentityByElement,
4244
4260
  readVariableDefaults: readDeclaredDefaults,
4245
4261
  parseHostVariables: parseHostVariableValues,
4262
+ resolveFilePath: (srcPath) => {
4263
+ const file = resolveCompositionFile(projectDir, srcPath, assetRoot);
4264
+ return file && relative2(projectDir, file).split(sep3).join("/");
4265
+ },
4246
4266
  resolveHtml: (srcPath) => {
4247
4267
  const compHtml = resolveMountHtml(srcPath);
4248
4268
  if (compHtml) budget.charge(srcPath, Buffer.byteLength(compHtml));
@@ -4333,7 +4353,8 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
4333
4353
  emitRootCompositionVariableStyles(
4334
4354
  document2,
4335
4355
  result.variablesByComp,
4336
- variableOverrides
4356
+ variableOverrides,
4357
+ { chargeBytes: (bytes) => budget.chargeGenerated("composition variables", bytes) }
4337
4358
  );
4338
4359
  assignMediaRenderIds(document2);
4339
4360
  return { html: document2.toString(), variablesByComp: result.variablesByComp };
@@ -4755,10 +4776,6 @@ function localizeFontFaceUrls(html, downloadDir) {
4755
4776
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
4756
4777
  );
4757
4778
  }
4758
- function urlOccurrenceRe(localPath) {
4759
- const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4760
- return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
4761
- }
4762
4779
  var MAX_LOCAL_FONT_DATA_URI_BYTES = 5 * 1024 * 1024;
4763
4780
  async function readLocalFont(absPath) {
4764
4781
  const chunks = [];
@@ -4773,59 +4790,83 @@ async function readLocalFont(absPath) {
4773
4790
  }
4774
4791
  return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
4775
4792
  }
4776
- async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
4777
- const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
4778
- let result = html;
4779
- const embeddedPaths = /* @__PURE__ */ new Set();
4793
+ async function localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log) {
4794
+ const absPath = localPath.startsWith("/") ? localPath : resolve6(projectDir, localPath);
4795
+ if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return void 0;
4796
+ if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
4797
+ return void 0;
4798
+ }
4799
+ if (isPrivateCompositionFile(projectDir, absPath)) return void 0;
4800
+ if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
4801
+ const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
4802
+ try {
4803
+ const font = await readLocalFont(absPath);
4804
+ if (font.kind === "file-backed") {
4805
+ dataUriByAbsolutePath.set(absPath, void 0);
4806
+ defaultLogger.debug(
4807
+ `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
4808
+ );
4809
+ return void 0;
4810
+ }
4811
+ const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
4812
+ const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
4813
+ dataUriByAbsolutePath.set(absPath, dataUri);
4814
+ defaultLogger.debug(
4815
+ `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
4816
+ );
4817
+ return dataUri;
4818
+ } catch (error) {
4819
+ defaultLogger.warn(
4820
+ `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
4821
+ );
4822
+ return void 0;
4823
+ }
4824
+ }
4825
+ var replaceInner = (whole, inner, tail, next) => whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
4826
+ async function embedLocalFontFaces(html, projectDir, assetRoot, budget, log = defaultLogger) {
4827
+ const dataUriByPath = /* @__PURE__ */ new Map();
4780
4828
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
4781
- const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
4782
4829
  for (const { parts: style } of styleBlockMatches(html)) {
4783
4830
  for (const { parts: face } of fontFaceBlockMatches(style[1])) {
4784
- const block = face[1];
4785
- for (const { parts } of localFontFaceUrlMatches(block)) {
4831
+ for (const { parts } of localFontFaceUrlMatches(face[1])) {
4786
4832
  const localPath = parts[1];
4787
- if (!localPath || embeddedPaths.has(localPath)) continue;
4788
- const absPath = localPath.startsWith("/") ? localPath : resolve6(projectDir, localPath);
4789
- if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
4790
- if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
4791
- embeddedPaths.add(localPath);
4792
- continue;
4793
- }
4794
- if (isPrivateCompositionFile(projectDir, absPath)) continue;
4795
- const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
4796
- try {
4797
- if (fileBackedAbsolutePaths.has(absPath)) {
4798
- embeddedPaths.add(localPath);
4799
- continue;
4800
- }
4801
- let dataUri = dataUriByAbsolutePath.get(absPath);
4802
- if (!dataUri) {
4803
- const font = await readLocalFont(absPath);
4804
- if (font.kind === "file-backed") {
4805
- fileBackedAbsolutePaths.add(absPath);
4806
- defaultLogger.debug(
4807
- `[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`
4808
- );
4809
- embeddedPaths.add(localPath);
4810
- continue;
4811
- }
4812
- dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
4813
- dataUriByAbsolutePath.set(absPath, dataUri);
4814
- defaultLogger.debug(
4815
- `[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB \u2192 data URI)`
4816
- );
4817
- }
4818
- result = result.replace(urlOccurrenceRe(localPath), `url("${dataUri}")`);
4819
- embeddedPaths.add(localPath);
4820
- } catch (error) {
4821
- defaultLogger.warn(
4822
- `[Compiler] Could not embed local font ${localPath}: ${error instanceof Error ? error.message : String(error)}`
4823
- );
4824
- }
4833
+ if (!localPath || dataUriByPath.has(localPath)) continue;
4834
+ dataUriByPath.set(
4835
+ localPath,
4836
+ await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log)
4837
+ );
4825
4838
  }
4826
4839
  }
4827
4840
  }
4828
- return result;
4841
+ if (![...dataUriByPath.values()].some(Boolean)) return html;
4842
+ let warned = false;
4843
+ const embed = (source, localPath) => {
4844
+ const dataUri = dataUriByPath.get(localPath);
4845
+ if (!dataUri) return source;
4846
+ const inlined = `url("${dataUri}")`;
4847
+ if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
4848
+ if (!warned) {
4849
+ warned = true;
4850
+ log.warn(
4851
+ `[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`
4852
+ );
4853
+ }
4854
+ return source;
4855
+ };
4856
+ return replaceMatches(
4857
+ html,
4858
+ styleBlockMatches(html),
4859
+ (style, css) => replaceInner(
4860
+ style,
4861
+ css,
4862
+ "</style>".length,
4863
+ replaceMatches(
4864
+ css,
4865
+ fontFaceBlockMatches(css),
4866
+ (face, body) => replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed))
4867
+ )
4868
+ )
4869
+ );
4829
4870
  }
4830
4871
  function renderGsapDist() {
4831
4872
  try {
@@ -4851,32 +4892,42 @@ function rewriteUnresolvableGsapToCdn(html, projectDir, compSrcPath) {
4851
4892
  return `${prefix}${gsapDist}${file}${suffix}`;
4852
4893
  });
4853
4894
  }
4854
- function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath) {
4895
+ function rebaseDirectEntryAssetPaths(html, projectDir, htmlPath, budget) {
4855
4896
  if (!isPathInside(htmlPath, projectDir)) return html;
4856
4897
  const entryPath = relative2(projectDir, htmlPath).replace(/\\/g, "/");
4857
4898
  if (!entryPath.includes("/")) return html;
4858
4899
  const { document: document2 } = parseHTML5(html);
4859
4900
  const assetExists = projectAssetExists(projectDir);
4901
+ const charge = (bytes) => budget.chargeGenerated(entryPath, bytes);
4860
4902
  rewriteAssetPaths(
4861
4903
  document2.querySelectorAll("[src], [href], [srcset]"),
4862
4904
  entryPath,
4863
4905
  (el, attr) => el.getAttribute(attr),
4864
4906
  (el, attr, value) => el.setAttribute(attr, value),
4865
- assetExists
4907
+ assetExists,
4908
+ charge
4866
4909
  );
4867
4910
  rewriteInlineStyleAssetUrls(
4868
4911
  document2.querySelectorAll("[style]"),
4869
4912
  entryPath,
4870
4913
  (el) => el.getAttribute("style"),
4871
4914
  (el, value) => el.setAttribute("style", value),
4872
- assetExists
4915
+ assetExists,
4916
+ charge
4873
4917
  );
4874
4918
  for (const style of document2.querySelectorAll("style")) {
4875
- style.textContent = rewriteCssAssetUrls(style.textContent || "", entryPath, assetExists);
4919
+ style.textContent = rewriteCssAssetUrls(
4920
+ style.textContent || "",
4921
+ entryPath,
4922
+ assetExists,
4923
+ charge
4924
+ );
4876
4925
  }
4877
4926
  return document2.toString();
4878
4927
  }
4879
- function bindVariableMediaSources(html, variables) {
4928
+ var MAX_VARIABLE_MEDIA_SRC_BYTES = 8 * 1024;
4929
+ var MEDIA_SRC_CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
4930
+ function bindVariableMediaSources(html, variables, budget, log) {
4880
4931
  if (!html.includes("data-var-src")) return html;
4881
4932
  const { document: document2 } = parseHTML5(html);
4882
4933
  const declared = {};
@@ -4887,8 +4938,17 @@ function bindVariableMediaSources(html, variables) {
4887
4938
  let changed = false;
4888
4939
  for (const el of document2.querySelectorAll("video[data-var-src], audio[data-var-src]")) {
4889
4940
  if (el.closest("[data-variable-values]")) continue;
4890
- const src = boundMediaSrc(el, values);
4891
- if (src === null || el.getAttribute("src") === src) continue;
4941
+ const bound = boundMediaSrc(el, values);
4942
+ if (bound === null) continue;
4943
+ const src = bound.trim();
4944
+ if (src.length > MAX_VARIABLE_MEDIA_SRC_BYTES || MEDIA_SRC_CONTROL_CHARS.test(src)) {
4945
+ log?.warn("[Compiler] Refused a variable media source that cannot be a URL", {
4946
+ length: src.length
4947
+ });
4948
+ continue;
4949
+ }
4950
+ if (el.getAttribute("src") === src) continue;
4951
+ budget.chargeGenerated("variable media sources", src.length);
4892
4952
  el.setAttribute("src", src);
4893
4953
  changed = true;
4894
4954
  }
@@ -4908,10 +4968,18 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4908
4968
  throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
4909
4969
  }
4910
4970
  assertCompositionFileSize(htmlPath, basename3(htmlPath));
4911
- const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
4971
+ const budget = new CompositionExpansionBudget();
4972
+ const entryHtml = rebaseDirectEntryAssetPaths(
4973
+ readTextFile(htmlPath),
4974
+ projectDir,
4975
+ htmlPath,
4976
+ budget
4977
+ );
4912
4978
  const rawHtml = bindVariableMediaSources(
4913
4979
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
4914
- options.variables ?? {}
4980
+ options.variables ?? {},
4981
+ budget,
4982
+ options.log
4915
4983
  );
4916
4984
  assertSubCompositionsUsable(rawHtml, projectDir, assetRoot, outsideFiles);
4917
4985
  const probes = /* @__PURE__ */ new Map();
@@ -4942,7 +5010,8 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4942
5010
  projectDir,
4943
5011
  options.variables ?? {},
4944
5012
  assetRoot,
4945
- outsideFiles
5013
+ outsideFiles,
5014
+ budget
4946
5015
  );
4947
5016
  const sanitizedHtml = stripPreloadNone(inlinedHtml);
4948
5017
  const renderModeHints = detectRenderModeHints(sanitizedHtml, options.pageMotionBlur);
@@ -5021,6 +5090,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
5021
5090
  htmlWithPreparedGifs,
5022
5091
  projectDir,
5023
5092
  assetRoot,
5093
+ budget,
5024
5094
  options.log
5025
5095
  );
5026
5096
  const { html, externalAssets } = options.allowOutsideProjectAssets ? collectExternalAssets(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": "0.1.0",
3
3
  "buildId": "dev",
4
- "sha256": "26bc2c53086737e056afd7751aeee6ff6f019d5c4a9e820a7d055c46b5737c73",
4
+ "sha256": "2a9e26f5b780e1f414573d4a7d513e409ef718f508650c18f6e32a52069b68a1",
5
5
  "artifacts": {
6
6
  "iife": "hyperframe.runtime.iife.js",
7
7
  "esm": "hyperframe.runtime.mjs"