vizmatic 0.1.2 → 0.1.4

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
@@ -365,6 +365,7 @@ Vizmatic treats generated visuals as source-controlled build artifacts. CI fails
365
365
  | `pnpm test` | Render pipeline behavior, watermark options, and output validation |
366
366
  | `pnpm render:examples` | Dark/light PNGs, animated GIFs, source snippets, and website HTML |
367
367
  | `pnpm docs:check` | Local asset references, `PROMPT.md` sync, source modal themes, and homepage affordances |
368
+ | `pnpm security:audit` | Fails on known low-or-higher npm advisories |
368
369
  | `npm pack --dry-run` | Published package contents before release |
369
370
  | CI generated-file check | Ensures rendered docs/examples are committed |
370
371
 
@@ -375,6 +376,17 @@ pnpm verify
375
376
  git diff --exit-code
376
377
  ```
377
378
 
379
+ ## Supply Chain Posture
380
+
381
+ Vizmatic keeps runtime dependencies narrow: `satori` for JSX layout, `@resvg/resvg-js` for rasterization, `gifenc` for animated GIF output, and `tsx` so the CLI can load TSX scene files directly.
382
+
383
+ Package resolution is intentionally conservative:
384
+
385
+ - `minimumReleaseAge: 10080` requires timestamped package releases to age seven days before pnpm can select them.
386
+ - `strictPeerDependencies`, `engineStrict`, and `packageManagerStrict` make install drift fail loudly.
387
+ - `overrides.esbuild: 0.28.1` keeps the build graph on the patched esbuild line used by `tsx` and `tsup`.
388
+ - `pnpm security:audit` runs inside `pnpm verify`, `prepublishOnly`, and CI.
389
+
378
390
  ## API
379
391
 
380
392
  ### Themes
package/dist/cli.js CHANGED
@@ -1,14 +1,587 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- renderAnimatedGif,
4
- renderToPng
5
- } from "./chunk-SGIYXUY3.js";
6
2
 
7
3
  // src/cli.ts
8
- import { mkdir, readFile, readdir, writeFile } from "fs/promises";
9
- import { basename, extname, join, relative, resolve } from "path";
4
+ import { mkdir as mkdir3, readFile as readFile2, readdir, writeFile as writeFile3 } from "fs/promises";
5
+ import { basename, extname, join as join2, relative, resolve } from "path";
10
6
  import { pathToFileURL } from "url";
11
7
  import { isValidElement } from "react";
8
+
9
+ // src/animate.ts
10
+ import satori2 from "satori";
11
+ import { Resvg as Resvg2 } from "@resvg/resvg-js";
12
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
13
+ import { dirname as dirname2 } from "path";
14
+ import * as gifenc from "gifenc";
15
+
16
+ // src/brand.ts
17
+ import React from "react";
18
+ var DEFAULT_WATERMARK_TEXT = "Vizmatic";
19
+ var WATERMARK_COLOR_DARK = "#a78bfa";
20
+ var WATERMARK_COLOR_LIGHT = "#7c3aed";
21
+ function VizmaticIcon({ size = 14, color }) {
22
+ return React.createElement(
23
+ "svg",
24
+ {
25
+ xmlns: "http://www.w3.org/2000/svg",
26
+ width: size,
27
+ height: size,
28
+ viewBox: "0 0 28 28",
29
+ fill: "none"
30
+ },
31
+ React.createElement("rect", { x: 2.5, y: 2.5, width: 23, height: 23, rx: 6.5, stroke: color, strokeWidth: 2, opacity: 0.54 }),
32
+ React.createElement("rect", { x: 7, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.35 }),
33
+ React.createElement("rect", { x: 15.5, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color }),
34
+ React.createElement("rect", { x: 7, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.82 }),
35
+ React.createElement("rect", { x: 15.5, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, stroke: color, strokeWidth: 1.5, opacity: 0.72 }),
36
+ React.createElement("path", { d: "M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5", stroke: color, strokeWidth: 1.6, strokeLinecap: "round", opacity: 0.88 })
37
+ );
38
+ }
39
+ function normalizeWatermark(watermark) {
40
+ if (watermark == null || watermark === false) return void 0;
41
+ if (watermark === true) return {};
42
+ if (typeof watermark === "string") return { text: watermark };
43
+ if (React.isValidElement(watermark)) {
44
+ if (watermark.type !== Watermark) return { element: watermark };
45
+ const { children, ...props } = watermark.props;
46
+ return {
47
+ ...props,
48
+ element: children ?? props.element
49
+ };
50
+ }
51
+ return watermark;
52
+ }
53
+ function Watermark(_props) {
54
+ return null;
55
+ }
56
+ function positionStyle(position) {
57
+ switch (position) {
58
+ case "top-left":
59
+ return { top: 8, left: 10 };
60
+ case "bottom-left":
61
+ return { bottom: 8, left: 10 };
62
+ case "bottom-right":
63
+ return { bottom: 8, right: 10 };
64
+ case "top-right":
65
+ default:
66
+ return { top: 8, right: 10 };
67
+ }
68
+ }
69
+ function imageNode(image) {
70
+ if (!image) return void 0;
71
+ const imageOptions = typeof image === "string" ? { src: image } : image;
72
+ return React.createElement("img", {
73
+ src: imageOptions.src,
74
+ alt: imageOptions.alt ?? "",
75
+ width: imageOptions.width ?? 14,
76
+ height: imageOptions.height ?? 14,
77
+ style: {
78
+ display: "block",
79
+ width: imageOptions.width ?? 14,
80
+ height: imageOptions.height ?? 14,
81
+ objectFit: "contain"
82
+ }
83
+ });
84
+ }
85
+ function iconNode(icon, color) {
86
+ if (icon === false) return void 0;
87
+ if (icon == null) return React.createElement(VizmaticIcon, { size: 13, color });
88
+ if (typeof icon !== "string") return icon;
89
+ return React.createElement("div", {
90
+ style: {
91
+ minWidth: 13,
92
+ height: 13,
93
+ display: "flex",
94
+ alignItems: "center",
95
+ justifyContent: "center",
96
+ color,
97
+ fontSize: icon.length > 2 ? 8 : 10,
98
+ fontWeight: 800,
99
+ fontFamily: "Inter",
100
+ lineHeight: 1
101
+ }
102
+ }, icon);
103
+ }
104
+ function wrapWithWatermark(element, width, height, theme = "dark", watermark = true) {
105
+ const isDark = theme === "dark";
106
+ const options = normalizeWatermark(watermark);
107
+ const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
108
+ const position = options?.position ?? "top-right";
109
+ const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
110
+ const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
111
+ const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
112
+ const content = options?.element ?? [
113
+ icon,
114
+ text !== false && text && React.createElement("div", {
115
+ key: "text",
116
+ style: {
117
+ fontSize: 11,
118
+ fontWeight: 600,
119
+ color,
120
+ fontFamily: "Inter",
121
+ letterSpacing: 0.3
122
+ }
123
+ }, text)
124
+ ];
125
+ return React.createElement(
126
+ "div",
127
+ {
128
+ style: {
129
+ width,
130
+ height,
131
+ display: "flex",
132
+ position: "relative"
133
+ }
134
+ },
135
+ element,
136
+ options && React.createElement(
137
+ "div",
138
+ {
139
+ style: {
140
+ position: "absolute",
141
+ ...positionStyle(position),
142
+ display: "flex",
143
+ alignItems: "center",
144
+ gap: 5,
145
+ opacity
146
+ }
147
+ },
148
+ content
149
+ )
150
+ );
151
+ }
152
+
153
+ // src/render.ts
154
+ import satori from "satori";
155
+ import { Resvg } from "@resvg/resvg-js";
156
+ import { homedir } from "os";
157
+ import { readFile, writeFile, mkdir } from "fs/promises";
158
+ import { dirname, join } from "path";
159
+ import { existsSync } from "fs";
160
+
161
+ // src/autocrop.ts
162
+ function detectBackgroundColor(pixels) {
163
+ const r = pixels[0];
164
+ const g = pixels[1];
165
+ const b = pixels[2];
166
+ const a = pixels[3];
167
+ if (a < 10) {
168
+ return "#000000";
169
+ }
170
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
171
+ }
172
+ function parseHexColor(hex) {
173
+ const h = hex.startsWith("#") ? hex.slice(1) : hex;
174
+ return [
175
+ parseInt(h.slice(0, 2), 16),
176
+ parseInt(h.slice(2, 4), 16),
177
+ parseInt(h.slice(4, 6), 16)
178
+ ];
179
+ }
180
+ function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
181
+ if (a < 10) return true;
182
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
183
+ }
184
+ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
185
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
186
+ let minX = width;
187
+ let minY = height;
188
+ let maxX = 0;
189
+ let maxY = 0;
190
+ for (let y = 0; y < height; y++) {
191
+ for (let x = 0; x < width; x++) {
192
+ const idx = (y * width + x) * 4;
193
+ const r = pixels[idx];
194
+ const g = pixels[idx + 1];
195
+ const b = pixels[idx + 2];
196
+ const a = pixels[idx + 3];
197
+ if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
198
+ if (x < minX) minX = x;
199
+ if (x > maxX) maxX = x;
200
+ if (y < minY) minY = y;
201
+ if (y > maxY) maxY = y;
202
+ }
203
+ }
204
+ }
205
+ if (minX > maxX || minY > maxY) {
206
+ return { x: 0, y: 0, width, height };
207
+ }
208
+ const cropX = Math.max(0, minX - padding);
209
+ const cropY = Math.max(0, minY - padding);
210
+ const cropRight = Math.min(width, maxX + 1 + padding);
211
+ const cropBottom = Math.min(height, maxY + 1 + padding);
212
+ return {
213
+ x: cropX,
214
+ y: cropY,
215
+ width: cropRight - cropX,
216
+ height: cropBottom - cropY
217
+ };
218
+ }
219
+ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
220
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
221
+ function isContentPixel(x, y) {
222
+ const idx = (y * width + x) * 4;
223
+ const a = pixels[idx + 3];
224
+ if (a < alphaThreshold) return false;
225
+ return !isBackground(
226
+ pixels[idx],
227
+ pixels[idx + 1],
228
+ pixels[idx + 2],
229
+ a,
230
+ bgR,
231
+ bgG,
232
+ bgB
233
+ );
234
+ }
235
+ function checkEdge(scanFn, length) {
236
+ for (let offset = 0; offset < edgeTolerance; offset++) {
237
+ let contentCount = 0;
238
+ for (let i = 0; i < length; i++) {
239
+ const [x, y] = scanFn(i, offset);
240
+ if (x >= 0 && x < width && y >= 0 && y < height && isContentPixel(x, y)) {
241
+ contentCount++;
242
+ }
243
+ }
244
+ if (contentCount / length >= minDensity) {
245
+ return true;
246
+ }
247
+ }
248
+ return false;
249
+ }
250
+ const bottom = checkEdge((i, off) => [i, height - 1 - off], width);
251
+ const right = checkEdge((i, off) => [width - 1 - off, i], height);
252
+ const top = checkEdge((i, off) => [i, off], width);
253
+ const left = checkEdge((i, off) => [off, i], height);
254
+ const overflowEdges = [];
255
+ if (top) overflowEdges.push("top");
256
+ if (right) overflowEdges.push("right");
257
+ if (bottom) overflowEdges.push("bottom");
258
+ if (left) overflowEdges.push("left");
259
+ const overflows = overflowEdges.length > 0;
260
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
261
+ return {
262
+ overflows,
263
+ edges: { top, right, bottom, left },
264
+ message
265
+ };
266
+ }
267
+
268
+ // src/render.ts
269
+ var FONT_DIR = process.env.VIZMATIC_FONT_DIR ?? join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "vizmatic", "fonts");
270
+ var FONT_URLS = {
271
+ interRegular: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",
272
+ interSemiBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",
273
+ interBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",
274
+ jetbrainsMono: "https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",
275
+ // Noto Sans (544KB from gstatic): fallback for Phonetic Extensions
276
+ // (ᵀ U+1D40, ᵢ U+1D62) and extended Latin/Greek not covered by Inter.
277
+ notoSans: "https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",
278
+ // Noto Sans Math (766KB from gstatic): math operators (√, ∞, ≠, ×, ≫),
279
+ // Greek letters (τ, Σ), and arrows (→, ←)
280
+ notoSansMath: "https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"
281
+ };
282
+ async function ensureFont(filename, url) {
283
+ const localPath = join(FONT_DIR, filename);
284
+ if (existsSync(localPath)) {
285
+ return readFile(localPath);
286
+ }
287
+ console.log(` \u2193 Downloading font: ${filename}`);
288
+ const response = await fetch(url);
289
+ if (!response.ok) {
290
+ throw new Error(`Failed to download font ${filename}: ${response.statusText}`);
291
+ }
292
+ const buffer = Buffer.from(await response.arrayBuffer());
293
+ await mkdir(FONT_DIR, { recursive: true });
294
+ await writeFile(localPath, buffer);
295
+ return buffer;
296
+ }
297
+ function toArrayBuffer(buffer) {
298
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
299
+ }
300
+ async function loadFonts() {
301
+ await mkdir(FONT_DIR, { recursive: true });
302
+ const fonts = [];
303
+ try {
304
+ const [regular, semiBold, bold] = await Promise.all([
305
+ ensureFont("Inter-Regular.ttf", FONT_URLS.interRegular),
306
+ ensureFont("Inter-SemiBold.ttf", FONT_URLS.interSemiBold),
307
+ ensureFont("Inter-Bold.ttf", FONT_URLS.interBold)
308
+ ]);
309
+ fonts.push(
310
+ { name: "Inter", data: toArrayBuffer(regular), weight: 400, style: "normal" },
311
+ { name: "Inter", data: toArrayBuffer(semiBold), weight: 600, style: "normal" },
312
+ { name: "Inter", data: toArrayBuffer(bold), weight: 700, style: "normal" }
313
+ );
314
+ } catch (e) {
315
+ console.warn("Warning: Could not load Inter font:", e);
316
+ }
317
+ try {
318
+ const jetbrains = await ensureFont("JetBrainsMono-Regular.ttf", FONT_URLS.jetbrainsMono);
319
+ fonts.push({ name: "JetBrains Mono", data: toArrayBuffer(jetbrains), weight: 400, style: "normal" });
320
+ } catch (e) {
321
+ console.warn("Warning: Could not load JetBrains Mono font:", e);
322
+ }
323
+ try {
324
+ const notoSans = await ensureFont("NotoSans-Regular.ttf", FONT_URLS.notoSans);
325
+ fonts.push(
326
+ { name: "Noto Sans", data: toArrayBuffer(notoSans), weight: 400, style: "normal" }
327
+ );
328
+ } catch (e) {
329
+ console.warn("Warning: Could not load Noto Sans font:", e);
330
+ }
331
+ try {
332
+ const notoMath = await ensureFont("NotoSansMath-Regular.ttf", FONT_URLS.notoSansMath);
333
+ fonts.push(
334
+ { name: "Noto Sans Math", data: toArrayBuffer(notoMath), weight: 400, style: "normal" }
335
+ );
336
+ } catch (e) {
337
+ console.warn("Warning: Could not load Noto Sans Math font:", e);
338
+ }
339
+ return fonts;
340
+ }
341
+ var EMOJI_CACHE_DIR = join(FONT_DIR, "emoji");
342
+ async function loadEmoji(segment) {
343
+ const codepoints = [...segment].map((c) => c.codePointAt(0).toString(16)).filter((cp) => cp !== "fe0f").join("-");
344
+ const filename = `${codepoints}.svg`;
345
+ const localPath = join(EMOJI_CACHE_DIR, filename);
346
+ if (existsSync(localPath)) {
347
+ const svgData = await readFile(localPath, "utf8");
348
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
349
+ }
350
+ const url = `https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/${codepoints}.svg`;
351
+ try {
352
+ console.log(` \u2193 Downloading emoji: ${filename}`);
353
+ const response = await fetch(url);
354
+ if (!response.ok) {
355
+ console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);
356
+ return "";
357
+ }
358
+ const svgData = await response.text();
359
+ await mkdir(EMOJI_CACHE_DIR, { recursive: true });
360
+ await writeFile(localPath, svgData);
361
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
362
+ } catch (e) {
363
+ console.warn(`Warning: Could not fetch emoji ${filename}:`, e);
364
+ return "";
365
+ }
366
+ }
367
+ async function loadAdditionalAsset(code, segment) {
368
+ if (code === "emoji") {
369
+ return loadEmoji(segment);
370
+ }
371
+ return [];
372
+ }
373
+ var cachedFonts = null;
374
+ async function getFonts() {
375
+ if (!cachedFonts) {
376
+ cachedFonts = await loadFonts();
377
+ }
378
+ return cachedFonts;
379
+ }
380
+ function sanitizeSvg(svg) {
381
+ return svg.replace(/width="0"/g, 'width="1"').replace(/height="0"/g, 'height="1"');
382
+ }
383
+ var AUTOCROP_PADDING = 24;
384
+ var CROP_THRESHOLD_PERCENT = 10;
385
+ function resolveWatermark(options) {
386
+ return options.watermark ?? options.brand;
387
+ }
388
+ async function renderToPng(element, options, createFn, theme) {
389
+ const fonts = await getFonts();
390
+ let svg = await satori(element, {
391
+ width: options.width,
392
+ height: options.height,
393
+ fonts,
394
+ loadAdditionalAsset
395
+ });
396
+ svg = sanitizeSvg(svg);
397
+ const detectResvg = new Resvg(svg, {
398
+ fitTo: { mode: "width", value: options.width },
399
+ background: "rgba(0, 0, 0, 0)"
400
+ });
401
+ const detectResult = detectResvg.render();
402
+ const detectPixels = detectResult.pixels;
403
+ const pixelData = new Uint8Array(detectPixels.buffer);
404
+ const detectedBg = detectBackgroundColor(pixelData);
405
+ const bounds = detectContentBounds(
406
+ pixelData,
407
+ options.width,
408
+ detectResult.height,
409
+ detectedBg,
410
+ AUTOCROP_PADDING
411
+ );
412
+ const overflow = detectOverflow(
413
+ pixelData,
414
+ options.width,
415
+ detectResult.height,
416
+ detectedBg
417
+ );
418
+ if (overflow.overflows) {
419
+ throw new Error(
420
+ `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
421
+ );
422
+ }
423
+ const finalWidth = options.width;
424
+ let finalHeight = options.height;
425
+ let finalElement = element;
426
+ const heightSaved = options.height - bounds.height;
427
+ const heightSavedPercent = heightSaved / options.height * 100;
428
+ if (options.crop !== false && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
429
+ finalHeight = bounds.height;
430
+ if (createFn && theme) {
431
+ finalElement = createFn(theme);
432
+ }
433
+ }
434
+ const watermark = resolveWatermark(options);
435
+ const outputElement = watermark ? wrapWithWatermark(
436
+ finalElement,
437
+ finalWidth,
438
+ finalHeight,
439
+ theme || "dark",
440
+ watermark
441
+ ) : finalElement;
442
+ let finalSvg = await satori(outputElement, {
443
+ width: finalWidth,
444
+ height: finalHeight,
445
+ fonts,
446
+ loadAdditionalAsset
447
+ });
448
+ finalSvg = sanitizeSvg(finalSvg);
449
+ const resvg = new Resvg(finalSvg, {
450
+ fitTo: {
451
+ mode: "width",
452
+ value: finalWidth * (options.scale ?? 2)
453
+ },
454
+ background: "rgba(0, 0, 0, 0)"
455
+ });
456
+ const pngData = resvg.render();
457
+ const pngBuffer = pngData.asPng();
458
+ await mkdir(dirname(options.outputPath), { recursive: true });
459
+ await writeFile(options.outputPath, pngBuffer);
460
+ }
461
+
462
+ // src/animate.ts
463
+ function resolveGifenc(api) {
464
+ if (typeof api.GIFEncoder === "function" && typeof api.applyPalette === "function" && typeof api.quantize === "function") {
465
+ return api;
466
+ }
467
+ const fallback = api.default;
468
+ if (fallback && typeof fallback.GIFEncoder === "function" && typeof fallback.applyPalette === "function" && typeof fallback.quantize === "function") {
469
+ return fallback;
470
+ }
471
+ throw new Error("gifenc exports could not be resolved");
472
+ }
473
+ var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
474
+ async function renderToPixels(element, width, height, scale) {
475
+ const fonts = await getFonts();
476
+ const svg = await satori2(element, {
477
+ width,
478
+ height,
479
+ fonts,
480
+ loadAdditionalAsset
481
+ });
482
+ const resvg = new Resvg2(svg, {
483
+ fitTo: { mode: "width", value: width * scale },
484
+ background: "rgba(0, 0, 0, 0)"
485
+ });
486
+ const rendered = resvg.render();
487
+ return {
488
+ pixels: rendered.pixels,
489
+ width: rendered.width,
490
+ height: rendered.height
491
+ };
492
+ }
493
+ function blendPixels(base, overlay, opacity) {
494
+ const result = new Uint8Array(base.length);
495
+ const inverse = 1 - opacity;
496
+ for (let index = 0; index < base.length; index += 4) {
497
+ result[index] = Math.round(base[index] * inverse + overlay[index] * opacity);
498
+ result[index + 1] = Math.round(base[index + 1] * inverse + overlay[index + 1] * opacity);
499
+ result[index + 2] = Math.round(base[index + 2] * inverse + overlay[index + 2] * opacity);
500
+ result[index + 3] = 255;
501
+ }
502
+ return result;
503
+ }
504
+ function backgroundPixels(width, height, theme) {
505
+ const buffer = new Uint8Array(width * height * 4);
506
+ const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
507
+ for (let index = 0; index < buffer.length; index += 4) {
508
+ buffer[index] = color.r;
509
+ buffer[index + 1] = color.g;
510
+ buffer[index + 2] = color.b;
511
+ buffer[index + 3] = 255;
512
+ }
513
+ return buffer;
514
+ }
515
+ function encodeGif(frames, loop) {
516
+ if (frames.length === 0) throw new Error("No GIF frames to encode");
517
+ const firstFrame = frames[0];
518
+ const gif = GIFEncoder();
519
+ for (const frame of frames) {
520
+ const palette = quantize(frame.pixels, 256, { format: "rgba4444" });
521
+ const index = applyPalette(frame.pixels, palette, "rgba4444");
522
+ gif.writeFrame(index, firstFrame.width, firstFrame.height, {
523
+ palette,
524
+ delay: Math.max(2, Math.round(frame.delay / 10)),
525
+ repeat: loop
526
+ });
527
+ }
528
+ gif.finish();
529
+ return gif.bytes();
530
+ }
531
+ var TRANSITION_FPS = 15;
532
+ var MIN_TRANSITION_FRAMES = 3;
533
+ async function scenesToFrames(scenes, options) {
534
+ if (scenes.length === 0) throw new Error("Animated GIF requires at least one scene");
535
+ const renderedScenes = [];
536
+ for (const scene of scenes) {
537
+ const watermark = options.watermark ?? options.brand;
538
+ const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
539
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
540
+ }
541
+ const frames = [];
542
+ const scaledWidth = options.width * options.scale;
543
+ const scaledHeight = options.height * options.scale;
544
+ for (let index = 0; index < scenes.length; index += 1) {
545
+ const scene = scenes[index];
546
+ const current = renderedScenes[index];
547
+ const transition = scene.transition ?? "none";
548
+ const transitionDuration = scene.transitionDuration ?? 400;
549
+ if (index > 0 && transition !== "none") {
550
+ const previous = renderedScenes[index - 1];
551
+ const transitionFrames = Math.max(
552
+ MIN_TRANSITION_FRAMES,
553
+ Math.round(transitionDuration / 1e3 * TRANSITION_FPS)
554
+ );
555
+ const frameDelay = transitionDuration / transitionFrames;
556
+ for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
557
+ const amount = (frameIndex + 1) / transitionFrames;
558
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
559
+ frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
560
+ }
561
+ }
562
+ frames.push({
563
+ pixels: current.pixels,
564
+ delay: scene.duration,
565
+ width: scaledWidth,
566
+ height: scaledHeight
567
+ });
568
+ }
569
+ return frames;
570
+ }
571
+ async function renderAnimatedGif(scenes, options) {
572
+ const normalized = {
573
+ ...options,
574
+ loop: options.loop ?? 0,
575
+ scale: options.scale ?? 1,
576
+ theme: options.theme ?? "dark"
577
+ };
578
+ await mkdir2(dirname2(options.outputPath), { recursive: true });
579
+ const frames = await scenesToFrames(scenes, normalized);
580
+ const bytes = encodeGif(frames, normalized.loop);
581
+ await writeFile2(options.outputPath, bytes);
582
+ }
583
+
584
+ // src/cli.ts
12
585
  var RENDER_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".mjs", ".ts", ".tsx"]);
