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/dist/index.js CHANGED
@@ -1,20 +1,3 @@
1
- import {
2
- Watermark,
3
- cropPixels,
4
- detectBackgroundColor,
5
- detectContentBounds,
6
- detectOverflow,
7
- getFonts,
8
- loadAdditionalAsset,
9
- normalizeWatermark,
10
- renderAnimatedGif,
11
- renderToBuffer,
12
- renderToPng,
13
- renderToSvg,
14
- wrapWithBrand,
15
- wrapWithWatermark
16
- } from "./chunk-SGIYXUY3.js";
17
-
18
1
  // src/theme.ts
19
2
  var darkColors = {
20
3
  // Canvas backgrounds
@@ -4609,6 +4592,635 @@ function Legend({ items, c, title }) {
4609
4592
  )
4610
4593
  );
4611
4594
  }
4595
+
4596
+ // src/render.ts
4597
+ import satori from "satori";
4598
+ import { Resvg } from "@resvg/resvg-js";
4599
+ import { homedir } from "os";
4600
+ import { readFile, writeFile, mkdir } from "fs/promises";
4601
+ import { dirname, join } from "path";
4602
+ import { existsSync } from "fs";
4603
+
4604
+ // src/brand.ts
4605
+ import React2 from "react";
4606
+ var DEFAULT_WATERMARK_TEXT = "Vizmatic";
4607
+ var WATERMARK_COLOR_DARK = "#a78bfa";
4608
+ var WATERMARK_COLOR_LIGHT = "#7c3aed";
4609
+ function VizmaticIcon({ size = 14, color }) {
4610
+ return React2.createElement(
4611
+ "svg",
4612
+ {
4613
+ xmlns: "http://www.w3.org/2000/svg",
4614
+ width: size,
4615
+ height: size,
4616
+ viewBox: "0 0 28 28",
4617
+ fill: "none"
4618
+ },
4619
+ React2.createElement("rect", { x: 2.5, y: 2.5, width: 23, height: 23, rx: 6.5, stroke: color, strokeWidth: 2, opacity: 0.54 }),
4620
+ React2.createElement("rect", { x: 7, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.35 }),
4621
+ React2.createElement("rect", { x: 15.5, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color }),
4622
+ React2.createElement("rect", { x: 7, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.82 }),
4623
+ React2.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 }),
4624
+ React2.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 })
4625
+ );
4626
+ }
4627
+ function normalizeWatermark(watermark) {
4628
+ if (watermark == null || watermark === false) return void 0;
4629
+ if (watermark === true) return {};
4630
+ if (typeof watermark === "string") return { text: watermark };
4631
+ if (React2.isValidElement(watermark)) {
4632
+ if (watermark.type !== Watermark) return { element: watermark };
4633
+ const { children, ...props } = watermark.props;
4634
+ return {
4635
+ ...props,
4636
+ element: children ?? props.element
4637
+ };
4638
+ }
4639
+ return watermark;
4640
+ }
4641
+ function Watermark(_props) {
4642
+ return null;
4643
+ }
4644
+ function positionStyle(position) {
4645
+ switch (position) {
4646
+ case "top-left":
4647
+ return { top: 8, left: 10 };
4648
+ case "bottom-left":
4649
+ return { bottom: 8, left: 10 };
4650
+ case "bottom-right":
4651
+ return { bottom: 8, right: 10 };
4652
+ case "top-right":
4653
+ default:
4654
+ return { top: 8, right: 10 };
4655
+ }
4656
+ }
4657
+ function imageNode(image) {
4658
+ if (!image) return void 0;
4659
+ const imageOptions = typeof image === "string" ? { src: image } : image;
4660
+ return React2.createElement("img", {
4661
+ src: imageOptions.src,
4662
+ alt: imageOptions.alt ?? "",
4663
+ width: imageOptions.width ?? 14,
4664
+ height: imageOptions.height ?? 14,
4665
+ style: {
4666
+ display: "block",
4667
+ width: imageOptions.width ?? 14,
4668
+ height: imageOptions.height ?? 14,
4669
+ objectFit: "contain"
4670
+ }
4671
+ });
4672
+ }
4673
+ function iconNode(icon, color) {
4674
+ if (icon === false) return void 0;
4675
+ if (icon == null) return React2.createElement(VizmaticIcon, { size: 13, color });
4676
+ if (typeof icon !== "string") return icon;
4677
+ return React2.createElement("div", {
4678
+ style: {
4679
+ minWidth: 13,
4680
+ height: 13,
4681
+ display: "flex",
4682
+ alignItems: "center",
4683
+ justifyContent: "center",
4684
+ color,
4685
+ fontSize: icon.length > 2 ? 8 : 10,
4686
+ fontWeight: 800,
4687
+ fontFamily: "Inter",
4688
+ lineHeight: 1
4689
+ }
4690
+ }, icon);
4691
+ }
4692
+ function wrapWithWatermark(element, width, height, theme = "dark", watermark = true) {
4693
+ const isDark = theme === "dark";
4694
+ const options = normalizeWatermark(watermark);
4695
+ const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
4696
+ const position = options?.position ?? "top-right";
4697
+ const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
4698
+ const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
4699
+ const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
4700
+ const content = options?.element ?? [
4701
+ icon,
4702
+ text !== false && text && React2.createElement("div", {
4703
+ key: "text",
4704
+ style: {
4705
+ fontSize: 11,
4706
+ fontWeight: 600,
4707
+ color,
4708
+ fontFamily: "Inter",
4709
+ letterSpacing: 0.3
4710
+ }
4711
+ }, text)
4712
+ ];
4713
+ return React2.createElement(
4714
+ "div",
4715
+ {
4716
+ style: {
4717
+ width,
4718
+ height,
4719
+ display: "flex",
4720
+ position: "relative"
4721
+ }
4722
+ },
4723
+ element,
4724
+ options && React2.createElement(
4725
+ "div",
4726
+ {
4727
+ style: {
4728
+ position: "absolute",
4729
+ ...positionStyle(position),
4730
+ display: "flex",
4731
+ alignItems: "center",
4732
+ gap: 5,
4733
+ opacity
4734
+ }
4735
+ },
4736
+ content
4737
+ )
4738
+ );
4739
+ }
4740
+ function wrapWithBrand(element, width, height, theme = "dark", label = DEFAULT_WATERMARK_TEXT) {
4741
+ return wrapWithWatermark(element, width, height, theme, label);
4742
+ }
4743
+
4744
+ // src/autocrop.ts
4745
+ function detectBackgroundColor(pixels) {
4746
+ const r = pixels[0];
4747
+ const g = pixels[1];
4748
+ const b = pixels[2];
4749
+ const a = pixels[3];
4750
+ if (a < 10) {
4751
+ return "#000000";
4752
+ }
4753
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
4754
+ }
4755
+ function parseHexColor(hex) {
4756
+ const h = hex.startsWith("#") ? hex.slice(1) : hex;
4757
+ return [
4758
+ parseInt(h.slice(0, 2), 16),
4759
+ parseInt(h.slice(2, 4), 16),
4760
+ parseInt(h.slice(4, 6), 16)
4761
+ ];
4762
+ }
4763
+ function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
4764
+ if (a < 10) return true;
4765
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4766
+ }
4767
+ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4768
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
4769
+ let minX = width;
4770
+ let minY = height;
4771
+ let maxX = 0;
4772
+ let maxY = 0;
4773
+ for (let y = 0; y < height; y++) {
4774
+ for (let x = 0; x < width; x++) {
4775
+ const idx = (y * width + x) * 4;
4776
+ const r = pixels[idx];
4777
+ const g = pixels[idx + 1];
4778
+ const b = pixels[idx + 2];
4779
+ const a = pixels[idx + 3];
4780
+ if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
4781
+ if (x < minX) minX = x;
4782
+ if (x > maxX) maxX = x;
4783
+ if (y < minY) minY = y;
4784
+ if (y > maxY) maxY = y;
4785
+ }
4786
+ }
4787
+ }
4788
+ if (minX > maxX || minY > maxY) {
4789
+ return { x: 0, y: 0, width, height };
4790
+ }
4791
+ const cropX = Math.max(0, minX - padding);
4792
+ const cropY = Math.max(0, minY - padding);
4793
+ const cropRight = Math.min(width, maxX + 1 + padding);
4794
+ const cropBottom = Math.min(height, maxY + 1 + padding);
4795
+ return {
4796
+ x: cropX,
4797
+ y: cropY,
4798
+ width: cropRight - cropX,
4799
+ height: cropBottom - cropY
4800
+ };
4801
+ }
4802
+ function cropPixels(pixels, srcWidth, region) {
4803
+ const out = new Uint8Array(region.width * region.height * 4);
4804
+ for (let y = 0; y < region.height; y++) {
4805
+ const srcOffset = ((region.y + y) * srcWidth + region.x) * 4;
4806
+ const dstOffset = y * region.width * 4;
4807
+ out.set(
4808
+ pixels.subarray(srcOffset, srcOffset + region.width * 4),
4809
+ dstOffset
4810
+ );
4811
+ }
4812
+ return out;
4813
+ }
4814
+ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
4815
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
4816
+ function isContentPixel(x, y) {
4817
+ const idx = (y * width + x) * 4;
4818
+ const a = pixels[idx + 3];
4819
+ if (a < alphaThreshold) return false;
4820
+ return !isBackground(
4821
+ pixels[idx],
4822
+ pixels[idx + 1],
4823
+ pixels[idx + 2],
4824
+ a,
4825
+ bgR,
4826
+ bgG,
4827
+ bgB
4828
+ );
4829
+ }
4830
+ function checkEdge(scanFn, length) {
4831
+ for (let offset = 0; offset < edgeTolerance; offset++) {
4832
+ let contentCount = 0;
4833
+ for (let i = 0; i < length; i++) {
4834
+ const [x, y] = scanFn(i, offset);
4835
+ if (x >= 0 && x < width && y >= 0 && y < height && isContentPixel(x, y)) {
4836
+ contentCount++;
4837
+ }
4838
+ }
4839
+ if (contentCount / length >= minDensity) {
4840
+ return true;
4841
+ }
4842
+ }
4843
+ return false;
4844
+ }
4845
+ const bottom = checkEdge((i, off) => [i, height - 1 - off], width);
4846
+ const right = checkEdge((i, off) => [width - 1 - off, i], height);
4847
+ const top = checkEdge((i, off) => [i, off], width);
4848
+ const left = checkEdge((i, off) => [off, i], height);
4849
+ const overflowEdges = [];
4850
+ if (top) overflowEdges.push("top");
4851
+ if (right) overflowEdges.push("right");
4852
+ if (bottom) overflowEdges.push("bottom");
4853
+ if (left) overflowEdges.push("left");
4854
+ const overflows = overflowEdges.length > 0;
4855
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
4856
+ return {
4857
+ overflows,
4858
+ edges: { top, right, bottom, left },
4859
+ message
4860
+ };
4861
+ }
4862
+
4863
+ // src/render.ts
4864
+ var FONT_DIR = process.env.VIZMATIC_FONT_DIR ?? join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "vizmatic", "fonts");
4865
+ var FONT_URLS = {
4866
+ interRegular: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",
4867
+ interSemiBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",
4868
+ interBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",
4869
+ jetbrainsMono: "https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",
4870
+ // Noto Sans (544KB from gstatic): fallback for Phonetic Extensions
4871
+ // (ᵀ U+1D40, ᵢ U+1D62) and extended Latin/Greek not covered by Inter.
4872
+ notoSans: "https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",
4873
+ // Noto Sans Math (766KB from gstatic): math operators (√, ∞, ≠, ×, ≫),
4874
+ // Greek letters (τ, Σ), and arrows (→, ←)
4875
+ notoSansMath: "https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"
4876
+ };
4877
+ async function ensureFont(filename, url) {
4878
+ const localPath = join(FONT_DIR, filename);
4879
+ if (existsSync(localPath)) {
4880
+ return readFile(localPath);
4881
+ }
4882
+ console.log(` \u2193 Downloading font: ${filename}`);
4883
+ const response = await fetch(url);
4884
+ if (!response.ok) {
4885
+ throw new Error(`Failed to download font ${filename}: ${response.statusText}`);
4886
+ }
4887
+ const buffer = Buffer.from(await response.arrayBuffer());
4888
+ await mkdir(FONT_DIR, { recursive: true });
4889
+ await writeFile(localPath, buffer);
4890
+ return buffer;
4891
+ }
4892
+ function toArrayBuffer(buffer) {
4893
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
4894
+ }
4895
+ async function loadFonts() {
4896
+ await mkdir(FONT_DIR, { recursive: true });
4897
+ const fonts = [];
4898
+ try {
4899
+ const [regular, semiBold, bold] = await Promise.all([
4900
+ ensureFont("Inter-Regular.ttf", FONT_URLS.interRegular),
4901
+ ensureFont("Inter-SemiBold.ttf", FONT_URLS.interSemiBold),
4902
+ ensureFont("Inter-Bold.ttf", FONT_URLS.interBold)
4903
+ ]);
4904
+ fonts.push(
4905
+ { name: "Inter", data: toArrayBuffer(regular), weight: 400, style: "normal" },
4906
+ { name: "Inter", data: toArrayBuffer(semiBold), weight: 600, style: "normal" },
4907
+ { name: "Inter", data: toArrayBuffer(bold), weight: 700, style: "normal" }
4908
+ );
4909
+ } catch (e) {
4910
+ console.warn("Warning: Could not load Inter font:", e);
4911
+ }
4912
+ try {
4913
+ const jetbrains = await ensureFont("JetBrainsMono-Regular.ttf", FONT_URLS.jetbrainsMono);
4914
+ fonts.push({ name: "JetBrains Mono", data: toArrayBuffer(jetbrains), weight: 400, style: "normal" });
4915
+ } catch (e) {
4916
+ console.warn("Warning: Could not load JetBrains Mono font:", e);
4917
+ }
4918
+ try {
4919
+ const notoSans = await ensureFont("NotoSans-Regular.ttf", FONT_URLS.notoSans);
4920
+ fonts.push(
4921
+ { name: "Noto Sans", data: toArrayBuffer(notoSans), weight: 400, style: "normal" }
4922
+ );
4923
+ } catch (e) {
4924
+ console.warn("Warning: Could not load Noto Sans font:", e);
4925
+ }
4926
+ try {
4927
+ const notoMath = await ensureFont("NotoSansMath-Regular.ttf", FONT_URLS.notoSansMath);
4928
+ fonts.push(
4929
+ { name: "Noto Sans Math", data: toArrayBuffer(notoMath), weight: 400, style: "normal" }
4930
+ );
4931
+ } catch (e) {
4932
+ console.warn("Warning: Could not load Noto Sans Math font:", e);
4933
+ }
4934
+ return fonts;
4935
+ }
4936
+ var EMOJI_CACHE_DIR = join(FONT_DIR, "emoji");
4937
+ async function loadEmoji(segment) {
4938
+ const codepoints = [...segment].map((c) => c.codePointAt(0).toString(16)).filter((cp) => cp !== "fe0f").join("-");
4939
+ const filename = `${codepoints}.svg`;
4940
+ const localPath = join(EMOJI_CACHE_DIR, filename);
4941
+ if (existsSync(localPath)) {
4942
+ const svgData = await readFile(localPath, "utf8");
4943
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
4944
+ }
4945
+ const url = `https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/${codepoints}.svg`;
4946
+ try {
4947
+ console.log(` \u2193 Downloading emoji: ${filename}`);
4948
+ const response = await fetch(url);
4949
+ if (!response.ok) {
4950
+ console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);
4951
+ return "";
4952
+ }
4953
+ const svgData = await response.text();
4954
+ await mkdir(EMOJI_CACHE_DIR, { recursive: true });
4955
+ await writeFile(localPath, svgData);
4956
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
4957
+ } catch (e) {
4958
+ console.warn(`Warning: Could not fetch emoji ${filename}:`, e);
4959
+ return "";
4960
+ }
4961
+ }
4962
+ async function loadAdditionalAsset(code, segment) {
4963
+ if (code === "emoji") {
4964
+ return loadEmoji(segment);
4965
+ }
4966
+ return [];
4967
+ }
4968
+ var cachedFonts = null;
4969
+ async function getFonts() {
4970
+ if (!cachedFonts) {
4971
+ cachedFonts = await loadFonts();
4972
+ }
4973
+ return cachedFonts;
4974
+ }
4975
+ function sanitizeSvg(svg) {
4976
+ return svg.replace(/width="0"/g, 'width="1"').replace(/height="0"/g, 'height="1"');
4977
+ }
4978
+ var AUTOCROP_PADDING = 24;
4979
+ var CROP_THRESHOLD_PERCENT = 10;
4980
+ function resolveWatermark(options) {
4981
+ return options.watermark ?? options.brand;
4982
+ }
4983
+ async function renderToPng(element, options, createFn, theme) {
4984
+ const fonts = await getFonts();
4985
+ let svg = await satori(element, {
4986
+ width: options.width,
4987
+ height: options.height,
4988
+ fonts,
4989
+ loadAdditionalAsset
4990
+ });
4991
+ svg = sanitizeSvg(svg);
4992
+ const detectResvg = new Resvg(svg, {
4993
+ fitTo: { mode: "width", value: options.width },
4994
+ background: "rgba(0, 0, 0, 0)"
4995
+ });
4996
+ const detectResult = detectResvg.render();
4997
+ const detectPixels = detectResult.pixels;
4998
+ const pixelData = new Uint8Array(detectPixels.buffer);
4999
+ const detectedBg = detectBackgroundColor(pixelData);
5000
+ const bounds = detectContentBounds(
5001
+ pixelData,
5002
+ options.width,
5003
+ detectResult.height,
5004
+ detectedBg,
5005
+ AUTOCROP_PADDING
5006
+ );
5007
+ const overflow = detectOverflow(
5008
+ pixelData,
5009
+ options.width,
5010
+ detectResult.height,
5011
+ detectedBg
5012
+ );
5013
+ if (overflow.overflows) {
5014
+ throw new Error(
5015
+ `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
5016
+ );
5017
+ }
5018
+ const finalWidth = options.width;
5019
+ let finalHeight = options.height;
5020
+ let finalElement = element;
5021
+ const heightSaved = options.height - bounds.height;
5022
+ const heightSavedPercent = heightSaved / options.height * 100;
5023
+ if (options.crop !== false && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
5024
+ finalHeight = bounds.height;
5025
+ if (createFn && theme) {
5026
+ finalElement = createFn(theme);
5027
+ }
5028
+ }
5029
+ const watermark = resolveWatermark(options);
5030
+ const outputElement = watermark ? wrapWithWatermark(
5031
+ finalElement,
5032
+ finalWidth,
5033
+ finalHeight,
5034
+ theme || "dark",
5035
+ watermark
5036
+ ) : finalElement;
5037
+ let finalSvg = await satori(outputElement, {
5038
+ width: finalWidth,
5039
+ height: finalHeight,
5040
+ fonts,
5041
+ loadAdditionalAsset
5042
+ });
5043
+ finalSvg = sanitizeSvg(finalSvg);
5044
+ const resvg = new Resvg(finalSvg, {
5045
+ fitTo: {
5046
+ mode: "width",
5047
+ value: finalWidth * (options.scale ?? 2)
5048
+ },
5049
+ background: "rgba(0, 0, 0, 0)"
5050
+ });
5051
+ const pngData = resvg.render();
5052
+ const pngBuffer = pngData.asPng();
5053
+ await mkdir(dirname(options.outputPath), { recursive: true });
5054
+ await writeFile(options.outputPath, pngBuffer);
5055
+ }
5056
+ async function renderToBuffer(element, width, height, options = {}) {
5057
+ const fonts = await getFonts();
5058
+ const watermark = resolveWatermark(options);
5059
+ const outputElement = watermark ? wrapWithWatermark(
5060
+ element,
5061
+ width,
5062
+ height,
5063
+ "dark",
5064
+ watermark
5065
+ ) : element;
5066
+ let svg = await satori(outputElement, {
5067
+ width,
5068
+ height,
5069
+ fonts,
5070
+ loadAdditionalAsset
5071
+ });
5072
+ svg = sanitizeSvg(svg);
5073
+ const resvg = new Resvg(svg, {
5074
+ fitTo: { mode: "width", value: width * (options.scale ?? 2) }
5075
+ });
5076
+ const pngData = resvg.render();
5077
+ return Buffer.from(pngData.asPng());
5078
+ }
5079
+ async function renderToSvg(element, width, height, options = {}) {
5080
+ const fonts = await getFonts();
5081
+ const watermark = resolveWatermark(options);
5082
+ const outputElement = watermark ? wrapWithWatermark(
5083
+ element,
5084
+ width,
5085
+ height,
5086
+ "dark",
5087
+ watermark
5088
+ ) : element;
5089
+ const svg = await satori(outputElement, {
5090
+ width,
5091
+ height,
5092
+ fonts,
5093
+ loadAdditionalAsset
5094
+ });
5095
+ return sanitizeSvg(svg);
5096
+ }
5097
+
5098
+ // src/animate.ts
5099
+ import satori2 from "satori";
5100
+ import { Resvg as Resvg2 } from "@resvg/resvg-js";
5101
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
5102
+ import { dirname as dirname2 } from "path";
5103
+ import * as gifenc from "gifenc";
5104
+ function resolveGifenc(api) {
5105
+ if (typeof api.GIFEncoder === "function" && typeof api.applyPalette === "function" && typeof api.quantize === "function") {
5106
+ return api;
5107
+ }
5108
+ const fallback = api.default;
5109
+ if (fallback && typeof fallback.GIFEncoder === "function" && typeof fallback.applyPalette === "function" && typeof fallback.quantize === "function") {
5110
+ return fallback;
5111
+ }
5112
+ throw new Error("gifenc exports could not be resolved");
5113
+ }
5114
+ var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
5115
+ async function renderToPixels(element, width, height, scale) {
5116
+ const fonts = await getFonts();
5117
+ const svg = await satori2(element, {
5118
+ width,
5119
+ height,
5120
+ fonts,
5121
+ loadAdditionalAsset
5122
+ });
5123
+ const resvg = new Resvg2(svg, {
5124
+ fitTo: { mode: "width", value: width * scale },
5125
+ background: "rgba(0, 0, 0, 0)"
5126
+ });
5127
+ const rendered = resvg.render();
5128
+ return {
5129
+ pixels: rendered.pixels,
5130
+ width: rendered.width,
5131
+ height: rendered.height
5132
+ };
5133
+ }
5134
+ function blendPixels(base, overlay, opacity) {
5135
+ const result = new Uint8Array(base.length);
5136
+ const inverse = 1 - opacity;
5137
+ for (let index = 0; index < base.length; index += 4) {
5138
+ result[index] = Math.round(base[index] * inverse + overlay[index] * opacity);
5139
+ result[index + 1] = Math.round(base[index + 1] * inverse + overlay[index + 1] * opacity);
5140
+ result[index + 2] = Math.round(base[index + 2] * inverse + overlay[index + 2] * opacity);
5141
+ result[index + 3] = 255;
5142
+ }
5143
+ return result;
5144
+ }
5145
+ function backgroundPixels(width, height, theme) {
5146
+ const buffer = new Uint8Array(width * height * 4);
5147
+ const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
5148
+ for (let index = 0; index < buffer.length; index += 4) {
5149
+ buffer[index] = color.r;
5150
+ buffer[index + 1] = color.g;
5151
+ buffer[index + 2] = color.b;
5152
+ buffer[index + 3] = 255;
5153
+ }
5154
+ return buffer;
5155
+ }
5156
+ function encodeGif(frames, loop) {
5157
+ if (frames.length === 0) throw new Error("No GIF frames to encode");
5158
+ const firstFrame = frames[0];
5159
+ const gif = GIFEncoder();
5160
+ for (const frame of frames) {
5161
+ const palette = quantize(frame.pixels, 256, { format: "rgba4444" });
5162
+ const index = applyPalette(frame.pixels, palette, "rgba4444");
5163
+ gif.writeFrame(index, firstFrame.width, firstFrame.height, {
5164
+ palette,
5165
+ delay: Math.max(2, Math.round(frame.delay / 10)),
5166
+ repeat: loop
5167
+ });
5168
+ }
5169
+ gif.finish();
5170
+ return gif.bytes();
5171
+ }
5172
+ var TRANSITION_FPS = 15;
5173
+ var MIN_TRANSITION_FRAMES = 3;
5174
+ async function scenesToFrames(scenes, options) {
5175
+ if (scenes.length === 0) throw new Error("Animated GIF requires at least one scene");
5176
+ const renderedScenes = [];
5177
+ for (const scene of scenes) {
5178
+ const watermark = options.watermark ?? options.brand;
5179
+ const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
5180
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
5181
+ }
5182
+ const frames = [];
5183
+ const scaledWidth = options.width * options.scale;
5184
+ const scaledHeight = options.height * options.scale;
5185
+ for (let index = 0; index < scenes.length; index += 1) {
5186
+ const scene = scenes[index];
5187
+ const current = renderedScenes[index];
5188
+ const transition = scene.transition ?? "none";
5189
+ const transitionDuration = scene.transitionDuration ?? 400;
5190
+ if (index > 0 && transition !== "none") {
5191
+ const previous = renderedScenes[index - 1];
5192
+ const transitionFrames = Math.max(
5193
+ MIN_TRANSITION_FRAMES,
5194
+ Math.round(transitionDuration / 1e3 * TRANSITION_FPS)
5195
+ );
5196
+ const frameDelay = transitionDuration / transitionFrames;
5197
+ for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
5198
+ const amount = (frameIndex + 1) / transitionFrames;
5199
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
5200
+ frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
5201
+ }
5202
+ }
5203
+ frames.push({
5204
+ pixels: current.pixels,
5205
+ delay: scene.duration,
5206
+ width: scaledWidth,
5207
+ height: scaledHeight
5208
+ });
5209
+ }
5210
+ return frames;
5211
+ }
5212
+ async function renderAnimatedGif(scenes, options) {
5213
+ const normalized = {
5214
+ ...options,
5215
+ loop: options.loop ?? 0,
5216
+ scale: options.scale ?? 1,
5217
+ theme: options.theme ?? "dark"
5218
+ };
5219
+ await mkdir2(dirname2(options.outputPath), { recursive: true });
5220
+ const frames = await scenesToFrames(scenes, normalized);
5221
+ const bytes = encodeGif(frames, normalized.loop);
5222
+ await writeFile2(options.outputPath, bytes);
5223
+ }
4612
5224
  export {
4613
5225
  Arrow,
4614
5226
  ArrowMarkerDef,