@ethercorps/sveltekit-og 4.2.0 → 4.3.0-beta.1

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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -193
  3. package/dist/fonts.d.ts +5 -13
  4. package/dist/fonts.js +28 -24
  5. package/dist/helpers/create.d.ts +7 -5
  6. package/dist/helpers/create.js +38 -35
  7. package/dist/helpers/defaults.d.ts +4 -4
  8. package/dist/helpers/defaults.js +28 -18
  9. package/dist/helpers/emoji.d.ts +1 -1
  10. package/dist/helpers/emoji.js +31 -21
  11. package/dist/helpers/error-handler.d.ts +37 -0
  12. package/dist/helpers/error-handler.js +75 -0
  13. package/dist/helpers/logger.d.ts +7 -0
  14. package/dist/helpers/logger.js +21 -0
  15. package/dist/helpers/response.d.ts +30 -0
  16. package/dist/helpers/response.js +52 -0
  17. package/dist/helpers/to-html.d.ts +10 -0
  18. package/dist/helpers/to-html.js +10 -0
  19. package/dist/helpers/toJSX.d.ts +3 -0
  20. package/dist/helpers/toJSX.js +11 -0
  21. package/dist/helpers/utils.d.ts +2 -0
  22. package/dist/helpers/utils.js +25 -0
  23. package/dist/image-response.d.ts +2 -2
  24. package/dist/image-response.js +13 -21
  25. package/dist/plugin.js +6 -6
  26. package/dist/providers/instances.d.ts +3 -3
  27. package/dist/providers/instances.js +43 -15
  28. package/dist/providers/resvg/edge.d.ts +1 -1
  29. package/dist/providers/resvg/edge.js +10 -6
  30. package/dist/providers/resvg/node.d.ts +1 -1
  31. package/dist/providers/resvg/node.js +18 -9
  32. package/dist/providers/satori/edge.d.ts +6 -0
  33. package/dist/providers/satori/edge.js +12 -0
  34. package/dist/providers/satori/node.d.ts +1 -1
  35. package/dist/providers/satori/node.js +4 -4
  36. package/dist/takumi/fonts.d.ts +16 -0
  37. package/dist/takumi/fonts.js +15 -0
  38. package/dist/takumi/image-response.d.ts +6 -0
  39. package/dist/takumi/image-response.js +27 -0
  40. package/dist/takumi/index.d.ts +5 -0
  41. package/dist/takumi/index.js +4 -0
  42. package/dist/takumi/render.d.ts +4 -0
  43. package/dist/takumi/render.js +23 -0
  44. package/dist/takumi/renderer.d.ts +7 -0
  45. package/dist/takumi/renderer.js +39 -0
  46. package/dist/takumi/types.d.ts +64 -0
  47. package/dist/takumi/types.js +1 -0
  48. package/dist/types.d.ts +10 -14
  49. package/package.json +73 -17
  50. package/dist/providers/resvg/resvg.wasm +0 -0
@@ -1,4 +1,5 @@
1
- import { DEFAULT_EMOJI_PROVIDER } from '../helpers/defaults.js';
1
+ import { DEFAULT_EMOJI_PROVIDER } from "../helpers/defaults.js";
2
+ import { handleAsync, ErrorCodes } from "./error-handler.js";
2
3
  // Code stolen from @vercel/og and https://github.com/fineshopdesign/cf-wasm
3
4
  const U200D = String.fromCharCode(8205);
4
5
  const UFE0Fg = /\uFE0F/g;
