@ethercorps/sveltekit-og 4.3.0-next.7 → 4.3.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.
- package/README.md +9 -1
- package/dist/fonts.js +4 -2
- package/dist/helpers/create.d.ts +5 -2
- package/dist/helpers/create.js +15 -6
- package/dist/helpers/defaults.js +10 -1
- package/dist/helpers/emoji.d.ts +1 -1
- package/dist/helpers/emoji.js +1 -6
- package/dist/helpers/error-handler.d.ts +2 -0
- package/dist/helpers/error-handler.js +7 -0
- package/dist/helpers/logger.js +2 -2
- package/dist/helpers/response.d.ts +30 -0
- package/dist/helpers/response.js +52 -0
- package/dist/helpers/to-html.d.ts +3 -6
- package/dist/helpers/to-html.js +3 -6
- package/dist/helpers/toJSX.d.ts +1 -1
- package/dist/helpers/toJSX.js +5 -8
- package/dist/helpers/utils.d.ts +1 -1
- package/dist/helpers/utils.js +2 -2
- package/dist/image-response.js +13 -40
- package/dist/providers/instances.js +38 -38
- package/dist/providers/resvg/edge.js +7 -3
- package/dist/providers/resvg/node.js +16 -7
- package/dist/providers/satori/edge.js +5 -9
- package/dist/takumi/fonts.d.ts +3 -13
- package/dist/takumi/fonts.js +2 -5
- package/dist/takumi/image-response.d.ts +1 -4
- package/dist/takumi/image-response.js +15 -50
- package/dist/takumi/index.js +1 -1
- package/dist/takumi/render.d.ts +2 -5
- package/dist/takumi/render.js +7 -20
- package/dist/takumi/renderer.d.ts +4 -7
- package/dist/takumi/renderer.js +24 -24
- package/dist/types.d.ts +0 -4
- package/package.json +8 -8
- package/dist/providers/resvg/resvg.wasm +0 -0
- package/dist/providers/satori/yoga.wasm +0 -0
- package/dist/providers/takumi/edge.d.ts +0 -6
- package/dist/providers/takumi/edge.js +0 -16
- package/dist/providers/takumi/node.d.ts +0 -6
- package/dist/providers/takumi/node.js +0 -10
- package/dist/providers/takumi/takumi.wasm +0 -0
package/README.md
CHANGED
|
@@ -4,7 +4,12 @@
|
|
|
4
4
|
|
|
5
5
|
# SvelteKit Open Graph Image Generation
|
|
6
6
|
|
|
7
|
-
Dynamically generate Open Graph images from an HTML+CSS template or Svelte component
|
|
7
|
+
Dynamically generate Open Graph images from an HTML+CSS template or Svelte component. No headless browser required.
|
|
8
|
+
|
|
9
|
+
Pick the rendering engine that fits your needs:
|
|
10
|
+
|
|
11
|
+
- **Satori** (default) — HTML → SVG → PNG, based on [Satori](https://github.com/vercel/satori#documentation).
|
|
12
|
+
- **[Takumi](https://takumi.kane.tw)** — a Rust/WASM engine with more output formats (`webp`, `jpeg`, `ico`, `svg`, …) and a built-in font, available from `@ethercorps/sveltekit-og/takumi` (v4.3.0+).
|
|
8
13
|
|
|
9
14
|
## Table of Contents
|
|
10
15
|
|
|
@@ -35,6 +40,8 @@ pnpm install @ethercorps/sveltekit-og
|
|
|
35
40
|
|
|
36
41
|
For detailed usage instructions, please see the [Getting Started](https://sveltekit-og.dev/docs/getting-started) section of our documentation.
|
|
37
42
|
|
|
43
|
+
Prefer the Takumi engine — more output formats and a built-in font? See the [Takumi Engine](https://sveltekit-og.dev/docs/usage/takumi) guide.
|
|
44
|
+
|
|
38
45
|
## Examples
|
|
39
46
|
|
|
40
47
|
- **ImageResponse**: [_source_](/src/routes/+server.ts) · [_demo_](https://vercel.sveltekit-og.dev)
|
|
@@ -57,6 +64,7 @@ This project is licensed under the [MIT License](LICENSE).
|
|
|
57
64
|
This project would not be possible without the following projects:
|
|
58
65
|
|
|
59
66
|
- [Satori & @vercel/og](https://github.com/vercel/satori)
|
|
67
|
+
- [Takumi](https://takumi.kane.tw)
|
|
60
68
|
- [Noto by Google Fonts](https://fonts.google.com/noto)
|
|
61
69
|
- [fineshopdesign](https://github.com/fineshopdesign/cf-wasm)
|
|
62
70
|
|
package/dist/fonts.js
CHANGED
|
@@ -50,8 +50,10 @@ const constructGoogleFontCssUrl = (family, { text, weight = 400, style = "normal
|
|
|
50
50
|
};
|
|
51
51
|
if (text)
|
|
52
52
|
params.text = encodeURIComponent(text);
|
|
53
|
-
|
|
54
|
-
.
|
|
53
|
+
if (display)
|
|
54
|
+
params.display = display;
|
|
55
|
+
return `https://fonts.googleapis.com/css2?${Object.entries(params)
|
|
56
|
+
.map(([key, value]) => `${key}=${value}`)
|
|
55
57
|
.join("&")}`;
|
|
56
58
|
};
|
|
57
59
|
/** Loads Google font ArrayBuffer with caching. */
|
package/dist/helpers/create.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { Component } from "svelte";
|
|
2
2
|
import type { ComponentOptions, ImageOptions } from "../types.js";
|
|
3
|
-
|
|
4
|
-
export declare function
|
|
3
|
+
/** Single entry for the Satori and ReSVG engine */
|
|
4
|
+
export declare function createImage(element: string | Component<any>, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<Uint8Array | string>;
|
|
5
|
+
/** Create an SVG string from a Svelte component or HTML string using Satori */
|
|
6
|
+
export declare function createSvg(element: string | Component<any>, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<string>;
|
|
7
|
+
export declare function createPng(element: string | Component<any>, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<Uint8Array<ArrayBufferLike>>;
|
package/dist/helpers/create.js
CHANGED
|
@@ -3,15 +3,23 @@ import { default_fonts, DEFAULT_WIDTH } from "../helpers/defaults.js";
|
|
|
3
3
|
import { useResvg, useSatori } from "../providers/instances.js";
|
|
4
4
|
import { createVNode } from "./toJSX.js";
|
|
5
5
|
import { createLogger } from "./logger.js";
|
|
6
|
-
import {
|
|
6
|
+
import { handleAsync, ErrorCodes } from "./error-handler.js";
|
|
7
|
+
/** Single entry for the Satori and ReSVG engine */
|
|
8
|
+
export function createImage(element, imageOptions, componentOptions) {
|
|
9
|
+
return imageOptions.format === "svg"
|
|
10
|
+
? createSvg(element, imageOptions, componentOptions)
|
|
11
|
+
: createPng(element, imageOptions, componentOptions);
|
|
12
|
+
}
|
|
13
|
+
/** Create an SVG string from a Svelte component or HTML string using Satori */
|
|
7
14
|
export async function createSvg(element, imageOptions, componentOptions) {
|
|
8
15
|
const log = createLogger(imageOptions.debug ?? false);
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
16
|
+
const vnodes = createVNode(element, componentOptions);
|
|
17
|
+
const satori = await useSatori(imageOptions.debug);
|
|
18
|
+
const satoriOptions = { ...imageOptions };
|
|
19
|
+
if (!satoriOptions.fonts) {
|
|
20
|
+
satoriOptions.fonts = await handleAsync(() => default_fonts(), ErrorCodes.FONT_LOAD_FAILED, "Failed to load default fonts for Satori");
|
|
13
21
|
}
|
|
14
|
-
satoriOptions
|
|
22
|
+
satoriOptions.loadAdditionalAsset = loadDynamicAsset({
|
|
15
23
|
emoji: imageOptions.emoji,
|
|
16
24
|
});
|
|
17
25
|
log.debug("Generating SVG with Satori");
|
|
@@ -19,6 +27,7 @@ export async function createSvg(element, imageOptions, componentOptions) {
|
|
|
19
27
|
log.info("Options provided to satori:", imageOptions);
|
|
20
28
|
return handleAsync(() => satori(vnodes, satoriOptions), ErrorCodes.SATORI_RENDER_FAILED, "Failed to render SVG with Satori");
|
|
21
29
|
}
|
|
30
|
+
/* Create a PNG image from a Svelte component or HTML string using Satori and ReSVG */
|
|
22
31
|
export async function createPng(element, imageOptions, componentOptions) {
|
|
23
32
|
const log = createLogger(imageOptions.debug ?? false);
|
|
24
33
|
const svg = await handleAsync(() => createSvg(element, imageOptions, componentOptions), ErrorCodes.SATORI_RENDER_FAILED, "Failed to create SVG for PNG rendering");
|
package/dist/helpers/defaults.js
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { handleAsyncAll, validateResponse, ErrorCodes } from "./error-handler.js";
|
|
2
|
-
|
|
2
|
+
// fetched once per process; a rejected fetch clears the cache so the next request retries
|
|
3
|
+
let defaultFontsPromise;
|
|
4
|
+
export function default_fonts() {
|
|
5
|
+
defaultFontsPromise ??= loadDefaultFonts().catch((error) => {
|
|
6
|
+
defaultFontsPromise = undefined;
|
|
7
|
+
throw error;
|
|
8
|
+
});
|
|
9
|
+
return defaultFontsPromise;
|
|
10
|
+
}
|
|
11
|
+
async function loadDefaultFonts() {
|
|
3
12
|
const [noto_sans_regular_font_resp, noto_sans_bold_font_reps] = await handleAsyncAll([
|
|
4
13
|
() => fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Regular.ttf"),
|
|
5
14
|
() => fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Bold.ttf"),
|
package/dist/helpers/emoji.d.ts
CHANGED
|
@@ -8,6 +8,6 @@ declare const emoji_apis: {
|
|
|
8
8
|
};
|
|
9
9
|
export declare const loadDynamicAsset: ({ emoji }: {
|
|
10
10
|
emoji: EmojiType;
|
|
11
|
-
}) => (
|
|
11
|
+
}) => (code: string, text: string) => Promise<string | undefined>;
|
|
12
12
|
export type EmojiType = keyof typeof emoji_apis;
|
|
13
13
|
export {};
|
package/dist/helpers/emoji.js
CHANGED
|
@@ -51,7 +51,7 @@ async function loadEmoji(code, type) {
|
|
|
51
51
|
}, ErrorCodes.EMOJI_LOAD_FAILED, `Failed to load emoji for code: ${code}`);
|
|
52
52
|
}
|
|
53
53
|
export const loadDynamicAsset = ({ emoji }) => {
|
|
54
|
-
|
|
54
|
+
return async (code, text) => {
|
|
55
55
|
if (code === "emoji") {
|
|
56
56
|
return handleAsync(async () => {
|
|
57
57
|
const iconCode = getIconCode(text);
|
|
@@ -62,9 +62,4 @@ export const loadDynamicAsset = ({ emoji }) => {
|
|
|
62
62
|
}, ErrorCodes.EMOJI_LOAD_FAILED, `Failed to process emoji: ${text}`);
|
|
63
63
|
}
|
|
64
64
|
};
|
|
65
|
-
return async (...args) => {
|
|
66
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
67
|
-
// @ts-ignore
|
|
68
|
-
return await fn(...args);
|
|
69
|
-
};
|
|
70
65
|
};
|
|
@@ -3,6 +3,8 @@ export declare class ImageResponseError extends Error {
|
|
|
3
3
|
originalError?: Error | undefined;
|
|
4
4
|
constructor(message: string, code: string, originalError?: Error | undefined);
|
|
5
5
|
}
|
|
6
|
+
/** Coerce anything thrown into an ImageResponseError, keeping existing ones as-is. */
|
|
7
|
+
export declare function toImageResponseError(error: unknown): ImageResponseError;
|
|
6
8
|
export declare const ErrorCodes: {
|
|
7
9
|
readonly FONT_LOAD_FAILED: "FONT_LOAD_FAILED";
|
|
8
10
|
readonly VNODE_CREATION_FAILED: "VNODE_CREATION_FAILED";
|
|
@@ -8,6 +8,13 @@ export class ImageResponseError extends Error {
|
|
|
8
8
|
this.name = "ImageResponseError";
|
|
9
9
|
}
|
|
10
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
|
+
}
|
|
11
18
|
export const ErrorCodes = {
|
|
12
19
|
FONT_LOAD_FAILED: "FONT_LOAD_FAILED",
|
|
13
20
|
VNODE_CREATION_FAILED: "VNODE_CREATION_FAILED",
|
package/dist/helpers/logger.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const PREFIX =
|
|
1
|
+
const PREFIX = "[SvelteKit-OG]";
|
|
2
2
|
export function createLogger(debug) {
|
|
3
3
|
return {
|
|
4
4
|
debug: (message, ...args) => {
|
|
@@ -16,6 +16,6 @@ export function createLogger(debug) {
|
|
|
16
16
|
error: (message, ...args) => {
|
|
17
17
|
if (debug)
|
|
18
18
|
console.error(`${PREFIX} ❌ ${message}`, ...args);
|
|
19
|
-
}
|
|
19
|
+
},
|
|
20
20
|
};
|
|
21
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
|
+
}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import type { Component } from "svelte";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* `satori-html`, while the takumi path passes an HTML string to its renderer.
|
|
7
|
-
* Components that need their styles inlined should use
|
|
8
|
-
* `<svelte:options css="injected" />` so the CSS lands in `head`.
|
|
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`.
|
|
9
6
|
*/
|
|
10
7
|
export declare function renderComponentToHtml(component: Component<any>, props?: Record<string, unknown>): {
|
|
11
8
|
head: string;
|
package/dist/helpers/to-html.js
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import { render } from "svelte/server";
|
|
2
2
|
import { handleSync, ErrorCodes } from "./error-handler.js";
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* `satori-html`, while the takumi path passes an HTML string to its renderer.
|
|
8
|
-
* Components that need their styles inlined should use
|
|
9
|
-
* `<svelte:options css="injected" />` so the CSS lands in `head`.
|
|
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`.
|
|
10
7
|
*/
|
|
11
8
|
export function renderComponentToHtml(component, props = {}) {
|
|
12
9
|
return handleSync(() => render(component, { props }), ErrorCodes.VNODE_CREATION_FAILED, "Failed to render Svelte component to HTML");
|
package/dist/helpers/toJSX.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { Component } from "svelte";
|
|
2
2
|
import type { ComponentOptions, VNode } from "../types.js";
|
|
3
|
-
export declare function createVNode(element: string | Component
|
|
3
|
+
export declare function createVNode(element: string | Component<any>, componentOptions?: ComponentOptions): VNode;
|
package/dist/helpers/toJSX.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import { html } from "satori-html";
|
|
2
2
|
import { handleSync, ErrorCodes } from "./error-handler.js";
|
|
3
3
|
import { renderComponentToHtml } from "./to-html.js";
|
|
4
|
-
function
|
|
4
|
+
export function createVNode(element, componentOptions) {
|
|
5
5
|
return handleSync(() => {
|
|
6
|
-
|
|
6
|
+
if (typeof element === "string")
|
|
7
|
+
return html(element.replaceAll("\n", "").trim());
|
|
8
|
+
const { body, head } = renderComponentToHtml(element, componentOptions?.props);
|
|
7
9
|
return html(body + head);
|
|
8
|
-
}, ErrorCodes.VNODE_CREATION_FAILED, "Failed to
|
|
9
|
-
}
|
|
10
|
-
export function createVNode(element, componentOptions) {
|
|
11
|
-
return handleSync(() => typeof element === "string"
|
|
12
|
-
? html(element.replaceAll("\n", "").trim())
|
|
13
|
-
: svelteComponentToHTML(element, componentOptions?.props), ErrorCodes.VNODE_CREATION_FAILED, "Failed to create VNode");
|
|
10
|
+
}, ErrorCodes.VNODE_CREATION_FAILED, "Failed to create VNode");
|
|
14
11
|
}
|
package/dist/helpers/utils.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const formatBytes: (bytes: number, decimals?: number) => string;
|
|
2
|
-
export declare function importWasm(input:
|
|
2
|
+
export declare function importWasm(input: unknown): Promise<any>;
|
package/dist/helpers/utils.js
CHANGED
|
@@ -4,7 +4,7 @@ export const formatBytes = (bytes, decimals = 2) => {
|
|
|
4
4
|
if (bytes === 0)
|
|
5
5
|
return "0 Bytes";
|
|
6
6
|
const decimalPoint = decimals < 0 ? 0 : decimals;
|
|
7
|
-
const sizeIndex = Math.min(Math.floor(Math.log(bytes) / Math.log(kbSize)),
|
|
7
|
+
const sizeIndex = Math.min(Math.floor(Math.log(bytes) / Math.log(kbSize)), sizeFormats.length - 1);
|
|
8
8
|
return (parseFloat((bytes / Math.pow(kbSize, sizeIndex)).toFixed(decimalPoint)) +
|
|
9
9
|
" " +
|
|
10
10
|
sizeFormats[sizeIndex]);
|
|
@@ -12,7 +12,7 @@ export const formatBytes = (bytes, decimals = 2) => {
|
|
|
12
12
|
export async function importWasm(input) {
|
|
13
13
|
// may be a nested await for some reason
|
|
14
14
|
const _input = await input;
|
|
15
|
-
const _module = _input
|
|
15
|
+
const _module = _input?.default || _input;
|
|
16
16
|
// this is from rollup/wasm, it does some magic we need to recover from
|
|
17
17
|
if (typeof _module === "function") {
|
|
18
18
|
// empty input is to avoid instantiating the wasm module
|
package/dist/image-response.js
CHANGED
|
@@ -1,45 +1,18 @@
|
|
|
1
|
-
import { DEFAULT_OPTIONS
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { handleAsync, ImageResponseError, ErrorCodes } from "./helpers/error-handler.js";
|
|
5
|
-
import { formatBytes } from "./helpers/utils.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";
|
|
6
4
|
export class ImageResponse extends Response {
|
|
7
5
|
constructor(element, options, props) {
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
props,
|
|
18
|
-
}), ErrorCodes.UNKNOWN_ERROR, `Failed to generate ${extended_options.format?.toUpperCase()}`));
|
|
19
|
-
log.debug(buffer.length.toLocaleString());
|
|
20
|
-
log.info(`Generated ${extended_options.format.toUpperCase()}: ${formatBytes(buffer.length)}`);
|
|
21
|
-
controller.enqueue(buffer);
|
|
22
|
-
controller.close();
|
|
23
|
-
}
|
|
24
|
-
catch (error) {
|
|
25
|
-
const err = error instanceof ImageResponseError
|
|
26
|
-
? error
|
|
27
|
-
: new ImageResponseError(error instanceof Error ? error.message : String(error), ErrorCodes.UNKNOWN_ERROR, error instanceof Error ? error : new Error(String(error)));
|
|
28
|
-
log.error("Failed to create image response:", err.message);
|
|
29
|
-
controller.error(err);
|
|
30
|
-
}
|
|
31
|
-
},
|
|
32
|
-
});
|
|
33
|
-
super(body, {
|
|
34
|
-
headers: {
|
|
35
|
-
"Content-Type": `image/${extended_options.format}${extended_options.format === "svg" ? "+xml" : ""}`,
|
|
36
|
-
"Cache-Control": extended_options.debug
|
|
37
|
-
? "no-cache, no-store"
|
|
38
|
-
: "public, immutable, no-transform, max-age=31536000",
|
|
39
|
-
...extended_options.headers,
|
|
40
|
-
},
|
|
41
|
-
status: extended_options.status || DEFAULT_STATUS_CODE,
|
|
42
|
-
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,
|
|
43
15
|
});
|
|
16
|
+
super(body, init);
|
|
44
17
|
}
|
|
45
18
|
}
|
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
import { isEdgeLight, isWorkerd } from "std-env";
|
|
2
2
|
import { createLogger } from "../helpers/logger.js";
|
|
3
3
|
import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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
|
+
};
|
|
30
|
+
}
|
|
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
|
+
});
|
|
13
40
|
export async function useResvg(debug = false) {
|
|
14
|
-
|
|
15
|
-
if (resvgInstance.instance) {
|
|
16
|
-
return resvgInstance.instance.Resvg;
|
|
17
|
-
}
|
|
18
|
-
log.debug("Initializing ReSVG WASM");
|
|
19
|
-
const isWorkerLikeRuntime = isEdgeLight || isWorkerd;
|
|
20
|
-
log.info(`Detected runtime: ${isWorkerLikeRuntime ? "Edge Light or Workerd" : "Node.js"}`);
|
|
21
|
-
// Keep both dynamic imports as direct expressions so the bundler (unwasm/Rollup)
|
|
22
|
-
// can statically analyse them and emit the `?module` wasm chunk correctly.
|
|
23
|
-
// Burying these inside nested async callbacks breaks wasm bundling on Cloudflare.
|
|
24
|
-
const moduleImport = isWorkerLikeRuntime
|
|
25
|
-
? import("./resvg/edge.js")
|
|
26
|
-
: import("./resvg/node.js");
|
|
27
|
-
resvgInstance.instance = await handleAsync(() => moduleImport.then((m) => m.default), ErrorCodes.RESVG_INIT_FAILED, "Failed to import ReSVG module");
|
|
28
|
-
await handleAsync(() => resvgInstance.instance.initWasmPromise, ErrorCodes.RESVG_INIT_FAILED, "Failed to initialize ReSVG WASM");
|
|
29
|
-
return resvgInstance.instance.Resvg;
|
|
41
|
+
return (await useResvgModule(debug)).Resvg;
|
|
30
42
|
}
|
|
31
43
|
export async function useSatori(debug = false) {
|
|
32
|
-
|
|
33
|
-
if (satoriInstance.instance) {
|
|
34
|
-
return satoriInstance.instance.satori;
|
|
35
|
-
}
|
|
36
|
-
log.debug("Initializing Satori");
|
|
37
|
-
const isWorkerLikeRuntime = isEdgeLight || isWorkerd;
|
|
38
|
-
log.info(`Detected runtime: ${isWorkerLikeRuntime ? "Edge Light or Workerd" : "Node.js"}`);
|
|
39
|
-
const moduleImport = isWorkerLikeRuntime
|
|
40
|
-
? import("./satori/edge.js")
|
|
41
|
-
: import("./satori/node.js");
|
|
42
|
-
satoriInstance.instance = await handleAsync(() => moduleImport.then((m) => m.default), ErrorCodes.SATORI_INIT_FAILED, "Failed to import Satori module");
|
|
43
|
-
await handleAsync(() => satoriInstance.instance.initWasmPromise, ErrorCodes.SATORI_INIT_FAILED, "Failed to initialize Satori WASM");
|
|
44
|
-
return satoriInstance.instance.satori;
|
|
44
|
+
return (await useSatoriModule(debug)).satori;
|
|
45
45
|
}
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { Resvg as _Resvg, initWasm } from "@resvg/resvg-wasm";
|
|
2
2
|
|
|
3
3
|
export default {
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
initWasmPromise: initWasm(
|
|
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
|
+
),
|
|
7
11
|
Resvg: _Resvg,
|
|
8
12
|
};
|
|
@@ -1,13 +1,22 @@
|
|
|
1
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
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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(
|
|
20
|
+
initWasmPromise: initWasm(loadResvgWasm()),
|
|
12
21
|
Resvg: _Resvg,
|
|
13
22
|
};
|
|
@@ -1,16 +1,12 @@
|
|
|
1
1
|
import _satori, { init } from "satori/standalone";
|
|
2
2
|
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// `satori/standalone` exposes `init()` so we can hand it a pre-compiled
|
|
8
|
-
// WebAssembly.Module instead. Importing the vendored yoga.wasm with `?module`
|
|
9
|
-
// makes the consumer bundler emit a real CompiledWasm module, so no runtime
|
|
10
|
-
// byte compilation happens. Mirrors providers/resvg/edge.js.
|
|
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.
|
|
11
7
|
export default {
|
|
12
8
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
13
9
|
// @ts-ignore
|
|
14
|
-
initWasmPromise: init(import("
|
|
10
|
+
initWasmPromise: init(import("satori/yoga.wasm?module").then((r) => r.default || r)),
|
|
15
11
|
satori: _satori,
|
|
16
12
|
};
|
package/dist/takumi/fonts.d.ts
CHANGED
|
@@ -1,26 +1,16 @@
|
|
|
1
1
|
import type { FontDetails } from "takumi-js/node";
|
|
2
2
|
import { BaseFont } from "../fonts.js";
|
|
3
3
|
import type { MayBePromise } from "../types.js";
|
|
4
|
-
/** Font bytes Takumi accepts for registration. */
|
|
5
4
|
type ByteBuf = Uint8Array | ArrayBuffer | Buffer;
|
|
6
|
-
/**
|
|
7
|
-
* A Takumi-native font descriptor. `data` may be the bytes directly or a lazy
|
|
8
|
-
* loader returning them — matching `takumi-js`'s own font option shape.
|
|
9
|
-
*/
|
|
5
|
+
/** Takumi-native font descriptor; data is the bytes or a lazy loader, like takumi-js wants. */
|
|
10
6
|
export interface TakumiFontDescriptor {
|
|
11
7
|
name?: string;
|
|
12
8
|
data: ByteBuf | (() => MayBePromise<ByteBuf>);
|
|
13
9
|
weight?: number;
|
|
14
10
|
style?: FontDetails["style"];
|
|
15
11
|
}
|
|
16
|
-
/**
|
|
17
|
-
* Accepted font inputs on the Takumi path: this library's `GoogleFont` /
|
|
18
|
-
* `CustomFont` helpers (any `BaseFont`) or a raw Takumi descriptor.
|
|
19
|
-
*/
|
|
12
|
+
/** What the takumi path accepts: our GoogleFont/CustomFont, or a raw takumi descriptor. */
|
|
20
13
|
export type TakumiFontInput = BaseFont | TakumiFontDescriptor;
|
|
21
|
-
/**
|
|
22
|
-
* Resolves mixed font inputs into Takumi `FontDetails` ready for
|
|
23
|
-
* `renderer.registerFont`. Loaders run in parallel.
|
|
24
|
-
*/
|
|
14
|
+
/** Normalize mixed font inputs to FontDetails for registerFont, loaders run in parallel. */
|
|
25
15
|
export declare function resolveTakumiFonts(fonts: TakumiFontInput[]): Promise<FontDetails[]>;
|
|
26
16
|
export {};
|
package/dist/takumi/fonts.js
CHANGED
|
@@ -2,17 +2,14 @@ import { BaseFont } from "../fonts.js";
|
|
|
2
2
|
import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
|
|
3
3
|
async function normalizeFont(font) {
|
|
4
4
|
if (font instanceof BaseFont) {
|
|
5
|
-
//
|
|
5
|
+
// our font classes lazily load + cache through the data getter
|
|
6
6
|
const data = (await font.data);
|
|
7
7
|
return { name: font.name, data, weight: font.weight, style: font.style };
|
|
8
8
|
}
|
|
9
9
|
const data = typeof font.data === "function" ? await font.data() : await font.data;
|
|
10
10
|
return { name: font.name, data, weight: font.weight, style: font.style };
|
|
11
11
|
}
|
|
12
|
-
/**
|
|
13
|
-
* Resolves mixed font inputs into Takumi `FontDetails` ready for
|
|
14
|
-
* `renderer.registerFont`. Loaders run in parallel.
|
|
15
|
-
*/
|
|
12
|
+
/** Normalize mixed font inputs to FontDetails for registerFont, loaders run in parallel. */
|
|
16
13
|
export async function resolveTakumiFonts(fonts) {
|
|
17
14
|
return handleAsync(() => Promise.all(fonts.map(normalizeFont)), ErrorCodes.FONT_LOAD_FAILED, "Failed to resolve fonts for Takumi");
|
|
18
15
|
}
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import type { Component, ComponentProps } from "svelte";
|
|
2
2
|
import type { TakumiImageResponseOptions } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
* Generates an Open Graph image with the Takumi engine and returns it as a
|
|
5
|
-
* `Response`. Accepts an HTML string or a Svelte component (with props).
|
|
6
|
-
*/
|
|
3
|
+
/** OG image rendered by Takumi. Takes an HTML string or a Svelte component. */
|
|
7
4
|
export declare class ImageResponse<T extends string | Component<any>> extends Response {
|
|
8
5
|
constructor(element: T, options?: TakumiImageResponseOptions, props?: T extends Component<any> ? ComponentProps<T> : never);
|
|
9
6
|
}
|
|
@@ -1,62 +1,27 @@
|
|
|
1
1
|
import { createTakumiImage } from "./render.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { formatBytes } from "../helpers/utils.js";
|
|
2
|
+
import { DEFAULT_WIDTH, DEFAULT_HEIGHT } from "../helpers/defaults.js";
|
|
3
|
+
import { buildImageResponse, CONTENT_TYPES as SHARED_CONTENT_TYPES } from "../helpers/response.js";
|
|
5
4
|
const DEFAULT_OPTIONS = {
|
|
6
|
-
width:
|
|
7
|
-
height:
|
|
5
|
+
width: DEFAULT_WIDTH,
|
|
6
|
+
height: DEFAULT_HEIGHT,
|
|
8
7
|
format: "png",
|
|
9
8
|
emoji: "twemoji",
|
|
10
9
|
debug: false,
|
|
11
10
|
};
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
webp: "image/webp",
|
|
16
|
-
ico: "image/x-icon",
|
|
17
|
-
raw: "application/octet-stream",
|
|
18
|
-
svg: "image/svg+xml",
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Generates an Open Graph image with the Takumi engine and returns it as a
|
|
22
|
-
* `Response`. Accepts an HTML string or a Svelte component (with props).
|
|
23
|
-
*/
|
|
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. */
|
|
24
14
|
export class ImageResponse extends Response {
|
|
25
15
|
constructor(element, options, props) {
|
|
26
16
|
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
// renderSvg returns a string; raster formats return bytes. A
|
|
35
|
-
// Response body stream must emit Uint8Array chunks.
|
|
36
|
-
const bytes = typeof output === "string" ? new TextEncoder().encode(output) : output;
|
|
37
|
-
log.info(`Generated ${format.toUpperCase()}: ${formatBytes(bytes.byteLength)}`);
|
|
38
|
-
controller.enqueue(bytes);
|
|
39
|
-
controller.close();
|
|
40
|
-
}
|
|
41
|
-
catch (error) {
|
|
42
|
-
const err = error instanceof ImageResponseError
|
|
43
|
-
? error
|
|
44
|
-
: new ImageResponseError(error instanceof Error ? error.message : String(error), ErrorCodes.UNKNOWN_ERROR, error instanceof Error ? error : new Error(String(error)));
|
|
45
|
-
log.error("Failed to create Takumi image response:", err.message);
|
|
46
|
-
controller.error(err);
|
|
47
|
-
}
|
|
48
|
-
},
|
|
49
|
-
});
|
|
50
|
-
super(body, {
|
|
51
|
-
headers: {
|
|
52
|
-
"Content-Type": CONTENT_TYPES[format],
|
|
53
|
-
"Cache-Control": opts.debug
|
|
54
|
-
? "no-cache, no-store"
|
|
55
|
-
: "public, immutable, no-transform, max-age=31536000",
|
|
56
|
-
...opts.headers,
|
|
57
|
-
},
|
|
58
|
-
status: opts.status || 200,
|
|
59
|
-
statusText: opts.statusText || "Success",
|
|
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,
|
|
60
24
|
});
|
|
25
|
+
super(body, init);
|
|
61
26
|
}
|
|
62
27
|
}
|
package/dist/takumi/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { ImageResponse } from "./image-response.js";
|
|
2
2
|
export { resolveTakumiFonts } from "./fonts.js";
|
|
3
|
-
//
|
|
3
|
+
// re-export the font helpers so the takumi path works from one import
|
|
4
4
|
export { GoogleFont, CustomFont, loadGoogleFont } from "../fonts.js";
|
package/dist/takumi/render.d.ts
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import type { Component } from "svelte";
|
|
2
2
|
import type { TakumiImageOptions } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
* using a cached, font-registered Takumi renderer for the current runtime.
|
|
6
|
-
*/
|
|
7
|
-
export declare function createTakumiImage(element: string | Component, options: TakumiImageOptions, props?: Record<string, unknown>): Promise<Uint8Array | string>;
|
|
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>;
|
package/dist/takumi/render.js
CHANGED
|
@@ -1,36 +1,23 @@
|
|
|
1
1
|
import { render as takumiRender, renderSvg } from "takumi-js";
|
|
2
|
-
import { renderComponentToHtml } from "../helpers/to-html.js";
|
|
3
2
|
import { useTakumiRenderer, registerTakumiFonts } from "./renderer.js";
|
|
4
3
|
import { resolveTakumiFonts } from "./fonts.js";
|
|
5
4
|
import { createLogger } from "../helpers/logger.js";
|
|
6
|
-
import { handleAsync,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return element.replaceAll("\n", "").trim();
|
|
10
|
-
// Takumi reads inline `style`/`<style>`; `head` carries CSS injected via
|
|
11
|
-
// `<svelte:options css="injected" />`, so it goes first.
|
|
12
|
-
const { head, body } = renderComponentToHtml(element, props);
|
|
13
|
-
return head + body;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Renders an HTML string or Svelte component to image bytes (or an SVG string)
|
|
17
|
-
* using a cached, font-registered Takumi renderer for the current runtime.
|
|
18
|
-
*/
|
|
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). */
|
|
19
8
|
export async function createTakumiImage(element, options, props) {
|
|
20
9
|
const log = createLogger(options.debug ?? false);
|
|
21
|
-
const
|
|
22
|
-
const renderer = await useTakumiRenderer(
|
|
10
|
+
const vNode = handleSync(() => createVNode(element, { props }), ErrorCodes.VNODE_CREATION_FAILED, "Failed to create HTML for Takumi");
|
|
11
|
+
const renderer = await useTakumiRenderer();
|
|
23
12
|
if (options.fonts?.length) {
|
|
24
13
|
const fonts = await resolveTakumiFonts(options.fonts);
|
|
25
14
|
await registerTakumiFonts(renderer, fonts);
|
|
26
15
|
}
|
|
27
16
|
const { width, height, format = "png", quality, stylesheets, emoji } = options;
|
|
28
|
-
// `renderer` is typed as the native Renderer; on edge it's the wasm Renderer,
|
|
29
|
-
// which is structurally compatible for takumi-js's managed render.
|
|
30
17
|
const shared = { renderer: renderer, width, height, stylesheets, emoji };
|
|
31
18
|
log.debug(`Rendering ${format.toUpperCase()} with Takumi`);
|
|
32
19
|
if (format === "svg") {
|
|
33
|
-
return handleAsync(() => renderSvg(
|
|
20
|
+
return handleAsync(() => renderSvg(vNode, shared), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render SVG with Takumi");
|
|
34
21
|
}
|
|
35
|
-
return handleAsync(() => takumiRender(
|
|
22
|
+
return handleAsync(() => takumiRender(vNode, { ...shared, format, quality }), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render image with Takumi");
|
|
36
23
|
}
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import type { Renderer as NodeRenderer, FontDetails } from "takumi-js/node";
|
|
2
|
-
/** Either backend's Renderer; both expose `render`/`renderSvg`/`registerFont`. */
|
|
3
2
|
export type TakumiRenderer = NodeRenderer;
|
|
4
|
-
/** Lazily creates and caches the Takumi renderer for the current runtime.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
* same face isn't re-registered across requests.
|
|
9
|
-
*/
|
|
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. */
|
|
10
7
|
export declare function registerTakumiFonts(renderer: TakumiRenderer, fonts: FontDetails[]): Promise<void>;
|
package/dist/takumi/renderer.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createLogger } from "../helpers/logger.js";
|
|
1
|
+
import autoModule, { init as initTakumiWasm, Renderer } from "takumi-js/wasm";
|
|
3
2
|
import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// track which have already been registered to avoid duplicate work.
|
|
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.
|
|
7
5
|
let rendererPromise;
|
|
8
6
|
const registeredFontKeys = new Set();
|
|
9
|
-
async function initRenderer(
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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();
|
|
21
20
|
}
|
|
22
|
-
/** Lazily creates and caches the Takumi renderer for the current runtime.
|
|
23
|
-
|
|
24
|
-
|
|
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
|
+
});
|
|
25
28
|
return rendererPromise;
|
|
26
29
|
}
|
|
27
|
-
/**
|
|
28
|
-
* Registers each font on the renderer once. Keyed by name/weight/style so the
|
|
29
|
-
* same face isn't re-registered across requests.
|
|
30
|
-
*/
|
|
30
|
+
/** Register each font once, keyed by name/weight/style. */
|
|
31
31
|
export async function registerTakumiFonts(renderer, fonts) {
|
|
32
32
|
for (const font of fonts) {
|
|
33
33
|
const key = `${font.name ?? "unnamed"}-${font.weight ?? "auto"}-${font.style ?? "normal"}`;
|
package/dist/types.d.ts
CHANGED
|
@@ -85,7 +85,3 @@ export interface VNode {
|
|
|
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;
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ethercorps/sveltekit-og",
|
|
3
|
-
"version": "4.3.0
|
|
3
|
+
"version": "4.3.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"homepage": "https://sveltekit-og.dev",
|
|
6
|
-
"repository": "github:
|
|
6
|
+
"repository": "github:etherCorps/sveltekit-og",
|
|
7
7
|
"funding": "https://github.com/sponsors/ethercorps",
|
|
8
8
|
"author": "Shivam Meena <https://github.com/theetherGit>",
|
|
9
9
|
"description": "Dynamically generate Open Graph images from an HTML, CSS template or Svelte component using fast and efficient conversion from HTML > SVG > PNG",
|
|
@@ -36,10 +36,9 @@
|
|
|
36
36
|
"scripts": {
|
|
37
37
|
"dev": "vite dev",
|
|
38
38
|
"build": "vite build && npm run package",
|
|
39
|
-
"build:examples": "pnpm -F \"./examples/**\" --parallel --color build",
|
|
40
|
-
"check:examples": "pnpm install -r",
|
|
41
39
|
"preview": "vite preview",
|
|
42
40
|
"package": "svelte-kit sync && svelte-package && publint",
|
|
41
|
+
"prepare": "svelte-kit sync && svelte-package",
|
|
43
42
|
"prepublishOnly": "pnpm run package",
|
|
44
43
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
|
45
44
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
|
@@ -70,7 +69,8 @@
|
|
|
70
69
|
"./plugin": {
|
|
71
70
|
"types": "./dist/plugin.d.ts",
|
|
72
71
|
"import": "./dist/plugin.js"
|
|
73
|
-
}
|
|
72
|
+
},
|
|
73
|
+
"./package.json": "./package.json"
|
|
74
74
|
},
|
|
75
75
|
"files": [
|
|
76
76
|
"dist",
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@eslint/compat": "^2.0.3",
|
|
82
82
|
"@eslint/js": "^9.39.3",
|
|
83
|
-
"@sveltejs/adapter-
|
|
83
|
+
"@sveltejs/adapter-auto": "^3.3.1",
|
|
84
84
|
"@sveltejs/kit": "^2.53.4",
|
|
85
85
|
"@sveltejs/package": "^2.5.7",
|
|
86
86
|
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"typescript": "^5.9.3",
|
|
106
106
|
"typescript-eslint": "^8.57.0",
|
|
107
107
|
"vite": "^5.4.21",
|
|
108
|
-
"takumi-js": "2.0.
|
|
108
|
+
"takumi-js": "2.0.1",
|
|
109
109
|
"vitest": "^1.6.1"
|
|
110
110
|
},
|
|
111
111
|
"main": "./dist/index.js",
|
|
@@ -121,7 +121,7 @@
|
|
|
121
121
|
},
|
|
122
122
|
"peerDependencies": {
|
|
123
123
|
"@sveltejs/kit": ">=2.0.0",
|
|
124
|
-
"takumi-js": "^2.0.
|
|
124
|
+
"takumi-js": "^2.0.1"
|
|
125
125
|
},
|
|
126
126
|
"peerDependenciesMeta": {
|
|
127
127
|
"takumi-js": {
|
|
Binary file
|
|
Binary file
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { init, Renderer } from "takumi-js/wasm";
|
|
2
|
-
|
|
3
|
-
// Worker-like runtimes (Cloudflare Workers, Vercel Edge) can't compile WASM at
|
|
4
|
-
// runtime, so we hand the wasm-bindgen `init` a pre-compiled module. Importing
|
|
5
|
-
// the vendored takumi.wasm with `?module` makes the consumer bundler emit a real
|
|
6
|
-
// CompiledWasm module — mirrors providers/resvg/edge.js and providers/satori/edge.js.
|
|
7
|
-
export default {
|
|
8
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
9
|
-
// @ts-ignore
|
|
10
|
-
initWasmPromise: init({
|
|
11
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
12
|
-
// @ts-ignore
|
|
13
|
-
module_or_path: import("./takumi.wasm?module").then((r) => r.default || r),
|
|
14
|
-
}),
|
|
15
|
-
Renderer,
|
|
16
|
-
};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { Renderer } from "takumi-js/node";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Native Node.js backend (@takumi-rs/core). The renderer is a native addon, so
|
|
5
|
-
* there is no WASM to initialize — construction is synchronous.
|
|
6
|
-
* */
|
|
7
|
-
export default {
|
|
8
|
-
initWasmPromise: Promise.resolve(),
|
|
9
|
-
Renderer,
|
|
10
|
-
};
|
|
Binary file
|