@hyperframes/producer 0.9.51 → 0.9.53

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/README.md CHANGED
@@ -38,6 +38,24 @@ await startServer({ port: 8080 });
38
38
  // POST /render or /render/stream with projectDir, html, or previewUrl (public HTTPS only) and render options
39
39
  ```
40
40
 
41
+ A browser request (one that carries an `Origin` or `Sec-Fetch-Site` header) is accepted
42
+ only under an IP address, `localhost` or a `*.localhost` name, so a page that points its
43
+ own domain at the server cannot start renders or lint. If browsers reach the server
44
+ through a proxy name, list that name in `allowedHosts` or in the comma-separated
45
+ `PRODUCER_ALLOWED_HOSTS` variable. Requests without those headers, such as curl or
46
+ another service, are unaffected.
47
+
48
+ The server listens on `127.0.0.1` unless you pass `hostname` or set `PRODUCER_HOST`. To
49
+ listen on any other address, also set `authToken` or `PRODUCER_AUTH_TOKEN`. Every route
50
+ except `/health` then requires `Authorization: Bearer <token>`, and the server refuses to
51
+ start without one. A request's `projectDir` must resolve, symlinks included, inside
52
+ `projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
53
+ must stay inside that project, and `outputPath` must be inside `rendersDir`
54
+ (`PRODUCER_RENDERS_DIR`, default `/tmp`). `debug: true` is refused unless you set
55
+ `allowDebug` or `PRODUCER_ALLOW_DEBUG=1`. `createProducerApp` applies these path and
56
+ debug checks by default. `createRenderHandlers`, for mounting the handlers inside your own
57
+ trusted service, applies them only with `confineRequests: true`.
58
+
41
59
  Both HTTP routes accept optional `pageMotionBlur: "off"` to disable authored page
42
60
  motion blur. Omit it to preserve the composition's behavior. Other explicit values
43
61
  are rejected before a render starts. This is separate from engine sub-frame