13
586
  function usageText() {
14
587
  return `Usage:
@@ -45,7 +618,7 @@ function imageMime(source) {
45
618
  async function imageSourceToDataUri(source) {
46
619
  if (/^(data:|https?:\/\/)/i.test(source)) return source;
47
620
  const filePath = resolve(source);
48
- const data = await readFile(filePath);
621
+ const data = await readFile2(filePath);
49
622
  return `data:${imageMime(filePath)};base64,${data.toString("base64")}`;
50
623
  }
51
624
  async function resolveWatermarkAssets(watermark) {
@@ -178,7 +751,7 @@ async function findFrameFiles(inputs) {
178
751
  return;
179
752
  }
180
753
  for (const entry of entries) {
181
- const next = join(resolved, entry.name);
754
+ const next = join2(resolved, entry.name);
182
755
  if (entry.isDirectory()) {
183
756
  if (entry.name === "node_modules" || entry.name === "dist") continue;
184
757
  await walk(next);
@@ -221,7 +794,7 @@ async function renderCommand(argv) {
221
794
  const cliWatermark = await resolveWatermarkAssets(args.watermark);
222
795
  const files = await findFrameFiles(args.inputs);
223
796
  if (files.length === 0) throw new Error("no frame files found");
224
- await mkdir(args.outDir, { recursive: true });
797
+ await mkdir3(args.outDir, { recursive: true });
225
798
  const manifest = [];
226
799
  for (const file of files) {
227
800
  const rawMod = await importFrame(file);
@@ -231,7 +804,7 @@ async function renderCommand(argv) {
231
804
  const moduleWatermark = await resolveWatermarkAssets(mod.watermark ?? mod.brand);
232
805
  for (const theme of args.themes) {
233
806
  const outputName = `${name}_${theme}.png`;
234
- const outputPath = join(args.outDir, outputName);
807
+ const outputPath = join2(args.outDir, outputName);
235
808
  await renderToPng(frameElement(mod, theme), {
236
809
  width: mod.width,
237
810
  height: mod.height,
@@ -251,7 +824,7 @@ async function renderCommand(argv) {
251
824
  outputs
252
825
  });
253
826
  }
254
- await writeFile(join(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
827
+ await writeFile3(join2(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
255
828
  `);
