@hyperframes/producer 0.9.58 → 0.9.59

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.
@@ -0,0 +1,9 @@
1
+ // src/services/hyperframeLintWorker.ts
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+ import { lintHyperframeHtml } from "@hyperframes/lint";
4
+ var { html, opts } = workerData;
5
+ try {
6
+ parentPort?.postMessage({ result: await lintHyperframeHtml(html, opts) });
7
+ } catch (error) {
8
+ parentPort?.postMessage({ error: error instanceof Error ? error.message : String(error) });
9
+ }
package/dist/index.js CHANGED
@@ -1580,6 +1580,30 @@ function reportEncodeProgress(job, done, total, onProgress, from) {
1580
1580
  "encoding"
1581
1581
  );
1582
1582
  }
1583
+ var AUDIO_STAGE = "Processing audio tracks";
1584
+ var AUDIO_WAIT_REPORT_MS = 5e3;
1585
+ function audioWaitReporter(job, onProgress) {
1586
+ let waiting2 = false;
1587
+ let reportedAt = -Infinity;
1588
+ return {
1589
+ progressed() {
1590
+ const now = Date.now();
1591
+ if (!waiting2 || now - reportedAt < AUDIO_WAIT_REPORT_MS) return;
1592
+ reportedAt = now;
1593
+ updateJobStatus(job, job.status, AUDIO_STAGE, job.progress, onProgress, {
1594
+ code: "process_audio"
1595
+ });
1596
+ },
1597
+ async wait(audio) {
1598
+ waiting2 = true;
1599
+ try {
1600
+ return await audio;
1601
+ } finally {
1602
+ waiting2 = false;
1603
+ }
1604
+ }
1605
+ };
1606
+ }
1583
1607
  var lastAssembleReportAt = /* @__PURE__ */ new WeakMap();
1584
1608
  function reportAssembleProgress(job, done, total, onProgress) {
1585
1609
  if (total <= 0) return;
@@ -8511,7 +8535,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8511
8535
  {},
8512
8536
  variableOverrides
8513
8537
  );
8514
- return emitted ? document2.toString() : html;
8538
+ return { html: emitted ? document2.toString() : html, variablesByComp: {} };
8515
8539
  }
8516
8540
  const hostIdentityByElement = new ProducerHostIdentityMap(
8517
8541
  document2,
@@ -8625,7 +8649,7 @@ function inlineSubCompositions(html, subCompositions, projectDir, variableOverri
8625
8649
  variableOverrides
8626
8650
  );
8627
8651
  assignMediaRenderIds(document2);
8628
- return document2.toString();
8652
+ return { html: document2.toString(), variablesByComp: result.variablesByComp };
8629
8653
  }
8630
8654
  function ensureFullDocument(html) {
8631
8655
  const trimmed = html.trim();
@@ -9222,7 +9246,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9222
9246
  assetRoot
9223
9247
  );
9224
9248
  const fullHtml = ensureFullDocument(compiledHtml);
