@ethercorps/sveltekit-og 2.0.2 → 3.0.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/README.md CHANGED
@@ -1,58 +1,171 @@
1
- # create-svelte
1
+ # SvelteKit Open Graph Image Generation
2
2
 
3
- Everything you need to build a Svelte library, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
3
+ Dynamically generate Open Graph images from an HTML+CSS template or Svelte component using fast and efficient conversion from HTML > SVG > PNG. Based on [Satori](https://github.com/vercel/satori#documentation). No headless browser required.
4
4
 
5
- Read more about creating a library [in the docs](https://kit.svelte.dev/docs/packaging).
5
+ ## Disclaimer
6
+ This project doesn't support edge services like vercel edge and cloudflare workers.
6
7
 
7
- ## Creating a project
8
-
9
- If you're seeing this, you've probably already done this step. Congrats!
8
+ ## Installation
10
9
 
11
10
  ```bash
12
- # create a new project in the current directory
13
- npm create svelte@latest
11
+ pnpm install @ethercorps/sveltekit-og
12
+ ```
14
13
 
15
- # create a new project in my-app
16
- npm create svelte@latest my-app
14
+ ## Usage
15
+
16
+ Create a file at `/src/routes/og/+server.ts`. Alternatively, you can use JavaScript by removing the types from this example.
17
+
18
+ ```typescript
19
+ // src/routes/og/+server.ts
20
+ import { ImageResponse } from '@ethercorps/sveltekit-og';
21
+ import { RequestHandler } from './$types';
22
+
23
+ const template = `
24
+ <div tw="bg-gray-50 flex w-full h-full items-center justify-center">
25
+ <div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
26
+ <h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
27
+ <span>Ready to dive in?</span>
28
+ <span tw="text-indigo-600">Start your free trial today.</span>
29
+ </h2>
30
+ <div tw="mt-8 flex md:mt-0">
31
+ <div tw="flex rounded-md shadow">
32
+ <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>
33
+ </div>
34
+ <div tw="ml-3 flex rounded-md shadow">
35
+ <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>
36
+ </div>
37
+ </div>
38
+ </div>
39
+ </div>
40
+ `;
41
+
42
+ const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
43
+ const fontData: ArrayBuffer = await fontFile.arrayBuffer();
44
+
45
+ export const GET: RequestHandler = async () => {
46
+ return await ImageResponse(template, {
47
+ height: 630,
48
+ width: 1200,
49
+ fonts: [
50
+ {
51
+ name: 'Inter Latin',
52
+ data: fontData,
53
+ weight: 400
54
+ }
55
+ ]
56
+ });
57
+ };
17
58
  ```
18
59
 
19
- ## Developing
60
+ Then run `npm dev` and visit `localhost:5173/og` to view your generated PNG. Remember that hot module reloading does not work with server routes, so if you change your HTML or CSS, hard refresh the route to see changes.
20
61
 
21
- Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
62
+ ## Example Output
22
63
 
23
- ```bash
24
- npm run dev
64
+ ![Rendered OG image](static/demo.png)
25
65
 
26
- # or start the server and open the app in a new browser tab
27
- npm run dev -- --open
28
- ```
66
+ ## Headers
29
67
 
30
- Everything inside `src/lib` is part of your library, everything inside `src/routes` can be used as a showcase or preview app.
68
+ When run in development, image headers contain `cache-control: no-cache, no-store`. In production, image headers contain `'cache-control': 'public, immutable, no-transform, max-age=31536000'`, which caches the image for 1 year. In both cases, the `'content-type': 'image/png'` is used.
31
69
 
32
- ## Building
70
+ ## Styling
33
71
 
34
- To build your library:
72
+ Notice that our example uses TailwindCSS classes (e.g. `tw="bg-gray-50"`). Alternatively, your HTML can contain style attributes using any of [the subset of CSS supported by Satori](https://github.com/vercel/satori#css).
35
73
 
36
- ```bash
37
- npm run package
38
- ```
74
+ Satori supports only a subset of HTML and CSS. For full details, see [Satori’s documentation](https://github.com/vercel/satori#documentation). Notably, Satori only supports flex-based layouts.
39
75
 
40
- To create a production version of your showcase app:
76
+ ## Fonts
41
77
 
42
- ```bash
43
- npm run build
78
+ Satori supports `ttf`, `otf`, and `woff` font formats; `woff2` is not supported. To maximize the font parsing speed, `ttf` or `otf` are recommended over `woff`.
79
+
80
+ By default, `@ethercorps/sveltekit-og` includes only 'Noto Sans' font. If you need to use other fonts, you can specify them as shown in the example. Notably, you can also import a font file that is stored locally within your project and are not required to use fetch.
81
+
82
+ ## Examples
83
+
84
+ - `ImageResponse` · [_source_](/src/routes/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app)
85
+ - `Component Rendering` · [_source_](/src/routes/sc/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app/sc)
86
+
87
+ ## API Reference
88
+
89
+ The package exposes an `ImageResponse` constructors, with the following options available:
90
+
91
+ ```typescript
92
+ import {ImageResponse} from '@ethercorps/sveltekit-og'
93
+ import {SvelteComponent} from "svelte";
94
+
95
+ // ...
96
+ ImageResponse(
97
+ element : string,
98
+ options : {
99
+ width ? : number = 1200
100
+ height ? : number = 630,
101
+ backgroundColor ? : string = "#fff"
102
+ fonts ? : {
103
+ name: string,
104
+ data: ArrayBuffer,
105
+ weight: number,
106
+ style: 'normal' | 'italic'
107
+ }[]
108
+ debug ? : boolean = false
109
+ graphemeImages ? : Record<string, string>;
110
+ loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
111
+ // Options that will be passed to the HTTP response
112
+ status ? : number = 200
113
+ statusText ? : string
114
+ headers ? : Record<string, string>
115
+ } {props})
44
116
  ```
45
117
 
46
- You can preview the production build with `npm run preview`.
118
+ ## Changelog
47
119
 
48
- > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
120
+ ### v3.0.0 (Breaking Changes)
49
121
 
50
- ## Publishing
122
+ > Just install @ethercorps/sveltekit-og
123
+ > No wasm as of now, only support for nodejs based runtime.
51
124
 
52
- Go into the `package.json` and give your package the desired name through the `"name"` option. Also consider adding a `"license"` field and point it to a `LICENSE` file which you can create from a template (one popular option is the [MIT license](https://opensource.org/license/mit/)).
125
+ ### v1.2.3 Update (Breaking Changes)
53
126
 
54
- To publish your library to [npm](https://www.npmjs.com):
127
+ > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
55
128
 
56
- ```bash
57
- npm publish
58
129
  ```
130
+ npm i @resvg/resvg-js
131
+ ```
132
+
133
+ ```
134
+ npm i satori
135
+ ```
136
+
137
+ > From now on their will be no issues related to build, and soon this library going to have its own documentation.
138
+
139
+ ### v1.2.2 Update (Breaking Change)
140
+
141
+ - We don't provide access to satori from `@ethercorps/sveltekit-og`.
142
+
143
+ ### v1.0.0 Update (Breaking Changes)
144
+
145
+ Finally, We have added html to react like element like object converter out of the box and with svelte compiler.
146
+ Now you can use `{ toReactElement }` with `"@ethercorps/sveltekit-og"` like:
147
+
148
+ - We have changed to function based instead of class based ImageResponse and componentToImageResponse.
149
+ - Removed `@resvg/resvg-wasm` with `@resvg/resvg-js` because of internal errors.
150
+ - Removed `satori-html` because now we have `toReactElement` out of the box with svelte compiler.
151
+ > If you find a problem related to undefined a please check [_vite.config.js_](/vite.config.ts) and add ` define: { _a: 'undefined' } in config.`
152
+
153
+ > If you find any issue and have suggestion for this project please open a ticket and if you want to contribute please create a new discussion.
154
+
155
+ ## Acknowledgements
156
+
157
+ This project will not be possible without the following projects:
158
+
159
+ - [Satori & @vercel/og](https://github.com/vercel/satori)
160
+ - [Noto by Google Fonts](https://fonts.google.com/noto)
161
+
162
+ [//]: # (- [svg2png-wasm]&#40;https://github.com/ssssota/svg2png-wasm&#41;)
163
+
164
+ ## Authors
165
+
166
+ - [@theetherGit](https://www.github.com/theetherGit)
167
+ - [@etherCorps](https://www.github.com/etherCorps)
168
+
169
+ ## Contributors
170
+
171
+ - [@jasongitmail](https://github.com/jasongitmail)
@@ -0,0 +1,5 @@
1
+ import type { SvelteComponent } from "svelte";
2
+ import type { ComponentOptions, ImageOptions, VNode } from '../types.js';
3
+ export declare function createVNode(element: string | SvelteComponent, componentOptions?: ComponentOptions): VNode;
4
+ export declare function createSvg(element: string | SvelteComponent, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<string>;
5
+ export declare function createPng(element: string | SvelteComponent, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<Uint8Array>;
@@ -0,0 +1,45 @@
1
+ import { svelteComponentToJsx, toReactElement } from '@ethercorps/svelte-h2j';
2
+ import { loadDynamicAsset } from './emoji.js';
3
+ import { default_fonts } from '../helpers/defaults.js';
4
+ import { useResvg, useSatori } from '../providers/instances.js';
5
+ // TODO: Export VNode Type from svelte-h2j
6
+ // TODO: Make svelte-h2j functions async in new v5 support
7
+ export async function createVNode(element, componentOptions) {
8
+ return typeof element === 'string' ? toReactElement(element) : svelteComponentToJsx(element, componentOptions?.props);
9
+ }
10
+ export async function createSvg(element, imageOptions, componentOptions) {
11
+ const [satori, vnodes] = await Promise.all([useSatori(), createVNode(element, componentOptions)]);
12
+ if (!Object.hasOwn(imageOptions, 'fonts')) {
13
+ imageOptions['fonts'] = await default_fonts();
14
+ }
15
+ // Add dynamic emoji loading handler
16
+ imageOptions['loadAdditionalAsset'] = loadDynamicAsset({
17
+ emoji: imageOptions.emoji
18
+ });
19
+ if (imageOptions.debug) {
20
+ console.info('VNode proivided to satori:', vnodes, '\n');
21
+ console.info('Options proivided to satori:', imageOptions, '\n');
22
+ }
23
+ return satori(vnodes, imageOptions);
24
+ }
25
+ export async function createPng(element, imageOptions, componentOptions) {
26
+ const svg = await createSvg(element, imageOptions, componentOptions);
27
+ if (imageOptions.debug) {
28
+ console.info('SVG generated by satori:', svg, '\n');
29
+ }
30
+ const resvg_instance = await useResvg();
31
+ console.log(resvg_instance, 'f');
32
+ const resvg_options = {
33
+ fitTo: {
34
+ mode: 'width',
35
+ value: imageOptions.width
36
+ },
37
+ logLevel: imageOptions.debug ? 'info' : 'error'
38
+ };
39
+ if (imageOptions.debug) {
40
+ console.info('Options provided to ReSVG:', resvg_options, '\n');
41
+ }
42
+ const resvg = new resvg_instance(svg, resvg_options);
43
+ const png_data = resvg.render();
44
+ return png_data.asPng();
45
+ }
@@ -0,0 +1,10 @@
1
+ import type { SatoriOptions } from 'satori';
2
+ import type { ImageOptions } from '../types.js';
3
+ export declare function default_fonts(): SatoriOptions['fonts'];
4
+ export declare const DEFAULT_FORMAT = "png";
5
+ export declare const DEFAULT_WIDTH = 1200;
6
+ export declare const DEFAULT_HEIGHT = 630;
7
+ export declare const DEFAULT_EMOJI_PROVIDER = "twemoji";
8
+ export declare const DEFAULT_STATUS_CODE = 200;
9
+ export declare const DEFAULT_STATUS_TEXT = "Success";
10
+ export declare const DEFAULT_OPTIONS: ImageOptions;
@@ -0,0 +1,37 @@
1
+ export async function default_fonts() {
2
+ const [noto_sans_regular_font_resp, noto_sans_bold_font_reps] = await Promise.all([
3
+ fetch('https://cdn-sveltekit-og.ethercorps.io/NotoSans-Regular.ttf'), fetch('https://cdn-sveltekit-og.ethercorps.io/NotoSans-Bold.ttf')
4
+ ]);
5
+ if (!(noto_sans_bold_font_reps.ok || noto_sans_bold_font_reps.ok)) {
6
+ console.error('Not able to load default fonts');
7
+ throw new Error('Not able to load default fonts');
8
+ }
9
+ const [noto_sans_regular_font, noto_sans_bold_font] = await Promise.all([noto_sans_regular_font_resp.arrayBuffer(), noto_sans_bold_font_reps.arrayBuffer()]);
10
+ return [
11
+ {
12
+ data: noto_sans_regular_font,
13
+ name: 'Inter',
14
+ weight: 400,
15
+ style: 'normal'
16
+ },
17
+ {
18
+ data: noto_sans_bold_font,
19
+ name: 'Inter',
20
+ weight: 700,
21
+ style: 'normal'
22
+ }
23
+ ];
24
+ }
25
+ export const DEFAULT_FORMAT = 'png';
26
+ export const DEFAULT_WIDTH = 1200;
27
+ export const DEFAULT_HEIGHT = 630;
28
+ export const DEFAULT_EMOJI_PROVIDER = 'twemoji';
29
+ export const DEFAULT_STATUS_CODE = 200;
30
+ export const DEFAULT_STATUS_TEXT = 'Success';
31
+ export const DEFAULT_OPTIONS = {
32
+ height: DEFAULT_HEIGHT,
33
+ width: DEFAULT_WIDTH,
34
+ debug: false,
35
+ format: 'png',
36
+ emoji: 'twemoji'
37
+ };
@@ -0,0 +1,3 @@
1
+ export declare const loadDynamicAsset: ({ emoji }: {
2
+ emoji: any;
3
+ }) => (...args: any[]) => Promise<string | undefined>;
@@ -0,0 +1,53 @@
1
+ import { DEFAULT_EMOJI_PROVIDER } from '../helpers/defaults.js';
2
+ // Code stolen from @vercel/og
3
+ const U200D = String.fromCharCode(8205);
4
+ const UFE0Fg = /\uFE0F/g;
5
+ function getIconCode(char) {
6
+ return toCodePoint(char.indexOf(U200D) < 0 ? char.replace(UFE0Fg, "") : char);
7
+ }
8
+ function toCodePoint(unicodeSurrogates) {
9
+ const r = [];
10
+ let c = 0, p = 0, i = 0;
11
+ while (i < unicodeSurrogates.length) {
12
+ c = unicodeSurrogates.charCodeAt(i++);
13
+ if (p) {
14
+ r.push((65536 + (p - 55296 << 10) + (c - 56320)).toString(16));
15
+ p = 0;
16
+ }
17
+ else if (55296 <= c && c <= 56319) {
18
+ p = c;
19
+ }
20
+ else {
21
+ r.push(c.toString(16));
22
+ }
23
+ }
24
+ return r.join("-");
25
+ }
26
+ const emoji_apis = {
27
+ twemoji: (code) => "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/" + code.toLowerCase() + ".svg",
28
+ openmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/openmoji@2.0.0/svg/",
29
+ blobmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/blob@2.0.0/svg/",
30
+ noto: "https://cdn.jsdelivr.net/gh/svgmoji/svgmoji/packages/svgmoji__noto/svg/",
31
+ fluent: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_color.svg",
32
+ fluentFlat: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_flat.svg"
33
+ };
34
+ function loadEmoji(code, type) {
35
+ if (!type || !apis[type]) {
36
+ type = DEFAULT_EMOJI_PROVIDER;
37
+ }
38
+ const api = apis[type];
39
+ if (typeof api === "function") {
40
+ return fetch(api(code));
41
+ }
42
+ return fetch(`${api}${code.toUpperCase()}.svg`);
43
+ }
44
+ export const loadDynamicAsset = ({ emoji }) => {
45
+ const fn = async (code, text) => {
46
+ if (code === "emoji") {
47
+ return `data:image/svg+xml;base64,` + btoa(await (await loadEmoji(getIconCode(text), emoji)).text());
48
+ }
49
+ };
50
+ return async (...args) => {
51
+ return await fn(...args);
52
+ };
53
+ };
@@ -0,0 +1,5 @@
1
+ import type { SvelteComponent } from 'svelte';
2
+ import type { ImageResponseOptions } from './types.js';
3
+ export declare class ImageResponse extends Response {
4
+ constructor(element: string | SvelteComponent, options?: ImageResponseOptions, props?: Record<string, any>);
5
+ }
@@ -0,0 +1,27 @@
1
+ import { DEFAULT_OPTIONS, DEFAULT_STATUS_CODE, DEFAULT_STATUS_TEXT } from './helpers/defaults.js';
2
+ import { createPng, createSvg } from './helpers/create.js';
3
+ import { isDevelopment } from 'std-env';
4
+ export class ImageResponse extends Response {
5
+ constructor(element, options, props) {
6
+ const extended_options = Object.assign({ ...DEFAULT_OPTIONS }, options);
7
+ const create_image_funtion = extended_options.format === 'png' ? createPng : createSvg;
8
+ const body = new ReadableStream({
9
+ async start(controller) {
10
+ const buffer = await create_image_funtion(element, extended_options, { props });
11
+ controller.enqueue(buffer);
12
+ controller.close();
13
+ }
14
+ });
15
+ super(body, {
16
+ headers: {
17
+ 'Content-Type': `image/${extended_options.format}`,
18
+ 'Cache-Control': (extended_options.debug || isDevelopment)
19
+ ? 'no-cache, no-store'
20
+ : 'public, immutable, no-transform, max-age=31536000',
21
+ ...extended_options.headers
22
+ },
23
+ status: extended_options.status || DEFAULT_STATUS_CODE,
24
+ statusText: extended_options.statusText || DEFAULT_STATUS_TEXT
25
+ });
26
+ }
27
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { componentToImageResponse, ImageResponse, type ImageResponseOptions } from "./api.js";
1
+ export { ImageResponse } from "./image-response.js";
2
+ export type { ImageResponseOptions, VNode } from "./types.js";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { componentToImageResponse, ImageResponse } from "./api.js";
1
+ export { ImageResponse } from "./image-response.js";
@@ -0,0 +1,38 @@
1
+ import type _satori from 'satori';
2
+ export declare function useResvg(): Promise<new (svg: Uint8Array | string, options?: import("@resvg/resvg-wasm").ResvgRenderOptions) => {
3
+ free(): void;
4
+ render(): {
5
+ free(): void;
6
+ asPng(): Uint8Array;
7
+ readonly height: number;
8
+ readonly pixels: Uint8Array;
9
+ readonly width: number;
10
+ };
11
+ toString(): string;
12
+ innerBBox(): {
13
+ free(): void;
14
+ height: number;
15
+ width: number;
16
+ x: number;
17
+ y: number;
18
+ } | undefined;
19
+ getBBox(): {
20
+ free(): void;
21
+ height: number;
22
+ width: number;
23
+ x: number;
24
+ y: number;
25
+ } | undefined;
26
+ cropByBBox(bbox: {
27
+ free(): void;
28
+ height: number;
29
+ width: number;
30
+ x: number;
31
+ y: number;
32
+ }): void;
33
+ imagesToResolve(): any[];
34
+ resolveImage(href: string, buffer: Uint8Array): void;
35
+ readonly height: number;
36
+ readonly width: number;
37
+ }>;
38
+ export declare function useSatori(): Promise<typeof _satori>;
@@ -0,0 +1,22 @@
1
+ import { isEdgeLight, isWorkerd } from 'std-env';
2
+ // we keep instances alive to avoid re-importing them on every request, maybe not needed but
3
+ // also helps with type inference
4
+ // Code from vue-og-images
5
+ const resvgInstance = { instance: undefined };
6
+ const satoriInstance = { instance: undefined };
7
+ export async function useResvg() {
8
+ const isEdge = isEdgeLight || isWorkerd;
9
+ try {
10
+ resvgInstance.instance = resvgInstance.instance || await import(`./resvg/${isEdge ? 'wasm' : 'node'}.js`).then(m => m.default);
11
+ await resvgInstance.instance.initWasmPromise;
12
+ }
13
+ catch (e) {
14
+ console.log(e);
15
+ }
16
+ return resvgInstance.instance.Resvg;
17
+ }
18
+ export async function useSatori() {
19
+ satoriInstance.instance = satoriInstance.instance || await import(`./satori/node.js`).then(m => m.default);
20
+ await satoriInstance.instance.initWasmPromise;
21
+ return satoriInstance.instance.satori;
22
+ }
@@ -0,0 +1,6 @@
1
+ declare namespace _default {
2
+ export let initWasmPromise: Promise<void>;
3
+ export { _Resvg as Resvg };
4
+ }
5
+ export default _default;
6
+ import { Resvg as _Resvg } from '@resvg/resvg-js';
@@ -0,0 +1,6 @@
1
+ import { Resvg as _Resvg } from '@resvg/resvg-js'
2
+
3
+ export default {
4
+ initWasmPromise: Promise.resolve(),
5
+ Resvg: _Resvg,
6
+ }
@@ -0,0 +1,6 @@
1
+ declare namespace _default {
2
+ export let initWasmPromise: Promise<void>;
3
+ export { _Resvg as Resvg };
4
+ }
5
+ export default _default;
6
+ import { Resvg as _Resvg } from '@resvg/resvg-wasm';
@@ -0,0 +1,6 @@
1
+ import { Resvg as _Resvg, initWasm } from '@resvg/resvg-wasm'
2
+
3
+ export default {
4
+ initWasmPromise: initWasm(import('@resvg/resvg-wasm/index_bg.wasm?module').then(r => r.default || r)),
5
+ Resvg: _Resvg,
6
+ }
@@ -0,0 +1,6 @@
1
+ declare namespace _default {
2
+ export let initWasmPromise: Promise<void>;
3
+ export { _satori as satori };
4
+ }
5
+ export default _default;
6
+ import _satori from 'satori';
@@ -0,0 +1,6 @@
1
+ import _satori from 'satori'
2
+
3
+ export default {
4
+ initWasmPromise: Promise.resolve(),
5
+ satori: _satori,
6
+ }
@@ -0,0 +1,6 @@
1
+ declare namespace _default {
2
+ export function initWasmPromise(resolve: any): void;
3
+ export { _satori as satori };
4
+ }
5
+ export default _default;
6
+ import _satori from 'satori/wasm';
@@ -0,0 +1,16 @@
1
+ import _satori from 'satori/wasm'
2
+ import initYoga from 'yoga-wasm-web'
3
+ import { init } from 'satori'
4
+
5
+ const wasm = import('yoga-wasm-web/dist/yoga.wasm?module')
6
+ .then(async yoga => await initYoga(yoga.default || yoga))
7
+
8
+ export default {
9
+ initWasmPromise: ((resolve) => {
10
+ wasm.then((yoga) => {
11
+ init(yoga)
12
+ resolve()
13
+ })
14
+ }),
15
+ satori: _satori,
16
+ }
@@ -0,0 +1,2 @@
1
+ import type { RuntimeCompatibility, SupportedRuntimes } from '../types.js';
2
+ export declare const runtimeCompatibility: Record<SupportedRuntimes, RuntimeCompatibility>;
@@ -0,0 +1,25 @@
1
+ const NodeRuntime = {
2
+ 'resvg': 'wasm',
3
+ 'satori': 'wasm',
4
+ };
5
+ const WorkersRuntime = {
6
+ 'resvg': 'wasm',
7
+ 'satori': 'node',
8
+ };
9
+ const WebContainerRuntime = {
10
+ 'resvg': 'wasm-fs',
11
+ 'satori': 'wasm-fs',
12
+ };
13
+ export const runtimeCompatibility = {
14
+ 'dev': NodeRuntime,
15
+ 'node': NodeRuntime,
16
+ 'stackblitz': WebContainerRuntime,
17
+ 'codesandbox': WebContainerRuntime,
18
+ 'aws-lambda': NodeRuntime,
19
+ 'netlify': NodeRuntime,
20
+ 'netlify-edge': WorkersRuntime,
21
+ 'vercel': NodeRuntime,
22
+ 'vercel-edge': WorkersRuntime,
23
+ 'cloudflare-pages': WorkersRuntime,
24
+ 'cloudflare-workers': WorkersRuntime
25
+ };
@@ -0,0 +1,3 @@
1
+ import type { RuntimeCompatibility, SupportedRuntimes } from '../types.js';
2
+ export declare function getRuntime(): SupportedRuntimes;
3
+ export declare function getRuntimeCompatibility(runtime?: SupportedRuntimes): RuntimeCompatibility;
@@ -0,0 +1,29 @@
1
+ import { provider, env, runtime, isDevelopment } from 'std-env';
2
+ import { runtimeCompatibility } from '../runtime/compatability.js';
3
+ export function getRuntime() {
4
+ if (provider === 'stackblitz' || provider === 'codesandbox')
5
+ return provider;
6
+ if (isDevelopment) {
7
+ return 'node';
8
+ }
9
+ const parsedProvider = provider.replace('_', '-');
10
+ const compatibility = runtimeCompatibility[env['OG_RUNTIME'] || parsedProvider];
11
+ if (compatibility)
12
+ return parsedProvider;
13
+ switch (runtime) {
14
+ case 'node':
15
+ case 'deno':
16
+ case 'bun':
17
+ case 'netlify':
18
+ default:
19
+ return 'node';
20
+ case 'edge-light':
21
+ return 'vercel-edge';
22
+ case 'workerd':
23
+ return 'cloudflare-workers';
24
+ }
25
+ ;
26
+ }
27
+ export function getRuntimeCompatibility(runtime = getRuntime()) {
28
+ return runtimeCompatibility[runtime];
29
+ }
@@ -0,0 +1,99 @@
1
+ import type { SatoriOptions } from 'satori/wasm';
2
+ export type ImageOptions = {
3
+ /**
4
+ * Width of the image
5
+ * @default 1200
6
+ * */
7
+ width?: number;
8
+ /**
9
+ * Height of the image
10
+ * @default 630
11
+ * */
12
+ height?: number;
13
+ /**
14
+ * Emoji provider
15
+ * @default twemoji
16
+ * */
17
+ emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' | 'fluent' | 'fluentFlat';
18
+ /**
19
+ * Fonts used for your text
20
+ * @default `helpers/defaults.js`
21
+ * */
22
+ fonts?: SatoriOptions['fonts'];
23
+ /**
24
+ * Tailwind config
25
+ * @default provided by satori
26
+ * */
27
+ tailwindConfig?: SatoriOptions['tailwindConfig'];
28
+ /**
29
+ * Debug operations
30
+ * @default false
31
+ * */
32
+ debug?: boolean;
33
+ /**
34
+ * Image format
35
+ * @default png
36
+ * */
37
+ format?: 'svg' | 'png';
38
+ };
39
+ export type ResponseImageOptions = {
40
+ /**
41
+ * Status code for response
42
+ * @default 200
43
+ * */
44
+ status?: number;
45
+ /**
46
+ * Status text for response
47
+ * @default Success
48
+ * */
49
+ statusText?: string;
50
+ /**
51
+ * Response Headers
52
+ * @default {
53
+ * 'Content-Type': 'image/png',
54
+ * 'Cache-Control': options.debug ? 'no-cache, no-store' : 'public, immutable, no-transform, max-age=31536000'
55
+ * }
56
+ * */
57
+ headers?: Record<string, string>;
58
+ };
59
+ /**
60
+ * Image response options type exposed to devs for ImageResponse Instance
61
+ * */
62
+ export type ImageResponseOptions = ImageOptions & ResponseImageOptions;
63
+ /**
64
+ * Svelte Component props to render the component which dynamic content
65
+ * */
66
+ export type ComponentOptions = {
67
+ props: Record<string, any>;
68
+ };
69
+ /**
70
+ * React virtual node, supported by satori as input (alternative to JSX input).
71
+ * */
72
+ export interface VNode {
73
+ type: string;
74
+ props: {
75
+ style?: Record<string, any>;
76
+ children?: string | VNode | VNode[];
77
+ [prop: string]: any;
78
+ };
79
+ }
80
+ /**
81
+ * Supported runtimes by sveltekit-og
82
+ * TODO: Test all the runtimes.
83
+ * */
84
+ export type SupportedRuntimes = 'node' | 'stackblitz' | 'codesandbox' | 'aws-lambda' | 'netlify' | 'netlify-edge' | 'vercel' | 'vercel-edge' | 'cloudflare-pages' | 'cloudflare-workers';
85
+ /**
86
+ * Files support on the basis of runtime
87
+ * node: Use nodejs based implementation of the provider
88
+ * wasm: Use wasm based implementation of the provider
89
+ * wasm-fs: Mainly provided for web containers which supports `fs`.
90
+ * */
91
+ type SupportedImplementations = 'node' | 'wasm' | 'wasm-fs';
92
+ /**
93
+ * Provider and There supported Implementations
94
+ * */
95
+ export interface RuntimeCompatibility {
96
+ resvg: SupportedImplementations;
97
+ satori: SupportedImplementations;
98
+ }
99
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ ;
2
+ ;
3
+ export {};
package/package.json CHANGED
@@ -1,55 +1,69 @@
1
1
  {
2
- "name": "@ethercorps/sveltekit-og",
3
- "version": "2.0.2",
4
- "exports": {
5
- ".": {
6
- "types": "./dist/index.d.ts",
7
- "svelte": "./dist/index.js"
8
- }
9
- },
10
- "files": [
11
- "dist",
12
- "!dist/**/*.test.*",
13
- "!dist/**/*.spec.*"
14
- ],
15
- "peerDependencies": {
16
- "svelte": "^4.0.0"
17
- },
18
- "devDependencies": {
19
- "@sveltejs/adapter-auto": "^2.0.0",
20
- "@sveltejs/kit": "^1.20.4",
21
- "@sveltejs/package": "^2.0.0",
22
- "@typescript-eslint/eslint-plugin": "^5.45.0",
23
- "@typescript-eslint/parser": "^5.45.0",
24
- "eslint": "^8.28.0",
25
- "eslint-config-prettier": "^8.5.0",
26
- "eslint-plugin-svelte": "^2.30.0",
27
- "prettier": "^2.8.0",
28
- "prettier-plugin-svelte": "^2.10.1",
29
- "publint": "^0.1.9",
30
- "svelte": "^4.0.5",
31
- "svelte-check": "^3.4.3",
32
- "tslib": "^2.4.1",
33
- "typescript": "^5.0.0",
34
- "vite": "^4.4.2",
35
- "vitest": "^0.34.0"
36
- },
37
- "svelte": "./dist/index.js",
38
- "types": "./dist/index.d.ts",
39
- "type": "module",
40
- "dependencies": {
41
- "@vercel/og": "^0.5.17",
42
- "satori-html": "^0.3.2"
43
- },
44
- "scripts": {
45
- "dev": "vite dev",
46
- "build": "vite build && npm run package",
47
- "preview": "vite preview",
48
- "package": "svelte-kit sync && svelte-package && publint",
49
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
50
- "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
51
- "test": "vitest",
52
- "lint": "prettier --plugin-search-dir . --check . && eslint .",
53
- "format": "prettier --plugin-search-dir . --write ."
54
- }
2
+ "name": "@ethercorps/sveltekit-og",
3
+ "version": "3.0.0-next.10",
4
+ "scripts": {
5
+ "dev": "vite dev",
6
+ "build": "vite build && npm run package",
7
+ "preview": "vite preview",
8
+ "package": "svelte-kit sync && svelte-package && publint",
9
+ "prepublishOnly": "npm run package",
10
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
11
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
12
+ "test": "vitest",
13
+ "lint": "prettier --plugin-search-dir . --check . && eslint .",
14
+ "format": "prettier --plugin-search-dir . --write .",
15
+ "publishBeta": "npm publish --tag beta"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "svelte": "./dist/index.js",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "!dist/**/*.test.*",
27
+ "!dist/**/*.spec.*"
28
+ ],
29
+ "peerDependencies": {
30
+ "svelte": "^4.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@sveltejs/adapter-auto": "^3.2.2",
34
+ "@sveltejs/adapter-vercel": "^5.3.2",
35
+ "@sveltejs/kit": "^2.5.17",
36
+ "@sveltejs/package": "^2.3.2",
37
+ "@sveltejs/vite-plugin-svelte": "^3.1.1",
38
+ "@typescript-eslint/eslint-plugin": "^5.62.0",
39
+ "@typescript-eslint/parser": "^5.62.0",
40
+ "css-tree": "^2.3.1",
41
+ "eslint": "^8.57.0",
42
+ "eslint-config-prettier": "^8.10.0",
43
+ "eslint-plugin-svelte": "^2.40.0",
44
+ "prettier": "^2.8.8",
45
+ "prettier-plugin-svelte": "^2.10.1",
46
+ "publint": "^0.1.16",
47
+ "svelte": "^4.2.18",
48
+ "svelte-check": "^3.8.1",
49
+ "tslib": "^2.6.3",
50
+ "typescript": "^5.5.2",
51
+ "vite": "^5.3.1",
52
+ "vite-plugin-wasm": "^3.3.0",
53
+ "vitest": "^1.6.0"
54
+ },
55
+ "svelte": "./dist/index.js",
56
+ "types": "./dist/index.d.ts",
57
+ "type": "module",
58
+ "dependencies": {
59
+ "@ethercorps/svelte-h2j": "^4.0.0",
60
+ "satori": "^0.10.13",
61
+ "std-env": "^3.7.0",
62
+ "unwasm": "^0.3.9",
63
+ "yoga-wasm-web": "^0.3.3"
64
+ },
65
+ "optionalDependencies": {
66
+ "@resvg/resvg-js": "^2.6.2",
67
+ "@resvg/resvg-wasm": "^2.6.2"
68
+ }
55
69
  }
package/dist/api.d.ts DELETED
@@ -1,63 +0,0 @@
1
- /// <reference types="node" />
2
- import { ImageResponse as IR } from "@vercel/og";
3
- import type { SvelteComponent } from "svelte";
4
- export declare const ImageResponse: (htmlTemplate: string, options?: ImageResponseOptions) => Promise<IR>;
5
- export declare const componentToImageResponse: (component: SvelteComponent, props: Record<string, any>, options?: ImageResponseOptions) => Promise<IR>;
6
- declare const apis: {
7
- twemoji: (code: any) => string;
8
- openmoji: string;
9
- blobmoji: string;
10
- noto: string;
11
- fluent: (code: any) => string;
12
- fluentFlat: (code: any) => string;
13
- };
14
- declare type EmojiType = keyof typeof apis;
15
- type Weight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
16
- type Style$1 = 'normal' | 'italic';
17
- interface FontOptions {
18
- data: Buffer | ArrayBuffer;
19
- name: string;
20
- weight?: Weight;
21
- style?: Style$1;
22
- lang?: string;
23
- }
24
- export declare type ImageResponseOptions = ImageOptions & ConstructorParameters<typeof Response>[1];
25
- declare type ImageOptions = {
26
- /**
27
- * The width of the image.
28
- *
29
- * @type {number}
30
- * @default 1200
31
- */
32
- width?: number;
33
- /**
34
- * The height of the image.
35
- *
36
- * @type {number}
37
- * @default 630
38
- */
39
- height?: number;
40
- /**
41
- * Display debug information on the image.
42
- *
43
- * @type {boolean}
44
- * @default false
45
- */
46
- debug?: boolean;
47
- /**
48
- * A list of fonts to use.
49
- *
50
- * @type {{ data: ArrayBuffer; name: string; weight?: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; style?: 'normal' | 'italic' }[]}
51
- * @default Noto Sans Latin Regular.
52
- */
53
- fonts?: FontOptions[];
54
- /**
55
- * Using a specific Emoji style. Defaults to `twemoji`.
56
- *
57
- * @link https://github.com/vercel/og#emoji
58
- * @type {EmojiType}
59
- * @default 'twemoji'
60
- */
61
- emoji?: EmojiType;
62
- };
63
- export {};
package/dist/api.js DELETED
@@ -1,12 +0,0 @@
1
- import { html } from "satori-html";
2
- import { ImageResponse as IR } from "@vercel/og";
3
- export const ImageResponse = async (htmlTemplate, options) => {
4
- const reactVNode = html(`${htmlTemplate}`);
5
- console.log(reactVNode);
6
- return new IR(reactVNode, options);
7
- };
8
- export const componentToImageResponse = async (component, props, options) => {
9
- const ssrSvelte = component.render(props);
10
- console.log(ssrSvelte);
11
- return ImageResponse(`${ssrSvelte.html}<style>${ssrSvelte.css.code}</style>`, options);
12
- };