@@ -329,6 +329,7 @@ var MIME_TYPES = {
329
329
  ".css": "text/css; charset=utf-8",
330
330
  ".js": "application/javascript; charset=utf-8",
331
331
  ".mjs": "application/javascript; charset=utf-8",
332
+ ".cjs": "application/javascript; charset=utf-8",
332
333
  ".json": "application/json; charset=utf-8",
333
334
  ".cube": "text/plain; charset=utf-8",
334
335
  ".png": "image/png",
@@ -868,6 +869,10 @@ function createFileServer(options) {
868
869
  const bodyScripts = options.bodyScripts ?? [buildRenderModeScript(options.fps), HF_BRIDGE_SCRIPT];
869
870
  const app = new Hono();
870
871
  const warnLeftOut = (line) => console.warn(`[FileServer] ${line}`);
872
+ app.use(async function loadEachFileOnlyAsItsNamedType(c, next) {
873
+ await next();
874
+ c.res.headers.set("X-Content-Type-Options", "nosniff");
875
+ });
871
876
  app.get("/*", async (c) => {
872
877
  let requestPath = c.req.path;
873
878
  if (requestPath === "/") requestPath = "/index.html";
@@ -1055,6 +1060,9 @@ import {
1055
1060
  import {
1056
1061
  mediaIdPathSegment
1057
1062
  } from "@hyperframes/engine";
1063
+ function audioWorkDir(workDir) {
1064
+ return join3(workDir, "audio-work");
1065
+ }
1058
1066
  var BROWSER_MEDIA_EPSILON = 1e-4;
1059
1067
  function resolveBrowserMediaEnd(start, end, duration) {
1060
1068
  return Number.isFinite(duration) && duration > 0 ? start + duration : end;
@@ -2220,12 +2228,26 @@ import {
2220
2228
  // src/services/render/stages/compileStage.ts
2221
2229
  import { existsSync as existsSync8, writeFileSync as writeFileSync3 } from "node:fs";
2222
2230
  import { join as join10, relative as relative3 } from "node:path";
2231
+ import { privateCacheRoot } from "@hyperframes/engine";
2223
2232
  import { suggestMatchingPreset } from "@hyperframes/core";
2224
2233
  import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
2225
2234
  import { readTextFile as readTextFile2 } from "@hyperframes/parsers/asset-resolution";
2226
2235
 
2227
2236
  // src/services/htmlCompiler.ts
2228
2237
  import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
2238
+ import {
2239
+ cssRuleMatches,
2240
+ cssUrlMatches,
2241
+ fontFaceBlockMatches,
2242
+ hasBackgroundImageDeclaration,
2243
+ importRuleMatches,
2244
+ localFontFaceUrlMatches,
2245
+ remoteBackgroundUrlMatches,
2246
+ remoteFontFaceUrlMatches,
2247
+ replaceMatches,
2248
+ styleBlockMatches,
2249
+ stylesheetLinkMatches
2250
+ } from "@hyperframes/parsers/css-url-scans";
2229
2251
  import { createHash as createHash5 } from "node:crypto";
2230
2252
  import { createReadStream as createReadStream2, existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5 } from "fs";
2231
2253
  import { join as join9, dirname as dirname6, resolve as resolve6, basename as basename3, relative as relative2, sep as sep3 } from "path";
@@ -2251,7 +2273,6 @@ import {
2251
2273
  extractResolvedMedia,
2252
2274
  clampDurations,
2253
2275
  shouldClampResolvedMediaDuration,
2254
- CSS_URL_RE,
2255
2276
  isNonRelativeUrl,
2256
2277
  parseStrictFiniteTimingNumber,
2257
2278
  readMediaStart,
@@ -3329,10 +3350,16 @@ function normalizeCompositionSrcs(html, projectDir) {
3329
3350
  return `${name}${quote}${relative2(projectDir, file).split(sep3).join("/")}${quote}`;
3330
3351
  });
3331
3352
  }
3332
- function resolveCompositionFile(projectDir, src, assetRoot) {
3353
+ var COMPOSITION_FILE = /\.html?$/i;
3354
+ var NOT_A_COMPOSITION_FILE = "it is not an .html file, so it is refused";
3355
+ function resolveCompositionPath(projectDir, src, assetRoot) {
3333
3356
  const file = resolveCompositionSrc(projectDir, src);
3334
3357
  return file === null || escapesAssetRoot(file, assetRoot) ? null : file;
3335
3358
  }
3359
+ function resolveCompositionFile(projectDir, src, assetRoot) {
3360
+ const file = resolveCompositionPath(projectDir, src, assetRoot);
3361
+ return file !== null && COMPOSITION_FILE.test(file) ? file : null;
3362
+ }
3336
3363
  var isPrivateCompositionFile = (projectDir, filePath) => isPrivateFileUnder2(projectDir, filePath, isVcsOrSecretPath2);
3337
3364
  function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @__PURE__ */ new Set()) {
3338
3365
  const { document: document2 } = parseHTML5(html);
@@ -3342,7 +3369,7 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
3342
3369
  const srcPath = el.getAttribute("data-composition-src");
3343
3370
  if (!srcPath) continue;
3344
3371
  if (isUnresolvedAssetPlaceholder(srcPath)) continue;
3345
- const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot);
3372
+ const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot);
3346
3373
  if (filePath === null) {
3347
3374
  problems.push({ srcPath, detail: "it is outside the project folder" });
3348
3375
  continue;
@@ -3355,6 +3382,10 @@ function assertSubCompositionsUsable(html, projectDir, assetRoot, visited = /* @
3355
3382
  problems.push({ srcPath, detail: "it is git metadata or an env file" });
3356
3383
  continue;
3357
3384
  }
3385
+ if (!COMPOSITION_FILE.test(filePath)) {
3386
+ problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE });
3387
+ continue;
3388
+ }
3358
3389
  if (visited.has(filePath)) continue;
3359
3390
  const read = readProjectFile(filePath);
3360
3391
  if (read.kind === "missing") {
@@ -3450,7 +3481,6 @@ var THREE_D_CONTEXT_PATTERN = /transform-style\s*:\s*preserve-3d|backface-visibi
3450
3481
  function detectThreeDTransformUsage(html) {
3451
3482
  return THREE_D_CONTEXT_PATTERN.test(html);
3452
3483
  }
3453
- var BACKGROUND_IMAGE_DECL_PATTERN = /(?:^|;|\{)\s*background(?:-image)?\s*:[^;}]*(?:\bgradient\s*\(|url\s*\()/i;
3454
3484
  function detectAncestorBackgroundImage(html) {
3455
3485
  const { document: document2 } = parseHTML5(html);
3456
3486
  const root = document2.querySelector("[data-composition-id]");
@@ -3462,13 +3492,13 @@ function detectAncestorBackgroundImage(html) {
3462
3492
  }
3463
3493
  for (const el of ancestors) {
3464
3494
  const style = el.getAttribute("style");
3465
- if (style && BACKGROUND_IMAGE_DECL_PATTERN.test(`{${style}}`)) return true;
3495
+ if (style && hasBackgroundImageDeclaration(`{${style}}`)) return true;
3466
3496
  }
3467
3497
  for (const styleEl of document2.querySelectorAll("style")) {
3468
3498
  const css = styleEl.textContent ?? "";
3469
- for (const rule of css.matchAll(/([^{}]+)\{([^}]*)\}/g)) {
3470
- const [, selectorList = "", declarations = ""] = rule;
3471
- if (!BACKGROUND_IMAGE_DECL_PATTERN.test(`{${declarations}}`)) continue;
3499
+ for (const { parts: rule } of cssRuleMatches(css)) {
3500
+ const [, selectorList, declarations] = rule;
3501
+ if (!hasBackgroundImageDeclaration(`{${declarations}}`)) continue;
3472
3502
  for (const selector of selectorList.split(",")) {
3473
3503
  const sel = selector.trim();
3474
3504
  if (!sel || sel.startsWith("@")) continue;
@@ -3789,7 +3819,6 @@ function coalesceHeadStylesAndBodyScripts(html) {
3789
3819
  el.textContent = dedupedStyles[i] ?? "";
3790
3820
  });
3791
3821
  const styleEls = head ? Array.from(head.querySelectorAll("style")) : [];
3792
- const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
3793
3822
  for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
3794
3823
  const imports = [];
3795
3824
  const cssParts = [];
@@ -3797,7 +3826,7 @@ function coalesceHeadStylesAndBodyScripts(html) {
3797
3826
  for (const el of run) {
3798
3827
  const raw = (el.textContent || "").trim();
3799
3828
  if (!raw) continue;
3800
- const nonImportCss = raw.replace(importRe, (match) => {
3829
+ const nonImportCss = replaceMatches(raw, importRuleMatches(raw), (match) => {
3801
3830
  const cleaned = match.trim();
3802
3831
  if (!seenImports.has(cleaned)) {
3803
3832
  seenImports.add(cleaned);
@@ -4107,7 +4136,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
4107
4136
  for (const styleEl of document2.querySelectorAll("style")) {
4108
4137
  const css = styleEl.textContent || "";
4109
4138
  if (!css.includes("url(")) continue;
4110
- const rewritten = css.replace(CSS_URL_RE, (full, quote, rawUrl) => {
4139
+ const rewritten = replaceMatches(css, cssUrlMatches(css), (full, quote, rawUrl) => {
4111
4140
  const result = processPath((rawUrl || "").trim());
4112
4141
  if (!result) return full;
4113
4142
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -4117,7 +4146,7 @@ function collectExternalAssets(html, projectDir, log = defaultLogger, file = "in
4117
4146
  for (const el of document2.querySelectorAll("[style]")) {
4118
4147
  const style = el.getAttribute("style") || "";
4119
4148
  if (!style.includes("url(")) continue;
4120
- const rewritten = style.replace(CSS_URL_RE, (full, quote, rawUrl) => {
4149
+ const rewritten = replaceMatches(style, cssUrlMatches(style), (full, quote, rawUrl) => {
4121
4150
  const result = processPath((rawUrl || "").trim());
4122
4151
  if (!result) return full;
4123
4152
  return `url(${quote || ""}${result}${quote || ""})`;
@@ -4220,13 +4249,10 @@ async function localizeRemoteImageSources(html, downloadDir) {
4220
4249
  "Localized remote image source(s)"
4221
4250
  );
4222
4251
  }
4223
- var REMOTE_BG_URL_RE = /background(?:-image)?\s*:\s*[^;}"']*?url\(\s*["']?(https?:\/\/[^"')]+)["']?\s*\)/gi;
4224
4252
  async function localizeRemoteBackgroundImages(html, downloadDir) {
4225
4253
  const urlSet = /* @__PURE__ */ new Set();
4226
- const re = new RegExp(REMOTE_BG_URL_RE.source, REMOTE_BG_URL_RE.flags);
4227
- let m;
4228
- while ((m = re.exec(html)) !== null) {
4229
- if (m[1] && !isGoogleFontsUrl(m[1])) urlSet.add(m[1]);
4254
+ for (const { parts } of remoteBackgroundUrlMatches(html)) {
4255
+ if (parts[1] && !isGoogleFontsUrl(parts[1])) urlSet.add(parts[1]);
4230
4256
  }
4231
4257
  return downloadAndRewriteUrls(
4232
4258
  urlSet,
@@ -4239,7 +4265,6 @@ async function localizeRemoteBackgroundImages(html, downloadDir) {
4239
4265
  (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`)
4240
4266
  );
4241
4267
  }
4242
- var REMOTE_FONTFACE_URL_RE = /url\(["']?(https?:\/\/[^"')]+)["']?\)/gi;
4243
4268
  function isGoogleFontsUrl(href) {
4244
4269
  try {
4245
4270
  const host = new URL(href).hostname.toLowerCase();
@@ -4267,31 +4292,33 @@ async function fetchExternalStylesheetCss(href) {
4267
4292
  }
4268
4293
  function extractFontFaceBlocks(css) {
4269
4294
  const blocks = [];
4295
+ const closes = matchingBraces(css);
4270
4296
  const atRule = /@font-face\s*/gi;
4271
- let m;
4272
- while ((m = atRule.exec(css)) !== null) {
4273
- const openIdx = css.indexOf("{", m.index + m[0].length);
4274
- if (openIdx === -1) break;
4275
- let depth = 1;
4276
- let i = openIdx + 1;
4277
- for (; i < css.length && depth > 0; i++) {
4278
- if (css[i] === "{") depth++;
4279
- else if (css[i] === "}") depth--;
4280
- }
4281
- if (depth === 0) {
4282
- blocks.push(css.slice(m.index, i));
4283
- atRule.lastIndex = i;
4284
- }
4297
+ let open2 = -1;
4298
+ for (let m = atRule.exec(css); m; m = atRule.exec(css)) {
4299
+ if (open2 < atRule.lastIndex) open2 = css.indexOf("{", atRule.lastIndex);
4300
+ if (open2 === -1) break;
4301
+ const close = closes.get(open2);
4302
+ if (close === void 0) continue;
4303
+ blocks.push(css.slice(m.index, close + 1));
4304
+ atRule.lastIndex = close + 1;
4285
4305
  }
4286
4306
  return blocks;
4287
4307
  }
4308
+ function matchingBraces(css) {
4309
+ const closes = /* @__PURE__ */ new Map();
4310
+ const unclosed = [];
4311
+ for (let i = 0; i < css.length; i++) {
4312
+ if (css[i] === "{") unclosed.push(i);
4313
+ else if (css[i] === "}" && unclosed.length > 0) closes.set(unclosed.pop(), i);
4314
+ }
4315
+ return closes;
4316
+ }
4288
4317
  async function inlineExternalFontStylesheets(html) {
4289
- const linkRe = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
4290
4318
  const hrefRe = /\bhref=["']([^"']+)["']/i;
4291
4319
  const linkMatches = [];
4292
- let linkMatch;
4293
- while ((linkMatch = linkRe.exec(html)) !== null) {
4294
- const tag = linkMatch[0];
4320
+ for (const { parts } of stylesheetLinkMatches(html)) {
4321
+ const tag = parts[0];
4295
4322
  const hrefMatch = hrefRe.exec(tag);
4296
4323
  if (!hrefMatch?.[1]) continue;
4297
4324
  const href = hrefMatch[1];
@@ -4332,14 +4359,16 @@ ${fontFaceBlocks.join("\n")}
4332
4359
  }
4333
4360
  function projectStylesheetFontFamilies(html, projectDir) {
4334
4361
  const families = [];
4335
- for (const [tag] of html.matchAll(/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi)) {
4362
+ for (const {
4363
+ parts: [tag]
4364
+ } of stylesheetLinkMatches(html)) {
4336
4365
  const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1];
4337
4366
  if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue;
4338
4367
  const sheet = resolve6(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, ""));
4339
4368
  if (!isPathInside(sheet, projectDir) || !existsSync7(sheet)) continue;
4340
4369
  for (const face of extractFontFaceBlocks(readFileSync5(sheet, "utf8"))) {
4341
4370
  const family = /font-family\s*:\s*([^;}]+)/i.exec(face)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
4342
- const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => {
4371
+ const shipsFile = [...localFontFaceUrlMatches(face)].some(({ parts: [, url = ""] }) => {
4343
4372
  const path = decodedUrlPath(url);
4344
4373
  const file = path.startsWith("/") ? resolve6(projectDir, `.${path}`) : resolve6(dirname6(sheet), path);
4345
4374
  return isPathInside(file, projectDir) && existsSync7(file);
@@ -4350,11 +4379,9 @@ function projectStylesheetFontFamilies(html, projectDir) {
4350
4379
  return families;
4351
4380
  }
4352
4381
  function collectFontFaceUrls(html) {
4353
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
4354
4382
  const urlSet = /* @__PURE__ */ new Set();
4355
- let styleMatch;
4356
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
4357
- const cssText = styleMatch[1] ?? "";
4383
+ for (const { parts } of styleBlockMatches(html)) {
4384
+ const cssText = parts[1];
4358
4385
  let i = 0;
4359
4386
  while (i < cssText.length) {
4360
4387
  const atIdx = cssText.indexOf("@font-face", i);
@@ -4369,10 +4396,8 @@ function collectFontFaceUrls(html) {
4369
4396
  j++;
4370
4397
  }
4371
4398
  const block = cssText.slice(braceStart + 1, j - 1);
4372
- const urlRe = new RegExp(REMOTE_FONTFACE_URL_RE.source, REMOTE_FONTFACE_URL_RE.flags);
4373
- let urlMatch;
4374
- while ((urlMatch = urlRe.exec(block)) !== null) {
4375
- if (urlMatch[1]) urlSet.add(urlMatch[1]);
4399
+ for (const { parts: parts2 } of remoteFontFaceUrlMatches(block)) {
4400
+ if (parts2[1]) urlSet.add(parts2[1]);
4376
4401
  }
4377
4402
  i = j;
4378
4403
  }
@@ -4389,7 +4414,6 @@ function localizeFontFaceUrls(html, downloadDir) {
4389
4414
  (h, url, relPath) => h.replaceAll(`url(${url})`, `url("${relPath}")`)
4390
4415
  );
4391
4416
  }
4392
- var LOCAL_FONTFACE_URL_RE = /url\(["']?(?!data:|file:|https?:\/\/)([^"')]+)["']?\)/gi;
4393
4417
  function urlOccurrenceRe(localPath) {
4394
4418
  const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4395
4419
  return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
@@ -4410,23 +4434,15 @@ async function readLocalFont(absPath) {
4410
4434
  }
4411
4435
  async function embedLocalFontFaces(html, projectDir, assetRoot, log = defaultLogger) {
4412
4436
  const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
4413
- const styleBlockRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
4414
- const fontFaceRe = /@font-face\s*\{([^}]*)\}/gi;
4415
4437
  let result = html;
4416
4438
  const embeddedPaths = /* @__PURE__ */ new Set();
4417
4439
  const dataUriByAbsolutePath = /* @__PURE__ */ new Map();
4418
4440
  const fileBackedAbsolutePaths = /* @__PURE__ */ new Set();
4419
- let styleMatch;
4420
- while ((styleMatch = styleBlockRe.exec(html)) !== null) {
4421
- const cssText = styleMatch[1] ?? "";
4422
- const ffRe = new RegExp(fontFaceRe.source, fontFaceRe.flags);
4423
- let ffMatch;
4424
- while ((ffMatch = ffRe.exec(cssText)) !== null) {
4425
- const block = ffMatch[1] ?? "";
4426
- const urlRe = new RegExp(LOCAL_FONTFACE_URL_RE.source, LOCAL_FONTFACE_URL_RE.flags);
4427
- let urlMatch;
4428
- while ((urlMatch = urlRe.exec(block)) !== null) {
4429
- const localPath = urlMatch[1];
4441
+ for (const { parts: style } of styleBlockMatches(html)) {
4442
+ for (const { parts: face } of fontFaceBlockMatches(style[1])) {
4443
+ const block = face[1];
4444
+ for (const { parts } of localFontFaceUrlMatches(block)) {
4445
+ const localPath = parts[1];
4430
4446
  if (!localPath || embeddedPaths.has(localPath)) continue;
4431
4447
  const absPath = localPath.startsWith("/") ? localPath : resolve6(projectDir, localPath);
4432
4448
  if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
@@ -4545,6 +4561,9 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
4545
4561
  if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) {
4546
4562
  throw new Error(`Entry file ${htmlPath} leads outside the project folder`);
4547
4563
  }
4564
+ if (!COMPOSITION_FILE.test(htmlPath)) {
4565
+ throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`);
4566
+ }
4548
4567
  const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
4549
4568
  const rawHtml = bindVariableMediaSources(
4550
4569
  normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir),
@@ -5100,6 +5119,14 @@ async function recompileWithResolutions(compiled, resolutions, projectDir, downl
5100
5119
  }
5101
5120
 
5102
5121
  // src/services/render/stages/compileStage.ts
5122
+ function animatedGifCacheDir(extractCacheDir) {
5123
+ try {
5124
+ const root = extractCacheDir && privateCacheRoot(extractCacheDir);
5125
+ return root ? join10(root, "animated-gif") : void 0;
5126
+ } catch {
5127
+ return void 0;
5128
+ }
5129
+ }
5103
5130
  function adaptAspectAgnosticResolution(requested, aspectAgnostic, width, height, log) {
5104
5131
  if (!requested || !aspectAgnostic) return requested;
5105
5132
  const flipped = suggestMatchingPreset(width, height, requested);
@@ -5179,7 +5206,7 @@ async function runCompileStage(input) {
5179
5206
  variables: input.variables,
5180
5207
  urlByAbsentLocalPath: input.urlByAbsentLocalPath,
5181
5208
  pageMotionBlur: input.pageMotionBlur,
5182
- animatedGifCacheDir: cfg.extractCacheDir ? join10(cfg.extractCacheDir, "animated-gif") : void 0,
5209
+ animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
5183
5210
  ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
5184
5211
  allowOutsideProjectAssets: job.config.allowOutsideProjectAssets
5185
5212
  });
@@ -6059,6 +6086,10 @@ import {
6059
6086
  resolveVideoExtractionWindow as resolveVideoExtractionWindow2,
6060
6087
  isHttpUrl as isHttpUrl2,
6061
6088
  assertPublicHttpsUrl,
6089
+ downloadToTemp as downloadToTemp2,
6090
+ resolveRestrictPageNetwork,
6091
+ isUrlNotPermittedError,
6092
+ writeUrlDownloadTelemetry as writeUrlDownloadTelemetry2,
6062
6093
  resolveProjectRelativeSrc as resolveProjectRelativeSrc4,
6063
6094
  runVideoExtractionWithRetry as runVideoExtractionWithRetry2,
6064
6095
  safeVideoExtractionSourceIdentity,
@@ -6299,6 +6330,7 @@ async function runExtractVideosStage(input) {
6299
6330
  deferRangeExtraction,
6300
6331
  shownBoxes,
6301
6332
  urlByAbsentLocalPath,
6333
+ audioDownloadDir,
6302
6334
  skipFrameExtractionIds = []
6303
6335
  } = input;
6304
6336
  const stage2Start = Date.now();
@@ -6371,7 +6403,15 @@ async function runExtractVideosStage(input) {
6371
6403
  imageColorSpaces.push(...probed);
6372
6404
  }
6373
6405
  if (skipFrameExtractionIds.length > 0) {
6374
- await appendVideoAudioFromProbe({ projectDir, compiledDir, composition, urlByAbsentLocalPath });
6406
+ await appendVideoAudioFromProbe({
6407
+ projectDir,
6408
+ compiledDir,
6409
+ composition,
6410
+ urlByAbsentLocalPath,
6411
+ downloadDir: audioDownloadDir,
6412
+ signal: abortSignal,
6413
+ log
6414
+ });
6375
6415
  videoReadinessSkipIds = [...skipFrameExtractionIds];
6376
6416
  } else if (composition.videos.length > 0) {
6377
6417
  const totalVideos = composition.videos.length;
@@ -6478,17 +6518,37 @@ function isPublicHttpsUrl(url) {
6478
6518
  return false;
6479
6519
  }
6480
6520
  }
6521
+ function localProbeSource(src, input) {
6522
+ const path = resolveProjectRelativeSrc4(src, input.projectDir, input.compiledDir);
6523
+ const readFrom = input.urlByAbsentLocalPath?.get(path) ?? path;
6524
+ return isHttpUrl2(readFrom) || existsSync9(readFrom) ? readFrom : null;
6525
+ }
6526
+ async function remoteProbeSource(video, input) {
6527
+ if (!isPublicHttpsUrl(video.src)) return null;
6528
+ if (!resolveRestrictPageNetwork()) return video.src;
6529
+ if (!video.hasAudio || video.hidden) return null;
6530
+ const downloadDir = input.downloadDir ?? join12(input.compiledDir, REMOTE_MEDIA_SUBDIR);
6531
+ try {
6532
+ return await downloadToTemp2(video.src, downloadDir, void 0, input.signal, void 0, {
6533
+ onTelemetry: writeUrlDownloadTelemetry2
6534
+ });
6535
+ } catch (error) {
6536
+ if (!isUrlNotPermittedError(error)) throw error;
6537
+ input.log?.warn("Video sound skipped: its URL is outside the download address rules", {
6538
+ videoId: video.id
6539
+ });
6540
+ return null;
6541
+ }
6542
+ }
6481
6543
  async function appendVideoAudioFromProbe(input) {
6482
- const { projectDir, compiledDir, composition, urlByAbsentLocalPath } = input;
6544
+ const { composition } = input;
6483
6545
  const videos = composition.videos.filter(
6484
6546
  (video) => !isVideoPastTimelineEnd(video, composition.duration)
6485
6547
  );
6486
6548
  const probed = await Promise.all(
6487
6549
  videos.map(async (video) => {
6488
- if (isHttpUrl2(video.src) && !isPublicHttpsUrl(video.src)) return null;
6489
- const path = isHttpUrl2(video.src) ? video.src : resolveProjectRelativeSrc4(video.src, projectDir, compiledDir);
6490
- const readFrom = urlByAbsentLocalPath?.get(path) ?? path;
6491
- if (!isHttpUrl2(readFrom) && !existsSync9(readFrom)) return null;
6550
+ const readFrom = isHttpUrl2(video.src) ? await remoteProbeSource(video, input) : localProbeSource(video.src, input);
6551
+ if (readFrom === null) return null;
6492
6552
  const metadata = await extractMediaMetadata4(readFrom);
6493
6553
  const window2 = await resolveFinalFrameExtractionWindow2(
6494
6554
  readFrom,
@@ -7191,7 +7251,7 @@ async function mixAudioForDelivery(input, duration, pcmSourcePath) {
7191
7251
  audioResult = await processCompositionAudio(
7192
7252
  audios,
7193
7253
  projectDir,
7194
- join15(workDir, "audio-work"),
7254
+ audioWorkDir(workDir),
7195
7255
  audioOutputPath,
7196
7256
  duration,
7197
7257
  abortSignal,
@@ -11067,7 +11127,11 @@ async function buildPlanAudio(projectDir, config, workRoot, outputPath, options
11067
11127
  });
11068
11128
  try {
11069
11129
  let stageStarted = Date.now();
11070
- await appendVideoAudioFromProbe(c);
11130
+ await appendVideoAudioFromProbe({
11131
+ ...c,
11132
+ downloadDir: audioWorkDir(c.workDir),
11133
+ signal: c.abortSignal
11134
+ });
11071
11135
  logPlanStage(c.log, "extract", stageStarted);
11072
11136
  stageStarted = Date.now();
11073
11137
  const mixed = await mixPlanAudio(c, c.compiledDir);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": "0.1.0",
3
3
  "buildId": "dev",
4
- "sha256": "e5702a93408abbbca0bf52f923c5ef015eb627607f4966a67189611d3ae6e732",
4
+ "sha256": "50bd50498a46c38da53377cbd42bd0d50a43a1b8853a4ed20ed9b6455731bfe9",
5
5
  "artifacts": {
6
6
  "iife": "hyperframe.runtime.iife.js",
7
7
  "esm": "hyperframe.runtime.mjs"