@ethercorps/sveltekit-og 2.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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)
package/dist/api.d.ts CHANGED
@@ -1,63 +1,7 @@
1
1
  /// <reference types="node" />
2
- import { ImageResponse as IR } from "@vercel/og";
2
+ import type { ImageResponseOptions } from './types.js';
3
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;
4
+ export declare const og: (element: string | SvelteComponent, options: ImageResponseOptions, props?: {}) => Promise<string | Buffer>;
5
+ export declare class ImageResponse extends Response {
6
+ constructor(element: string | SvelteComponent, options?: ImageResponseOptions, props?: {});
23
7
  }
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 CHANGED
@@ -1,12 +1,64 @@
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);
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
+ export const og = async (element, options, props = {}) => {
6
+ const reactElement = typeof element === 'string' ? toReactElement(element) : svelteComponentToJsx(element, props);
7
+ // render the React element-like object into an SVG
8
+ const svg = await satori(reactElement, {
9
+ width: options.width || 1200,
10
+ height: options.height || 630,
11
+ fonts: options.fonts?.length
12
+ ? options.fonts
13
+ : [
14
+ {
15
+ name: 'Bitter',
16
+ data: await loadGoogleFont({ family: 'Bitter', weight: 600 }),
17
+ weight: 500,
18
+ style: 'normal'
19
+ }
20
+ ]
21
+ });
22
+ const requestedFormat = options.format || 'png';
23
+ if (requestedFormat === 'svg') {
24
+ return svg;
25
+ }
26
+ // convert the SVG into a PNG
27
+ const opts = {
28
+ // background: "rgba(238, 235, 230, .9)",
29
+ fitTo: {
30
+ mode: 'width',
31
+ value: options.width || 1200
32
+ },
33
+ font: {
34
+ loadSystemFonts: false // It will be faster to disable loading system fonts.
35
+ }
36
+ };
37
+ const resvg = new Resvg(svg, opts);
38
+ const pngData = resvg.render();
39
+ const pngBuffer = pngData.asPng();
40
+ return pngBuffer;
12
41
  };
42
+ export class ImageResponse extends Response {
43
+ constructor(element, options = {}, props = {}) {
44
+ super();
45
+ const body = new ReadableStream({
46
+ async start(controller) {
47
+ const buffer = await og(element, options, props);
48
+ controller.enqueue(buffer);
49
+ controller.close();
50
+ }
51
+ });
52
+ return new Response(body, {
53
+ headers: {
54
+ 'Content-Type': 'image/png',
55
+ 'Cache-Control': options.debug
56
+ ? 'no-cache, no-store'
57
+ : 'public, immutable, no-transform, max-age=31536000',
58
+ ...options.headers
59
+ },
60
+ status: options.status || 200,
61
+ statusText: options.statusText
62
+ });
63
+ }
64
+ }
package/dist/font.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare function loadGoogleFont({ family, weight, text }: {
2
+ family: string;
3
+ weight?: number;
4
+ text?: string;
5
+ }): Promise<ArrayBuffer>;
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
- export { componentToImageResponse, ImageResponse, type ImageResponseOptions } from "./api.js";
1
+ export { ImageResponse } from "./api.js";
2
+ export type { ImageResponseOptions } from "./types.js";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { componentToImageResponse, ImageResponse } from "./api.js";
1
+ export { ImageResponse } from "./api.js";
@@ -0,0 +1,11 @@
1
+ import type { SatoriOptions } from 'satori/wasm';
2
+ export interface ImageResponseOptions {
3
+ width?: number;
4
+ height?: number;
5
+ fonts?: SatoriOptions['fonts'];
6
+ debug?: boolean;
7
+ status?: number;
8
+ statusText?: string;
9
+ headers?: Record<string, string>;
10
+ format?: 'svg' | 'png';
11
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,55 +1,59 @@
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
- }
55
- }
2
+ "name": "@ethercorps/sveltekit-og",
3
+ "version": "3.0.0",
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
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "svelte": "./dist/index.js",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "!dist/**/*.test.*",
26
+ "!dist/**/*.spec.*"
27
+ ],
28
+ "peerDependencies": {
29
+ "svelte": "^4.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@sveltejs/adapter-auto": "^2.1.1",
33
+ "@sveltejs/kit": "^1.30.3",
34
+ "@sveltejs/package": "^2.2.5",
35
+ "@typescript-eslint/eslint-plugin": "^5.62.0",
36
+ "@typescript-eslint/parser": "^5.62.0",
37
+ "css-tree": "^2.3.1",
38
+ "eslint": "^8.56.0",
39
+ "eslint-config-prettier": "^8.10.0",
40
+ "eslint-plugin-svelte": "^2.35.1",
41
+ "prettier": "^2.8.8",
42
+ "prettier-plugin-svelte": "^2.10.1",
43
+ "publint": "^0.1.16",
44
+ "svelte": "^4.2.8",
45
+ "svelte-check": "^3.6.3",
46
+ "tslib": "^2.6.2",
47
+ "typescript": "^5.3.3",
48
+ "vite": "^4.5.1",
49
+ "vitest": "^0.34.6"
50
+ },
51
+ "svelte": "./dist/index.js",
52
+ "types": "./dist/index.d.ts",
53
+ "type": "module",
54
+ "dependencies": {
55
+ "@ethercorps/svelte-h2j": "^0.1.0",
56
+ "@resvg/resvg-js": "^2.6.0",
57
+ "satori": "^0.10.11"
58
+ }
59
+ }