@bendyline/squisq-cli 1.2.1 → 2.0.0

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,668 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ GIF_EXPORT_DEFAULTS
4
+ } from "./chunk-VM3ZFP3J.js";
5
+
6
+ // src/api.ts
7
+ import { resolveMediaSchedule } from "@bendyline/squisq/schemas";
8
+ import { flattenBlocks } from "@bendyline/squisq/doc";
9
+ import { ffmpegGifOutputArgs, generateRenderHtml } from "@bendyline/squisq-video";
10
+ import { resolveDimensions } from "@bendyline/squisq-video";
11
+ import { convert as formatsConvert } from "@bendyline/squisq-formats";
12
+
13
+ // src/util/detectFfmpeg.ts
14
+ import { execFile } from "child_process";
15
+ function run(command, args) {
16
+ return new Promise((resolve) => {
17
+ execFile(command, args, { timeout: 5e3 }, (err, stdout) => {
18
+ if (err || !stdout.trim()) {
19
+ resolve(null);
20
+ return;
21
+ }
22
+ resolve(stdout.trim());
23
+ });
24
+ });
25
+ }
26
+ async function getFfmpegVersion(path) {
27
+ const out = await run(path, ["-version"]);
28
+ return out ? out.split("\n")[0].trim() : null;
29
+ }
30
+ async function detectFfmpegDetailed() {
31
+ const envPath = process.env.SQUISQ_FFMPEG;
32
+ if (envPath) {
33
+ const version = await getFfmpegVersion(envPath);
34
+ if (!version) {
35
+ throw new Error(
36
+ `SQUISQ_FFMPEG is set to "${envPath}" but running "${envPath} -version" failed. Fix the path or unset SQUISQ_FFMPEG.`
37
+ );
38
+ }
39
+ return { path: envPath, source: "env" };
40
+ }
41
+ const command = process.platform === "win32" ? "where" : "which";
42
+ const found = await run(command, ["ffmpeg"]);
43
+ if (found) {
44
+ return { path: found.split("\n")[0].trim(), source: "path" };
45
+ }
46
+ try {
47
+ const specifier = "ffmpeg-static";
48
+ const mod = await import(specifier);
49
+ const candidate = typeof mod === "string" ? mod : typeof mod.default === "string" ? mod.default : null;
50
+ if (candidate) {
51
+ return { path: candidate, source: "ffmpeg-static" };
52
+ }
53
+ } catch {
54
+ }
55
+ return null;
56
+ }
57
+
58
+ // src/util/audioMix.ts
59
+ import { computeAudioTimeline } from "@bendyline/squisq-video";
60
+ async function buildMixedAudioTrack(doc, container, ffmpegPath, coverPreRoll) {
61
+ const timeline = computeAudioTimeline(doc, coverPreRoll);
62
+ if (timeline.length === 0) return null;
63
+ const bytesBySrc = /* @__PURE__ */ new Map();
64
+ const readSrc = async (src) => {
65
+ if (bytesBySrc.has(src)) return bytesBySrc.get(src);
66
+ const data = await container.readFile(src);
67
+ bytesBySrc.set(src, data ?? null);
68
+ return data ?? null;
69
+ };
70
+ const usable = [];
71
+ for (const clip of timeline) {
72
+ const buffer = await readSrc(clip.src);
73
+ if (buffer) usable.push({ clip, buffer });
74
+ }
75
+ if (usable.length === 0) return null;
76
+ return mixTimelineClips(ffmpegPath, usable);
77
+ }
78
+ async function mixTimelineClips(ffmpegPath, usable) {
79
+ const { writeFile, readFile: readFile3, mkdir, rm: rm2 } = await import("fs/promises");
80
+ const { join: join3 } = await import("path");
81
+ const { tmpdir: tmpdir2 } = await import("os");
82
+ const { randomBytes: randomBytes2 } = await import("crypto");
83
+ const { execFile: execFile2 } = await import("child_process");
84
+ const workDir = join3(tmpdir2(), `squisq-audio-mix-${randomBytes2(8).toString("hex")}`);
85
+ await mkdir(workDir, { recursive: true });
86
+ const ms = (s) => Math.max(0, Math.round(s * 1e3));
87
+ try {
88
+ const inputs = [];
89
+ const filters = [];
90
+ const labels = [];
91
+ for (const { clip, buffer } of usable) {
92
+ const p = join3(workDir, `clip-${inputs.length}.mp3`);
93
+ await writeFile(p, new Uint8Array(buffer));
94
+ const i = inputs.push(p) - 1;
95
+ const delayMs = ms(clip.startSec);
96
+ const start = Math.max(0, clip.sourceInSec);
97
+ const end = start + Math.max(0, clip.durationSec);
98
+ filters.push(
99
+ `[${i}:a]atrim=start=${start}:end=${end},asetpts=PTS-STARTPTS,adelay=${delayMs}|${delayMs}[a${i}]`
100
+ );
101
+ labels.push(`[a${i}]`);
102
+ }
103
+ const graph = `${filters.join(";")};${labels.join("")}amix=inputs=${labels.length}:normalize=0:dropout_transition=0[aout]`;
104
+ const outputPath = join3(workDir, "mixed.mp3");
105
+ const args = ["-y"];
106
+ for (const p of inputs) args.push("-i", p);
107
+ args.push(
108
+ "-filter_complex",
109
+ graph,
110
+ "-map",
111
+ "[aout]",
112
+ "-c:a",
113
+ "libmp3lame",
114
+ "-b:a",
115
+ "192k",
116
+ outputPath
117
+ );
118
+ await new Promise((resolve, reject) => {
119
+ execFile2(ffmpegPath, args, { timeout: 18e4 }, (err) => {
120
+ if (err) reject(new Error(`ffmpeg audio mix failed: ${err.message}`));
121
+ else resolve();
122
+ });
123
+ });
124
+ const data = await readFile3(outputPath);
125
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
126
+ } finally {
127
+ await rm2(workDir, { recursive: true, force: true });
128
+ }
129
+ }
130
+
131
+ // src/util/coverPreRoll.ts
132
+ function resolveAppliedCoverPreRoll(requestedSeconds, hasCover) {
133
+ if (!Number.isFinite(requestedSeconds) || requestedSeconds < 0) {
134
+ throw new Error("Cover pre-roll must be a finite number of seconds greater than or equal to 0");
135
+ }
136
+ return hasCover ? requestedSeconds : 0;
137
+ }
138
+
139
+ // src/registry.ts
140
+ import { randomBytes } from "crypto";
141
+ import { readFile, rm } from "fs/promises";
142
+ import { tmpdir } from "os";
143
+ import { join } from "path";
144
+ import { defaultRegistry } from "@bendyline/squisq-formats";
145
+ var MP4_DEFAULTS = {
146
+ fps: 30,
147
+ quality: "normal",
148
+ orientation: "landscape",
149
+ coverPreRoll: 0,
150
+ animationsEnabled: true
151
+ };
152
+ var GIF_DEFAULTS = {
153
+ fps: 10,
154
+ orientation: "landscape",
155
+ width: 960,
156
+ height: 540,
157
+ coverPreRoll: 0,
158
+ animationsEnabled: false,
159
+ loop: 0,
160
+ maxColors: 256,
161
+ dither: "sierra2_4a"
162
+ };
163
+ function mp4Format() {
164
+ return {
165
+ id: "mp4",
166
+ label: "MP4 Video",
167
+ mimeType: "video/mp4",
168
+ extensions: [".mp4"],
169
+ async exportDoc(input, options) {
170
+ const mp4Opts = options.formatOptions?.mp4 ?? {};
171
+ const fps = typeof mp4Opts.fps === "number" ? mp4Opts.fps : MP4_DEFAULTS.fps;
172
+ const quality = typeof mp4Opts.quality === "string" ? mp4Opts.quality : MP4_DEFAULTS.quality;
173
+ const orientation = typeof mp4Opts.orientation === "string" ? mp4Opts.orientation : MP4_DEFAULTS.orientation;
174
+ const coverPreRoll = typeof mp4Opts.coverPreRoll === "number" ? mp4Opts.coverPreRoll : MP4_DEFAULTS.coverPreRoll;
175
+ const animationsEnabled = typeof mp4Opts.animationsEnabled === "boolean" ? mp4Opts.animationsEnabled : MP4_DEFAULTS.animationsEnabled;
176
+ const outputPath = join(tmpdir(), `squisq-mp4-${randomBytes(8).toString("hex")}.mp4`);
177
+ try {
178
+ const { renderDocToMp4: renderDocToMp42 } = await import("./api-6KN3F6IQ.js");
179
+ await renderDocToMp42(input.doc, input.container, {
180
+ outputPath,
181
+ fps,
182
+ quality,
183
+ orientation,
184
+ width: mp4Opts.width,
185
+ height: mp4Opts.height,
186
+ captionStyle: mp4Opts.captionStyle,
187
+ coverPreRoll,
188
+ animationsEnabled
189
+ });
190
+ const data = await readFile(outputPath);
191
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
192
+ return { bytes, mimeType: "video/mp4", suggestedFilename: "", warnings: [] };
193
+ } finally {
194
+ await rm(outputPath, { force: true });
195
+ }
196
+ }
197
+ };
198
+ }
199
+ function gifFormat() {
200
+ return {
201
+ id: "gif",
202
+ label: "Animated GIF",
203
+ mimeType: "image/gif",
204
+ extensions: [".gif"],
205
+ async exportDoc(input, options) {
206
+ const gifOpts = options.formatOptions?.gif ?? {};
207
+ const orientation = typeof gifOpts.orientation === "string" ? gifOpts.orientation : GIF_DEFAULTS.orientation;
208
+ const portrait = orientation === "portrait";
209
+ const defaultWidth = portrait ? GIF_DEFAULTS.height : GIF_DEFAULTS.width;
210
+ const defaultHeight = portrait ? GIF_DEFAULTS.width : GIF_DEFAULTS.height;
211
+ const outputPath = join(tmpdir(), `squisq-gif-${randomBytes(8).toString("hex")}.gif`);
212
+ try {
213
+ const { renderDocToGif: renderDocToGif2 } = await import("./api-6KN3F6IQ.js");
214
+ const result = await renderDocToGif2(input.doc, input.container, {
215
+ outputPath,
216
+ fps: typeof gifOpts.fps === "number" ? gifOpts.fps : GIF_DEFAULTS.fps,
217
+ orientation,
218
+ width: typeof gifOpts.width === "number" ? gifOpts.width : defaultWidth,
219
+ height: typeof gifOpts.height === "number" ? gifOpts.height : defaultHeight,
220
+ captionStyle: gifOpts.captionStyle,
221
+ coverPreRoll: typeof gifOpts.coverPreRoll === "number" ? gifOpts.coverPreRoll : GIF_DEFAULTS.coverPreRoll,
222
+ animationsEnabled: typeof gifOpts.animationsEnabled === "boolean" ? gifOpts.animationsEnabled : GIF_DEFAULTS.animationsEnabled,
223
+ loop: typeof gifOpts.loop === "number" ? gifOpts.loop : GIF_DEFAULTS.loop,
224
+ maxColors: typeof gifOpts.maxColors === "number" ? gifOpts.maxColors : GIF_DEFAULTS.maxColors,
225
+ dither: gifOpts.dither ?? GIF_DEFAULTS.dither,
226
+ bayerScale: gifOpts.bayerScale
227
+ });
228
+ const data = await readFile(outputPath);
229
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
230
+ return {
231
+ bytes,
232
+ mimeType: "image/gif",
233
+ suggestedFilename: "",
234
+ warnings: result.warnings
235
+ };
236
+ } finally {
237
+ await rm(outputPath, { force: true });
238
+ }
239
+ }
240
+ };
241
+ }
242
+ function createCliRegistry() {
243
+ const registry = defaultRegistry();
244
+ registry.register(mp4Format());
245
+ registry.register(gifFormat());
246
+ return registry;
247
+ }
248
+
249
+ // src/api.ts
250
+ import { MemoryContentContainer as MemoryContentContainer2 } from "@bendyline/squisq/storage";
251
+
252
+ // src/util/readInput.ts
253
+ import { readFile as readFile2, readdir, stat } from "fs/promises";
254
+ import { join as join2, extname } from "path";
255
+ import { parseMarkdown, stringifyMarkdown } from "@bendyline/squisq/markdown";
256
+ import { markdownToDoc, resolveAudioMapping } from "@bendyline/squisq/doc";
257
+ import { MemoryContentContainer } from "@bendyline/squisq/storage";
258
+ import { zipToContainer } from "@bendyline/squisq-formats/container";
259
+ import { defaultRegistry as defaultRegistry2 } from "@bendyline/squisq-formats";
260
+ var MIME_TYPES = {
261
+ ".md": "text/markdown",
262
+ ".txt": "text/plain",
263
+ ".json": "application/json",
264
+ ".jpg": "image/jpeg",
265
+ ".jpeg": "image/jpeg",
266
+ ".png": "image/png",
267
+ ".gif": "image/gif",
268
+ ".webp": "image/webp",
269
+ ".svg": "image/svg+xml",
270
+ ".mp3": "audio/mpeg",
271
+ ".wav": "audio/wav",
272
+ ".ogg": "audio/ogg",
273
+ ".mp4": "video/mp4",
274
+ ".webm": "video/webm"
275
+ };
276
+ var IMPORTER_EXTS = [".docx", ".pptx", ".pdf", ".xlsx", ".csv", ".html", ".htm"];
277
+ function mimeFromExt(filePath) {
278
+ return MIME_TYPES[extname(filePath).toLowerCase()] ?? "application/octet-stream";
279
+ }
280
+ async function walkDir(root, prefix = "") {
281
+ const entries = await readdir(root, { withFileTypes: true });
282
+ const paths = [];
283
+ for (const entry of entries) {
284
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
285
+ if (entry.isDirectory()) {
286
+ paths.push(...await walkDir(join2(root, entry.name), relPath));
287
+ } else if (entry.isFile()) {
288
+ paths.push(relPath);
289
+ }
290
+ }
291
+ return paths;
292
+ }
293
+ async function readInput(inputPath, options) {
294
+ const result = await readInputRaw(inputPath, options);
295
+ const doc = await resolveAudioMapping(result.doc, result.container);
296
+ return doc === result.doc ? result : { ...result, doc };
297
+ }
298
+ async function readInputRaw(inputPath, options) {
299
+ const info = await stat(inputPath);
300
+ if (info.isDirectory()) {
301
+ return readFolder(inputPath);
302
+ }
303
+ const ext = extname(inputPath).toLowerCase();
304
+ if (ext === ".zip" || ext === ".dbk") {
305
+ return readContainer(inputPath);
306
+ }
307
+ if (ext === ".json") {
308
+ return readDocJsonFile(inputPath);
309
+ }
310
+ if (IMPORTER_EXTS.includes(ext)) {
311
+ const def = defaultRegistry2().byExtension(ext);
312
+ if (def && (def.importContainer || def.importDoc)) {
313
+ return readViaImporter(inputPath, def, options);
314
+ }
315
+ }
316
+ return readMarkdownFile(inputPath);
317
+ }
318
+ async function readArrayBuffer(filePath) {
319
+ const data = await readFile2(filePath);
320
+ return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
321
+ }
322
+ async function readMarkdownFile(filePath) {
323
+ const content = await readFile2(filePath, "utf-8");
324
+ const container = new MemoryContentContainer();
325
+ await container.writeDocument(content);
326
+ const markdownDoc = parseMarkdown(content);
327
+ return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat: "md" };
328
+ }
329
+ async function readDocJsonFile(filePath) {
330
+ const content = await readFile2(filePath, "utf-8");
331
+ const doc = JSON.parse(content);
332
+ const container = new MemoryContentContainer();
333
+ return { doc, container, sourceFormat: "json" };
334
+ }
335
+ async function readViaImporter(filePath, def, options) {
336
+ const buffer = await readArrayBuffer(filePath);
337
+ const convertOptions = {
338
+ formatOptions: {
339
+ [def.id]: {
340
+ inferTheme: options?.inferTheme !== false,
341
+ inferLayouts: options?.inferLayouts !== false
342
+ }
343
+ }
344
+ };
345
+ let container;
346
+ let markdownDoc;
347
+ if (def.importContainer) {
348
+ container = await def.importContainer(buffer, convertOptions);
349
+ const text = await container.readDocument();
350
+ markdownDoc = text ? parseMarkdown(text) : { type: "document", children: [] };
351
+ } else {
352
+ markdownDoc = await def.importDoc(buffer, convertOptions);
353
+ const mem = new MemoryContentContainer();
354
+ await mem.writeDocument(stringifyMarkdown(markdownDoc));
355
+ container = mem;
356
+ }
357
+ return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat: def.id };
358
+ }
359
+ var DOC_JSON_NAMES = ["doc.json", "story.json"];
360
+ async function resolveContainer(container, sourceFormat, missingMessage) {
361
+ for (const name of DOC_JSON_NAMES) {
362
+ const jsonData = await container.readFile(name);
363
+ if (jsonData) {
364
+ const doc = JSON.parse(new TextDecoder().decode(jsonData));
365
+ return { doc, container, sourceFormat };
366
+ }
367
+ }
368
+ const markdown = await container.readDocument();
369
+ if (!markdown) {
370
+ throw new Error(missingMessage);
371
+ }
372
+ const markdownDoc = parseMarkdown(markdown);
373
+ return { doc: markdownToDoc(markdownDoc), container, markdownDoc, sourceFormat };
374
+ }
375
+ async function readContainer(filePath) {
376
+ const container = await zipToContainer(await readArrayBuffer(filePath));
377
+ return resolveContainer(
378
+ container,
379
+ "dbk",
380
+ `No markdown document or doc.json found in container: ${filePath}`
381
+ );
382
+ }
383
+ async function readFolder(dirPath) {
384
+ const container = new MemoryContentContainer();
385
+ const files = await walkDir(dirPath);
386
+ for (const relPath of files) {
387
+ const absPath = join2(dirPath, relPath);
388
+ const data = await readFile2(absPath);
389
+ await container.writeFile(
390
+ relPath,
391
+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
392
+ mimeFromExt(relPath)
393
+ );
394
+ }
395
+ return resolveContainer(
396
+ container,
397
+ "folder",
398
+ `No markdown document or doc.json found in folder: ${dirPath}`
399
+ );
400
+ }
401
+
402
+ // src/api.ts
403
+ import { ConversionError } from "@bendyline/squisq-formats";
404
+ async function convert(source, to, options = {}) {
405
+ return formatsConvert(source, to, {
406
+ registry: createCliRegistry(),
407
+ resolvePlayerScript: () => import("@bendyline/squisq-react/standalone-source").then((m) => m.PLAYER_BUNDLE),
408
+ ...options
409
+ });
410
+ }
411
+ async function captureDocFrames(doc, container, options) {
412
+ const { fps, width, height, captionStyle, coverPreRoll, animationsEnabled, onProgress } = options;
413
+ resolveAppliedCoverPreRoll(coverPreRoll, true);
414
+ const ffmpegPath = (await detectFfmpegDetailed())?.path ?? null;
415
+ if (!ffmpegPath) {
416
+ throw new Error(
417
+ "ffmpeg is required but not found in PATH.\nInstall it with:\n macOS: brew install ffmpeg\n Ubuntu: sudo apt install ffmpeg\n Windows: winget install ffmpeg\nOr: npm install ffmpeg-static, or set SQUISQ_FFMPEG to an ffmpeg binary."
418
+ );
419
+ }
420
+ onProgress?.("collecting media", 0);
421
+ const { collectImagePaths } = await import("@bendyline/squisq-formats/html");
422
+ const images = /* @__PURE__ */ new Map();
423
+ for (const imgPath of collectImagePaths(doc)) {
424
+ const data = await container.readFile(imgPath);
425
+ if (data) images.set(imgPath, data);
426
+ }
427
+ const audio = /* @__PURE__ */ new Map();
428
+ for (const seg of doc.audio?.segments ?? []) {
429
+ const data = await container.readFile(seg.src);
430
+ if (data) {
431
+ audio.set(seg.src, data);
432
+ audio.set(seg.name, data);
433
+ }
434
+ }
435
+ const mediaSrcs = new Set(resolveMediaSchedule(doc).map((clip) => clip.src));
436
+ for (const block of flattenBlocks(doc.blocks)) {
437
+ for (const layer of block.layers ?? []) {
438
+ if (layer.type === "video") mediaSrcs.add(layer.content.src);
439
+ }
440
+ }
441
+ for (const src of mediaSrcs) {
442
+ if (images.has(src)) continue;
443
+ const data = await container.readFile(src);
444
+ if (data) images.set(src, data);
445
+ }
446
+ onProgress?.("generating render HTML", 10);
447
+ const { PLAYER_BUNDLE } = await import("@bendyline/squisq-react/standalone-source");
448
+ const renderHtml = generateRenderHtml(doc, {
449
+ playerScript: PLAYER_BUNDLE,
450
+ images,
451
+ audio: audio.size > 0 ? audio : void 0,
452
+ width,
453
+ height,
454
+ captionStyle,
455
+ animationsEnabled
456
+ });
457
+ onProgress?.("launching browser", 15);
458
+ const { chromium } = await import("playwright-core");
459
+ let browser;
460
+ try {
461
+ browser = await chromium.launch({ headless: true });
462
+ } catch (err) {
463
+ const detail = err instanceof Error ? err.message.split("\n")[0] : String(err);
464
+ throw new Error(
465
+ `Playwright Chromium is not installed. Run: npx playwright install chromium
466
+ (launch failed: ${detail})`
467
+ );
468
+ }
469
+ const page = await browser.newPage({ viewport: { width, height } });
470
+ const pageErrors = [];
471
+ page.on("pageerror", (err) => pageErrors.push(err.message));
472
+ let renderAPI = null;
473
+ try {
474
+ await page.setContent(renderHtml, { waitUntil: "load" });
475
+ await page.waitForTimeout(500);
476
+ try {
477
+ await page.waitForFunction(
478
+ () => {
479
+ const root = document.getElementById("squisq-root");
480
+ const player = window.SquisqPlayer;
481
+ return root ? player?.getHandle(root)?.getRenderAPI() != null : false;
482
+ },
483
+ { timeout: 15e3 }
484
+ );
485
+ } catch {
486
+ const errorDetail = pageErrors.length ? `
487
+ Page errors:
488
+ ${pageErrors.join("\n ")}` : "\nNo page errors captured \u2014 the player may have failed to mount.";
489
+ throw new Error(
490
+ `The standalone player failed to boot in headless Chromium. Render API did not initialize within 15 seconds.${errorDetail}`
491
+ );
492
+ }
493
+ renderAPI = await page.evaluateHandle(() => {
494
+ const root = document.getElementById("squisq-root");
495
+ const player = window.SquisqPlayer;
496
+ const api = root ? player?.getHandle(root)?.getRenderAPI() : null;
497
+ if (!api) throw new Error("Squisq render API disappeared after initialization.");
498
+ return api;
499
+ });
500
+ const docDuration = await renderAPI.evaluate((api) => api.getDuration());
501
+ if (docDuration <= 0) throw new Error("Document has zero duration \u2014 nothing to render");
502
+ const hasCover = coverPreRoll > 0 ? await renderAPI.evaluate((api) => api.hasCoverBlock()) : false;
503
+ const appliedCoverPreRoll = resolveAppliedCoverPreRoll(coverPreRoll, hasCover);
504
+ const storyFrameCount = Math.ceil(docDuration * fps);
505
+ const preRollFrameCount = Math.ceil(appliedCoverPreRoll * fps);
506
+ const totalFrames = preRollFrameCount + storyFrameCount;
507
+ const frames = [];
508
+ onProgress?.("capturing frames", 20);
509
+ if (preRollFrameCount > 0) {
510
+ await renderAPI.evaluate((api) => api.showCover());
511
+ await page.waitForTimeout(100);
512
+ const coverFrame = new Uint8Array(await page.screenshot({ type: "png" }));
513
+ for (let i = 0; i < preRollFrameCount; i++) frames.push(coverFrame);
514
+ await renderAPI.evaluate((api) => api.hideCover());
515
+ }
516
+ const frameInterval = 1 / fps;
517
+ for (let i = 0; i < storyFrameCount; i++) {
518
+ const time = i * frameInterval;
519
+ await renderAPI.evaluate((api, t) => api.seekTo(t), time);
520
+ frames.push(new Uint8Array(await page.screenshot({ type: "png" })));
521
+ if (i % Math.max(1, Math.floor(fps / 2)) === 0 || i === storyFrameCount - 1) {
522
+ onProgress?.("capturing frames", 20 + Math.round(frames.length / totalFrames * 60));
523
+ }
524
+ }
525
+ return {
526
+ frames,
527
+ totalDuration: docDuration + appliedCoverPreRoll,
528
+ appliedCoverPreRoll,
529
+ ffmpegPath
530
+ };
531
+ } finally {
532
+ await renderAPI?.dispose();
533
+ await browser.close();
534
+ }
535
+ }
536
+ async function renderDocToMp4(doc, container, options) {
537
+ const fps = options.fps ?? 30;
538
+ const quality = options.quality ?? "normal";
539
+ const orientation = options.orientation ?? "landscape";
540
+ const dimensions = resolveDimensions({
541
+ orientation,
542
+ width: options.width,
543
+ height: options.height,
544
+ fps,
545
+ quality
546
+ });
547
+ const capture = await captureDocFrames(doc, container, {
548
+ fps,
549
+ width: dimensions.width,
550
+ height: dimensions.height,
551
+ captionStyle: options.captionStyle,
552
+ coverPreRoll: options.coverPreRoll ?? 0,
553
+ animationsEnabled: options.animationsEnabled ?? true,
554
+ onProgress: options.onProgress
555
+ });
556
+ options.onProgress?.("encoding video", 80);
557
+ const encodingAudio = await buildMixedAudioTrack(
558
+ doc,
559
+ container,
560
+ capture.ffmpegPath,
561
+ capture.appliedCoverPreRoll
562
+ );
563
+ const { framesToMp4Native: framesToMp4Native2 } = await import("./nativeEncoder-WHUIQZLL.js");
564
+ await framesToMp4Native2(capture.ffmpegPath, capture.frames, encodingAudio, options.outputPath, {
565
+ fps,
566
+ quality,
567
+ orientation,
568
+ width: dimensions.width,
569
+ height: dimensions.height,
570
+ onProgress: (percent, phase) => options.onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2))
571
+ });
572
+ options.onProgress?.("done", 100);
573
+ return {
574
+ duration: capture.totalDuration,
575
+ frameCount: capture.frames.length,
576
+ outputPath: options.outputPath
577
+ };
578
+ }
579
+ async function renderDocToGif(doc, container, options) {
580
+ const fps = options.fps ?? GIF_EXPORT_DEFAULTS.fps;
581
+ if (!Number.isFinite(fps) || fps <= 0 || fps > 100) {
582
+ throw new RangeError("GIF FPS must be a finite number between 1 and 100.");
583
+ }
584
+ const orientation = options.orientation ?? "landscape";
585
+ const portrait = orientation === "portrait";
586
+ const width = options.width ?? (portrait ? GIF_EXPORT_DEFAULTS.height : GIF_EXPORT_DEFAULTS.width);
587
+ const height = options.height ?? (portrait ? GIF_EXPORT_DEFAULTS.width : GIF_EXPORT_DEFAULTS.height);
588
+ resolveDimensions({ orientation, width, height, fps });
589
+ ffmpegGifOutputArgs({
590
+ width,
591
+ height,
592
+ loop: options.loop ?? GIF_EXPORT_DEFAULTS.loop,
593
+ maxColors: options.maxColors ?? GIF_EXPORT_DEFAULTS.maxColors,
594
+ dither: options.dither ?? GIF_EXPORT_DEFAULTS.dither,
595
+ bayerScale: options.bayerScale
596
+ });
597
+ const capture = await captureDocFrames(doc, container, {
598
+ fps,
599
+ width,
600
+ height,
601
+ captionStyle: options.captionStyle,
602
+ coverPreRoll: options.coverPreRoll ?? 0,
603
+ animationsEnabled: options.animationsEnabled ?? false,
604
+ onProgress: options.onProgress
605
+ });
606
+ options.onProgress?.("encoding GIF", 80);
607
+ const { framesToGifNative: framesToGifNative2 } = await import("./nativeEncoder-WHUIQZLL.js");
608
+ await framesToGifNative2(capture.ffmpegPath, capture.frames, options.outputPath, {
609
+ fps,
610
+ orientation,
611
+ width,
612
+ height,
613
+ loop: options.loop,
614
+ maxColors: options.maxColors,
615
+ dither: options.dither,
616
+ bayerScale: options.bayerScale,
617
+ onProgress: (percent, phase) => options.onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2))
618
+ });
619
+ options.onProgress?.("done", 100);
620
+ const hasAudio = (doc.audio?.segments?.length ?? 0) > 0 || resolveMediaSchedule(doc).some((clip) => clip.kind === "audio");
621
+ return {
622
+ duration: capture.totalDuration,
623
+ frameCount: capture.frames.length,
624
+ outputPath: options.outputPath,
625
+ warnings: hasAudio ? ["Animated GIF does not support audio; audio tracks were omitted."] : []
626
+ };
627
+ }
628
+ async function extractThumbnails(options) {
629
+ const { videoPath, outputDir, slug, sizes, force } = options;
630
+ const { existsSync } = await import("fs");
631
+ const { join: join3 } = await import("path");
632
+ const { execFile: execFile2 } = await import("child_process");
633
+ const ffmpegPath = (await detectFfmpegDetailed())?.path ?? null;
634
+ if (!ffmpegPath) {
635
+ throw new Error(
636
+ "ffmpeg is required for thumbnail extraction but not found in PATH.\nInstall it with:\n macOS: brew install ffmpeg\n Ubuntu: sudo apt install ffmpeg\n Windows: winget install ffmpeg"
637
+ );
638
+ }
639
+ for (const thumb of sizes) {
640
+ const outputPath = join3(outputDir, `${slug}-${thumb.width}x${thumb.height}.jpg`);
641
+ if (!force && existsSync(outputPath)) continue;
642
+ await new Promise((resolve, reject) => {
643
+ execFile2(
644
+ ffmpegPath,
645
+ ["-y", "-i", videoPath, "-vf", thumb.filter, "-frames:v", "1", "-q:v", "2", outputPath],
646
+ { timeout: 3e4 },
647
+ (err) => {
648
+ if (err) reject(new Error(`Thumbnail extraction failed (${thumb.name}): ${err.message}`));
649
+ else resolve();
650
+ }
651
+ );
652
+ });
653
+ }
654
+ }
655
+
656
+ export {
657
+ readInput,
658
+ getFfmpegVersion,
659
+ detectFfmpegDetailed,
660
+ convert,
661
+ renderDocToMp4,
662
+ renderDocToGif,
663
+ extractThumbnails,
664
+ MemoryContentContainer2 as MemoryContentContainer,
665
+ ConversionError,
666
+ createCliRegistry
667
+ };
668
+ //# sourceMappingURL=chunk-JEE26SZS.js.map