@ethercorps/sveltekit-og 4.3.1-next.2 → 4.4.0-next.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 (68) hide show
  1. package/README.md +35 -193
  2. package/dist/client/assets/NotoSans-Bold.ttf +0 -0
  3. package/dist/client/assets/NotoSans-Regular.ttf +0 -0
  4. package/dist/client/component.d.ts +19 -0
  5. package/dist/client/component.js +32 -0
  6. package/dist/client/create.d.ts +7 -0
  7. package/dist/client/create.js +8 -0
  8. package/dist/client/engines/satori.d.ts +4 -0
  9. package/dist/client/engines/satori.js +81 -0
  10. package/dist/client/engines/takumi.d.ts +7 -0
  11. package/dist/client/engines/takumi.js +9 -0
  12. package/dist/client/fonts.d.ts +2 -0
  13. package/dist/client/fonts.js +36 -0
  14. package/dist/client/image-response.d.ts +13 -0
  15. package/dist/client/image-response.js +88 -0
  16. package/dist/client/index.d.ts +4 -0
  17. package/dist/client/index.js +6 -0
  18. package/dist/client/render.d.ts +7 -0
  19. package/dist/client/render.js +37 -0
  20. package/dist/client/types.d.ts +14 -0
  21. package/dist/client/types.js +1 -0
  22. package/dist/fonts.d.ts +4 -4
  23. package/dist/fonts.js +17 -13
  24. package/dist/helpers/create.d.ts +7 -4
  25. package/dist/helpers/create.js +39 -28
  26. package/dist/helpers/defaults.d.ts +4 -4
  27. package/dist/helpers/defaults.js +28 -18
  28. package/dist/helpers/emoji.d.ts +1 -1
  29. package/dist/helpers/emoji.js +31 -21
  30. package/dist/helpers/error-handler.d.ts +38 -0
  31. package/dist/helpers/error-handler.js +76 -0
  32. package/dist/helpers/logger.d.ts +7 -0
  33. package/dist/helpers/logger.js +21 -0
  34. package/dist/helpers/response.d.ts +30 -0
  35. package/dist/helpers/response.js +52 -0
  36. package/dist/helpers/to-html.d.ts +10 -0
  37. package/dist/helpers/to-html.js +10 -0
  38. package/dist/helpers/toJSX.d.ts +3 -3
  39. package/dist/helpers/toJSX.js +9 -7
  40. package/dist/helpers/utils.d.ts +2 -0
  41. package/dist/helpers/utils.js +25 -0
  42. package/dist/image-response.d.ts +2 -2
  43. package/dist/image-response.js +13 -21
  44. package/dist/plugin.js +12 -5
  45. package/dist/providers/instances.d.ts +3 -3
  46. package/dist/providers/instances.js +43 -15
  47. package/dist/providers/resvg/edge.d.ts +1 -1
  48. package/dist/providers/resvg/edge.js +10 -6
  49. package/dist/providers/resvg/node.d.ts +1 -1
  50. package/dist/providers/resvg/node.js +18 -9
  51. package/dist/providers/satori/edge.d.ts +6 -0
  52. package/dist/providers/satori/edge.js +12 -0
  53. package/dist/providers/satori/node.d.ts +1 -1
  54. package/dist/providers/satori/node.js +4 -4
  55. package/dist/takumi/fonts.d.ts +16 -0
  56. package/dist/takumi/fonts.js +15 -0
  57. package/dist/takumi/image-response.d.ts +6 -0
  58. package/dist/takumi/image-response.js +27 -0
  59. package/dist/takumi/index.d.ts +5 -0
  60. package/dist/takumi/index.js +4 -0
  61. package/dist/takumi/render.d.ts +4 -0
  62. package/dist/takumi/render.js +23 -0
  63. package/dist/takumi/renderer.d.ts +7 -0
  64. package/dist/takumi/renderer.js +39 -0
  65. package/dist/takumi/types.d.ts +64 -0
  66. package/dist/takumi/types.js +1 -0
  67. package/dist/types.d.ts +10 -14
  68. package/package.json +76 -21