9225
- const inlinedHtml = inlineSubCompositions(
9249
+ const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
9226
9250
  fullHtml,
9227
9251
  subCompositions,
9228
9252
  projectDir,
@@ -9375,6 +9399,7 @@ async function compileForRender(projectDir, htmlPath, downloadDir, options = {})
9375
9399
  gradedCanvas,
9376
9400
  ...masterFxChain ? { masterFxChain } : {},
9377
9401
  unresolvedCompositions,
9402
+ variablesByComp,
9378
9403
  externalAssets,
9379
9404
  width,
9380
9405
  height,
@@ -10017,15 +10042,22 @@ function hasAutoStartVideos(html) {
10017
10042
  const { document: document2 } = parseHTML6(html);
10018
10043
  return document2.querySelector("video[data-hf-auto-start]") !== null;
10019
10044
  }
10020
- function variableHasValue(element, variableId, variables) {
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;
10049
+ }
10050
+ function variableHasValue(element, variableId, variables, variablesByComp) {
10021
10051
  if (variables && Object.hasOwn(variables, variableId)) return true;
10052
+ const scoped = scopedVariablesFor(element, variablesByComp);
10053
+ if (scoped) return Object.hasOwn(scoped, variableId);
10022
10054
  for (let scope = element.parentElement; scope; scope = scope.parentElement) {
10023
10055
  if (Object.hasOwn(parseHostVariableValues2(scope), variableId)) return true;
10024
10056
  if (Object.hasOwn(readDeclaredDefaults2(scope), variableId)) return true;
10025
10057
  }
10026
10058
  return Object.hasOwn(readDeclaredDefaults2(element.ownerDocument.documentElement), variableId);
10027
10059
  }
10028
- function hasVariableBoundMedia(html, variables) {
10060
+ function hasVariableBoundMedia(html, variables, variablesByComp = {}) {
10029
10061
  const { document: document2 } = parseHTML6(html);
10030
10062
  return Array.from(
10031
10063
  document2.querySelectorAll(
@@ -10033,7 +10065,7 @@ function hasVariableBoundMedia(html, variables) {
10033
10065
  )
10034
10066
  ).some((element) => {
10035
10067
  const variableId = element.getAttribute("data-var-src")?.trim();
10036
- return Boolean(variableId && variableHasValue(element, variableId, variables));
10068
+ return Boolean(variableId && variableHasValue(element, variableId, variables, variablesByComp));
10037
10069
  });
10038
10070
  }
10039
10071
  function authoredMediaStarts(html) {
@@ -10148,7 +10180,11 @@ async function runProbeStage(input) {
10148
10180
  compiled.html,
10149
10181
  composition.audios.length
10150
10182
  );
10151
- const hasVariableMedia = hasVariableBoundMedia(compiled.html, job.config.variables);
10183
+ const hasVariableMedia = hasVariableBoundMedia(
10184
+ compiled.html,
10185
+ job.config.variables,
10186
+ compiled.variablesByComp
10187
+ );
10152
10188
  const hasInsertedMedia = hasRuntimeMediaChanges(compiled.html);
10153
10189
  const needsBrowser = cfg.videoLayerPassthrough || input.measuresShownBoxes === true || probeRequiresBrowser({
10154
10190
  durationSeconds: composition.duration,
@@ -11296,7 +11332,8 @@ import {
11296
11332
  audioFailureDiagnostics,
11297
11333
  processCompositionAudio,
11298
11334
  removeScratch as removeScratch2,
11299
- collectScratchLeftovers
11335
+ collectScratchLeftovers,
11336
+ withFfmpegProgress
11300
11337
  } from "@hyperframes/engine";
11301
11338
 
11302
11339
  // src/services/render/audioDeliveryLimit.ts
@@ -11322,7 +11359,8 @@ import {
11322
11359
  removeScratch,
11323
11360
  renameWithRetry as renameWithRetry5,
11324
11361
  runFfmpeg as runFfmpeg5,
11325
- trackChildProcess
11362
+ trackChildProcess,
11363
+ withPublicOnlyProxy
11326
11364
  } from "@hyperframes/engine";
11327
11365
  import { redactKnownPaths, redactTelemetryString as redactTelemetryString3 } from "@hyperframes/core";
11328
11366
 
@@ -11764,7 +11802,17 @@ async function runFfprobeJson(args, signal) {
11764
11802
  if (!args.includes("--")) {
11765
11803
  throw new Error('[audioPadTrim] ffprobe args must terminate options with "--".');
11766
11804
  }
11805
+ const proxying = withPublicOnlyProxy(args, [args.indexOf("--") + 1]);
11806
+ const routed = proxying && await proxying;
11807
+ try {
11808
+ return await spawnFfprobeJson(routed?.args ?? args, routed?.env, signal);
11809
+ } finally {
11810
+ await routed?.close();
11811
+ }
11812
+ }
11813
+ async function spawnFfprobeJson(args, env, signal) {
11767
11814
  const proc = spawn(getFfprobeBinary(), args, {
11815
+ ...env && { env },
11768
11816
  stdio: ["ignore", "pipe", "pipe"],
11769
11817
  windowsHide: true
11770
11818
  });
@@ -11880,7 +11928,8 @@ function assertAudioNotInterrupted(failures) {
11880
11928
  }
11881
11929
  function runAudioStage(input) {
11882
11930
  return collectScratchLeftovers(
11883
- () => runAudioStageScoped(input),
11931
+ () => withFfmpegProgress(input.onFfmpegProgress ?? (() => {
11932
+ }), () => runAudioStageScoped(input)),
11884
11933
  (left) => {
11885
11934
  if (left.length > 0) input.log?.warn("[audio] scratch left behind", { count: left.length });
11886
11935
  }
@@ -15385,9 +15434,10 @@ async function executeRenderPipeline(input) {
15385
15434
  nativeHdrVideoCount: nativeHdrVideoIds.size,
15386
15435
  nativeHdrImageCount: nativeHdrImageIds.size
15387
15436
  });
15388
- updateJobStatus(job, "preprocessing", "Processing audio tracks", 20, onProgress, {
15437
+ updateJobStatus(job, "preprocessing", AUDIO_STAGE, 20, onProgress, {
15389
15438
  code: "process_audio"
15390
15439
  });
15440
+ const audioWait = audioWaitReporter(job, onProgress);
15391
15441
  const audioStage = observeRenderStage(
15392
15442
  observability,
15393
15443
  "audio_process",
@@ -15406,7 +15456,8 @@ async function executeRenderPipeline(input) {
15406
15456
  abortSignal: executionSignal,
15407
15457
  assertNotAborted,
15408
15458
  log,
15409
- keepDeliverySource: true
15459
+ keepDeliverySource: true,
15460
+ onFfmpegProgress: audioWait.progressed
15410
15461
  })
15411
15462
  );
15412
15463
  pendingAudio = audioStage.catch(() => void 0);
@@ -16216,7 +16267,7 @@ async function executeRenderPipeline(input) {
16216
16267
  }
16217
16268
  const effectiveQuality = job.config.crf ?? preset.quality;
16218
16269
  const effectiveBitrate = job.config.crf != null ? void 0 : job.config.videoBitrate;
16219
- const audioResult = await audioStage;
16270
+ const audioResult = await audioWait.wait(audioStage);
16220
16271
  const { audioOutputPath, deliverySourcePath, hasAudio } = audioResult;
16221
16272
  perfStages.audioProcessMs = audioResult.audioProcessMs;
16222
16273
  recordLimiterAttenuation(job, audioResult.audioLoweredDb);
@@ -22054,7 +22105,7 @@ import {
22054
22105
  rmSync as rmSync19,
22055
22106
  createReadStream as createReadStream5
22056
22107
  } from "node:fs";
22057
- import { resolve as resolve12, dirname as dirname20, join as join49 } from "node:path";
22108
+ import { resolve as resolve12, dirname as dirname21, join as join49 } from "node:path";
22058
22109
  import { tmpdir as tmpdir5 } from "node:os";
22059
22110
  import { parseArgs } from "node:util";
22060
22111
  import { isIP } from "node:net";
@@ -22079,8 +22130,9 @@ import {
22079
22130
  closeSync as closeSync7,
22080
22131
  constants as constants3
22081
22132
  } from "node:fs";
22082
- import { resolve as resolve11, join as join47, relative as relative8, isAbsolute as isAbsolute5, sep as sep6 } from "node:path";
22083
- import { lintHyperframeHtml } from "@hyperframes/lint";
22133
+ import { resolve as resolve11, join as join47, relative as relative8, isAbsolute as isAbsolute5, sep as sep6, dirname as dirname19 } from "node:path";
22134
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
22135
+ import { Worker as Worker2 } from "node:worker_threads";
22084
22136
  function isStringRecord(value) {
22085
22137
  if (!value || typeof value !== "object" || Array.isArray(value)) {
22086
22138
  return false;
@@ -22186,17 +22238,111 @@ function prepareHyperframeLintBody(body, isAllowedEntry) {
22186
22238
  }
22187
22239
  return { error: "Missing lint source: provide projectDir, files, or html" };
22188
22240
  }
22189
- async function runHyperframeLint(prepared) {
22190
- return lintHyperframeHtml(prepared.html, {
22191
- filePath: prepared.entryFile,
22192
- compSrcPath: prepared.entryFile
22241
+ var LINT_HEAP_MB = 512;
22242
+ var LINT_TIMEOUT_MS = 15e3;
22243
+ var LINT_MAX_WORKERS = 2;
22244
+ var waiting = [];
22245
+ var running = 0;
22246
+ function takeLintSlot(limit, waitMs) {
22247
+ if (running < limit) {
22248
+ running++;
22249
+ return Promise.resolve(true);
22250
+ }
22251
+ return new Promise((resolve13) => {
22252
+ const entry = () => {
22253
+ clearTimeout(timer);
22254
+ running++;
22255
+ resolve13(true);
22256
+ };
22257
+ const timer = setTimeout(
22258
+ () => {
22259
+ waiting.splice(waiting.indexOf(entry), 1);
22260
+ resolve13(false);
22261
+ },
22262
+ Math.max(0, waitMs)
22263
+ );
22264
+ waiting.push(entry);
22265
+ });
22266
+ }
22267
+ function freeLintSlot() {
22268
+ running--;
22269
+ waiting.shift()?.();
22270
+ }
22271
+ function resolveLintWorkerEntry() {
22272
+ const here = dirname19(fileURLToPath6(import.meta.url));
22273
+ for (const name of ["hyperframeLintWorker.js", "hyperframeLintWorker.ts"]) {
22274
+ const candidate = join47(here, name);
22275
+ if (existsSync30(candidate)) return candidate;
22276
+ }
22277
+ return void 0;
22278
+ }
22279
+ function abortedLintResult(filePath, afterMs) {
22280
+ return {
22281
+ ok: false,
22282
+ errorCount: 1,
22283
+ warningCount: 0,
22284
+ infoCount: 0,
22285
+ findings: [
22286
+ {
22287
+ code: "lint_aborted",
22288
+ severity: "error",
22289
+ message: "This composition's script could not be checked: linting it ran too long or out of memory, so it was stopped. A very large or deeply nested script is the usual cause.",
22290
+ file: filePath
22291
+ }
22292
+ ],
22293
+ timings: { totalMs: afterMs, groupMs: {}, slowestRule: "", slowestRuleMs: 0 }
22294
+ };
22295
+ }
22296
+ async function runHyperframeLint(prepared, options = {}) {
22297
+ const began = performance.now();
22298
+ const aborted = () => abortedLintResult(prepared.entryFile, Math.round(performance.now() - began));
22299
+ const entry = options.workerEntry ?? resolveLintWorkerEntry();
22300
+ if (!entry) return aborted();
22301
+ const timeoutMs = options.timeoutMs ?? LINT_TIMEOUT_MS;
22302
+ const gotSlot = await takeLintSlot(options.maxWorkers ?? LINT_MAX_WORKERS, timeoutMs);
22303
+ if (!gotSlot) return aborted();
22304
+ const remainingMs = Math.max(0, timeoutMs - (performance.now() - began));
22305
+ return new Promise((resolvePromise, reject) => {
22306
+ let worker;
22307
+ try {
22308
+ worker = new Worker2(entry, {
22309
+ workerData: {
22310
+ html: prepared.html,
22311
+ opts: { filePath: prepared.entryFile, compSrcPath: prepared.entryFile }
22312
+ },
22313
+ resourceLimits: { maxOldGenerationSizeMb: options.heapMb ?? LINT_HEAP_MB },
22314
+ stdout: false,
22315
+ stderr: false
22316
+ });
22317
+ } catch {
22318
+ freeLintSlot();
22319
+ resolvePromise(aborted());
22320
+ return;
22321
+ }
22322
+ let settled = false;
22323
+ const settle = (finish) => {
22324
+ if (settled) return;
22325
+ settled = true;
22326
+ clearTimeout(timer);
22327
+ void worker.terminate().finally(freeLintSlot);
22328
+ finish();
22329
+ };
22330
+ const timer = setTimeout(() => settle(() => resolvePromise(aborted())), remainingMs);
22331
+ worker.on(
22332
+ "message",
22333
+ (message) => settle(
22334
+ () => message.result ? resolvePromise(message.result) : reject(new Error(message.error))
22335
+ )
22336
+ );
22337
+ worker.on("error", () => settle(() => resolvePromise(aborted())));
22338
+ worker.on("exit", () => settle(() => resolvePromise(aborted())));
22193
22339
  });
22194
22340
  }
22195
22341
 
22196
22342
  // src/services/healthWorker.ts
22197
- import { Worker as Worker2 } from "node:worker_threads";
22198
- import { fileURLToPath as fileURLToPath6 } from "node:url";
22199
- import { dirname as dirname19, join as join48 } from "node:path";
22343
+ import { Worker as Worker3 } from "node:worker_threads";
22344
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
22345
+ import { dirname as dirname20, join as join48 } from "node:path";
22200
22346
  import { existsSync as existsSync31 } from "node:fs";
22201
22347
  var DEFAULT_HEALTH_PORT = 9848;
22202
22348
  async function startHealthWorker(options = {}) {
@@ -22208,7 +22354,7 @@ async function startHealthWorker(options = {}) {
22208
22354
  "[healthWorker] could not resolve worker entry. Pass options.workerEntry or ensure healthWorkerThread.{js,ts} is co-located."
22209
22355
  );
22210
22356
  }
22211
- const worker = new Worker2(entry, {
22357
+ const worker = new Worker3(entry, {
22212
22358
  workerData: { port },
22213
22359
  // Keep stdio inherited so the worker's console logs land in the pod logs
22214
22360
  // alongside the main thread's.
@@ -22271,7 +22417,7 @@ function defaultLogger2() {
22271
22417
  };
22272
22418
  }
22273
22419
  function resolveWorkerEntry2() {
22274
- const here = dirname19(fileURLToPath6(import.meta.url));
22420
+ const here = dirname20(fileURLToPath7(import.meta.url));
22275
22421
  const candidates = [join48(here, "healthWorkerThread.js"), join48(here, "healthWorkerThread.ts")];
22276
22422
  for (const candidate of candidates) {
22277
22423
  if (existsSync31(candidate)) return candidate;
@@ -22441,7 +22587,7 @@ function resolvePreparedRenderOutput(prepared, rendersDir, log, confineOutput) {
22441
22587
  throw new Error("outputPath must be inside the renders directory");
22442
22588
  }
22443
22589
  }
22444
- const outputDir = dirname20(absoluteOutputPath);
22590
+ const outputDir = dirname21(absoluteOutputPath);
22445
22591
  if (!existsSync32(outputDir)) mkdirSync21(outputDir, { recursive: true });
22446
22592
  return { input, cleanupProjectDir, absoluteOutputPath };
22447
22593
  }
@@ -23153,7 +23299,7 @@ import {
23153
23299
  statSync as statSync15,
23154
23300
  writeFileSync as writeFileSync15
23155
23301
  } from "node:fs";
23156
- import { basename as basename8, dirname as dirname21, join as join50 } from "node:path";
23302
+ import { basename as basename8, dirname as dirname22, join as join50 } from "node:path";
23157
23303
  import {
23158
23304
  appendRateCapArgs as appendRateCapArgs2,
23159
23305
  appendRenderProvenanceArgs as appendRenderProvenanceArgs2,
@@ -23200,10 +23346,10 @@ async function assemble(planDir, chunkOutputs, audioPath, outputPath, options) {
23200
23346
  }
23201
23347
  const format = plan2.dimensions.format;
23202
23348
  const cfrEncoder = cfr ? readCfrEncoder(planDir, format) : null;
23203
- if (!existsSync33(dirname21(outputPath))) {
23204
- mkdirSync22(dirname21(outputPath), { recursive: true });
23349
+ if (!existsSync33(dirname22(outputPath))) {
23350
+ mkdirSync22(dirname22(outputPath), { recursive: true });
23205
23351
  }
23206
- const workDir = createStagingDir7(dirname21(outputPath), `${basename8(outputPath)}.assemble-work-`);
23352
+ const workDir = createStagingDir7(dirname22(outputPath), `${basename8(outputPath)}.assemble-work-`);
23207
23353
  const fps = { num: plan2.dimensions.fpsNum, den: plan2.dimensions.fpsDen };
23208
23354
  const stageMs = {};
23209
23355
  const ctx = {