@@ -11,7 +12,7 @@ function toCodePoint(unicodeSurrogates) {
11
12
  while (i < unicodeSurrogates.length) {
12
13
  c = unicodeSurrogates.charCodeAt(i++);
13
14
  if (p) {
14
- r.push((65536 + (p - 55296 << 10) + (c - 56320)).toString(16));
15
+ r.push((65536 + ((p - 55296) << 10) + (c - 56320)).toString(16));
15
16
  p = 0;
16
17
  }
17
18
  else if (55296 <= c && c <= 56319) {
@@ -24,32 +25,41 @@ function toCodePoint(unicodeSurrogates) {
24
25
  return r.join("-");
25
26
  }
26
27
  const emoji_apis = {
27
- twemoji: (code) => "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/" + code.toLowerCase() + ".svg",
28
+ twemoji: (code) => "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/" +
29
+ code.toLowerCase() +
30
+ ".svg",
28
31
  openmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/openmoji@2.0.0/svg/",
29
32
  blobmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/blob@2.0.0/svg/",
30
33
  noto: "https://cdn.jsdelivr.net/gh/svgmoji/svgmoji/packages/svgmoji__noto/svg/",
31
- fluent: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_color.svg",
32
- fluentFlat: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_flat.svg"
34
+ fluent: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" +
35
+ code.toLowerCase() +
36
+ "_color.svg",
37
+ fluentFlat: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" +
38
+ code.toLowerCase() +
39
+ "_flat.svg",
33
40
  };
34
- function loadEmoji(code, type) {
35
- if (!type || !emoji_apis[type]) {
36
- type = DEFAULT_EMOJI_PROVIDER;
37
- }
38
- const api = emoji_apis[type];
39
- if (typeof api === "function") {
40
- return fetch(api(code));
41
- }
42
- return fetch(`${api}${code.toUpperCase()}.svg`);
41
+ async function loadEmoji(code, type) {
42
+ return handleAsync(async () => {
43
+ if (!type || !emoji_apis[type]) {
44
+ type = DEFAULT_EMOJI_PROVIDER;
45
+ }
46
+ const api = emoji_apis[type];
47
+ if (typeof api === "function") {
48
+ return fetch(api(code));
49
+ }
50
+ return fetch(`${api}${code.toUpperCase()}.svg`);
51
+ }, ErrorCodes.EMOJI_LOAD_FAILED, `Failed to load emoji for code: ${code}`);
43
52
  }
44
53
  export const loadDynamicAsset = ({ emoji }) => {
45
- const fn = async (code, text) => {
54
+ return async (code, text) => {
46
55
  if (code === "emoji") {
47
- return `data:image/svg+xml;base64,` + btoa(await (await loadEmoji(getIconCode(text), emoji)).text());
56
+ return handleAsync(async () => {
57
+ const iconCode = getIconCode(text);
58
+ const emojiResponse = await loadEmoji(iconCode, emoji);
59
+ const svgText = await emojiResponse.text();
60
+ const base64Data = btoa(svgText);
61
+ return `data:image/svg+xml;base64,` + base64Data;
62
+ }, ErrorCodes.EMOJI_LOAD_FAILED, `Failed to process emoji: ${text}`);
48
63
  }
49
64
  };
50
- return async (...args) => {
51
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
52
- // @ts-ignore
53
- return await fn(...args);
54
- };
55
65
  };
@@ -0,0 +1,37 @@
1
+ export declare class ImageResponseError extends Error {
2
+ code: string;
3
+ originalError?: Error | undefined;
4
+ constructor(message: string, code: string, originalError?: Error | undefined);
5
+ }
6
+ /** Coerce anything thrown into an ImageResponseError, keeping existing ones as-is. */
7
+ export declare function toImageResponseError(error: unknown): ImageResponseError;
8
+ export declare const ErrorCodes: {
9
+ readonly FONT_LOAD_FAILED: "FONT_LOAD_FAILED";
10
+ readonly VNODE_CREATION_FAILED: "VNODE_CREATION_FAILED";
11
+ readonly SATORI_RENDER_FAILED: "SATORI_RENDER_FAILED";
12
+ readonly RESVG_INIT_FAILED: "RESVG_INIT_FAILED";
13
+ readonly RESVG_RENDER_FAILED: "RESVG_RENDER_FAILED";
14
+ readonly SATORI_INIT_FAILED: "SATORI_INIT_FAILED";
15
+ readonly EMOJI_LOAD_FAILED: "EMOJI_LOAD_FAILED";
16
+ readonly TAKUMI_INIT_FAILED: "TAKUMI_INIT_FAILED";
17
+ readonly TAKUMI_RENDER_FAILED: "TAKUMI_RENDER_FAILED";
18
+ readonly UNKNOWN_ERROR: "UNKNOWN_ERROR";
19
+ };
20
+ /**
21
+ * Wraps an async operation with error handling and logging
22
+ */
23
+ export declare function handleAsync<T = unknown>(operation: () => Promise<T>, errorCode: string, errorMessage: string): Promise<T>;
24
+ /**
25
+ * Wraps a sync operation with error handling and logging
26
+ */
27
+ export declare function handleSync<T>(operation: () => T, errorCode: string, errorMessage: string): T;
28
+ /**
29
+ * Wraps multiple async operations with error handling
30
+ */
31
+ export declare function handleAsyncAll<T extends readonly unknown[]>(operations: {
32
+ readonly [K in keyof T]: () => Promise<T[K]>;
33
+ }, errorCode: string, errorMessage: string): Promise<T>;
34
+ /**
35
+ * Validates a response and throws if not ok
36
+ */
37
+ export declare function validateResponse(response: Response, errorCode: string, errorMessage: string): Promise<ArrayBuffer>;
@@ -0,0 +1,75 @@
1
+ export class ImageResponseError extends Error {
2
+ code;
3
+ originalError;
4
+ constructor(message, code, originalError) {
5
+ super(message);
6
+ this.code = code;
7
+ this.originalError = originalError;
8
+ this.name = "ImageResponseError";
9
+ }
10
+ }
11
+ /** Coerce anything thrown into an ImageResponseError, keeping existing ones as-is. */
12
+ export function toImageResponseError(error) {
13
+ if (error instanceof ImageResponseError)
14
+ return error;
15
+ const err = error instanceof Error ? error : new Error(String(error));
16
+ return new ImageResponseError(err.message, ErrorCodes.UNKNOWN_ERROR, err);
17
+ }
18
+ export const ErrorCodes = {
19
+ FONT_LOAD_FAILED: "FONT_LOAD_FAILED",
20
+ VNODE_CREATION_FAILED: "VNODE_CREATION_FAILED",
21
+ SATORI_RENDER_FAILED: "SATORI_RENDER_FAILED",
22
+ RESVG_INIT_FAILED: "RESVG_INIT_FAILED",
23
+ RESVG_RENDER_FAILED: "RESVG_RENDER_FAILED",
24
+ SATORI_INIT_FAILED: "SATORI_INIT_FAILED",
25
+ EMOJI_LOAD_FAILED: "EMOJI_LOAD_FAILED",
26
+ TAKUMI_INIT_FAILED: "TAKUMI_INIT_FAILED",
27
+ TAKUMI_RENDER_FAILED: "TAKUMI_RENDER_FAILED",
28
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
29
+ };
30
+ /**
31
+ * Wraps an async operation with error handling and logging
32
+ */
33
+ export async function handleAsync(operation, errorCode, errorMessage) {
34
+ try {
35
+ return await operation();
36
+ }
37
+ catch (error) {
38
+ const err = error instanceof Error ? error : new Error(String(error));
39
+ throw new ImageResponseError(errorMessage, errorCode, err);
40
+ }
41
+ }
42
+ /**
43
+ * Wraps a sync operation with error handling and logging
44
+ */
45
+ export function handleSync(operation, errorCode, errorMessage) {
46
+ try {
47
+ return operation();
48
+ }
49
+ catch (error) {
50
+ const err = error instanceof Error ? error : new Error(String(error));
51
+ throw new ImageResponseError(errorMessage, errorCode, err);
52
+ }
53
+ }
54
+ /**
55
+ * Wraps multiple async operations with error handling
56
+ */
57
+ export async function handleAsyncAll(operations, errorCode, errorMessage) {
58
+ try {
59
+ return (await Promise.all(operations.map((op) => op())));
60
+ }
61
+ catch (error) {
62
+ const err = error instanceof Error ? error : new Error(String(error));
63
+ throw new ImageResponseError(errorMessage, errorCode, err);
64
+ }
65
+ }
66
+ /**
67
+ * Validates a response and throws if not ok
68
+ */
69
+ export async function validateResponse(response, errorCode, errorMessage) {
70
+ if (!response.ok) {
71
+ throw new ImageResponseError(`${errorMessage} (HTTP ${response.status})`, errorCode);
72
+ }
73
+ const buffer = await response.arrayBuffer();
74
+ return buffer;
75
+ }
@@ -0,0 +1,7 @@
1
+ export type Logger = ReturnType<typeof createLogger>;
2
+ export declare function createLogger(debug: boolean): {
3
+ debug: (message: string, ...args: unknown[]) => void;
4
+ info: (message: string, ...args: unknown[]) => void;
5
+ warn: (message: string, ...args: unknown[]) => void;
6
+ error: (message: string, ...args: unknown[]) => void;
7
+ };
@@ -0,0 +1,21 @@
1
+ const PREFIX = '[SvelteKit-OG]';
2
+ export function createLogger(debug) {
3
+ return {
4
+ debug: (message, ...args) => {
5
+ if (debug)
6
+ console.log(`${PREFIX} 🔍 ${message}`, ...args);
7
+ },
8
+ info: (message, ...args) => {
9
+ if (debug)
10
+ console.info(`${PREFIX} ℹ️ ${message}`, ...args);
11
+ },
12
+ warn: (message, ...args) => {
13
+ if (debug)
14
+ console.warn(`${PREFIX} ⚠️ ${message}`, ...args);
15
+ },
16
+ error: (message, ...args) => {
17
+ if (debug)
18
+ console.error(`${PREFIX} ❌ ${message}`, ...args);
19
+ }
20
+ };
21
+ }
@@ -0,0 +1,30 @@
1
+ /** format → content type for every format either engine can emit; satori uses the
2
+ * png/svg subset, takumi the whole map. */
3
+ export declare const CONTENT_TYPES: {
4
+ readonly png: "image/png";
5
+ readonly jpeg: "image/jpeg";
6
+ readonly webp: "image/webp";
7
+ readonly ico: "image/x-icon";
8
+ readonly raw: "application/octet-stream";
9
+ readonly svg: "image/svg+xml";
10
+ };
11
+ type ImageProducer = () => Promise<Uint8Array | string>;
12
+ interface BuildOptions {
13
+ /** uppercased format, used in logs e.g. "PNG" */
14
+ label: string;
15
+ contentType: string;
16
+ debug: boolean;
17
+ headers?: Record<string, string>;
18
+ status?: number;
19
+ statusText?: string;
20
+ }
21
+ /**
22
+ * Shared body + response init for both engines' ImageResponse. Streams the image
23
+ * out as bytes (a Response stream can't take a raw string), with consistent
24
+ * cache headers and error handling.
25
+ */
26
+ export declare function buildImageResponse(produce: ImageProducer, opts: BuildOptions): {
27
+ body: ReadableStream;
28
+ init: ResponseInit;
29
+ };
30
+ export {};
@@ -0,0 +1,52 @@
1
+ import { createLogger } from "./logger.js";
2
+ import { handleAsync, toImageResponseError, ErrorCodes } from "./error-handler.js";
3
+ import { DEFAULT_STATUS_CODE, DEFAULT_STATUS_TEXT } from "./defaults.js";
4
+ import { formatBytes } from "./utils.js";
5
+ /** format → content type for every format either engine can emit; satori uses the
6
+ * png/svg subset, takumi the whole map. */
7
+ export const CONTENT_TYPES = {
8
+ png: "image/png",
9
+ jpeg: "image/jpeg",
10
+ webp: "image/webp",
11
+ ico: "image/x-icon",
12
+ raw: "application/octet-stream",
13
+ svg: "image/svg+xml",
14
+ };
15
+ // TextEncoder is stateless; one shared instance instead of one per svg response
16
+ const textEncoder = new TextEncoder();
17
+ /**
18
+ * Shared body + response init for both engines' ImageResponse. Streams the image
19
+ * out as bytes (a Response stream can't take a raw string), with consistent
20
+ * cache headers and error handling.
21
+ */
22
+ export function buildImageResponse(produce, opts) {
23
+ const log = createLogger(opts.debug);
24
+ const body = new ReadableStream({
25
+ async start(controller) {
26
+ try {
27
+ const out = await handleAsync(produce, ErrorCodes.UNKNOWN_ERROR, `Failed to generate ${opts.label}`);
28
+ const bytes = typeof out === "string" ? textEncoder.encode(out) : out;
29
+ log.info(`Generated ${opts.label}: ${formatBytes(bytes.byteLength)}`);
30
+ controller.enqueue(bytes);
31
+ controller.close();
32
+ }
33
+ catch (error) {
34
+ const err = toImageResponseError(error);
35
+ log.error("Failed to create image response:", err.message);
36
+ controller.error(err);
37
+ }
38
+ },
39
+ });
40
+ const init = {
41
+ headers: {
42
+ "Content-Type": opts.contentType,
43
+ "Cache-Control": opts.debug
44
+ ? "no-cache, no-store"
45
+ : "public, immutable, no-transform, max-age=31536000",
46
+ ...opts.headers,
47
+ },
48
+ status: opts.status || DEFAULT_STATUS_CODE,
49
+ statusText: opts.statusText || DEFAULT_STATUS_TEXT,
50
+ };
51
+ return { body, init };
52
+ }
@@ -0,0 +1,10 @@
1
+ import type { Component } from "svelte";
2
+ /**
3
+ * Render a Svelte component to its SSR html parts. Shared by both engines — satori
4
+ * feeds body+head to satori-html, takumi passes the html string straight in. Use
5
+ * `<svelte:options css="injected" />` to get component styles into `head`.
6
+ */
7
+ export declare function renderComponentToHtml(component: Component<any>, props?: Record<string, unknown>): {
8
+ head: string;
9
+ body: string;
10
+ };
@@ -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
+ }
@@ -0,0 +1,3 @@
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;
@@ -0,0 +1,11 @@
1
+ import { html } from "satori-html";
2
+ import { handleSync, ErrorCodes } from "./error-handler.js";
3
+ import { renderComponentToHtml } from "./to-html.js";
4
+ export function createVNode(element, componentOptions) {
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");
11
+ }
@@ -0,0 +1,2 @@
1
+ export declare const formatBytes: (bytes: number, decimals?: number) => string;
2
+ export declare function importWasm(input: any): 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,20 @@ 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',
11
+ name: "vite-plugin-sveltekit-og",
12
12
  config() {
13
13
  return {
14
14
  build: {
15
15
  rollupOptions: {
16
- plugins: [rollupWasm(options)]
17
- }
18
- }
16
+ plugins: [rollupWasm(options)],
17
+ },
18
+ },
19
19
  };
20
- }
20
+ },
21
21
  };
22
22
  }
@@ -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.wasm?module').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
+ };