@ethercorps/sveltekit-og 3.0.0-alpha.1 → 4.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -0,0 +1,171 @@
1
+ # SvelteKit Open Graph Image Generation
2
+
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
+
5
+ ## Disclaimer
6
+ This project doesn't support edge services like vercel edge and cloudflare workers.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pnpm install @ethercorps/sveltekit-og
12
+ ```
13
+
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 new 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
+ };
58
+ ```
59
+
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.
61
+
62
+ ## Example Output
63
+
64
+ ![Rendered OG image](static/demo.png)
65
+
66
+ ## Headers
67
+
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.
69
+
70
+ ## Styling
71
+
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).
73
+
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.
75
+
76
+ ## Fonts
77
+
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})
116
+ ```
117
+
118
+ ## Changelog
119
+
120
+ ### v3.0.0 (Breaking Changes)
121
+
122
+ > Just install @ethercorps/sveltekit-og
123
+ > No wasm as of now, only support for nodejs based runtime.
124
+
125
+ ### v1.2.3 Update (Breaking Changes)
126
+
127
+ > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
128
+
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)
package/dist/api.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { ImageResponseOptions } from './types.js';
2
- import type { SvelteComponent } from "svelte";
3
- export declare const og: (element: string | SvelteComponent, options: ImageResponseOptions, props?: {}) => Promise<string | Uint8Array>;
1
+ import type { ComponentOptions, ImageResponseOptions } from './types.js';
2
+ import { SvelteComponent } from "svelte";
3
+ export declare const og: (element: string | typeof SvelteComponent, options: ImageResponseOptions, componentOptions: ComponentOptions) => Promise<any>;
4
4
  export declare class ImageResponse extends Response {
5
- constructor(element: string | SvelteComponent, options?: ImageResponseOptions, props?: {});
5
+ constructor(element: string | typeof SvelteComponent, options: ImageResponseOptions | undefined, { props, style }: ComponentOptions);
6
6
  }
package/dist/api.js ADDED
@@ -0,0 +1,65 @@
1
+ import satori from 'satori';
2
+ import { Resvg } from '@resvg/resvg-js';
3
+ import { loadGoogleFont } from './font.js';
4
+ import { toReactElement, svelteComponentToJsx } from "@ethercorps/svelte-h2j";
5
+ import { SvelteComponent } from "svelte";
6
+ export const og = async (element, options, componentOptions) => {
7
+ const reactElement = typeof element === 'string' ? toReactElement(element) : svelteComponentToJsx(element, componentOptions);
8
+ // render the React element-like object into an SVG
9
+ const svg = await satori(reactElement, {
10
+ width: options.width || 1200,
11
+ height: options.height || 630,
12
+ fonts: options.fonts?.length
13
+ ? options.fonts
14
+ : [
15
+ {
16
+ name: 'Bitter',
17
+ data: await loadGoogleFont({ family: 'Bitter', weight: 600 }),
18
+ weight: 500,
19
+ style: 'normal'
20
+ }
21
+ ]
22
+ });
23
+ const requestedFormat = options.format || 'png';
24
+ if (requestedFormat === 'svg') {
25
+ return svg;
26
+ }
27
+ // convert the SVG into a PNG
28
+ const opts = {
29
+ // background: "rgba(238, 235, 230, .9)",
30
+ fitTo: {
31
+ mode: 'width',
32
+ value: options.width || 1200
33
+ },
34
+ font: {
35
+ loadSystemFonts: false // It will be faster to disable loading system fonts.
36
+ }
37
+ };
38
+ const resvg = new Resvg(svg, opts);
39
+ const pngData = resvg.render();
40
+ const pngBuffer = pngData.asPng();
41
+ return pngBuffer;
42
+ };
43
+ export class ImageResponse extends Response {
44
+ constructor(element, options = {}, { props = {}, style = '' }) {
45
+ super();
46
+ const body = new ReadableStream({
47
+ async start(controller) {
48
+ const buffer = await og(element, options, { props, style });
49
+ controller.enqueue(buffer);
50
+ controller.close();
51
+ }
52
+ });
53
+ return new Response(body, {
54
+ headers: {
55
+ 'Content-Type': 'image/png',
56
+ 'Cache-Control': options.debug
57
+ ? 'no-cache, no-store'
58
+ : 'public, immutable, no-transform, max-age=31536000',
59
+ ...options.headers
60
+ },
61
+ status: options.status || 200,
62
+ statusText: options.statusText
63
+ });
64
+ }
65
+ }
package/dist/font.js ADDED
@@ -0,0 +1,27 @@
1
+ export async function loadGoogleFont({ family, weight, text }) {
2
+ const params = {
3
+ family: `${encodeURIComponent(family)}${weight ? `:wght@${weight}` : ''}`
4
+ };
5
+ if (text) {
6
+ params.text = text;
7
+ }
8
+ else {
9
+ params.subset = 'latin';
10
+ }
11
+ const url = `https://fonts.googleapis.com/css2?${Object.keys(params)
12
+ .map((key) => `${key}=${params[key]}`)
13
+ .join('&')}`;
14
+ const res = await fetch(`${url}`, {
15
+ headers: {
16
+ // construct user agent to get TTF font
17
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
18
+ }
19
+ });
20
+ const body = await res.text();
21
+ // Get the font URL from the CSS text
22
+ const fontUrl = body.match(/src: url\((.+)\) format\('(opentype|truetype)'\)/)?.[1];
23
+ if (!fontUrl) {
24
+ throw new Error('Could not find font URL');
25
+ }
26
+ return fetch(fontUrl).then((res) => res.arrayBuffer());
27
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { ImageResponse } from "./api.js";
2
+ export type { ImageResponseOptions, ComponentOptions } from "./types.js";