256
829
  }
257
830
  async function gifCommand(argv) {
@@ -259,7 +832,7 @@ async function gifCommand(argv) {
259
832
  const cliWatermark = await resolveWatermarkAssets(args.watermark);
260
833
  const files = await findFrameFiles(args.inputs);
261
834
  if (files.length === 0) throw new Error("no frame files found");
262
- await mkdir(args.outDir, { recursive: true });
835
+ await mkdir3(args.outDir, { recursive: true });
263
836
  const manifest = [];
264
837
  for (const file of files) {
265
838
  const rawMod = await importFrame(file);
@@ -272,7 +845,7 @@ async function gifCommand(argv) {
272
845
  }
273
846
  for (const theme of args.themes) {
274
847
  const outputName = `${name}_${theme}.gif`;
275
- const outputPath = join(args.outDir, outputName);
848
+ const outputPath = join2(args.outDir, outputName);
276
849
  await renderAnimatedGif(mod.createScenes(theme), {
277
850
  width: mod.width,
278
851
  height: mod.height,
@@ -292,7 +865,7 @@ async function gifCommand(argv) {
292
865
  outputs
293
866
  });
294
867
  }
295
- await writeFile(join(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
868
+ await writeFile3(join2(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
296
869
  `);
297
870
  }
298
871
  async function main() {