@@ -0,0 +1,10 @@
1
+ import { render } from "svelte/server";
2
+ import { handleSync, ErrorCodes } from "./error-handler.js";
3
+ /**
4
+ * Render a Svelte component to its SSR html parts. Shared by both engines — satori
5
+ * feeds body+head to satori-html, takumi passes the html string straight in. Use
6
+ * `<svelte:options css="injected" />` to get component styles into `head`.
7
+ */
8
+ export function renderComponentToHtml(component, props = {}) {
9
+ return handleSync(() => render(component, { props }), ErrorCodes.VNODE_CREATION_FAILED, "Failed to render Svelte component to HTML");
10
+ }
@@ -1,3 +1,3 @@
1
- import type { Component } from 'svelte';
2
- import type { ComponentOptions, VNode } from '../types.js';
3
- export declare function createVNode(element: string | Component, componentOptions?: ComponentOptions): VNode;
1
+ import type { Component } from "svelte";
2
+ import type { ComponentOptions, VNode } from "../types.js";
3
+ export declare function createVNode(element: string | Component<any>, componentOptions?: ComponentOptions): VNode;
@@ -1,9 +1,11 @@
1
- import { render } from 'svelte/server';
2
- import { html } from 'satori-html';
3
- function svelteComponentToHTML(component, props = {}) {
4
- const { body, head } = render(component, { props });
5
- return html(body + head);
6
- }
1
+ import { html } from "satori-html";
2
+ import { handleSync, ErrorCodes } from "./error-handler.js";
3
+ import { renderComponentToHtml } from "./to-html.js";
7
4
  export function createVNode(element, componentOptions) {
8
- return typeof element === 'string' ? html(element.replaceAll('\n', '').trim()) : svelteComponentToHTML(element, componentOptions?.props);
5
+ return handleSync(() => {
6
+ if (typeof element === "string")
7
+ return html(element.replaceAll("\n", "").trim());
8
+ const { body, head } = renderComponentToHtml(element, componentOptions?.props);
9
+ return html(body + head);
10
+ }, ErrorCodes.VNODE_CREATION_FAILED, "Failed to create VNode");
9
11
  }
@@ -0,0 +1,2 @@
1
+ export declare const formatBytes: (bytes: number, decimals?: number) => string;
2
+ export declare function importWasm(input: unknown): Promise<any>;
@@ -0,0 +1,25 @@
1
+ const sizeFormats = ["Bytes", "KB", "MB", "GB"];
2
+ const kbSize = 1024;
3
+ export const formatBytes = (bytes, decimals = 2) => {
4
+ if (bytes === 0)
5
+ return "0 Bytes";
6
+ const decimalPoint = decimals < 0 ? 0 : decimals;
7
+ const sizeIndex = Math.min(Math.floor(Math.log(bytes) / Math.log(kbSize)), sizeFormats.length - 1);
8
+ return (parseFloat((bytes / Math.pow(kbSize, sizeIndex)).toFixed(decimalPoint)) +
9
+ " " +
10
+ sizeFormats[sizeIndex]);
11
+ };
12
+ export async function importWasm(input) {
13
+ // may be a nested await for some reason
14
+ const _input = await input;
15
+ const _module = _input?.default || _input;
16
+ // this is from rollup/wasm, it does some magic we need to recover from
17
+ if (typeof _module === "function") {
18
+ // empty input is to avoid instantiating the wasm module
19
+ // this will just compile it
20
+ const fnRes = await _module();
21
+ const _instance = fnRes.instance || fnRes;
22
+ return _instance.exports || _instance || _module;
23
+ }
24
+ return _module;
25
+ }
@@ -1,5 +1,5 @@
1
- import type { Component, ComponentProps } from 'svelte';
2
- import type { ImageResponseOptions } from './types.js';
1
+ import type { Component, ComponentProps } from "svelte";
2
+ import type { ImageResponseOptions } from "./types.js";
3
3
  export declare class ImageResponse<T extends string | Component<any>> extends Response {
4
4
  constructor(element: T, options?: ImageResponseOptions, props?: T extends Component<any> ? ComponentProps<T> : never);
5
5
  }
