vizmatic 0.1.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/PROMPT.md +500 -0
  3. package/README.md +530 -0
  4. package/dist/chunk-ADU7JROD.js +627 -0
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.js +303 -0
  7. package/dist/index.d.ts +1433 -0
  8. package/dist/index.js +4702 -0
  9. package/docs/PROMPT.md +500 -0
  10. package/docs/assets/examples/.gitkeep +1 -0
  11. package/docs/assets/examples/agent-pipeline_dark.png +0 -0
  12. package/docs/assets/examples/agent-pipeline_light.png +0 -0
  13. package/docs/assets/examples/animated-pipeline_dark.gif +0 -0
  14. package/docs/assets/examples/animated-pipeline_dark.png +0 -0
  15. package/docs/assets/examples/animated-pipeline_light.gif +0 -0
  16. package/docs/assets/examples/animated-pipeline_light.png +0 -0
  17. package/docs/assets/examples/attention-head_dark.png +0 -0
  18. package/docs/assets/examples/attention-head_light.png +0 -0
  19. package/docs/assets/examples/embedding-map_dark.png +0 -0
  20. package/docs/assets/examples/embedding-map_light.png +0 -0
  21. package/docs/assets/examples/eval-dashboard_dark.png +0 -0
  22. package/docs/assets/examples/eval-dashboard_light.png +0 -0
  23. package/docs/assets/examples/gif-manifest.json +12 -0
  24. package/docs/assets/examples/manifest.json +108 -0
  25. package/docs/assets/examples/model-router_dark.png +0 -0
  26. package/docs/assets/examples/model-router_light.png +0 -0
  27. package/docs/assets/examples/presentation-frame_dark.png +0 -0
  28. package/docs/assets/examples/presentation-frame_light.png +0 -0
  29. package/docs/assets/examples/rag-graph_dark.png +0 -0
  30. package/docs/assets/examples/rag-graph_light.png +0 -0
  31. package/docs/assets/examples/release-card_dark.png +0 -0
  32. package/docs/assets/examples/release-card_light.png +0 -0
  33. package/docs/assets/examples/research-landscape_dark.png +0 -0
  34. package/docs/assets/examples/research-landscape_light.png +0 -0
  35. package/docs/assets/examples/sources.json +93 -0
  36. package/docs/assets/examples/spec-anatomy_dark.png +0 -0
  37. package/docs/assets/examples/spec-anatomy_light.png +0 -0
  38. package/docs/assets/examples/theme-system_dark.png +0 -0
  39. package/docs/assets/examples/theme-system_light.png +0 -0
  40. package/docs/assets/examples/token-matrix_dark.png +0 -0
  41. package/docs/assets/examples/token-matrix_light.png +0 -0
  42. package/docs/assets/icon.svg +16 -0
  43. package/docs/assets/logo.svg +30 -0
  44. package/examples/agent-pipeline.tsx +27 -0
  45. package/examples/animated-pipeline.tsx +72 -0
  46. package/examples/attention-head.tsx +27 -0
  47. package/examples/embedding-map.tsx +34 -0
  48. package/examples/eval-dashboard.tsx +44 -0
  49. package/examples/model-router.tsx +35 -0
  50. package/examples/presentation-frame.tsx +32 -0
  51. package/examples/rag-graph.tsx +36 -0
  52. package/examples/release-card.tsx +39 -0
  53. package/examples/research-landscape.tsx +34 -0
  54. package/examples/spec-anatomy.tsx +44 -0
  55. package/examples/theme-system.tsx +30 -0
  56. package/examples/token-matrix.tsx +49 -0
  57. package/package.json +84 -0
