@ethercorps/sveltekit-og 4.3.0-next.1 → 4.3.0-next.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fonts.js +0 -5
- package/dist/helpers/create.js +20 -18
- package/dist/helpers/defaults.js +9 -12
- package/dist/helpers/emoji.js +19 -14
- package/dist/helpers/error-handler.d.ts +37 -0
- package/dist/helpers/error-handler.js +75 -0
- package/dist/helpers/logger.d.ts +2 -10
- package/dist/helpers/logger.js +19 -37
- package/dist/helpers/response.d.ts +20 -0
- package/dist/helpers/response.js +39 -0
- package/dist/helpers/to-html.d.ts +10 -0
- package/dist/helpers/to-html.js +10 -0
- package/dist/helpers/toJSX.js +8 -5
- package/dist/helpers/utils.d.ts +2 -0
- package/dist/helpers/utils.js +25 -0
- package/dist/image-response.js +13 -25
- package/dist/providers/instances.d.ts +2 -2
- package/dist/providers/instances.js +23 -11
- package/dist/providers/resvg/edge.js +4 -2
- package/dist/providers/resvg/node.js +16 -7
- package/dist/providers/resvg/resvg.wasm +0 -0
- package/dist/providers/satori/edge.d.ts +6 -0
- package/dist/providers/satori/edge.js +12 -0
- package/dist/takumi/fonts.d.ts +16 -0
- package/dist/takumi/fonts.js +15 -0
- package/dist/takumi/image-response.d.ts +6 -0
- package/dist/takumi/image-response.js +33 -0
- package/dist/takumi/index.d.ts +5 -0
- package/dist/takumi/index.js +4 -0
- package/dist/takumi/render.d.ts +4 -0
- package/dist/takumi/render.js +30 -0
- package/dist/takumi/renderer.d.ts +6 -0
- package/dist/takumi/renderer.js +35 -0
- package/dist/takumi/types.d.ts +64 -0
- package/dist/takumi/types.js +1 -0
- package/dist/types.d.ts +1 -1
- package/package.json +130 -116
package/dist/fonts.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { FONT_CACHE_MAP } from "./helpers/cache.js";
|
|
2
|
-
import { logger } from "./helpers/logger.js";
|
|
3
2
|
/** * Base font class defining the structure required by Satori.
|
|
4
3
|
* All font types inherit from this class.
|
|
5
4
|
*/
|
|
@@ -64,26 +63,22 @@ export const loadGoogleFont = async (family, { text, weight = 400, style = "norm
|
|
|
64
63
|
}
|
|
65
64
|
const cssResponse = await fetch(cssUrl);
|
|
66
65
|
if (!cssResponse.ok) {
|
|
67
|
-
logger.error(`Failed to fetch Google Font CSS for ${family}. Status: ${cssResponse.status}`);
|
|
68
66
|
throw new Error(`Failed to fetch Google Font CSS for ${family}. Status: ${cssResponse.status}`);
|
|
69
67
|
}
|
|
70
68
|
const css = await cssResponse.text();
|
|
71
69
|
// 3. Extract the font file URL (the actual TTF/OTF file)
|
|
72
70
|
const fontUrl = css.match(/src: url\((.+)\) format\('(opentype|truetype)'\)/)?.[1];
|
|
73
71
|
if (!fontUrl) {
|
|
74
|
-
logger.error(`Could not find a compatible truetype font source in the CSS for ${family}.`);
|
|
75
72
|
throw new Error(`Could not find a compatible truetype font source in the CSS for ${family}.`);
|
|
76
73
|
}
|
|
77
74
|
// 4. Fetch the font buffer
|
|
78
75
|
const fontResponse = await fetch(fontUrl);
|
|
79
76
|
if (!fontResponse.ok) {
|
|
80
|
-
logger.error(`Failed to fetch font file from URL. Status: ${fontResponse.status}`);
|
|
81
77
|
throw new Error(`Failed to fetch font file from URL. Status: ${fontResponse.status}`);
|
|
82
78
|
}
|
|
83
79
|
const buffer = await fontResponse.arrayBuffer();
|
|
84
80
|
// 5. CACHE AND RETURN: Store the resolved ArrayBuffer in the Map, keyed by the CSS URL.
|
|
85
81
|
FONT_CACHE_MAP.set(cssUrl, buffer);
|
|
86
|
-
logger.debug(`Loaded Google Font: ${family}`);
|
|
87
82
|
return buffer;
|
|
88
83
|
};
|
|
89
84
|
export class GoogleFont extends BaseFont {
|
package/dist/helpers/create.js
CHANGED
|
@@ -2,37 +2,39 @@ import { loadDynamicAsset } from "./emoji.js";
|
|
|
2
2
|
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
|
-
import {
|
|
5
|
+
import { createLogger } from "./logger.js";
|
|
6
|
+
import { handleAsyncAll, handleAsync, ErrorCodes } from "./error-handler.js";
|
|
6
7
|
export async function createSvg(element, imageOptions, componentOptions) {
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
createVNode(element, componentOptions),
|
|
10
|
-
]);
|
|
8
|
+
const log = createLogger(imageOptions.debug ?? false);
|
|
9
|
+
const [satori, vnodes] = await handleAsyncAll([() => useSatori(imageOptions.debug), () => Promise.resolve(createVNode(element, componentOptions))], ErrorCodes.SATORI_RENDER_FAILED, "Failed to initialize Satori or create VNode");
|
|
11
10
|
const satoriOptions = structuredClone(imageOptions);
|
|
12
11
|
if (!Object.hasOwn(satoriOptions, "fonts")) {
|
|
13
|
-
satoriOptions["fonts"] = await default_fonts();
|
|
12
|
+
satoriOptions["fonts"] = await handleAsync(() => default_fonts(), ErrorCodes.FONT_LOAD_FAILED, "Failed to load default fonts for Satori");
|
|
14
13
|
}
|
|
15
14
|
satoriOptions["loadAdditionalAsset"] = loadDynamicAsset({
|
|
16
15
|
emoji: imageOptions.emoji,
|
|
17
16
|
});
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return satori(vnodes, satoriOptions);
|
|
17
|
+
log.debug("Generating SVG with Satori");
|
|
18
|
+
log.info("VNode provided to satori:", JSON.stringify(vnodes, null, 2), "\n");
|
|
19
|
+
log.info("Options provided to satori:", imageOptions);
|
|
20
|
+
return handleAsync(() => satori(vnodes, satoriOptions), ErrorCodes.SATORI_RENDER_FAILED, "Failed to render SVG with Satori");
|
|
22
21
|
}
|
|
23
22
|
export async function createPng(element, imageOptions, componentOptions) {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
const log = createLogger(imageOptions.debug ?? false);
|
|
24
|
+
const svg = await handleAsync(() => createSvg(element, imageOptions, componentOptions), ErrorCodes.SATORI_RENDER_FAILED, "Failed to create SVG for PNG rendering");
|
|
25
|
+
log.debug("SVG generated by satori for ReSVG: \n", svg, "\n");
|
|
26
|
+
const resvg_instance = await handleAsync(() => useResvg(imageOptions.debug), ErrorCodes.RESVG_INIT_FAILED, "Failed to initialize ReSVG");
|
|
27
27
|
const resvg_options = {
|
|
28
28
|
fitTo: {
|
|
29
29
|
mode: "width",
|
|
30
30
|
value: imageOptions.width || DEFAULT_WIDTH,
|
|
31
31
|
},
|
|
32
32
|
};
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
log.debug("Rendering PNG with ReSVG");
|
|
34
|
+
log.info("Options provided to ReSVG:", resvg_options, "\n");
|
|
35
|
+
return handleAsync(async () => {
|
|
36
|
+
const resvg = new resvg_instance(svg, resvg_options);
|
|
37
|
+
const png_data = resvg.render();
|
|
38
|
+
return png_data.asPng();
|
|
39
|
+
}, ErrorCodes.RESVG_RENDER_FAILED, "Failed to render PNG with ReSVG");
|
|
38
40
|
}
|
package/dist/helpers/defaults.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
|
+
import { handleAsyncAll, validateResponse, ErrorCodes } from "./error-handler.js";
|
|
1
2
|
export async function default_fonts() {
|
|
2
|
-
const [noto_sans_regular_font_resp, noto_sans_bold_font_reps] = await
|
|
3
|
-
fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Regular.ttf"),
|
|
4
|
-
fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Bold.ttf"),
|
|
5
|
-
]);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const [noto_sans_regular_font, noto_sans_bold_font] = await Promise.all([
|
|
11
|
-
noto_sans_regular_font_resp.arrayBuffer(),
|
|
12
|
-
noto_sans_bold_font_reps.arrayBuffer(),
|
|
13
|
-
]);
|
|
3
|
+
const [noto_sans_regular_font_resp, noto_sans_bold_font_reps] = await handleAsyncAll([
|
|
4
|
+
() => fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Regular.ttf"),
|
|
5
|
+
() => fetch("https://cdn-sveltekit-og.ethercorps.io/NotoSans-Bold.ttf"),
|
|
6
|
+
], ErrorCodes.FONT_LOAD_FAILED, "Failed to fetch default fonts");
|
|
7
|
+
const [noto_sans_regular_font, noto_sans_bold_font] = await handleAsyncAll([
|
|
8
|
+
() => validateResponse(noto_sans_regular_font_resp, ErrorCodes.FONT_LOAD_FAILED, "Failed to validate regular font response"),
|
|
9
|
+
() => validateResponse(noto_sans_bold_font_reps, ErrorCodes.FONT_LOAD_FAILED, "Failed to validate bold font response"),
|
|
10
|
+
], ErrorCodes.FONT_LOAD_FAILED, "Failed to process font responses");
|
|
14
11
|
return [
|
|
15
12
|
{
|
|
16
13
|
data: noto_sans_regular_font,
|
package/dist/helpers/emoji.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
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;
|
|
@@ -37,24 +38,28 @@ const emoji_apis = {
|
|
|
37
38
|
code.toLowerCase() +
|
|
38
39
|
"_flat.svg",
|
|
39
40
|
};
|
|
40
|
-
function loadEmoji(code, type) {
|
|
41
|
-
|
|
42
|
-
type
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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}`);
|
|
49
52
|
}
|
|
50
53
|
export const loadDynamicAsset = ({ emoji }) => {
|
|
51
54
|
const fn = async (code, text) => {
|
|
52
55
|
if (code === "emoji") {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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}`);
|
|
58
63
|
}
|
|
59
64
|
};
|
|
60
65
|
return async (...args) => {
|
|
@@ -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
|
+
}
|
package/dist/helpers/logger.d.ts
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Call this once at the beginning of your request handler
|
|
4
|
-
*/
|
|
5
|
-
export declare function setDebug(enabled: boolean): void;
|
|
6
|
-
/**
|
|
7
|
-
* Get the current debug flag from the request context
|
|
8
|
-
*/
|
|
9
|
-
export declare function isDebugEnabled(): boolean;
|
|
10
|
-
export declare const logger: {
|
|
1
|
+
export type Logger = ReturnType<typeof createLogger>;
|
|
2
|
+
export declare function createLogger(debug: boolean): {
|
|
11
3
|
debug: (message: string, ...args: unknown[]) => void;
|
|
12
4
|
info: (message: string, ...args: unknown[]) => void;
|
|
13
5
|
warn: (message: string, ...args: unknown[]) => void;
|
package/dist/helpers/logger.js
CHANGED
|
@@ -1,39 +1,21 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
1
|
const PREFIX = '[SvelteKit-OG]';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
if (isDebugEnabled()) {
|
|
21
|
-
console.log(`${PREFIX} 🔍 ${message}`, ...args);
|
|
22
|
-
}
|
|
23
|
-
},
|
|
24
|
-
info: (message, ...args) => {
|
|
25
|
-
if (isDebugEnabled()) {
|
|
26
|
-
console.info(`${PREFIX} ℹ️ ${message}`, ...args);
|
|
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);
|
|
27
19
|
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
if (isDebugEnabled()) {
|
|
31
|
-
console.warn(`${PREFIX} ⚠️ ${message}`, ...args);
|
|
32
|
-
}
|
|
33
|
-
},
|
|
34
|
-
error: (message, ...args) => {
|
|
35
|
-
if (isDebugEnabled()) {
|
|
36
|
-
console.error(`${PREFIX} ❌ ${message}`, ...args);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
};
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
type ImageProducer = () => Promise<Uint8Array | string>;
|
|
2
|
+
interface BuildOptions {
|
|
3
|
+
/** uppercased format, used in logs e.g. "PNG" */
|
|
4
|
+
label: string;
|
|
5
|
+
contentType: string;
|
|
6
|
+
debug: boolean;
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
status?: number;
|
|
9
|
+
statusText?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Shared body + response init for both engines' ImageResponse. Streams the image
|
|
13
|
+
* out as bytes (a Response stream can't take a raw string), with consistent
|
|
14
|
+
* cache headers and error handling.
|
|
15
|
+
*/
|
|
16
|
+
export declare function buildImageResponse(produce: ImageProducer, opts: BuildOptions): {
|
|
17
|
+
body: ReadableStream;
|
|
18
|
+
init: ResponseInit;
|
|
19
|
+
};
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createLogger } from "./logger.js";
|
|
2
|
+
import { handleAsync, toImageResponseError, ErrorCodes } from "./error-handler.js";
|
|
3
|
+
import { formatBytes } from "./utils.js";
|
|
4
|
+
/**
|
|
5
|
+
* Shared body + response init for both engines' ImageResponse. Streams the image
|
|
6
|
+
* out as bytes (a Response stream can't take a raw string), with consistent
|
|
7
|
+
* cache headers and error handling.
|
|
8
|
+
*/
|
|
9
|
+
export function buildImageResponse(produce, opts) {
|
|
10
|
+
const log = createLogger(opts.debug);
|
|
11
|
+
const body = new ReadableStream({
|
|
12
|
+
async start(controller) {
|
|
13
|
+
try {
|
|
14
|
+
const out = await handleAsync(produce, ErrorCodes.UNKNOWN_ERROR, `Failed to generate ${opts.label}`);
|
|
15
|
+
const bytes = typeof out === "string" ? new TextEncoder().encode(out) : out;
|
|
16
|
+
log.info(`Generated ${opts.label}: ${formatBytes(bytes.byteLength)}`);
|
|
17
|
+
controller.enqueue(bytes);
|
|
18
|
+
controller.close();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
const err = toImageResponseError(error);
|
|
22
|
+
log.error("Failed to create image response:", err.message);
|
|
23
|
+
controller.error(err);
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
const init = {
|
|
28
|
+
headers: {
|
|
29
|
+
"Content-Type": opts.contentType,
|
|
30
|
+
"Cache-Control": opts.debug
|
|
31
|
+
? "no-cache, no-store"
|
|
32
|
+
: "public, immutable, no-transform, max-age=31536000",
|
|
33
|
+
...opts.headers,
|
|
34
|
+
},
|
|
35
|
+
status: opts.status || 200,
|
|
36
|
+
statusText: opts.statusText || "Success",
|
|
37
|
+
};
|
|
38
|
+
return { body, init };
|
|
39
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/helpers/toJSX.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import { render } from "svelte/server";
|
|
2
1
|
import { html } from "satori-html";
|
|
2
|
+
import { handleSync, ErrorCodes } from "./error-handler.js";
|
|
3
|
+
import { renderComponentToHtml } from "./to-html.js";
|
|
3
4
|
function svelteComponentToHTML(component, props = {}) {
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
return handleSync(() => {
|
|
6
|
+
const { body, head } = renderComponentToHtml(component, props);
|
|
7
|
+
return html(body + head);
|
|
8
|
+
}, ErrorCodes.VNODE_CREATION_FAILED, "Failed to render Svelte component to HTML");
|
|
6
9
|
}
|
|
7
10
|
export function createVNode(element, componentOptions) {
|
|
8
|
-
return typeof element === "string"
|
|
11
|
+
return handleSync(() => typeof element === "string"
|
|
9
12
|
? html(element.replaceAll("\n", "").trim())
|
|
10
|
-
: svelteComponentToHTML(element, componentOptions?.props);
|
|
13
|
+
: svelteComponentToHTML(element, componentOptions?.props), ErrorCodes.VNODE_CREATION_FAILED, "Failed to create VNode");
|
|
11
14
|
}
|
|
@@ -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)), 3);
|
|
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
|
+
}
|
package/dist/image-response.js
CHANGED
|
@@ -1,31 +1,19 @@
|
|
|
1
|
-
import { DEFAULT_OPTIONS
|
|
1
|
+
import { DEFAULT_OPTIONS } from "./helpers/defaults.js";
|
|
2
2
|
import { createPng, createSvg } from "./helpers/create.js";
|
|
3
|
-
import {
|
|
3
|
+
import { buildImageResponse } from "./helpers/response.js";
|
|
4
4
|
export class ImageResponse extends Response {
|
|
5
5
|
constructor(element, options, props) {
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
controller.close();
|
|
17
|
-
},
|
|
18
|
-
});
|
|
19
|
-
super(body, {
|
|
20
|
-
headers: {
|
|
21
|
-
"Content-Type": `image/${extended_options.format}${extended_options.format === "svg" ? "+xml" : ""}`,
|
|
22
|
-
"Cache-Control": extended_options.debug
|
|
23
|
-
? "no-cache, no-store"
|
|
24
|
-
: "public, immutable, no-transform, max-age=31536000",
|
|
25
|
-
...extended_options.headers,
|
|
26
|
-
},
|
|
27
|
-
status: extended_options.status || DEFAULT_STATUS_CODE,
|
|
28
|
-
statusText: extended_options.statusText || DEFAULT_STATUS_TEXT,
|
|
6
|
+
const opts = Object.assign({ ...DEFAULT_OPTIONS }, options);
|
|
7
|
+
const format = opts.format ?? "png";
|
|
8
|
+
const createImage = format === "png" ? createPng : createSvg;
|
|
9
|
+
const { body, init } = buildImageResponse(() => createImage(element, opts, { props }), {
|
|
10
|
+
label: format.toUpperCase(),
|
|
11
|
+
contentType: `image/${format}${format === "svg" ? "+xml" : ""}`,
|
|
12
|
+
debug: opts.debug ?? false,
|
|
13
|
+
headers: opts.headers,
|
|
14
|
+
status: opts.status,
|
|
15
|
+
statusText: opts.statusText,
|
|
29
16
|
});
|
|
17
|
+
super(body, init);
|
|
30
18
|
}
|
|
31
19
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type _satori from "satori";
|
|
2
|
-
export declare function useResvg(): Promise<new (svg: Uint8Array | string, options?: import("@resvg/resvg-wasm").ResvgRenderOptions) => {
|
|
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,5 +1,6 @@
|
|
|
1
1
|
import { isEdgeLight, isWorkerd } from "std-env";
|
|
2
|
-
import {
|
|
2
|
+
import { createLogger } from "../helpers/logger.js";
|
|
3
|
+
import { handleAsync, ErrorCodes } from "../helpers/error-handler.js";
|
|
3
4
|
// we keep instances alive to avoid re-importing them on every request, maybe not needed but
|
|
4
5
|
// also helps with type inference
|
|
5
6
|
// Code from vue-og-images
|
|
@@ -9,24 +10,35 @@ const resvgInstance = {
|
|
|
9
10
|
const satoriInstance = {
|
|
10
11
|
instance: undefined,
|
|
11
12
|
};
|
|
12
|
-
export async function useResvg() {
|
|
13
|
+
export async function useResvg(debug = false) {
|
|
14
|
+
const log = createLogger(debug);
|
|
13
15
|
if (resvgInstance.instance) {
|
|
14
16
|
return resvgInstance.instance.Resvg;
|
|
15
17
|
}
|
|
16
|
-
|
|
18
|
+
log.debug("Initializing ReSVG WASM");
|
|
17
19
|
const isWorkerLikeRuntime = isEdgeLight || isWorkerd;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
log.info(`Detected runtime: ${isWorkerLikeRuntime ? "Edge Light or Workerd" : "Node.js"}`);
|
|
21
|
+
// workers take a precompiled `?module`; node takes raw wasm bytes. keep both
|
|
22
|
+
// as direct import() expressions so the bundler can emit the wasm chunk.
|
|
23
|
+
const moduleImport = isWorkerLikeRuntime
|
|
24
|
+
? import("./resvg/edge.js")
|
|
25
|
+
: import("./resvg/node.js");
|
|
26
|
+
resvgInstance.instance = await handleAsync(() => moduleImport.then((m) => m.default), ErrorCodes.RESVG_INIT_FAILED, "Failed to import ReSVG module");
|
|
27
|
+
await handleAsync(() => resvgInstance.instance.initWasmPromise, ErrorCodes.RESVG_INIT_FAILED, "Failed to initialize ReSVG WASM");
|
|
22
28
|
return resvgInstance.instance.Resvg;
|
|
23
29
|
}
|
|
24
|
-
export async function useSatori() {
|
|
30
|
+
export async function useSatori(debug = false) {
|
|
31
|
+
const log = createLogger(debug);
|
|
25
32
|
if (satoriInstance.instance) {
|
|
26
33
|
return satoriInstance.instance.satori;
|
|
27
34
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
35
|
+
log.debug("Initializing Satori");
|
|
36
|
+
const isWorkerLikeRuntime = isEdgeLight || isWorkerd;
|
|
37
|
+
log.info(`Detected runtime: ${isWorkerLikeRuntime ? "Edge Light or Workerd" : "Node.js"}`);
|
|
38
|
+
const moduleImport = isWorkerLikeRuntime
|
|
39
|
+
? import("./satori/edge.js")
|
|
40
|
+
: import("./satori/node.js");
|
|
41
|
+
satoriInstance.instance = await handleAsync(() => moduleImport.then((m) => m.default), ErrorCodes.SATORI_INIT_FAILED, "Failed to import Satori module");
|
|
42
|
+
await handleAsync(() => satoriInstance.instance.initWasmPromise, ErrorCodes.SATORI_INIT_FAILED, "Failed to initialize Satori WASM");
|
|
31
43
|
return satoriInstance.instance.satori;
|
|
32
44
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { Resvg as _Resvg, initWasm } from "@resvg/resvg-wasm";
|
|
2
2
|
|
|
3
3
|
export default {
|
|
4
|
-
//
|
|
5
|
-
//
|
|
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
6
|
initWasmPromise: initWasm(
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
8
|
+
// @ts-ignore
|
|
7
9
|
import("@resvg/resvg-wasm/index_bg.wasm?module").then((r) => r.default || r)
|
|
8
10
|
),
|
|
9
11
|
Resvg: _Resvg,
|
|
@@ -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
|
};
|
|
Binary file
|
|
@@ -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
|
+
};
|
|
@@ -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,33 @@
|
|
|
1
|
+
import { createTakumiImage } from "./render.js";
|
|
2
|
+
import { buildImageResponse } from "../helpers/response.js";
|
|
3
|
+
const DEFAULT_OPTIONS = {
|
|
4
|
+
width: 1200,
|
|
5
|
+
height: 630,
|
|
6
|
+
format: "png",
|
|
7
|
+
emoji: "twemoji",
|
|
8
|
+
debug: false,
|
|
9
|
+
};
|
|
10
|
+
// takumi can also encode jpeg/webp/ico/raw, plus svg as text
|
|
11
|
+
const CONTENT_TYPES = {
|
|
12
|
+
png: "image/png",
|
|
13
|
+
jpeg: "image/jpeg",
|
|
14
|
+
webp: "image/webp",
|
|
15
|
+
ico: "image/x-icon",
|
|
16
|
+
raw: "application/octet-stream",
|
|
17
|
+
svg: "image/svg+xml",
|
|
18
|
+
};
|
|
19
|
+
/** OG image rendered by Takumi. Takes an HTML string or a Svelte component. */
|
|
20
|
+
export class ImageResponse extends Response {
|
|
21
|
+
constructor(element, options, props) {
|
|
22
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
23
|
+
const { body, init } = buildImageResponse(() => createTakumiImage(element, opts, props), {
|
|
24
|
+
label: opts.format.toUpperCase(),
|
|
25
|
+
contentType: CONTENT_TYPES[opts.format],
|
|
26
|
+
debug: opts.debug,
|
|
27
|
+
headers: opts.headers,
|
|
28
|
+
status: opts.status,
|
|
29
|
+
statusText: opts.statusText,
|
|
30
|
+
});
|
|
31
|
+
super(body, init);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -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
|
+
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, options: TakumiImageOptions, props?: Record<string, unknown>): Promise<Uint8Array | string>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { render as takumiRender, renderSvg } from "takumi-js";
|
|
2
|
+
import { renderComponentToHtml } from "../helpers/to-html.js";
|
|
3
|
+
import { useTakumiRenderer, registerTakumiFonts } from "./renderer.js";
|
|
4
|
+
import { resolveTakumiFonts } from "./fonts.js";
|
|
5
|
+
import { createLogger } from "../helpers/logger.js";
|
|
6
|
+
import { handleAsync, handleSync, ErrorCodes } from "../helpers/error-handler.js";
|
|
7
|
+
function elementToHtml(element, props) {
|
|
8
|
+
if (typeof element === "string")
|
|
9
|
+
return element.replaceAll("\n", "").trim();
|
|
10
|
+
// head carries css injected via <svelte:options css="injected" />, so it goes first
|
|
11
|
+
const { head, body } = renderComponentToHtml(element, props);
|
|
12
|
+
return head + body;
|
|
13
|
+
}
|
|
14
|
+
/** Render an HTML string or Svelte component to image bytes (or an svg string). */
|
|
15
|
+
export async function createTakumiImage(element, options, props) {
|
|
16
|
+
const log = createLogger(options.debug ?? false);
|
|
17
|
+
const html = handleSync(() => elementToHtml(element, props), ErrorCodes.VNODE_CREATION_FAILED, "Failed to create HTML for Takumi");
|
|
18
|
+
const renderer = await useTakumiRenderer(options.debug);
|
|
19
|
+
if (options.fonts?.length) {
|
|
20
|
+
const fonts = await resolveTakumiFonts(options.fonts);
|
|
21
|
+
await registerTakumiFonts(renderer, fonts);
|
|
22
|
+
}
|
|
23
|
+
const { width, height, format = "png", quality, stylesheets, emoji } = options;
|
|
24
|
+
const shared = { renderer: renderer, width, height, stylesheets, emoji };
|
|
25
|
+
log.debug(`Rendering ${format.toUpperCase()} with Takumi`);
|
|
26
|
+
if (format === "svg") {
|
|
27
|
+
return handleAsync(() => renderSvg(html, shared), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render SVG with Takumi");
|
|
28
|
+
}
|
|
29
|
+
return handleAsync(() => takumiRender(html, { ...shared, format, quality }), ErrorCodes.TAKUMI_RENDER_FAILED, "Failed to render image with Takumi");
|
|
30
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
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
|
+
export declare function useTakumiRenderer(_debug?: boolean): Promise<TakumiRenderer>;
|
|
5
|
+
/** Register each font once, keyed by name/weight/style. */
|
|
6
|
+
export declare function registerTakumiFonts(renderer: TakumiRenderer, fonts: FontDetails[]): Promise<void>;
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
export async function useTakumiRenderer(_debug = false) {
|
|
23
|
+
rendererPromise ??= initRenderer();
|
|
24
|
+
return rendererPromise;
|
|
25
|
+
}
|
|
26
|
+
/** Register each font once, keyed by name/weight/style. */
|
|
27
|
+
export async function registerTakumiFonts(renderer, fonts) {
|
|
28
|
+
for (const font of fonts) {
|
|
29
|
+
const key = `${font.name ?? "unnamed"}-${font.weight ?? "auto"}-${font.style ?? "normal"}`;
|
|
30
|
+
if (registeredFontKeys.has(key))
|
|
31
|
+
continue;
|
|
32
|
+
await handleAsync(() => renderer.registerFont(font), ErrorCodes.FONT_LOAD_FAILED, `Failed to register Takumi font: ${key}`);
|
|
33
|
+
registeredFontKeys.add(key);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -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
package/package.json
CHANGED
|
@@ -1,117 +1,131 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
2
|
+
"name": "@ethercorps/sveltekit-og",
|
|
3
|
+
"version": "4.3.0-next.10",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"homepage": "https://sveltekit-og.dev",
|
|
6
|
+
"repository": "github:ethercorps/sveltekit-og",
|
|
7
|
+
"funding": "https://github.com/sponsors/ethercorps",
|
|
8
|
+
"author": "Shivam Meena <https://github.com/theetherGit>",
|
|
9
|
+
"description": "Dynamically generate Open Graph images from an HTML, CSS template or Svelte component using fast and efficient conversion from HTML > SVG > PNG",
|
|
10
|
+
"contributors": [
|
|
11
|
+
{
|
|
12
|
+
"name": "Shivam Meena",
|
|
13
|
+
"github": "https://github.com/theetherGit"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"name": "Jason",
|
|
17
|
+
"github": "https://github.com/jasongitmail"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"name": "Mihkel Martin Kasterpalu",
|
|
21
|
+
"github": "https://github.com/MihkelMK"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"name": "Luke Parke",
|
|
25
|
+
"github": "https://github.com/LukasParke"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"name": "Willow (GHOST)",
|
|
29
|
+
"github": "https://github.com/ghostdevv"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"name": "Minseo Lee",
|
|
33
|
+
"github": "https://github.com/quiple"
|
|
34
|
+
}
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"dev": "vite dev",
|
|
38
|
+
"build": "vite build && npm run package",
|
|
39
|
+
"build:examples": "pnpm -F \"./examples/**\" --parallel --color build",
|
|
40
|
+
"check:examples": "pnpm install -r",
|
|
41
|
+
"preview": "vite preview",
|
|
42
|
+
"package": "svelte-kit sync && svelte-package && publint",
|
|
43
|
+
"prepublishOnly": "pnpm run package",
|
|
44
|
+
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
|
45
|
+
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
|
46
|
+
"test": "vitest",
|
|
47
|
+
"bench": "vitest bench --run",
|
|
48
|
+
"bench:save": "vitest bench --run --outputJson benchmarks/baseline.json",
|
|
49
|
+
"bench:compare": "vitest bench --run --compare benchmarks/baseline.json",
|
|
50
|
+
"bench:snapshot": "node scripts/bench-snapshot.mjs",
|
|
51
|
+
"lint": "oxlint . && eslint .",
|
|
52
|
+
"format": "prettier --plugin-search-dir . --write .",
|
|
53
|
+
"publishBeta": "npm publish --tag beta"
|
|
54
|
+
},
|
|
55
|
+
"exports": {
|
|
56
|
+
".": {
|
|
57
|
+
"types": "./dist/index.d.ts",
|
|
58
|
+
"svelte": "./dist/index.js",
|
|
59
|
+
"import": "./dist/index.js"
|
|
60
|
+
},
|
|
61
|
+
"./fonts": {
|
|
62
|
+
"types": "./dist/fonts.d.ts",
|
|
63
|
+
"import": "./dist/fonts.js"
|
|
64
|
+
},
|
|
65
|
+
"./takumi": {
|
|
66
|
+
"types": "./dist/takumi/index.d.ts",
|
|
67
|
+
"svelte": "./dist/takumi/index.js",
|
|
68
|
+
"import": "./dist/takumi/index.js"
|
|
69
|
+
},
|
|
70
|
+
"./plugin": {
|
|
71
|
+
"types": "./dist/plugin.d.ts",
|
|
72
|
+
"import": "./dist/plugin.js"
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"files": [
|
|
76
|
+
"dist",
|
|
77
|
+
"!dist/**/*.test.*",
|
|
78
|
+
"!dist/**/*.spec.*"
|
|
79
|
+
],
|
|
80
|
+
"devDependencies": {
|
|
81
|
+
"@eslint/compat": "^2.0.3",
|
|
82
|
+
"@eslint/js": "^9.39.3",
|
|
83
|
+
"@sveltejs/adapter-vercel": "^5.10.3",
|
|
84
|
+
"@sveltejs/kit": "^2.53.4",
|
|
85
|
+
"@sveltejs/package": "^2.5.7",
|
|
86
|
+
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
|
87
|
+
"@types/node": "^24.11.0",
|
|
88
|
+
"@typescript-eslint/eslint-plugin": "^5.62.0",
|
|
89
|
+
"@typescript-eslint/parser": "^5.62.0",
|
|
90
|
+
"css-tree": "^2.3.1",
|
|
91
|
+
"eslint": "^8.57.1",
|
|
92
|
+
"eslint-config-prettier": "^8.10.2",
|
|
93
|
+
"eslint-plugin-oxlint": "^1.55.0",
|
|
94
|
+
"eslint-plugin-svelte": "^2.46.1",
|
|
95
|
+
"globals": "^16.5.0",
|
|
96
|
+
"oxlint": "^1.55.0",
|
|
97
|
+
"prettier": "^3.8.1",
|
|
98
|
+
"prettier-plugin-svelte": "^3.5.1",
|
|
99
|
+
"prettier-plugin-tailwindcss": "^0.6.14",
|
|
100
|
+
"publint": "^0.1.16",
|
|
101
|
+
"rollup-plugin-visualizer": "^5.14.0",
|
|
102
|
+
"svelte": "^5.53.10",
|
|
103
|
+
"svelte-check": "^4.4.5",
|
|
104
|
+
"tslib": "^2.8.1",
|
|
105
|
+
"typescript": "^5.9.3",
|
|
106
|
+
"typescript-eslint": "^8.57.0",
|
|
107
|
+
"vite": "^5.4.21",
|
|
108
|
+
"takumi-js": "2.0.0-beta.14",
|
|
109
|
+
"vitest": "^1.6.1"
|
|
110
|
+
},
|
|
111
|
+
"main": "./dist/index.js",
|
|
112
|
+
"svelte": "./dist/index.js",
|
|
113
|
+
"types": "./dist/index.d.ts",
|
|
114
|
+
"type": "module",
|
|
115
|
+
"dependencies": {
|
|
116
|
+
"@resvg/resvg-wasm": "^2.6.2",
|
|
117
|
+
"satori": "^0.25.0",
|
|
118
|
+
"satori-html": "0.3.2",
|
|
119
|
+
"std-env": "^4.1.0",
|
|
120
|
+
"unwasm": "^0.5.3"
|
|
121
|
+
},
|
|
122
|
+
"peerDependencies": {
|
|
123
|
+
"@sveltejs/kit": ">=2.0.0",
|
|
124
|
+
"takumi-js": "^2.0.0-beta.14"
|
|
125
|
+
},
|
|
126
|
+
"peerDependenciesMeta": {
|
|
127
|
+
"takumi-js": {
|
|
128
|
+
"optional": true
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|