@bendyline/squisq-cli 1.1.4 → 1.1.6

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.
Files changed (41) hide show
  1. package/dist/api.d.ts +45 -14
  2. package/dist/api.js +393 -304
  3. package/dist/api.js.map +1 -1
  4. package/dist/index.d.ts +2 -12
  5. package/dist/index.js +722 -20
  6. package/dist/index.js.map +1 -1
  7. package/package.json +5 -5
  8. package/dist/__tests__/convert.test.d.ts +0 -7
  9. package/dist/__tests__/convert.test.d.ts.map +0 -1
  10. package/dist/__tests__/convert.test.js +0 -127
  11. package/dist/__tests__/convert.test.js.map +0 -1
  12. package/dist/__tests__/html-export.test.d.ts +0 -8
  13. package/dist/__tests__/html-export.test.d.ts.map +0 -1
  14. package/dist/__tests__/html-export.test.js +0 -126
  15. package/dist/__tests__/html-export.test.js.map +0 -1
  16. package/dist/__tests__/readInput.test.d.ts +0 -5
  17. package/dist/__tests__/readInput.test.d.ts.map +0 -1
  18. package/dist/__tests__/readInput.test.js +0 -120
  19. package/dist/__tests__/readInput.test.js.map +0 -1
  20. package/dist/api.d.ts.map +0 -1
  21. package/dist/commands/convert.d.ts +0 -15
  22. package/dist/commands/convert.d.ts.map +0 -1
  23. package/dist/commands/convert.js +0 -264
  24. package/dist/commands/convert.js.map +0 -1
  25. package/dist/commands/video.d.ts +0 -12
  26. package/dist/commands/video.d.ts.map +0 -1
  27. package/dist/commands/video.js +0 -122
  28. package/dist/commands/video.js.map +0 -1
  29. package/dist/index.d.ts.map +0 -1
  30. package/dist/util/detectFfmpeg.d.ts +0 -15
  31. package/dist/util/detectFfmpeg.d.ts.map +0 -1
  32. package/dist/util/detectFfmpeg.js +0 -29
  33. package/dist/util/detectFfmpeg.js.map +0 -1
  34. package/dist/util/nativeEncoder.d.ts +0 -27
  35. package/dist/util/nativeEncoder.d.ts.map +0 -1
  36. package/dist/util/nativeEncoder.js +0 -106
  37. package/dist/util/nativeEncoder.js.map +0 -1
  38. package/dist/util/readInput.d.ts +0 -31
  39. package/dist/util/readInput.d.ts.map +0 -1
  40. package/dist/util/readInput.js +0 -142
  41. package/dist/util/readInput.js.map +0 -1