@@ -0,0 +1,627 @@
1
+ // src/brand.ts
2
+ import React from "react";
3
+ var DEFAULT_WATERMARK_TEXT = "Vizmatic";
4
+ var WATERMARK_COLOR_DARK = "#a78bfa";
5
+ var WATERMARK_COLOR_LIGHT = "#7c3aed";
6
+ function VizmaticIcon({ size = 14, color }) {
7
+ return React.createElement(
8
+ "svg",
9
+ {
10
+ xmlns: "http://www.w3.org/2000/svg",
11
+ width: size,
12
+ height: size,
13
+ viewBox: "0 0 28 28",
14
+ fill: "none"
15
+ },
16
+ React.createElement("rect", { x: 2.5, y: 2.5, width: 23, height: 23, rx: 6.5, stroke: color, strokeWidth: 2, opacity: 0.54 }),
17
+ React.createElement("rect", { x: 7, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.35 }),
18
+ React.createElement("rect", { x: 15.5, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color }),
19
+ React.createElement("rect", { x: 7, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.82 }),
20
+ 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 }),
21
+ 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 })
22
+ );
23
+ }
24
+ function normalizeWatermark(watermark) {
25
+ if (watermark == null || watermark === false) return void 0;
26
+ if (watermark === true) return {};
27
+ if (typeof watermark === "string") return { text: watermark };
28
+ return watermark;
29
+ }
30
+ function positionStyle(position) {
31
+ switch (position) {
32
+ case "top-left":
33
+ return { top: 8, left: 10 };
34
+ case "bottom-left":
35
+ return { bottom: 8, left: 10 };
36
+ case "bottom-right":
37
+ return { bottom: 8, right: 10 };
38
+ case "top-right":
39
+ default:
40
+ return { top: 8, right: 10 };
41
+ }
42
+ }
43
+ function imageNode(image) {
44
+ if (!image) return void 0;
45
+ const imageOptions = typeof image === "string" ? { src: image } : image;
46
+ return React.createElement("img", {
47
+ src: imageOptions.src,
48
+ alt: imageOptions.alt ?? "",
49
+ width: imageOptions.width ?? 14,
50
+ height: imageOptions.height ?? 14,
51
+ style: {
52
+ display: "block",
53
+ width: imageOptions.width ?? 14,
54
+ height: imageOptions.height ?? 14,
55
+ objectFit: "contain"
56
+ }
57
+ });
58
+ }
59
+ function iconNode(icon, color) {
60
+ if (icon === false) return void 0;
61
+ if (icon == null) return React.createElement(VizmaticIcon, { size: 13, color });
62
+ if (typeof icon !== "string") return icon;
63
+ return React.createElement("div", {
64
+ style: {
65
+ minWidth: 13,
66
+ height: 13,
67
+ display: "flex",
68
+ alignItems: "center",
69
+ justifyContent: "center",
70
+ color,
71
+ fontSize: icon.length > 2 ? 8 : 10,
72
+ fontWeight: 800,
73
+ fontFamily: "Inter",
74
+ lineHeight: 1
75
+ }
76
+ }, icon);
77
+ }
78
+ function wrapWithWatermark(element, width, height, theme = "dark", watermark = true) {
79
+ const isDark = theme === "dark";
80
+ const options = normalizeWatermark(watermark);
81
+ const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
82
+ const position = options?.position ?? "top-right";
83
+ const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
84
+ const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
85
+ const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
86
+ return React.createElement(
87
+ "div",
88
+ {
89
+ style: {
90
+ width,
91
+ height,
92
+ display: "flex",
93
+ position: "relative"
94
+ }
95
+ },
96
+ element,
97
+ options && React.createElement(
98
+ "div",
99
+ {
100
+ style: {
101
+ position: "absolute",
102
+ ...positionStyle(position),
103
+ display: "flex",
104
+ alignItems: "center",
105
+ gap: 5,
106
+ opacity
107
+ }
108
+ },
109
+ icon,
110
+ text !== false && text && React.createElement("div", {
111
+ style: {
112
+ fontSize: 11,
113
+ fontWeight: 600,
114
+ color,
115
+ fontFamily: "Inter",
116
+ letterSpacing: 0.3
117
+ }
118
+ }, text)
119
+ )
120
+ );
121
+ }
122
+ function wrapWithBrand(element, width, height, theme = "dark", label = DEFAULT_WATERMARK_TEXT) {
123
+ return wrapWithWatermark(element, width, height, theme, label);
124
+ }
125
+
126
+ // src/autocrop.ts
127
+ function detectBackgroundColor(pixels) {
128
+ const r = pixels[0];
129
+ const g = pixels[1];
130
+ const b = pixels[2];
131
+ const a = pixels[3];
132
+ if (a < 10) {
133
+ return "#000000";
134
+ }
135
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
136
+ }
137
+ function parseHexColor(hex) {
138
+ const h = hex.startsWith("#") ? hex.slice(1) : hex;
139
+ return [
140
+ parseInt(h.slice(0, 2), 16),
141
+ parseInt(h.slice(2, 4), 16),
142
+ parseInt(h.slice(4, 6), 16)
143
+ ];
144
+ }
145
+ function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
146
+ if (a < 10) return true;
147
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
148
+ }
149
+ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
150
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
151
+ let minX = width;
152
+ let minY = height;
153
+ let maxX = 0;
154
+ let maxY = 0;
155
+ for (let y = 0; y < height; y++) {
156
+ for (let x = 0; x < width; x++) {
157
+ const idx = (y * width + x) * 4;
158
+ const r = pixels[idx];
159
+ const g = pixels[idx + 1];
160
+ const b = pixels[idx + 2];
161
+ const a = pixels[idx + 3];
162
+ if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
163
+ if (x < minX) minX = x;
164
+ if (x > maxX) maxX = x;
165
+ if (y < minY) minY = y;
166
+ if (y > maxY) maxY = y;
167
+ }
168
+ }
169
+ }
170
+ if (minX > maxX || minY > maxY) {
171
+ return { x: 0, y: 0, width, height };
172
+ }
173
+ const cropX = Math.max(0, minX - padding);
174
+ const cropY = Math.max(0, minY - padding);
175
+ const cropRight = Math.min(width, maxX + 1 + padding);
176
+ const cropBottom = Math.min(height, maxY + 1 + padding);
177
+ return {
178
+ x: cropX,
179
+ y: cropY,
180
+ width: cropRight - cropX,
181
+ height: cropBottom - cropY
182
+ };
183
+ }
184
+ function cropPixels(pixels, srcWidth, region) {
185
+ const out = new Uint8Array(region.width * region.height * 4);
186
+ for (let y = 0; y < region.height; y++) {
187
+ const srcOffset = ((region.y + y) * srcWidth + region.x) * 4;
188
+ const dstOffset = y * region.width * 4;
189
+ out.set(
190
+ pixels.subarray(srcOffset, srcOffset + region.width * 4),
191
+ dstOffset
192
+ );
193
+ }
194
+ return out;
195
+ }
196
+ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
197
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
198
+ function isContentPixel(x, y) {
199
+ const idx = (y * width + x) * 4;
200
+ const a = pixels[idx + 3];
201
+ if (a < alphaThreshold) return false;
202
+ return !isBackground(
203
+ pixels[idx],
204
+ pixels[idx + 1],
205
+ pixels[idx + 2],
206
+ a,
207
+ bgR,
208
+ bgG,
209
+ bgB
210
+ );
211
+ }
212
+ function checkEdge(scanFn, length) {
213
+ for (let offset = 0; offset < edgeTolerance; offset++) {
214
+ let contentCount = 0;
215
+ for (let i = 0; i < length; i++) {
216
+ const [x, y] = scanFn(i, offset);
217
+ if (x >= 0 && x < width && y >= 0 && y < height && isContentPixel(x, y)) {
218
+ contentCount++;
219
+ }
220
+ }
221
+ if (contentCount / length >= minDensity) {
222
+ return true;
223
+ }
224
+ }
225
+ return false;
226
+ }
227
+ const bottom = checkEdge((i, off) => [i, height - 1 - off], width);
228
+ const right = checkEdge((i, off) => [width - 1 - off, i], height);
229
+ const top = checkEdge((i, off) => [i, off], width);
230
+ const left = checkEdge((i, off) => [off, i], height);
231
+ const overflowEdges = [];
232
+ if (top) overflowEdges.push("top");
233
+ if (right) overflowEdges.push("right");
234
+ if (bottom) overflowEdges.push("bottom");
235
+ if (left) overflowEdges.push("left");
236
+ const overflows = overflowEdges.length > 0;
237
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
238
+ return {
239
+ overflows,
240
+ edges: { top, right, bottom, left },
241
+ message
242
+ };
243
+ }
244
+
245
+ // src/render.ts
246
+ import satori from "satori";
247
+ import { Resvg } from "@resvg/resvg-js";
248
+ import { homedir } from "os";
249
+ import { readFile, writeFile, mkdir } from "fs/promises";
250
+ import { dirname, join } from "path";
251
+ import { existsSync } from "fs";
252
+ var FONT_DIR = process.env.VIZMATIC_FONT_DIR ?? join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "vizmatic", "fonts");
253
+ var FONT_URLS = {
254
+ interRegular: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",
255
+ interSemiBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",
256
+ interBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",
257
+ jetbrainsMono: "https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",
258
+ // Noto Sans (544KB from gstatic): fallback for Phonetic Extensions
259
+ // (ᵀ U+1D40, ᵢ U+1D62) and extended Latin/Greek not covered by Inter.
260
+ notoSans: "https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",
261
+ // Noto Sans Math (766KB from gstatic): math operators (√, ∞, ≠, ×, ≫),
262
+ // Greek letters (τ, Σ), and arrows (→, ←)
263
+ notoSansMath: "https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"
264
+ };
265
+ async function ensureFont(filename, url) {
266
+ const localPath = join(FONT_DIR, filename);
267
+ if (existsSync(localPath)) {
268
+ return readFile(localPath);
269
+ }
270
+ console.log(` \u2193 Downloading font: ${filename}`);
271
+ const response = await fetch(url);
272
+ if (!response.ok) {
273
+ throw new Error(`Failed to download font ${filename}: ${response.statusText}`);
274
+ }
275
+ const buffer = Buffer.from(await response.arrayBuffer());
276
+ await mkdir(FONT_DIR, { recursive: true });
277
+ await writeFile(localPath, buffer);
278
+ return buffer;
279
+ }
280
+ function toArrayBuffer(buffer) {
281
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
282
+ }
283
+ async function loadFonts() {
284
+ await mkdir(FONT_DIR, { recursive: true });
285
+ const fonts = [];
286
+ try {
287
+ const [regular, semiBold, bold] = await Promise.all([
288
+ ensureFont("Inter-Regular.ttf", FONT_URLS.interRegular),
289
+ ensureFont("Inter-SemiBold.ttf", FONT_URLS.interSemiBold),
290
+ ensureFont("Inter-Bold.ttf", FONT_URLS.interBold)
291
+ ]);
292
+ fonts.push(
293
+ { name: "Inter", data: toArrayBuffer(regular), weight: 400, style: "normal" },
294
+ { name: "Inter", data: toArrayBuffer(semiBold), weight: 600, style: "normal" },
295
+ { name: "Inter", data: toArrayBuffer(bold), weight: 700, style: "normal" }
296
+ );
297
+ } catch (e) {
298
+ console.warn("Warning: Could not load Inter font:", e);
299
+ }
300
+ try {
301
+ const jetbrains = await ensureFont("JetBrainsMono-Regular.ttf", FONT_URLS.jetbrainsMono);
302
+ fonts.push({ name: "JetBrains Mono", data: toArrayBuffer(jetbrains), weight: 400, style: "normal" });
303
+ } catch (e) {
304
+ console.warn("Warning: Could not load JetBrains Mono font:", e);
305
+ }
306
+ try {
307
+ const notoSans = await ensureFont("NotoSans-Regular.ttf", FONT_URLS.notoSans);
308
+ fonts.push(
309
+ { name: "Noto Sans", data: toArrayBuffer(notoSans), weight: 400, style: "normal" }
310
+ );
311
+ } catch (e) {
312
+ console.warn("Warning: Could not load Noto Sans font:", e);
313
+ }
314
+ try {
315
+ const notoMath = await ensureFont("NotoSansMath-Regular.ttf", FONT_URLS.notoSansMath);
316
+ fonts.push(
317
+ { name: "Noto Sans Math", data: toArrayBuffer(notoMath), weight: 400, style: "normal" }
318
+ );
319
+ } catch (e) {
320
+ console.warn("Warning: Could not load Noto Sans Math font:", e);
321
+ }
322
+ return fonts;
323
+ }
324
+ var EMOJI_CACHE_DIR = join(FONT_DIR, "emoji");
325
+ async function loadEmoji(segment) {
326
+ const codepoints = [...segment].map((c) => c.codePointAt(0).toString(16)).filter((cp) => cp !== "fe0f").join("-");
327
+ const filename = `${codepoints}.svg`;
328
+ const localPath = join(EMOJI_CACHE_DIR, filename);
329
+ if (existsSync(localPath)) {
330
+ const svgData = await readFile(localPath, "utf8");
331
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
332
+ }
333
+ const url = `https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/${codepoints}.svg`;
334
+ try {
335
+ console.log(` \u2193 Downloading emoji: ${filename}`);
336
+ const response = await fetch(url);
337
+ if (!response.ok) {
338
+ console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);
339
+ return "";
340
+ }
341
+ const svgData = await response.text();
342
+ await mkdir(EMOJI_CACHE_DIR, { recursive: true });
343
+ await writeFile(localPath, svgData);
344
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
345
+ } catch (e) {
346
+ console.warn(`Warning: Could not fetch emoji ${filename}:`, e);
347
+ return "";
348
+ }
349
+ }
350
+ async function loadAdditionalAsset(code, segment) {
351
+ if (code === "emoji") {
352
+ return loadEmoji(segment);
353
+ }
354
+ return [];
355
+ }
356
+ var cachedFonts = null;
357
+ async function getFonts() {
358
+ if (!cachedFonts) {
359
+ cachedFonts = await loadFonts();
360
+ }
361
+ return cachedFonts;
362
+ }
363
+ function sanitizeSvg(svg) {
364
+ return svg.replace(/width="0"/g, 'width="1"').replace(/height="0"/g, 'height="1"');
365
+ }
366
+ var AUTOCROP_PADDING = 24;
367
+ var CROP_THRESHOLD_PERCENT = 10;
368
+ function resolveWatermark(options) {
369
+ return options.watermark ?? options.brand;
370
+ }
371
+ async function renderToPng(element, options, createFn, theme) {
372
+ const fonts = await getFonts();
373
+ let svg = await satori(element, {
374
+ width: options.width,
375
+ height: options.height,
376
+ fonts,
377
+ loadAdditionalAsset
378
+ });
379
+ svg = sanitizeSvg(svg);
380
+ const detectResvg = new Resvg(svg, {
381
+ fitTo: { mode: "width", value: options.width },
382
+ background: "rgba(0, 0, 0, 0)"
383
+ });
384
+ const detectResult = detectResvg.render();
385
+ const detectPixels = detectResult.pixels;
386
+ const pixelData = new Uint8Array(detectPixels.buffer);
387
+ const detectedBg = detectBackgroundColor(pixelData);
388
+ const bounds = detectContentBounds(
389
+ pixelData,
390
+ options.width,
391
+ detectResult.height,
392
+ detectedBg,
393
+ AUTOCROP_PADDING
394
+ );
395
+ const overflow = detectOverflow(
396
+ pixelData,
397
+ options.width,
398
+ detectResult.height,
399
+ detectedBg
400
+ );
401
+ if (overflow.overflows) {
402
+ throw new Error(
403
+ `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
404
+ );
405
+ }
406
+ const finalWidth = options.width;
407
+ let finalHeight = options.height;
408
+ let finalElement = element;
409
+ const heightSaved = options.height - bounds.height;
410
+ const heightSavedPercent = heightSaved / options.height * 100;
411
+ if (options.crop !== false && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
412
+ finalHeight = bounds.height;
413
+ if (createFn && theme) {
414
+ finalElement = createFn(theme);
415
+ }
416
+ }
417
+ const watermark = resolveWatermark(options);
418
+ const outputElement = watermark ? wrapWithWatermark(
419
+ finalElement,
420
+ finalWidth,
421
+ finalHeight,
422
+ theme || "dark",
423
+ watermark
424
+ ) : finalElement;
425
+ let finalSvg = await satori(outputElement, {
426
+ width: finalWidth,
427
+ height: finalHeight,
428
+ fonts,
429
+ loadAdditionalAsset
430
+ });
431
+ finalSvg = sanitizeSvg(finalSvg);
432
+ const resvg = new Resvg(finalSvg, {
433
+ fitTo: {
434
+ mode: "width",
435
+ value: finalWidth * (options.scale ?? 2)
436
+ },
437
+ background: "rgba(0, 0, 0, 0)"
438
+ });
439
+ const pngData = resvg.render();
440
+ const pngBuffer = pngData.asPng();
441
+ await mkdir(dirname(options.outputPath), { recursive: true });
442
+ await writeFile(options.outputPath, pngBuffer);
443
+ }
444
+ async function renderToBuffer(element, width, height, options = {}) {
445
+ const fonts = await getFonts();
446
+ const watermark = resolveWatermark(options);
447
+ const outputElement = watermark ? wrapWithWatermark(
448
+ element,
449
+ width,
450
+ height,
451
+ "dark",
452
+ watermark
453
+ ) : element;
454
+ let svg = await satori(outputElement, {
455
+ width,
456
+ height,
457
+ fonts,
458
+ loadAdditionalAsset
459
+ });
460
+ svg = sanitizeSvg(svg);
461
+ const resvg = new Resvg(svg, {
462
+ fitTo: { mode: "width", value: width * (options.scale ?? 2) }
463
+ });
464
+ const pngData = resvg.render();
465
+ return Buffer.from(pngData.asPng());
466
+ }
467
+ async function renderToSvg(element, width, height, options = {}) {
468
+ const fonts = await getFonts();
469
+ const watermark = resolveWatermark(options);
470
+ const outputElement = watermark ? wrapWithWatermark(
471
+ element,
472
+ width,
473
+ height,
474
+ "dark",
475
+ watermark
476
+ ) : element;
477
+ const svg = await satori(outputElement, {
478
+ width,
479
+ height,
480
+ fonts,
481
+ loadAdditionalAsset
482
+ });
483
+ return sanitizeSvg(svg);
484
+ }
485
+
486
+ // src/animate.ts
487
+ import satori2 from "satori";
488
+ import { Resvg as Resvg2 } from "@resvg/resvg-js";
489
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
490
+ import { dirname as dirname2 } from "path";
491
+ import * as gifenc from "gifenc";
492
+ function resolveGifenc(api) {
493
+ if (typeof api.GIFEncoder === "function" && typeof api.applyPalette === "function" && typeof api.quantize === "function") {
494
+ return api;
495
+ }
496
+ const fallback = api.default;
497
+ if (fallback && typeof fallback.GIFEncoder === "function" && typeof fallback.applyPalette === "function" && typeof fallback.quantize === "function") {
498
+ return fallback;
499
+ }
500
+ throw new Error("gifenc exports could not be resolved");
501
+ }
502
+ var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
503
+ async function renderToPixels(element, width, height, scale) {
504
+ const fonts = await getFonts();
505
+ const svg = await satori2(element, {
506
+ width,
507
+ height,
508
+ fonts,
509
+ loadAdditionalAsset
510
+ });
511
+ const resvg = new Resvg2(svg, {
512
+ fitTo: { mode: "width", value: width * scale },
513
+ background: "rgba(0, 0, 0, 0)"
514
+ });
515
+ const rendered = resvg.render();
516
+ return {
517
+ pixels: rendered.pixels,
518
+ width: rendered.width,
519
+ height: rendered.height
520
+ };
521
+ }
522
+ function blendPixels(base, overlay, opacity) {
523
+ const result = new Uint8Array(base.length);
524
+ const inverse = 1 - opacity;
525
+ for (let index = 0; index < base.length; index += 4) {
526
+ result[index] = Math.round(base[index] * inverse + overlay[index] * opacity);
527
+ result[index + 1] = Math.round(base[index + 1] * inverse + overlay[index + 1] * opacity);
528
+ result[index + 2] = Math.round(base[index + 2] * inverse + overlay[index + 2] * opacity);
529
+ result[index + 3] = 255;
530
+ }
531
+ return result;
532
+ }
533
+ function backgroundPixels(width, height, theme) {
534
+ const buffer = new Uint8Array(width * height * 4);
535
+ const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
536
+ for (let index = 0; index < buffer.length; index += 4) {
537
+ buffer[index] = color.r;
538
+ buffer[index + 1] = color.g;
539
+ buffer[index + 2] = color.b;
540
+ buffer[index + 3] = 255;
541
+ }
542
+ return buffer;
543
+ }
544
+ function encodeGif(frames, loop) {
545
+ if (frames.length === 0) throw new Error("No GIF frames to encode");
546
+ const firstFrame = frames[0];
547
+ const gif = GIFEncoder();
548
+ for (const frame of frames) {
549
+ const palette = quantize(frame.pixels, 256, { format: "rgba4444" });
550
+ const index = applyPalette(frame.pixels, palette, "rgba4444");
551
+ gif.writeFrame(index, firstFrame.width, firstFrame.height, {
552
+ palette,
553
+ delay: Math.max(2, Math.round(frame.delay / 10)),
554
+ repeat: loop
555
+ });
556
+ }
557
+ gif.finish();
558
+ return gif.bytes();
559
+ }
560
+ var TRANSITION_FPS = 15;
561
+ var MIN_TRANSITION_FRAMES = 3;
562
+ async function scenesToFrames(scenes, options) {
563
+ if (scenes.length === 0) throw new Error("Animated GIF requires at least one scene");
564
+ const renderedScenes = [];
565
+ for (const scene of scenes) {
566
+ const watermark = options.watermark ?? options.brand;
567
+ const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
568
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
569
+ }
570
+ const frames = [];
571
+ const scaledWidth = options.width * options.scale;
572
+ const scaledHeight = options.height * options.scale;
573
+ for (let index = 0; index < scenes.length; index += 1) {
574
+ const scene = scenes[index];
575
+ const current = renderedScenes[index];
576
+ const transition = scene.transition ?? "none";
577
+ const transitionDuration = scene.transitionDuration ?? 400;
578
+ if (index > 0 && transition !== "none") {
579
+ const previous = renderedScenes[index - 1];
580
+ const transitionFrames = Math.max(
581
+ MIN_TRANSITION_FRAMES,
582
+ Math.round(transitionDuration / 1e3 * TRANSITION_FPS)
583
+ );
584
+ const frameDelay = transitionDuration / transitionFrames;
585
+ for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
586
+ const amount = (frameIndex + 1) / transitionFrames;
587
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
588
+ frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
589
+ }
590
+ }
591
+ frames.push({
592
+ pixels: current.pixels,
593
+ delay: scene.duration,
594
+ width: scaledWidth,
595
+ height: scaledHeight
596
+ });
597
+ }
598
+ return frames;
599
+ }
600
+ async function renderAnimatedGif(scenes, options) {
601
+ const normalized = {
602
+ ...options,
603
+ loop: options.loop ?? 0,
604
+ scale: options.scale ?? 1,
605
+ theme: options.theme ?? "dark"
606
+ };
607
+ await mkdir2(dirname2(options.outputPath), { recursive: true });
608
+ const frames = await scenesToFrames(scenes, normalized);
609
+ const bytes = encodeGif(frames, normalized.loop);
610
+ await writeFile2(options.outputPath, bytes);
611
+ }
612
+
613
+ export {
614
+ normalizeWatermark,
615
+ wrapWithWatermark,
616
+ wrapWithBrand,
617
+ detectBackgroundColor,
618
+ detectContentBounds,
619
+ cropPixels,
620
+ detectOverflow,
621
+ loadAdditionalAsset,
622
+ getFonts,
623
+ renderToPng,
624
+ renderToBuffer,
625
+ renderToSvg,
626
+ renderAnimatedGif
627
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node