@@ -1,26 +1,18 @@
1
- import { DEFAULT_OPTIONS, DEFAULT_STATUS_CODE, DEFAULT_STATUS_TEXT } from './helpers/defaults.js';
2
- import { createPng, createSvg } from './helpers/create.js';
1
+ import { DEFAULT_OPTIONS } from "./helpers/defaults.js";
2
+ import { createImage } from "./helpers/create.js";
3
+ import { buildImageResponse, CONTENT_TYPES } from "./helpers/response.js";
3
4
  export class ImageResponse extends Response {
4
5
  constructor(element, options, props) {
5
- const extended_options = Object.assign({ ...DEFAULT_OPTIONS }, options);
6
- const create_image_function = extended_options.format === 'png' ? createPng : createSvg;
7
- const body = new ReadableStream({
8
- async start(controller) {
9
- const buffer = await create_image_function(element, extended_options, { props });
10
- controller.enqueue(buffer);
11
- controller.close();
12
- }
13
- });
14
- super(body, {
15
- headers: {
16
- 'Content-Type': `image/${extended_options.format}${extended_options.format === 'svg' ? '+xml' : ''}`,
17
- 'Cache-Control': extended_options.debug
18
- ? 'no-cache, no-store'
19
- : 'public, immutable, no-transform, max-age=31536000',
20
- ...extended_options.headers
21
- },
22
- status: extended_options.status || DEFAULT_STATUS_CODE,
23
- statusText: extended_options.statusText || DEFAULT_STATUS_TEXT
6
+ const opts = { ...DEFAULT_OPTIONS, ...options };
7
+ const format = opts.format ?? "png";
8
+ const { body, init } = buildImageResponse(() => createImage(element, { ...opts, format }, { props }), {
9
+ label: format.toUpperCase(),
10
+ contentType: CONTENT_TYPES[format],
11
+ debug: opts.debug ?? false,
12
+ headers: opts.headers,
13
+ status: opts.status,
14
+ statusText: opts.statusText,
24
15
  });
16
+ super(body, init);
25
17
  }
26
18
  }
package/dist/plugin.js CHANGED
@@ -3,20 +3,27 @@ export function rollupWasm(options) {
3
3
  return unwasm({
4
4
  esmImport: true,
5
5
  lazy: true,
6
- ...options
6
+ ...options,
7
7
  });
8
8
  }
9
9
  export function sveltekitOG(options) {
10
10
  return {
11
- name: 'vite-plugin-sveltekit-og',
12
- config() {
11
+ name: "vite-plugin-sveltekit-og",
12
+ // run after sveltekit(), whose config hook is what sets build.ssr
13
+ enforce: "post",
14
+ // SSR bundle only: the client build (e.g. the /client entry) loads its wasm
15
+ // through Vite's own asset handling, and unwasm would break that. Vite computes
16
+ // env.isSsrBuild before SvelteKit sets build.ssr, so check the merged config too.
17
+ config(config, { isSsrBuild }) {
18
+ if (!isSsrBuild && !config.build?.ssr)
19
+ return;
13
20
  return {
14
21
  build: {
15
22
  rollupOptions: {
16
23
  plugins: [rollupWasm(options)],
17
24
  },
18
- }
25
+ },
19
26
  };
20
- }
27
+ },
21
28
  };
22
29
  }
@@ -1,5 +1,5 @@
1
- import type _satori from 'satori';
2
- export declare function useResvg(): Promise<new (svg: Uint8Array | string, options?: import("@resvg/resvg-wasm").ResvgRenderOptions) => {
1
+ import type _satori from "satori";
2
+ export declare function useResvg(debug?: boolean): Promise<new (svg: Uint8Array | string, options?: import("@resvg/resvg-wasm").ResvgRenderOptions) => {
3
3
  free(): void;
4
4
  render(): {
5
5
  free(): void;
@@ -35,4 +35,4 @@ export declare function useResvg(): Promise<new (svg: Uint8Array | string, optio
35
35
  readonly height: number;
36
36
  readonly width: number;
37
37
  }>;
38
- export declare function useSatori(): Promise<typeof _satori>;
38
+ export declare function useSatori(debug?: boolean): Promise<typeof _satori>;
@@ -1,17 +1,45 @@
1
- import { isEdgeLight, isWorkerd } from 'std-env';
2
- // we keep instances alive to avoid re-importing them on every request, maybe not needed but
3
- // also helps with type inference
4
- // Code from vue-og-images
5
- const resvgInstance = { instance: undefined };
6
- const satoriInstance = { instance: undefined };
7
- export async function useResvg() {
8
- const moduleImport = isEdgeLight || isWorkerd ? import(`./resvg/edge.js`) : import('./resvg/node.js');
9
- resvgInstance.instance = resvgInstance.instance || await moduleImport.then(m => m.default);
10
- await resvgInstance.instance.initWasmPromise;
11
- return resvgInstance.instance.Resvg;
1
+ import { isEdgeLight, isWorkerd } from "std-env";
2
+ import { createLogger } from "../helpers/logger.js";
3
+ import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
4
+ /**
5
+ * Lazy singleton around a node/edge wasm module pair. The edge/node choice is
6
+ * made per-runtime via std-env; both sides stay direct import() expressions so
7
+ * the bundler can emit the wasm chunk. Memoizes the init promise (like
8
+ * takumi/renderer.ts) so concurrent first requests share one init, and clears
9
+ * it on rejection so a failed init can be retried.
10
+ */
11
+ function createProvider(label, errorCode, imports) {
12
+ let instancePromise;
13
+ const init = async (debug) => {
14
+ const log = createLogger(debug);
15
+ log.debug(`Initializing ${label}`);
16
+ const isWorkerLikeRuntime = isEdgeLight || isWorkerd;
17
+ log.info(`Detected runtime: ${isWorkerLikeRuntime ? "Edge Light or Workerd" : "Node.js"}`);
18
+ const moduleImport = isWorkerLikeRuntime ? imports.edge() : imports.node();
19
+ const loaded = await handleAsync(() => moduleImport.then((m) => m.default), errorCode, `Failed to import ${label} module`);
20
+ await handleAsync(() => loaded.initWasmPromise, errorCode, `Failed to initialize ${label} WASM`);
21
+ return loaded;
22
+ };
23
+ return (debug = false) => {
24
+ instancePromise ??= init(debug).catch((error) => {
25
+ instancePromise = undefined;
26
+ throw error;
27
+ });
28
+ return instancePromise;
29
+ };
12
30
  }
13
- export async function useSatori() {
14
- satoriInstance.instance = satoriInstance.instance || await import(`./satori/node.js`).then(m => m.default);
15
- await satoriInstance.instance.initWasmPromise;
16
- return satoriInstance.instance.satori;
31
+ const useResvgModule = createProvider("ReSVG", ErrorCodes.RESVG_INIT_FAILED, {
32
+ // workers take a precompiled `?module`; node takes raw wasm bytes
33
+ edge: () => import("./resvg/edge.js"),
34
+ node: () => import("./resvg/node.js"),
35
+ });
36
+ const useSatoriModule = createProvider("Satori", ErrorCodes.SATORI_INIT_FAILED, {
37
+ edge: () => import("./satori/edge.js"),
38
+ node: () => import("./satori/node.js"),
39
+ });
40
+ export async function useResvg(debug = false) {
41
+ return (await useResvgModule(debug)).Resvg;
42
+ }
43
+ export async function useSatori(debug = false) {
44
+ return (await useSatoriModule(debug)).satori;
17
45
  }
@@ -3,4 +3,4 @@ declare namespace _default {
3
3
  export { _Resvg as Resvg };
4
4
  }
5
5
  export default _default;
6
- import { Resvg as _Resvg } from '@resvg/resvg-wasm';
6
+ import { Resvg as _Resvg } from "@resvg/resvg-wasm";
@@ -1,8 +1,12 @@
1
- import { Resvg as _Resvg, initWasm } from '@resvg/resvg-wasm'
1
+ import { Resvg as _Resvg, initWasm } from "@resvg/resvg-wasm";
2
2
 
3
3
  export default {
4
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
5
- // @ts-ignore
6
- initWasmPromise: initWasm(import('@resvg/resvg-wasm/index_bg.wasm').then(r => r.default || r)),
7
- Resvg: _Resvg,
8
- }
4
+ // load resvg's wasm from the dep (it exports ./index_bg.wasm) via ?module, so we
5
+ // don't vendor a copy. precompiled module works on node + workers alike.
6
+ initWasmPromise: initWasm(
7
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8
+ // @ts-ignore
9
+ import("@resvg/resvg-wasm/index_bg.wasm?module").then((r) => r.default || r)
10
+ ),
11
+ Resvg: _Resvg,
12
+ };
@@ -3,4 +3,4 @@ declare namespace _default {
3
3
  export { _Resvg as Resvg };
4
4
  }
5
5
  export default _default;
6
- import { Resvg as _Resvg } from '@resvg/resvg-wasm';
6
+ import { Resvg as _Resvg } from "@resvg/resvg-wasm";
@@ -1,13 +1,22 @@
1
- import { Resvg as _Resvg, initWasm } from '@resvg/resvg-wasm';
1
+ import { Resvg as _Resvg, initWasm } from "@resvg/resvg-wasm";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createRequire } from "node:module";
2
4
 
3
- /**
4
- * Fetch will be called only once whenever you load this file.
5
- * In vercel serverless functions, fetch will run on cold start.
6
- * In Node.js (Stateful e.g. Linux servers), Fetch will run once when you start your server.
7
- * */
8
- const resvgWasm = fetch('https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm')
5
+ // prefer reading resvg's wasm straight from the installed dependency (no
6
+ // network). some serverless bundlers (vercel/netlify via nft) don't trace the
7
+ // sibling .wasm onto disk, so fall back to fetching it there. either way we hand
8
+ // initWasm raw bytes / a Response — never a `?module` import, which node
9
+ // serverless can't instantiate. runs once when this module first loads.
10
+ async function loadResvgWasm() {
11
+ try {
12
+ const require = createRequire(import.meta.url);
13
+ return await readFile(require.resolve("@resvg/resvg-wasm/index_bg.wasm"));
14
+ } catch {
15
+ return fetch("https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm");
16
+ }
17
+ }
9
18
 
10
19
  export default {
11
- initWasmPromise: initWasm(resvgWasm),
20
+ initWasmPromise: initWasm(loadResvgWasm()),
12
21
  Resvg: _Resvg,
13
- }
22
+ };
@@ -0,0 +1,6 @@
1
+ declare namespace _default {
2
+ export let initWasmPromise: Promise<void>;
3
+ export { _satori as satori };
4
+ }
5
+ export default _default;
6
+ import _satori from "satori/standalone";
@@ -0,0 +1,12 @@
1
+ import _satori, { init } from "satori/standalone";
2
+
3
+ // the default satori entry compiles yoga's wasm at runtime, which workers block
4
+ // ("Wasm code generation disallowed by embedder"). satori/standalone takes a
5
+ // precompiled module via init(), so we hand it satori's own yoga wasm (it exports
6
+ // ./yoga.wasm) through ?module — no vendored copy. mirrors providers/resvg.
7
+ export default {
8
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
9
+ // @ts-ignore
10
+ initWasmPromise: init(import("satori/yoga.wasm?module").then((r) => r.default || r)),
11
+ satori: _satori,
12
+ };
@@ -3,4 +3,4 @@ declare namespace _default {
3
3
  export { _satori as satori };
4
4
  }
5
5
  export default _default;
6
- import _satori from 'satori';
6
+ import _satori from "satori";
@@ -1,6 +1,6 @@
1
- import _satori from 'satori'
1
+ import _satori from "satori";
2
2
 
3
3
  export default {
4
- initWasmPromise: Promise.resolve(),
5
- satori: _satori,
6
- }
4
+ initWasmPromise: Promise.resolve(),
5
+ satori: _satori,
6
+ };
@@ -0,0 +1,16 @@
1
+ import type { FontDetails } from "takumi-js/node";
2
+ import { BaseFont } from "../fonts.js";
3
+ import type { MayBePromise } from "../types.js";
4
+ type ByteBuf = Uint8Array | ArrayBuffer | Buffer;
5
+ /** Takumi-native font descriptor; data is the bytes or a lazy loader, like takumi-js wants. */
6
+ export interface TakumiFontDescriptor {
7
+ name?: string;
8
+ data: ByteBuf | (() => MayBePromise<ByteBuf>);
9
+ weight?: number;
10
+ style?: FontDetails["style"];
11
+ }
12
+ /** What the takumi path accepts: our GoogleFont/CustomFont, or a raw takumi descriptor. */
13
+ export type TakumiFontInput = BaseFont | TakumiFontDescriptor;
14
+ /** Normalize mixed font inputs to FontDetails for registerFont, loaders run in parallel. */
15
+ export declare function resolveTakumiFonts(fonts: TakumiFontInput[]): Promise<FontDetails[]>;
16
+ export {};
@@ -0,0 +1,15 @@
1
+ import { BaseFont } from "../fonts.js";
2
+ import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
3
+ async function normalizeFont(font) {
4
+ if (font instanceof BaseFont) {
5
+ // our font classes lazily load + cache through the data getter
6
+ const data = (await font.data);
7
+ return { name: font.name, data, weight: font.weight, style: font.style };
8
+ }
9
+ const data = typeof font.data === "function" ? await font.data() : await font.data;
10
+ return { name: font.name, data, weight: font.weight, style: font.style };
11
+ }
12
+ /** Normalize mixed font inputs to FontDetails for registerFont, loaders run in parallel. */
13
+ export async function resolveTakumiFonts(fonts) {
14
+ return handleAsync(() => Promise.all(fonts.map(normalizeFont)), ErrorCodes.FONT_LOAD_FAILED, "Failed to resolve fonts for Takumi");
15
+ }
@@ -0,0 +1,6 @@
1
+ import type { Component, ComponentProps } from "svelte";
2
+ import type { TakumiImageResponseOptions } from "./types.js";
3
+ /** OG image rendered by Takumi. Takes an HTML string or a Svelte component. */
4
+ export declare class ImageResponse<T extends string | Component<any>> extends Response {
5
+ constructor(element: T, options?: TakumiImageResponseOptions, props?: T extends Component<any> ? ComponentProps<T> : never);
6
+ }
@@ -0,0 +1,27 @@
1
+ import { createTakumiImage } from "./render.js";
2
+ import { DEFAULT_WIDTH, DEFAULT_HEIGHT } from "../helpers/defaults.js";
3
+ import { buildImageResponse, CONTENT_TYPES as SHARED_CONTENT_TYPES } from "../helpers/response.js";
4
+ const DEFAULT_OPTIONS = {
5
+ width: DEFAULT_WIDTH,
6
+ height: DEFAULT_HEIGHT,
7
+ format: "png",
8
+ emoji: "twemoji",
9
+ debug: false,
10
+ };
11
+ // Verifies the shared map covers every takumi format
12
+ const CONTENT_TYPES = SHARED_CONTENT_TYPES;
13
+ /** OG image rendered by Takumi. Takes an HTML string or a Svelte component. */
14
+ export class ImageResponse extends Response {
15
+ constructor(element, options, props) {
16
+ const opts = { ...DEFAULT_OPTIONS, ...options };
17
+ const { body, init } = buildImageResponse(() => createTakumiImage(element, opts, props), {
18
+ label: opts.format.toUpperCase(),
19
+ contentType: CONTENT_TYPES[opts.format],
20
+ debug: opts.debug,
21
+ headers: opts.headers,
22
+ status: opts.status,
23
+ statusText: opts.statusText,
24
+ });
25
+ super(body, init);
26
+ }
27
+ }
@@ -0,0 +1,5 @@
1
+ export { ImageResponse } from "./image-response.js";
2
+ export type { TakumiImageResponseOptions, TakumiImageOptions, TakumiResponseOptions, TakumiFormat, } from "./types.js";
3
+ export type { TakumiFontInput, TakumiFontDescriptor } from "./fonts.js";
4
+ export { resolveTakumiFonts } from "./fonts.js";
5
+ export { GoogleFont, CustomFont, loadGoogleFont } from "../fonts.js";
@@ -0,0 +1,4 @@
1
+ export { ImageResponse } from "./image-response.js";
2
+ export { resolveTakumiFonts } from "./fonts.js";
3
+ // re-export the font helpers so the takumi path works from one import
4
+ export { GoogleFont, CustomFont, loadGoogleFont } from "../fonts.js";
@@ -0,0 +1,4 @@
1
+ import type { Component } from "svelte";
2
+ import type { TakumiImageOptions } from "./types.js";
3
+ /** Render an HTML string or Svelte component to image bytes (or an svg string). */
4
+ export declare function createTakumiImage(element: string | Component<any>, options: TakumiImageOptions, props?: Record<string, unknown>): Promise<Uint8Array | string>;
@@ -0,0 +1,23 @@
1
+ import { render as takumiRender, renderSvg } from "takumi-js";
2
+ import { useTakumiRenderer, registerTakumiFonts } from "./renderer.js";
3
+ import { resolveTakumiFonts } from "./fonts.js";
4
+ import { createLogger } from "../helpers/logger.js";
5
+ import { handleAsync, ErrorCodes, handleSync } from "../helpers/error-handler.js";
6
+ import { createVNode } from "../helpers/toJSX.js";
7
+ /** Render an HTML string or Svelte component to image bytes (or an svg string). */
8
+ export async function createTakumiImage(element, options, props) {
9
+ const log = createLogger(options.debug ?? false);
10
+ const vNode = handleSync(() => createVNode(element, { props }), ErrorCodes.VNODE_CREATION_FAILED, "Failed to create HTML for Takumi");
11
+ const renderer = await useTakumiRenderer();
12
+ if (options.fonts?.length) {
13
+ const fonts = await resolveTakumiFonts(options.fonts);
14
+ await registerTakumiFonts(renderer, fonts);
15
+ }
16
+ const { width, height, format = "png", quality, stylesheets, emoji } = options;
17
+ const shared = { renderer: renderer, width, height, stylesheets, emoji };
18
+ log.debug(`Rendering ${format.toUpperCase()} with Takumi`);
19
+ if (format === "svg") {
20
+ return handleAsync(() => renderSvg(vNode, shared), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render SVG with Takumi");
21
+ }
22
+ return handleAsync(() => takumiRender(vNode, { ...shared, format, quality }), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render image with Takumi");
23
+ }
@@ -0,0 +1,7 @@
1
+ import type { Renderer as NodeRenderer, FontDetails } from "takumi-js/node";
2
+ export type TakumiRenderer = NodeRenderer;
3
+ /** Lazily creates and caches the Takumi renderer for the current runtime.
4
+ * A rejected init clears the cache so the next request retries. */
5
+ export declare function useTakumiRenderer(): Promise<TakumiRenderer>;
6
+ /** Register each font once, keyed by name/weight/style. */
7
+ export declare function registerTakumiFonts(renderer: TakumiRenderer, fonts: FontDetails[]): Promise<void>;
@@ -0,0 +1,39 @@
1
+ import autoModule, { init as initTakumiWasm, Renderer } from "takumi-js/wasm";
2
+ import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
3
+ // keep one renderer alive across requests, same as the satori/resvg instances.
4
+ // fonts registered on it stick around, so we dedupe by key.
5
+ let rendererPromise;
6
+ const registeredFontKeys = new Set();
7
+ async function initRenderer() {
8
+ await handleAsync(async () => {
9
+ // reuse the wasm that ships with takumi-js instead of vendoring our own.
10
+ // @takumi-rs/wasm/auto picks the right binary per runtime (workerd, edge,
11
+ // node, ?module) via export conditions. this is the same dance takumi-js
12
+ // does internally.
13
+ const resolved = typeof autoModule === "function" ? await autoModule() : await autoModule;
14
+ const input = resolved && typeof resolved === "object" && "default" in resolved
15
+ ? resolved.default
16
+ : resolved;
17
+ await initTakumiWasm(input ? { module_or_path: input } : undefined);
18
+ }, ErrorCodes.TAKUMI_INIT_FAILED, "Failed to initialize Takumi WASM");
19
+ return new Renderer();
20
+ }
21
+ /** Lazily creates and caches the Takumi renderer for the current runtime.
22
+ * A rejected init clears the cache so the next request retries. */
23
+ export async function useTakumiRenderer() {
24
+ rendererPromise ??= initRenderer().catch((error) => {
25
+ rendererPromise = undefined;
26
+ throw error;
27
+ });
28
+ return rendererPromise;
29
+ }
30
+ /** Register each font once, keyed by name/weight/style. */
31
+ export async function registerTakumiFonts(renderer, fonts) {
32
+ for (const font of fonts) {
33
+ const key = `${font.name ?? "unnamed"}-${font.weight ?? "auto"}-${font.style ?? "normal"}`;
34
+ if (registeredFontKeys.has(key))
35
+ continue;
36
+ await handleAsync(() => renderer.registerFont(font), ErrorCodes.FONT_LOAD_FAILED, `Failed to register Takumi font: ${key}`);
37
+ registeredFontKeys.add(key);
38
+ }
39
+ }
@@ -0,0 +1,64 @@
1
+ import type { EmojiType } from "takumi-js/helpers/emoji";
2
+ import type { OutputFormat } from "takumi-js/node";
3
+ import type { TakumiFontInput } from "./fonts.js";
4
+ /** Static output formats Takumi can encode, plus vector `svg`. */
5
+ export type TakumiFormat = OutputFormat | "svg";
6
+ export type TakumiImageOptions = {
7
+ /**
8
+ * Width of the image.
9
+ * @default 1200
10
+ * */
11
+ width?: number;
12
+ /**
13
+ * Height of the image.
14
+ * @default 630
15
+ * */
16
+ height?: number;
17
+ /**
18
+ * Output format.
19
+ * @default png
20
+ * */
21
+ format?: TakumiFormat;
22
+ /**
23
+ * Quality for lossy formats (jpeg, lossy webp), 0-100.
24
+ * */
25
+ quality?: number;
26
+ /**
27
+ * Fonts to register. Accepts this library's `GoogleFont`/`CustomFont`
28
+ * helpers or raw Takumi font descriptors. If omitted, Takumi's built-in
29
+ * sans-serif is used.
30
+ * */
31
+ fonts?: TakumiFontInput[];
32
+ /**
33
+ * Extra CSS stylesheets applied before rendering.
34
+ * */
35
+ stylesheets?: string[];
36
+ /**
37
+ * Emoji provider, or `"from-font"` to source emoji glyphs from loaded fonts.
38
+ * @default twemoji
39
+ * */
40
+ emoji?: EmojiType | "from-font";
41
+ /**
42
+ * Enable debug logging.
43
+ * @default false
44
+ * */
45
+ debug?: boolean;
46
+ };
47
+ export type TakumiResponseOptions = {
48
+ /**
49
+ * Response status code.
50
+ * @default 200
51
+ * */
52
+ status?: number;
53
+ /**
54
+ * Response status text.
55
+ * @default Success
56
+ * */
57
+ statusText?: string;
58
+ /**
59
+ * Response headers.
60
+ * */
61
+ headers?: Record<string, string>;
62
+ };
63
+ /** Options for the Takumi `ImageResponse`. */
64
+ export type TakumiImageResponseOptions = TakumiImageOptions & TakumiResponseOptions;
@@ -0,0 +1 @@
1
+ export {};
package/dist/types.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import type { SatoriOptions } from 'satori/wasm';
2
- import type { EmojiType } from './helpers/emoji.js';
3
- export type Font = SatoriOptions['fonts'][number];
1
+ import type { SatoriOptions } from "satori";
2
+ import type { EmojiType } from "./helpers/emoji.js";
3
+ export type Font = SatoriOptions["fonts"][number];
4
4
  export type Fonts = Font[];
5
- export type FontStyle = Font['style'];
6
- export type FontWeight = Font['weight'];
5
+ export type FontStyle = Font["style"];
6
+ export type FontWeight = Font["weight"];
7
7
  export type FinalFontOptions = NonNullable<Fonts>;
8
8
  export type ImageOptions = {
9
9
  /**
@@ -30,7 +30,7 @@ export type ImageOptions = {
30
30
  * Tailwind config
31
31
  * @default provided by satori
32
32
  * */
33
- tailwindConfig?: SatoriOptions['tailwindConfig'];
33
+ tailwindConfig?: SatoriOptions["tailwindConfig"];
34
34
  /**
35
35
  * Debug operations
36
36
  * @default false
@@ -40,7 +40,7 @@ export type ImageOptions = {
40
40
  * Image format
41
41
  * @default png
42
42
  * */
43
- format?: 'svg' | 'png';
43
+ format?: "svg" | "png";
44
44
  };
45
45
  export type ResponseImageOptions = {
46
46
  /**
@@ -70,7 +70,7 @@ export type ImageResponseOptions = ImageOptions & ResponseImageOptions;
70
70
  * Svelte Component props to render the component which dynamic content
71
71
  * */
72
72
  export type ComponentOptions = {
73
- props?: Record<string, any>;
73
+ props?: Record<string, unknown>;
74
74
  };
75
75
  /**
76
76
  * React virtual node, supported by satori as input (alternative to JSX input).
@@ -78,14 +78,10 @@ export type ComponentOptions = {
78
78
  export interface VNode {
79
79
  type: string;
80
80
  props: {
81
- style?: Record<string, any>;
81
+ style?: Record<string, unknown>;
82
82
  children?: string | VNode | VNode[];
83
- [prop: string]: any;
83
+ [prop: string]: unknown;
84
84
  };
85
85
  }
86
86
  /** utils types */
87
87
  export type MayBePromise<T> = T | Promise<T>;
88
- export type OnlyProps<T, P> = {
89
- [K in keyof T as K extends P ? K : never]: T[K];
90
- };
91
- export type StringWithSuggestions<S extends string> = (string & Record<never, never>) | S;