mirror of
https://github.com/LukeHagar/sveltekit-og.git
synced 2025-12-09 04:21:44 +00:00
Complete rewrite and added html to react element using svelte compiler
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
import OG from './OG.svelte';
|
import OG from './OG.svelte';
|
||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import {componentToImageResponse} from "@ethercorps/sveltekit-og";
|
import { componentToImageResponse } from '@ethercorps/sveltekit-og';
|
||||||
|
|
||||||
const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-700-normal.woff');
|
const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-700-normal.woff');
|
||||||
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
||||||
|
|||||||
28
package.json
28
package.json
@@ -14,29 +14,31 @@
|
|||||||
"format": "prettier --plugin-search-dir . --write ."
|
"format": "prettier --plugin-search-dir . --write ."
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@playwright/test": "^1.27.1",
|
"@playwright/test": "^1.28.1",
|
||||||
"@sveltejs/adapter-auto": "next",
|
"@sveltejs/adapter-auto": "next",
|
||||||
"@sveltejs/kit": "next",
|
"@sveltejs/kit": "next",
|
||||||
"@sveltejs/package": "next",
|
"@sveltejs/package": "next",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
"@typescript-eslint/eslint-plugin": "^5.46.0",
|
||||||
"@typescript-eslint/parser": "^5.42.1",
|
"@typescript-eslint/parser": "^5.46.0",
|
||||||
"eslint": "^8.27.0",
|
"eslint": "^8.29.0",
|
||||||
"eslint-config-prettier": "^8.5.0",
|
"eslint-config-prettier": "^8.5.0",
|
||||||
"eslint-plugin-svelte3": "^4.0.0",
|
"eslint-plugin-svelte3": "^4.0.0",
|
||||||
"prettier": "^2.7.1",
|
"prettier": "^2.8.1",
|
||||||
"prettier-plugin-svelte": "^2.8.0",
|
"prettier-plugin-svelte": "^2.8.1",
|
||||||
"svelte": "^3.53.1",
|
"svelte": "^3.54.0",
|
||||||
"svelte-check": "^2.9.2",
|
"svelte-check": "^2.10.2",
|
||||||
"svelte-preprocess": "^4.10.7",
|
"svelte-preprocess": "^4.10.7",
|
||||||
"tslib": "^2.4.1",
|
"tslib": "^2.4.1",
|
||||||
"typescript": "^4.8.4",
|
"typescript": "^4.9.4",
|
||||||
"vite": "^3.2.3"
|
"vite": "^3.2.5"
|
||||||
},
|
},
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@resvg/resvg-wasm": "^2.1.0",
|
"@resvg/resvg-js": "^2.2.0",
|
||||||
"satori": "^0.0.44",
|
"satori": "^0.0.44"
|
||||||
"satori-html": "^0.3.0"
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"svelte": "^3.54.0"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"open graph image",
|
"open graph image",
|
||||||
|
|||||||
1001
pnpm-lock.yaml
generated
1001
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,56 +1,55 @@
|
|||||||
import { html as toReactNode } from 'satori-html';
|
import satori, { type SatoriOptions } from 'satori';
|
||||||
import satori from 'satori';
|
import { Resvg, type ResvgRenderOptions } from '@resvg/resvg-js';
|
||||||
import { Resvg, initWasm } from '@resvg/resvg-wasm';
|
|
||||||
import type { SatoriOptions } from 'satori';
|
|
||||||
import type { SvelteComponent } from 'svelte';
|
import type { SvelteComponent } from 'svelte';
|
||||||
|
import toReactElement from './toReactElement';
|
||||||
|
|
||||||
const resSvgWasm = initWasm(fetch('https://sveltekit-og.ethercorps.io/resvg.wasm'));
|
|
||||||
const fontFile = await fetch('https://sveltekit-og.ethercorps.io/noto-sans.ttf');
|
const fontFile = await fetch('https://sveltekit-og.ethercorps.io/noto-sans.ttf');
|
||||||
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
||||||
|
|
||||||
class ImageResponse {
|
const ImageResponse = async (htmlTemplate: string, optionsByUser: ImageResponseOptions) => {
|
||||||
constructor(htmlTemplate: string, optionsByUser: ImageResponseOptions) {
|
const options = Object.assign({ width: 1200, height: 630, debug: !1 }, optionsByUser);
|
||||||
const options = Object.assign({ width: 1200, height: 630, debug: !1 }, optionsByUser);
|
const svg = await satori(toReactElement(htmlTemplate), {
|
||||||
const png = new ReadableStream({
|
width: options.width,
|
||||||
async start(a) {
|
height: options.height,
|
||||||
await resSvgWasm;
|
debug: options.debug,
|
||||||
const svg = await satori(toReactNode(htmlTemplate), {
|
fonts: options.fonts || [
|
||||||
width: options.width,
|
{
|
||||||
height: options.height,
|
name: 'sans serif',
|
||||||
debug: options.debug,
|
data: fontData,
|
||||||
fonts: options.fonts || [
|
style: 'normal',
|
||||||
{
|
weight: 700
|
||||||
name: 'sans serif',
|
|
||||||
data: fontData,
|
|
||||||
style: 'normal',
|
|
||||||
weight: 700
|
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
|
||||||
const pngData = new Resvg(svg, { fitTo: { mode: 'width', value: options.width } });
|
|
||||||
a.enqueue(pngData.render().asPng());
|
|
||||||
a.close();
|
|
||||||
}
|
}
|
||||||
});
|
]
|
||||||
return new Response(png, {
|
});
|
||||||
headers: {
|
const reSvgOptions = {
|
||||||
'Content-Type': 'image/png',
|
fitTo: {
|
||||||
'cache-control': 'public, immutable, no-transform, max-age=31536000',
|
mode: 'width',
|
||||||
...options.headers
|
value: options.width
|
||||||
},
|
}
|
||||||
|
} as ResvgRenderOptions;
|
||||||
|
const reSvgObject = new Resvg(svg, reSvgOptions);
|
||||||
|
const pngData = await reSvgObject.render().asPng();
|
||||||
|
|
||||||
status: options.status,
|
return new Response(pngData, {
|
||||||
statusText: options.statusText
|
headers: {
|
||||||
});
|
'Content-Type': 'image/png',
|
||||||
}
|
'cache-control': 'public, immutable, no-transform, max-age=31536000',
|
||||||
}
|
...options.headers
|
||||||
|
},
|
||||||
|
|
||||||
class componentToImageResponse {
|
status: options.status,
|
||||||
constructor(component: typeof SvelteComponent, props = {}, optionsByUser: ImageResponseOptions) {
|
statusText: options.statusText
|
||||||
const htmlTemplate = componentToMarkup(component, props);
|
});
|
||||||
return new ImageResponse(htmlTemplate, optionsByUser);
|
};
|
||||||
}
|
|
||||||
}
|
const componentToImageResponse = (
|
||||||
|
component: typeof SvelteComponent,
|
||||||
|
props = {},
|
||||||
|
optionsByUser: ImageResponseOptions
|
||||||
|
) => {
|
||||||
|
const htmlTemplate = componentToMarkup(component, props);
|
||||||
|
return ImageResponse(htmlTemplate, optionsByUser);
|
||||||
|
};
|
||||||
|
|
||||||
const componentToMarkup = (component: typeof SvelteComponent, props = {}) => {
|
const componentToMarkup = (component: typeof SvelteComponent, props = {}) => {
|
||||||
const SvelteRenderedMarkup = (component as any).render(props);
|
const SvelteRenderedMarkup = (component as any).render(props);
|
||||||
@@ -75,4 +74,6 @@ type ImageOptions = {
|
|||||||
) => Promise<SatoriOptions['fonts'] | string | undefined>;
|
) => Promise<SatoriOptions['fonts'] | string | undefined>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { componentToImageResponse, ImageResponse };
|
type ImageResponseType = typeof ImageResponse;
|
||||||
|
|
||||||
|
export { componentToImageResponse, ImageResponse, toReactElement, satori, type ImageResponseType };
|
||||||
|
|||||||
107
src/lib/toReactElement.ts
Normal file
107
src/lib/toReactElement.ts
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
import { parse, walk } from 'svelte/compiler';
|
||||||
|
import type { Ast } from 'svelte/types/compiler/interfaces';
|
||||||
|
|
||||||
|
/* Start of code from satori-html for cssToObject converter*/
|
||||||
|
const camelize = (ident: string) => ident.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
||||||
|
const cssToObject = (str: string) => {
|
||||||
|
const obj: Record<string, string> = {};
|
||||||
|
let t = 0;
|
||||||
|
let pair = ['', ''];
|
||||||
|
const flags: Record<string, number> = {};
|
||||||
|
for (const c of str) {
|
||||||
|
if (!flags['('] && c === ':') {
|
||||||
|
t = 1;
|
||||||
|
} else if (c === ';') {
|
||||||
|
const [decl = '', value = ''] = pair;
|
||||||
|
obj[camelize(decl.trim())] = value.trim();
|
||||||
|
t = 0;
|
||||||
|
pair = ['', ''];
|
||||||
|
} else {
|
||||||
|
pair[t] += c;
|
||||||
|
switch (c) {
|
||||||
|
case '(': {
|
||||||
|
flags[c]++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ')': {
|
||||||
|
flags['(']--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [decl = '', value = ''] = pair;
|
||||||
|
if (decl.trim() && value.trim()) {
|
||||||
|
obj[camelize(decl.trim())] = value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
};
|
||||||
|
const nodeMap = new WeakMap();
|
||||||
|
interface VNode {
|
||||||
|
type: string;
|
||||||
|
props: {
|
||||||
|
style?: Record<string, any>;
|
||||||
|
children?: string | VNode | VNode[];
|
||||||
|
[prop: string]: any;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const root: VNode = {
|
||||||
|
type: 'div',
|
||||||
|
props: {
|
||||||
|
style: {
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
width: '100%',
|
||||||
|
height: '100%'
|
||||||
|
},
|
||||||
|
children: []
|
||||||
|
}
|
||||||
|
};
|
||||||
|
/* End of satori-html */
|
||||||
|
|
||||||
|
const toReactElement = (htmlString: string): VNode => {
|
||||||
|
const svelteAST: Ast = parse(htmlString);
|
||||||
|
walk(svelteAST, {
|
||||||
|
enter(node: any, parent: any, prop: any, index: any) {
|
||||||
|
let newNode: any = {};
|
||||||
|
if (node.type === 'Fragment') {
|
||||||
|
nodeMap.set(node, root);
|
||||||
|
} else if (node.type === 'Element') {
|
||||||
|
newNode.type = node.name;
|
||||||
|
const { ...props } = node.attributes;
|
||||||
|
if (node.attributes.length > 0) {
|
||||||
|
node.attributes.forEach((attribute: any) => {
|
||||||
|
if (attribute.name === 'style') {
|
||||||
|
props['style'] = cssToObject(attribute.value[0].data) as any;
|
||||||
|
} else props[attribute.name] = attribute.value[0].data as any;
|
||||||
|
});
|
||||||
|
delete props[0];
|
||||||
|
}
|
||||||
|
props.children = [] as unknown as string;
|
||||||
|
Object.assign(newNode, { props });
|
||||||
|
nodeMap.set(node, newNode);
|
||||||
|
if (parent) {
|
||||||
|
const newParent = nodeMap.get(parent);
|
||||||
|
newParent.props.children[index] = newNode;
|
||||||
|
}
|
||||||
|
} else if (node.type === 'Text') {
|
||||||
|
newNode = node.data.trim();
|
||||||
|
if (newNode) {
|
||||||
|
if (parent && parent.type !== 'Attribute') {
|
||||||
|
const newParent = nodeMap.get(parent);
|
||||||
|
if (parent.children.length === 1) {
|
||||||
|
newParent.props.children = newNode;
|
||||||
|
} else {
|
||||||
|
newParent.props.children[index] = newNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return root;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default toReactElement;
|
||||||
@@ -25,7 +25,7 @@ const fontData400: ArrayBuffer = await fontFile400.arrayBuffer();
|
|||||||
const fontData700: ArrayBuffer = await fontFile700.arrayBuffer();
|
const fontData700: ArrayBuffer = await fontFile700.arrayBuffer();
|
||||||
|
|
||||||
export const GET: RequestHandler = async () => {
|
export const GET: RequestHandler = async () => {
|
||||||
return new ImageResponse(template, {
|
return await ImageResponse(template, {
|
||||||
height: 250,
|
height: 250,
|
||||||
width: 500,
|
width: 500,
|
||||||
fonts: [
|
fonts: [
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-7
|
|||||||
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
|
||||||
|
|
||||||
export const GET: RequestHandler = async () => {
|
export const GET: RequestHandler = async () => {
|
||||||
return new componentToImageResponse(
|
return await componentToImageResponse(
|
||||||
OG,
|
OG,
|
||||||
{ text: 'Ready to dive in?', spanText: 'Start your free trial today.' },
|
{ text: 'Ready to dive in?', spanText: 'Start your free trial today.' },
|
||||||
{
|
{
|
||||||
|
|||||||
44
src/routes/new/+server.ts
Normal file
44
src/routes/new/+server.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { ImageResponse } from '$lib';
|
||||||
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
const template = `
|
||||||
|
<div tw="bg-gray-50 flex w-full h-full items-center justify-center">
|
||||||
|
<div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
|
||||||
|
<h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
|
||||||
|
<span>Ready to dive in?</span>
|
||||||
|
<span tw="text-indigo-600">Start your free trial today.</span>
|
||||||
|
</h2>
|
||||||
|
<div tw="mt-8 flex md:mt-0">
|
||||||
|
<div tw="flex rounded-md shadow">
|
||||||
|
<a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white">Get started</a>
|
||||||
|
</div>
|
||||||
|
<div tw="ml-3 flex rounded-md shadow">
|
||||||
|
<a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600">Learn more</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
const fontFile400 = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
|
||||||
|
const fontFile700 = await fetch('https://og-playground.vercel.app/inter-latin-ext-700-normal.woff');
|
||||||
|
const fontData400: ArrayBuffer = await fontFile400.arrayBuffer();
|
||||||
|
const fontData700: ArrayBuffer = await fontFile700.arrayBuffer();
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async () => {
|
||||||
|
return await ImageResponse(template, {
|
||||||
|
height: 250,
|
||||||
|
width: 500,
|
||||||
|
fonts: [
|
||||||
|
{
|
||||||
|
name: 'Inter Latin',
|
||||||
|
data: fontData400,
|
||||||
|
weight: 400
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Inter Latin',
|
||||||
|
data: fontData700,
|
||||||
|
weight: 700
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
};
|
||||||
43
src/routes/test/+page.server.js
Normal file
43
src/routes/test/+page.server.js
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import toReactElement from '$lib/toReactElement';
|
||||||
|
import satori from 'satori';
|
||||||
|
const htmlString = `
|
||||||
|
<div tw="bg-gray-50 flex w-full">
|
||||||
|
<div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
|
||||||
|
<h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
|
||||||
|
<span>Ready to dive in?</span>
|
||||||
|
<span tw="text-indigo-600">Start your free trial today.</span>
|
||||||
|
</h2>
|
||||||
|
<div tw="mt-8 flex md:mt-0">
|
||||||
|
<div tw="flex rounded-md shadow">
|
||||||
|
<a tw="flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white">Get started</a>
|
||||||
|
</div>
|
||||||
|
<div tw="ml-3 flex rounded-md shadow">
|
||||||
|
<a tw="flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600">Learn more</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
const newNode = toReactElement(htmlString);
|
||||||
|
|
||||||
|
/** @type {import('./$types').PageServerLoad} */
|
||||||
|
export async function load() {
|
||||||
|
const fontFile400 = await fetch(
|
||||||
|
'https://og-playground.vercel.app/inter-latin-ext-400-normal.woff'
|
||||||
|
);
|
||||||
|
const fontData400 = await fontFile400.arrayBuffer();
|
||||||
|
const svg = await satori(newNode, {
|
||||||
|
height: 350,
|
||||||
|
width: 500,
|
||||||
|
fonts: [
|
||||||
|
{
|
||||||
|
name: 'sans serif',
|
||||||
|
data: fontData400,
|
||||||
|
style: 'normal',
|
||||||
|
weight: 700
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
return { svg };
|
||||||
|
}
|
||||||
5
src/routes/test/+page.svelte
Normal file
5
src/routes/test/+page.svelte
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
export let data;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{@html data.svg}
|
||||||
BIN
static/favicon.ico
Normal file
BIN
static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
Binary file not shown.
BIN
static/yoga.wasm
BIN
static/yoga.wasm
Binary file not shown.
@@ -2,7 +2,10 @@ import { sveltekit } from '@sveltejs/kit/vite';
|
|||||||
import type { UserConfig } from 'vite';
|
import type { UserConfig } from 'vite';
|
||||||
|
|
||||||
const config: UserConfig = {
|
const config: UserConfig = {
|
||||||
plugins: [sveltekit()]
|
plugins: [sveltekit()],
|
||||||
|
define: {
|
||||||
|
_a: 'undefined'
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
|
|||||||
Reference in New Issue
Block a user