package/dist/api.js CHANGED
@@ -1,324 +1,413 @@
1
- /**
2
- * Programmatic Video API
3
- *
4
- * Provides a library-style entry point for rendering Squisq documents to MP4
5
- * from Node.js callers (e.g., Qualla's pipeline). This avoids the need to shell
6
- * out to the `squisq video` CLI and gives callers full control over the Doc,
7
- * MemoryContentContainer, and encoding options.
8
- *
9
- * Orchestrates the full pipeline: Doc → render HTML → Playwright frame capture → FFmpeg encode.
10
- *
11
- * Usage:
12
- * import { renderDocToMp4 } from '@bendyline/squisq-cli/api';
13
- *
14
- * await renderDocToMp4(doc, container, {
15
- * outputPath: '/tmp/output.mp4',
16
- * fps: 30,
17
- * quality: 'normal',
18
- * orientation: 'landscape',
19
- * });
20
- */
21
- import { generateRenderHtml } from '@bendyline/squisq-video';
22
- import { resolveDimensions } from '@bendyline/squisq-video';
23
- import { detectFfmpeg } from './util/detectFfmpeg.js';
24
- export { MemoryContentContainer } from '@bendyline/squisq/storage';
25
- export { readInput } from './util/readInput.js';
26
- /**
27
- * Render a Doc + media container to an MP4 video file.
28
- *
29
- * The container should contain audio and image files referenced by the Doc's
30
- * audio.segments[].src and block image paths. Files are embedded as base64
31
- * data URIs in a self-contained render HTML page.
32
- *
33
- * Requires:
34
- * - Playwright (chromium) — for headless frame capture
35
- * - FFmpeg — for video encoding (must be on PATH)
36
- *
37
- * @param doc - The Doc structure to render
38
- * @param container - MemoryContentContainer with audio/image files
39
- * @param options - Rendering and encoding options
40
- * @returns Result with duration and frame count
41
- */
42
- export async function renderDocToMp4(doc, container, options) {
43
- const { outputPath, fps = 30, quality = 'normal', orientation = 'landscape', captionStyle, coverPreRoll = 0, onProgress, } = options;
44
- const dimensions = resolveDimensions({
45
- orientation,
46
- width: options.width,
47
- height: options.height,
1
+ // src/api.ts
2
+ import { generateRenderHtml } from "@bendyline/squisq-video";
3
+ import { resolveDimensions } from "@bendyline/squisq-video";
4
+
5
+ // src/util/detectFfmpeg.ts
6
+ import { execFile } from "child_process";
7
+ async function detectFfmpeg() {
8
+ const command = process.platform === "win32" ? "where" : "which";
9
+ return new Promise((resolve) => {
10
+ execFile(command, ["ffmpeg"], { timeout: 5e3 }, (err, stdout) => {
11
+ if (err || !stdout.trim()) {
12
+ resolve(null);
13
+ return;
14
+ }
15
+ const path = stdout.trim().split("\n")[0].trim();
16
+ resolve(path);
48
17
  });
49
- // Detect ffmpeg early — needed for audio concat and video encoding
50
- const ffmpegPath = await detectFfmpeg();
51
- if (!ffmpegPath) {
52
- throw new Error('ffmpeg is required but not found in PATH.\n' +
53
- 'Install it with:\n' +
54
- ' macOS: brew install ffmpeg\n' +
55
- ' Ubuntu: sudo apt install ffmpeg\n' +
56
- ' Windows: winget install ffmpeg');
57
- }
58
- onProgress?.('collecting media', 0);
59
- // ── Collect images from container ───────────────────────────────
60
- const { collectImagePaths } = await import('@bendyline/squisq-formats/html');
61
- const imagePaths = collectImagePaths(doc);
62
- const images = new Map();
63
- for (const imgPath of imagePaths) {
64
- const data = await container.readFile(imgPath);
65
- if (data) {
66
- images.set(imgPath, data);
67
- }
18
+ });
19
+ }
20
+
21
+ // src/api.ts
22
+ import { MemoryContentContainer as MemoryContentContainer2 } from "@bendyline/squisq/storage";
23
+
24
+ // src/util/readInput.ts
25
+ import { readFile, readdir, stat } from "fs/promises";
26
+ import { join, extname } from "path";
27
+ import { parseMarkdown } from "@bendyline/squisq/markdown";
28
+ import { MemoryContentContainer } from "@bendyline/squisq/storage";
29
+ import { zipToContainer } from "@bendyline/squisq-formats/container";
30
+ var MIME_TYPES = {
31
+ ".md": "text/markdown",
32
+ ".txt": "text/plain",
33
+ ".json": "application/json",
34
+ ".jpg": "image/jpeg",
35
+ ".jpeg": "image/jpeg",
36
+ ".png": "image/png",
37
+ ".gif": "image/gif",
38
+ ".webp": "image/webp",
39
+ ".svg": "image/svg+xml",
40
+ ".mp3": "audio/mpeg",
41
+ ".wav": "audio/wav",
42
+ ".ogg": "audio/ogg",
43
+ ".mp4": "video/mp4",
44
+ ".webm": "video/webm"
45
+ };
46
+ function mimeFromExt(filePath) {
47
+ return MIME_TYPES[extname(filePath).toLowerCase()] ?? "application/octet-stream";
48
+ }
49
+ async function walkDir(root, prefix = "") {
50
+ const entries = await readdir(root, { withFileTypes: true });
51
+ const paths = [];
52
+ for (const entry of entries) {
53
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
54
+ if (entry.isDirectory()) {
55
+ paths.push(...await walkDir(join(root, entry.name), relPath));
56
+ } else if (entry.isFile()) {
57
+ paths.push(relPath);
68
58
  }
69
- // ── Collect audio segments ──────────────────────────────────────
70
- const audio = new Map();
71
- const audioBuffers = [];
72
- if (doc.audio?.segments?.length) {
73
- for (const seg of doc.audio.segments) {
74
- const data = await container.readFile(seg.src);
75
- if (data) {
76
- audio.set(seg.src, data);
77
- audio.set(seg.name, data);
78
- audioBuffers.push(data);
79
- }
80
- }
59
+ }
60
+ return paths;
61
+ }
62
+ async function readInput(inputPath) {
63
+ const info = await stat(inputPath);
64
+ if (info.isDirectory()) {
65
+ return readFolder(inputPath);
66
+ }
67
+ const ext = extname(inputPath).toLowerCase();
68
+ if (ext === ".zip" || ext === ".dbk") {
69
+ return readContainer(inputPath);
70
+ }
71
+ if (ext === ".json") {
72
+ return readDocJsonFile(inputPath);
73
+ }
74
+ return readMarkdownFile(inputPath);
75
+ }
76
+ async function readMarkdownFile(filePath) {
77
+ const content = await readFile(filePath, "utf-8");
78
+ const container = new MemoryContentContainer();
79
+ await container.writeDocument(content);
80
+ const markdownDoc = parseMarkdown(content);
81
+ return { container, markdownDoc };
82
+ }
83
+ async function readDocJsonFile(filePath) {
84
+ const content = await readFile(filePath, "utf-8");
85
+ const doc = JSON.parse(content);
86
+ const container = new MemoryContentContainer();
87
+ return { container, markdownDoc: null, doc };
88
+ }
89
+ var DOC_JSON_NAMES = ["doc.json", "story.json"];
90
+ async function readContainer(filePath) {
91
+ const data = await readFile(filePath);
92
+ const container = await zipToContainer(
93
+ data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
94
+ );
95
+ for (const name of DOC_JSON_NAMES) {
96
+ const jsonData = await container.readFile(name);
97
+ if (jsonData) {
98
+ const decoder = new TextDecoder();
99
+ const doc = JSON.parse(decoder.decode(jsonData));
100
+ return { container, markdownDoc: null, doc };
81
101
  }
82
- // Concatenate audio for the MP4's audio track
83
- let concatenatedAudio = null;
84
- if (audioBuffers.length > 0) {
85
- concatenatedAudio = await concatenateAudioBuffers(audioBuffers, ffmpegPath);
102
+ }
103
+ const markdown = await container.readDocument();
104
+ if (!markdown) {
105
+ throw new Error(`No markdown document or doc.json found in container: ${filePath}`);
106
+ }
107
+ const markdownDoc = parseMarkdown(markdown);
108
+ return { container, markdownDoc };
109
+ }
110
+ async function readFolder(dirPath) {
111
+ const container = new MemoryContentContainer();
112
+ const files = await walkDir(dirPath);
113
+ for (const relPath of files) {
114
+ const absPath = join(dirPath, relPath);
115
+ const data = await readFile(absPath);
116
+ await container.writeFile(
117
+ relPath,
118
+ new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
119
+ mimeFromExt(relPath)
120
+ );
121
+ }
122
+ for (const name of DOC_JSON_NAMES) {
123
+ const jsonData = await container.readFile(name);
124
+ if (jsonData) {
125
+ const decoder = new TextDecoder();
126
+ const doc = JSON.parse(decoder.decode(jsonData));
127
+ return { container, markdownDoc: null, doc };
86
128
  }
87
- onProgress?.('generating render HTML', 10);
88
- // ── Generate self-contained render HTML ─────────────────────────
89
- const { PLAYER_BUNDLE } = await import('@bendyline/squisq-react/standalone-source');
90
- const renderHtml = generateRenderHtml(doc, {
91
- playerScript: PLAYER_BUNDLE,
92
- images,
93
- audio: audio.size > 0 ? audio : undefined,
94
- width: dimensions.width,
95
- height: dimensions.height,
96
- captionStyle,
97
- });
98
- onProgress?.('launching browser', 15);
99
- // ── Playwright frame capture ────────────────────────────────────
100
- const { chromium } = await import('playwright-core');
101
- const browser = await chromium.launch({ headless: true });
102
- const page = await browser.newPage({
103
- viewport: { width: dimensions.width, height: dimensions.height },
104
- });
105
- const pageErrors = [];
106
- page.on('pageerror', (err) => pageErrors.push(err.message));
107
- await page.setContent(renderHtml, { waitUntil: 'load' });
108
- await page.waitForTimeout(500);
109
- try {
110
- await page.waitForFunction(() => typeof window.getDuration === 'function', { timeout: 15000 });
129
+ }
130
+ const markdown = await container.readDocument();
131
+ if (!markdown) {
132
+ throw new Error(`No markdown document or doc.json found in folder: ${dirPath}`);
133
+ }
134
+ const markdownDoc = parseMarkdown(markdown);
135
+ return { container, markdownDoc };
136
+ }
137
+
138
+ // src/api.ts
139
+ async function renderDocToMp4(doc, container, options) {
140
+ const {
141
+ outputPath,
142
+ fps = 30,
143
+ quality = "normal",
144
+ orientation = "landscape",
145
+ captionStyle,
146
+ coverPreRoll = 0,
147
+ onProgress
148
+ } = options;
149
+ const dimensions = resolveDimensions({
150
+ orientation,
151
+ width: options.width,
152
+ height: options.height
153
+ });
154
+ const ffmpegPath = await detectFfmpeg();
155
+ if (!ffmpegPath) {
156
+ throw new Error(
157
+ "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"
158
+ );
159
+ }
160
+ onProgress?.("collecting media", 0);
161
+ const { collectImagePaths } = await import("@bendyline/squisq-formats/html");
162
+ const imagePaths = collectImagePaths(doc);
163
+ const images = /* @__PURE__ */ new Map();
164
+ for (const imgPath of imagePaths) {
165
+ const data = await container.readFile(imgPath);
166
+ if (data) {
167
+ images.set(imgPath, data);
111
168
  }
112
- catch {
113
- await browser.close();
114
- const errorDetail = pageErrors.length
115
- ? `\nPage errors:\n ${pageErrors.join('\n ')}`
116
- : '\nNo page errors captured — the player may have failed to mount.';
117
- throw new Error(`Render API did not initialize within 15 seconds.${errorDetail}`);
169
+ }
170
+ const audio = /* @__PURE__ */ new Map();
171
+ const audioBuffers = [];
172
+ if (doc.audio?.segments?.length) {
173
+ for (const seg of doc.audio.segments) {
174
+ const data = await container.readFile(seg.src);
175
+ if (data) {
176
+ audio.set(seg.src, data);
177
+ audio.set(seg.name, data);
178
+ audioBuffers.push(data);
179
+ }
118
180
  }
119
- const docDuration = await page.evaluate(() => {
120
- return window.getDuration();
181
+ }
182
+ let concatenatedAudio = null;
183
+ if (audioBuffers.length > 0) {
184
+ concatenatedAudio = await concatenateAudioBuffers(audioBuffers, ffmpegPath);
185
+ }
186
+ onProgress?.("generating render HTML", 10);
187
+ const { PLAYER_BUNDLE } = await import("@bendyline/squisq-react/standalone-source");
188
+ const renderHtml = generateRenderHtml(doc, {
189
+ playerScript: PLAYER_BUNDLE,
190
+ images,
191
+ audio: audio.size > 0 ? audio : void 0,
192
+ width: dimensions.width,
193
+ height: dimensions.height,
194
+ captionStyle
195
+ });
196
+ onProgress?.("launching browser", 15);
197
+ const { chromium } = await import("playwright-core");
198
+ const browser = await chromium.launch({ headless: true });
199
+ const page = await browser.newPage({
200
+ viewport: { width: dimensions.width, height: dimensions.height }
201
+ });
202
+ const pageErrors = [];
203
+ page.on("pageerror", (err) => pageErrors.push(err.message));
204
+ await page.setContent(renderHtml, { waitUntil: "load" });
205
+ await page.waitForTimeout(500);
206
+ try {
207
+ await page.waitForFunction(
208
+ () => typeof window.getDuration === "function",
209
+ { timeout: 15e3 }
210
+ );
211
+ } catch {
212
+ await browser.close();
213
+ const errorDetail = pageErrors.length ? `
214
+ Page errors:
215
+ ${pageErrors.join("\n ")}` : "\nNo page errors captured \u2014 the player may have failed to mount.";
216
+ throw new Error(`Render API did not initialize within 15 seconds.${errorDetail}`);
217
+ }
218
+ const docDuration = await page.evaluate(() => {
219
+ return window.getDuration();
220
+ });
221
+ if (docDuration <= 0) {
222
+ await browser.close();
223
+ throw new Error("Document has zero duration \u2014 nothing to render");
224
+ }
225
+ const storyFrameCount = Math.ceil(docDuration * fps);
226
+ const preRollFrameCount = Math.ceil(coverPreRoll * fps);
227
+ const totalFrames = preRollFrameCount + storyFrameCount;
228
+ const frames = [];
229
+ onProgress?.("capturing frames", 20);
230
+ if (preRollFrameCount > 0) {
231
+ const hasCover = await page.evaluate(() => {
232
+ const w = window;
233
+ return typeof w.hasCoverBlock === "function" ? w.hasCoverBlock() : false;
121
234
  });
122
- if (docDuration <= 0) {
123
- await browser.close();
124
- throw new Error('Document has zero duration — nothing to render');
125
- }
126
- const storyFrameCount = Math.ceil(docDuration * fps);
127
- const preRollFrameCount = Math.ceil(coverPreRoll * fps);
128
- const totalFrames = preRollFrameCount + storyFrameCount;
129
- const frames = [];
130
- onProgress?.('capturing frames', 20);
131
- // Cover slide pre-roll (if requested)
132
- if (preRollFrameCount > 0) {
133
- const hasCover = await page.evaluate(() => {
134
- const w = window;
135
- return typeof w.hasCoverBlock === 'function' ? w.hasCoverBlock() : false;
136
- });
137
- if (hasCover) {
138
- await page.evaluate(() => {
139
- window.showCover();
140
- });
141
- await page.waitForTimeout(100);
142
- const coverFrame = new Uint8Array(await page.screenshot({ type: 'png' }));
143
- for (let i = 0; i < preRollFrameCount; i++) {
144
- frames.push(coverFrame);
145
- }
146
- await page.evaluate(() => {
147
- window.hideCover();
148
- });
149
- }
235
+ if (hasCover) {
236
+ await page.evaluate(() => {
237
+ window.showCover();
238
+ });
239
+ await page.waitForTimeout(100);
240
+ const coverFrame = new Uint8Array(await page.screenshot({ type: "png" }));
241
+ for (let i = 0; i < preRollFrameCount; i++) {
242
+ frames.push(coverFrame);
243
+ }
244
+ await page.evaluate(() => {
245
+ window.hideCover();
246
+ });
150
247
  }
151
- // Story frames via seekTo
152
- const frameInterval = 1 / fps;
153
- for (let i = 0; i < storyFrameCount; i++) {
154
- const time = i * frameInterval;
155
- await page.evaluate((t) => {
156
- return window.seekTo(t);
157
- }, time);
158
- const screenshot = await page.screenshot({ type: 'png' });
159
- frames.push(new Uint8Array(screenshot));
160
- // Report progress: frames phase is 20% to 80%
161
- if (i % Math.max(1, Math.floor(fps / 2)) === 0 || i === storyFrameCount - 1) {
162
- const pct = 20 + Math.round((frames.length / totalFrames) * 60);
163
- onProgress?.('capturing frames', pct);
164
- }
248
+ }
249
+ const frameInterval = 1 / fps;
250
+ for (let i = 0; i < storyFrameCount; i++) {
251
+ const time = i * frameInterval;
252
+ await page.evaluate((t) => {
253
+ return window.seekTo(t);
254
+ }, time);
255
+ const screenshot = await page.screenshot({ type: "png" });
256
+ frames.push(new Uint8Array(screenshot));
257
+ if (i % Math.max(1, Math.floor(fps / 2)) === 0 || i === storyFrameCount - 1) {
258
+ const pct = 20 + Math.round(frames.length / totalFrames * 60);
259
+ onProgress?.("capturing frames", pct);
165
260
  }
166
- await browser.close();
167
- onProgress?.('encoding video', 80);
168
- // If there's a pre-roll, delay the audio track to match
169
- let encodingAudio = concatenatedAudio;
170
- if (coverPreRoll > 0 && concatenatedAudio) {
171
- // Use FFmpeg to add silence padding at the start (adelay filter)
172
- encodingAudio = await addAudioDelay(ffmpegPath, concatenatedAudio, coverPreRoll);
261
+ }
262
+ await browser.close();
263
+ onProgress?.("encoding video", 80);
264
+ let encodingAudio = concatenatedAudio;
265
+ if (coverPreRoll > 0 && concatenatedAudio) {
266
+ encodingAudio = await addAudioDelay(ffmpegPath, concatenatedAudio, coverPreRoll);
267
+ }
268
+ const { framesToMp4Native } = await import("./nativeEncoder-MWHOONST.js");
269
+ await framesToMp4Native(ffmpegPath, frames, encodingAudio, outputPath, {
270
+ fps,
271
+ quality,
272
+ orientation,
273
+ width: dimensions.width,
274
+ height: dimensions.height,
275
+ onProgress: (percent, phase) => {
276
+ onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2));
173
277
  }
174
- const { framesToMp4Native } = await import('./util/nativeEncoder.js');
175
- await framesToMp4Native(ffmpegPath, frames, encodingAudio, outputPath, {
176
- fps,
177
- quality,
178
- orientation,
179
- width: dimensions.width,
180
- height: dimensions.height,
181
- onProgress: (percent, phase) => {
182
- onProgress?.(`encoding: ${phase}`, 80 + Math.round(percent * 0.2));
183
- },
184
- });
185
- onProgress?.('done', 100);
186
- const totalDuration = docDuration + coverPreRoll;
187
- return {
188
- duration: totalDuration,
189
- frameCount: frames.length,
190
- outputPath,
191
- };
278
+ });
279
+ onProgress?.("done", 100);
280
+ const totalDuration = docDuration + coverPreRoll;
281
+ return {
282
+ duration: totalDuration,
283
+ frameCount: frames.length,
284
+ outputPath
285
+ };
192
286
  }
193
- // ── Audio helpers ─────────────────────────────────────────────────
194
- /**
195
- * Concatenate multiple audio buffers into one.
196
- * Uses native ffmpeg concat when available, falls back to byte concatenation.
197
- */
198
287
  async function concatenateAudioBuffers(buffers, ffmpegPath) {
199
- if (buffers.length === 0)
200
- return new Uint8Array(0);
201
- if (buffers.length === 1)
202
- return new Uint8Array(buffers[0]);
203
- if (ffmpegPath) {
204
- return concatenateAudioNative(ffmpegPath, buffers);
205
- }
206
- // Fallback: naive byte concatenation (works for MP3)
207
- const totalLength = buffers.reduce((sum, b) => sum + b.byteLength, 0);
208
- const result = new Uint8Array(totalLength);
209
- let offset = 0;
210
- for (const buf of buffers) {
211
- result.set(new Uint8Array(buf), offset);
212
- offset += buf.byteLength;
213
- }
214
- return result;
288
+ if (buffers.length === 0) return new Uint8Array(0);
289
+ if (buffers.length === 1) return new Uint8Array(buffers[0]);
290
+ if (ffmpegPath) {
291
+ return concatenateAudioNative(ffmpegPath, buffers);
292
+ }
293
+ const totalLength = buffers.reduce((sum, b) => sum + b.byteLength, 0);
294
+ const result = new Uint8Array(totalLength);
295
+ let offset = 0;
296
+ for (const buf of buffers) {
297
+ result.set(new Uint8Array(buf), offset);
298
+ offset += buf.byteLength;
299
+ }
300
+ return result;
215
301
  }
216
302
  async function concatenateAudioNative(ffmpegPath, buffers) {
217
- const { writeFile, readFile, mkdir, rm } = await import('node:fs/promises');
218
- const { join } = await import('node:path');
219
- const { tmpdir } = await import('node:os');
220
- const { randomBytes } = await import('node:crypto');
221
- const { execFile } = await import('node:child_process');
222
- const tmpId = randomBytes(8).toString('hex');
223
- const workDir = join(tmpdir(), `squisq-audio-concat-${tmpId}`);
224
- await mkdir(workDir, { recursive: true });
225
- try {
226
- const segmentPaths = [];
227
- for (let i = 0; i < buffers.length; i++) {
228
- const segPath = join(workDir, `seg-${i}.mp3`);
229
- await writeFile(segPath, new Uint8Array(buffers[i]));
230
- segmentPaths.push(segPath);
231
- }
232
- const listPath = join(workDir, 'concat-list.txt');
233
- const listContent = segmentPaths.map((p) => `file '${p.replace(/\\/g, '/')}'`).join('\n');
234
- await writeFile(listPath, listContent);
235
- const outputPath = join(workDir, 'combined.mp3');
236
- await new Promise((resolve, reject) => {
237
- execFile(ffmpegPath, ['-y', '-f', 'concat', '-safe', '0', '-i', listPath, '-c', 'copy', outputPath], { timeout: 120000 }, (err) => {
238
- if (err)
239
- reject(new Error(`ffmpeg audio concat failed: ${err.message}`));
240
- else
241
- resolve();
242
- });
243
- });
244
- const data = await readFile(outputPath);
245
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
246
- }
247
- finally {
248
- await rm(workDir, { recursive: true, force: true });
303
+ const { writeFile, readFile: readFile2, mkdir, rm } = await import("fs/promises");
304
+ const { join: join2 } = await import("path");
305
+ const { tmpdir } = await import("os");
306
+ const { randomBytes } = await import("crypto");
307
+ const { execFile: execFile2 } = await import("child_process");
308
+ const tmpId = randomBytes(8).toString("hex");
309
+ const workDir = join2(tmpdir(), `squisq-audio-concat-${tmpId}`);
310
+ await mkdir(workDir, { recursive: true });
311
+ try {
312
+ const segmentPaths = [];
313
+ for (let i = 0; i < buffers.length; i++) {
314
+ const segPath = join2(workDir, `seg-${i}.mp3`);
315
+ await writeFile(segPath, new Uint8Array(buffers[i]));
316
+ segmentPaths.push(segPath);
249
317
  }
318
+ const listPath = join2(workDir, "concat-list.txt");
319
+ const listContent = segmentPaths.map((p) => `file '${p.replace(/\\/g, "/")}'`).join("\n");
320
+ await writeFile(listPath, listContent);
321
+ const outputPath = join2(workDir, "combined.mp3");
322
+ await new Promise((resolve, reject) => {
323
+ execFile2(
324
+ ffmpegPath,
325
+ ["-y", "-f", "concat", "-safe", "0", "-i", listPath, "-c", "copy", outputPath],
326
+ { timeout: 12e4 },
327
+ (err) => {
328
+ if (err) reject(new Error(`ffmpeg audio concat failed: ${err.message}`));
329
+ else resolve();
330
+ }
331
+ );
332
+ });
333
+ const data = await readFile2(outputPath);
334
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
335
+ } finally {
336
+ await rm(workDir, { recursive: true, force: true });
337
+ }
250
338
  }
251
- /**
252
- * Add silence at the start of an audio track by re-encoding with adelay filter.
253
- */
254
339
  async function addAudioDelay(ffmpegPath, audioData, delaySecs) {
255
- const { writeFile, readFile, rm } = await import('node:fs/promises');
256
- const { join } = await import('node:path');
257
- const { tmpdir } = await import('node:os');
258
- const { randomBytes } = await import('node:crypto');
259
- const { execFile } = await import('node:child_process');
260
- const tmpId = randomBytes(8).toString('hex');
261
- const inputPath = join(tmpdir(), `squisq-audio-delay-in-${tmpId}.mp3`);
262
- const outputPath = join(tmpdir(), `squisq-audio-delay-out-${tmpId}.mp3`);
263
- try {
264
- await writeFile(inputPath, audioData);
265
- const delayMs = Math.round(delaySecs * 1000);
266
- await new Promise((resolve, reject) => {
267
- execFile(ffmpegPath, [
268
- '-y',
269
- '-i',
270
- inputPath,
271
- '-af',
272
- `adelay=${delayMs}|${delayMs}`,
273
- '-c:a',
274
- 'libmp3lame',
275
- '-b:a',
276
- '128k',
277
- outputPath,
278
- ], { timeout: 60000 }, (err) => {
279
- if (err)
280
- reject(new Error(`ffmpeg audio delay failed: ${err.message}`));
281
- else
282
- resolve();
283
- });
284
- });
285
- const data = await readFile(outputPath);
286
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
287
- }
288
- finally {
289
- await rm(inputPath, { force: true });
290
- await rm(outputPath, { force: true });
291
- }
340
+ const { writeFile, readFile: readFile2, rm } = await import("fs/promises");
341
+ const { join: join2 } = await import("path");
342
+ const { tmpdir } = await import("os");
343
+ const { randomBytes } = await import("crypto");
344
+ const { execFile: execFile2 } = await import("child_process");
345
+ const tmpId = randomBytes(8).toString("hex");
346
+ const inputPath = join2(tmpdir(), `squisq-audio-delay-in-${tmpId}.mp3`);
347
+ const outputPath = join2(tmpdir(), `squisq-audio-delay-out-${tmpId}.mp3`);
348
+ try {
349
+ await writeFile(inputPath, audioData);
350
+ const delayMs = Math.round(delaySecs * 1e3);
351
+ await new Promise((resolve, reject) => {
352
+ execFile2(
353
+ ffmpegPath,
354
+ [
355
+ "-y",
356
+ "-i",
357
+ inputPath,
358
+ "-af",
359
+ `adelay=${delayMs}|${delayMs}`,
360
+ "-c:a",
361
+ "libmp3lame",
362
+ "-b:a",
363
+ "128k",
364
+ outputPath
365
+ ],
366
+ { timeout: 6e4 },
367
+ (err) => {
368
+ if (err) reject(new Error(`ffmpeg audio delay failed: ${err.message}`));
369
+ else resolve();
370
+ }
371
+ );
372
+ });
373
+ const data = await readFile2(outputPath);
374
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
375
+ } finally {
376
+ await rm(inputPath, { force: true });
377
+ await rm(outputPath, { force: true });
378
+ }
292
379
  }
293
- /**
294
- * Extract thumbnail images from the first frame of an MP4 video.
295
- * Produces JPEG files at each specified size using FFmpeg video filters.
296
- */
297
- export async function extractThumbnails(options) {
298
- const { videoPath, outputDir, slug, sizes, force } = options;
299
- const { existsSync } = await import('node:fs');
300
- const { join } = await import('node:path');
301
- const { execFile } = await import('node:child_process');
302
- const ffmpegPath = await detectFfmpeg();
303
- if (!ffmpegPath) {
304
- throw new Error('ffmpeg is required for thumbnail extraction but not found in PATH.\n' +
305
- 'Install it with:\n' +
306
- ' macOS: brew install ffmpeg\n' +
307
- ' Ubuntu: sudo apt install ffmpeg\n' +
308
- ' Windows: winget install ffmpeg');
309
- }
310
- for (const thumb of sizes) {
311
- const outputPath = join(outputDir, `${slug}-${thumb.width}x${thumb.height}.jpg`);
312
- if (!force && existsSync(outputPath))
313
- continue;
314
- await new Promise((resolve, reject) => {
315
- execFile(ffmpegPath, ['-y', '-i', videoPath, '-vf', thumb.filter, '-frames:v', '1', '-q:v', '2', outputPath], { timeout: 30000 }, (err) => {
316
- if (err)
317
- reject(new Error(`Thumbnail extraction failed (${thumb.name}): ${err.message}`));
318
- else
319
- resolve();
320
- });
321
- });
322
- }
380
+ async function extractThumbnails(options) {
381
+ const { videoPath, outputDir, slug, sizes, force } = options;
382
+ const { existsSync } = await import("fs");
383
+ const { join: join2 } = await import("path");
384
+ const { execFile: execFile2 } = await import("child_process");
385
+ const ffmpegPath = await detectFfmpeg();
386
+ if (!ffmpegPath) {
387
+ throw new Error(
388
+ "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"
389
+ );
390
+ }
391
+ for (const thumb of sizes) {
392
+ const outputPath = join2(outputDir, `${slug}-${thumb.width}x${thumb.height}.jpg`);
393
+ if (!force && existsSync(outputPath)) continue;
394
+ await new Promise((resolve, reject) => {
395
+ execFile2(
396
+ ffmpegPath,
397
+ ["-y", "-i", videoPath, "-vf", thumb.filter, "-frames:v", "1", "-q:v", "2", outputPath],
398
+ { timeout: 3e4 },
399
+ (err) => {
400
+ if (err) reject(new Error(`Thumbnail extraction failed (${thumb.name}): ${err.message}`));
401
+ else resolve();
402
+ }
403
+ );
404
+ });
405
+ }
323
406
  }
407
+ export {
408
+ MemoryContentContainer2 as MemoryContentContainer,
409
+ extractThumbnails,
410
+ readInput,
411
+ renderDocToMp4
412
+ };
324
413
  //# sourceMappingURL=api.js.map