@junejs/og 0.0.4 → 0.0.6-dev.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/dist/edge.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { OG_HEADERS, OgFont, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ import { ImageResponseOptions } from "./types.js";
3
+ import { ReactElement } from "react";
4
+ //#region src/edge.d.ts
5
+ declare class ImageResponse extends Response {
6
+ constructor(element: ReactElement, options?: ImageResponseOptions);
7
+ }
8
+ //#endregion
9
+ export { ImageResponse, type ImageResponseOptions, OG_HEADERS, type OgFont, hasCJK, loadDefaultFonts, loadGoogleFont };
package/dist/edge.js ADDED
@@ -0,0 +1,28 @@
1
+ import { OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ //#region src/edge.ts
3
+ const _import = new Function("m", "return import(m)");
4
+ var ImageResponse = class extends Response {
5
+ constructor(element, options = {}) {
6
+ const { readable, writable } = new TransformStream();
7
+ super(readable, {
8
+ status: options.status ?? 200,
9
+ headers: {
10
+ "cache-control": "public, max-age=86400, stale-while-revalidate=604800",
11
+ ...options.headers,
12
+ "content-type": "image/png"
13
+ }
14
+ });
15
+ _import("@vercel/og").then(({ ImageResponse: VercelOg }) => {
16
+ const rendered = new VercelOg(element, {
17
+ width: options.width ?? 1200,
18
+ height: options.height ?? 630,
19
+ fonts: options.fonts,
20
+ emoji: options.emoji,
21
+ debug: options.debug
22
+ });
23
+ return rendered.body ? rendered.body.pipeTo(writable) : writable.close();
24
+ }).catch((err) => writable.abort(err).catch(() => {}));
25
+ }
26
+ };
27
+ //#endregion
28
+ export { ImageResponse, OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont };
@@ -0,0 +1,29 @@
1
+ //#region src/fonts.d.ts
2
+ interface OgFont {
3
+ name: string;
4
+ data: ArrayBuffer;
5
+ weight: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
6
+ style: "normal" | "italic";
7
+ }
8
+ /**
9
+ * Load a Google Font subset for the given text. Only the glyphs that appear in
10
+ * `text` are fetched (the `text=` query parameter asks Google to subset the font),
11
+ * so even a full CJK face downloads just a few KB per title.
12
+ *
13
+ * Cache strategy: Cache API (available on Cloudflare Workers and Vercel Edge) first,
14
+ * then in-memory (survives the dev process lifetime).
15
+ */
16
+ declare function loadGoogleFont(family: string, weight: number, text: string): Promise<ArrayBuffer>;
17
+ /** True when the string contains CJK characters (Chinese, Japanese, Korean). */
18
+ declare const hasCJK: (s: string) => boolean;
19
+ /**
20
+ * Convenience: load Inter (always) + Noto Sans TC (when the title contains CJK).
21
+ * Pass `text` as all the strings that will be rendered so the subset is complete.
22
+ */
23
+ declare function loadDefaultFonts(text: string): Promise<OgFont[]>;
24
+ declare const OG_HEADERS: {
25
+ readonly "content-type": "image/png";
26
+ readonly "cache-control": "public, max-age=86400, stale-while-revalidate=604800";
27
+ };
28
+ //#endregion
29
+ export { OG_HEADERS, OgFont, hasCJK, loadDefaultFonts, loadGoogleFont };
package/dist/fonts.js ADDED
@@ -0,0 +1,54 @@
1
+ //#region src/fonts.ts
2
+ const memoryCache = /* @__PURE__ */ new Map();
3
+ /**
4
+ * Load a Google Font subset for the given text. Only the glyphs that appear in
5
+ * `text` are fetched (the `text=` query parameter asks Google to subset the font),
6
+ * so even a full CJK face downloads just a few KB per title.
7
+ *
8
+ * Cache strategy: Cache API (available on Cloudflare Workers and Vercel Edge) first,
9
+ * then in-memory (survives the dev process lifetime).
10
+ */
11
+ async function loadGoogleFont(family, weight, text) {
12
+ const cssUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
13
+ const cache = globalThis.caches?.default;
14
+ const cached = await cache?.match(cssUrl);
15
+ if (cached) return cached.arrayBuffer();
16
+ const memo = memoryCache.get(cssUrl);
17
+ if (memo) return memo;
18
+ return _fetchFont(cssUrl, family, cache);
19
+ }
20
+ async function _fetchFont(cssUrl, family, cache) {
21
+ const url = (await fetch(cssUrl, { headers: { "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1" } }).then((r) => r.text())).match(/src: url\((.+?)\)/)?.[1];
22
+ if (!url) throw new Error(`@junejs/og: could not extract font URL for "${family}"`);
23
+ const buf = await fetch(url).then((r) => r.arrayBuffer());
24
+ await cache?.put(cssUrl, new Response(buf, { headers: { "cache-control": "public, max-age=604800" } }));
25
+ memoryCache.set(cssUrl, buf);
26
+ return buf;
27
+ }
28
+ /** True when the string contains CJK characters (Chinese, Japanese, Korean). */
29
+ const hasCJK = (s) => /[ -鿿豈-﫿]/.test(s);
30
+ /**
31
+ * Convenience: load Inter (always) + Noto Sans TC (when the title contains CJK).
32
+ * Pass `text` as all the strings that will be rendered so the subset is complete.
33
+ */
34
+ async function loadDefaultFonts(text) {
35
+ const fonts = [{
36
+ name: "Inter",
37
+ data: await loadGoogleFont("Inter", 600, text),
38
+ weight: 600,
39
+ style: "normal"
40
+ }];
41
+ if (hasCJK(text)) fonts.push({
42
+ name: "Noto Sans TC",
43
+ data: await loadGoogleFont("Noto Sans TC", 600, text),
44
+ weight: 600,
45
+ style: "normal"
46
+ });
47
+ return fonts;
48
+ }
49
+ const OG_HEADERS = {
50
+ "content-type": "image/png",
51
+ "cache-control": "public, max-age=86400, stale-while-revalidate=604800"
52
+ };
53
+ //#endregion
54
+ export { OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont };
package/dist/node.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { OG_HEADERS, OgFont, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ import { ImageResponseOptions } from "./types.js";
3
+ import { ReactElement } from "react";
4
+ //#region src/node.d.ts
5
+ declare class ImageResponse extends Response {
6
+ constructor(element: ReactElement, options?: ImageResponseOptions);
7
+ }
8
+ //#endregion
9
+ export { ImageResponse, type ImageResponseOptions, OG_HEADERS, type OgFont, hasCJK, loadDefaultFonts, loadGoogleFont };
package/dist/node.js ADDED
@@ -0,0 +1,28 @@
1
+ import { OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ //#region src/node.ts
3
+ const _import = new Function("m", "return import(m)");
4
+ var ImageResponse = class extends Response {
5
+ constructor(element, options = {}) {
6
+ const { readable, writable } = new TransformStream();
7
+ super(readable, {
8
+ status: options.status ?? 200,
9
+ headers: {
10
+ "cache-control": "public, max-age=86400, stale-while-revalidate=604800",
11
+ ...options.headers,
12
+ "content-type": "image/png"
13
+ }
14
+ });
15
+ const writer = writable.getWriter();
16
+ Promise.all([_import("satori"), _import("@resvg/resvg-js")]).then(([{ default: satori }, { Resvg }]) => satori(element, {
17
+ width: options.width ?? 1200,
18
+ height: options.height ?? 630,
19
+ fonts: options.fonts ?? []
20
+ }).then((svg) => {
21
+ const png = new Resvg(svg).render().asPng();
22
+ writer.write(new Uint8Array(png));
23
+ writer.close();
24
+ })).catch((err) => writer.abort(err));
25
+ }
26
+ };
27
+ //#endregion
28
+ export { ImageResponse, OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont };
@@ -0,0 +1,19 @@
1
+ import { OgFont } from "./fonts.js";
2
+ //#region src/types.d.ts
3
+ /** Options accepted by ImageResponse across all backends. */
4
+ interface ImageResponseOptions {
5
+ width?: number;
6
+ height?: number;
7
+ /** Fonts to load for satori — use {@link loadGoogleFont} or {@link loadDefaultFonts}. */
8
+ fonts?: OgFont[];
9
+ /** HTTP status code. Default 200. */
10
+ status?: number;
11
+ /** Additional response headers (merged; do not override content-type). */
12
+ headers?: Record<string, string>;
13
+ /** Emoji rendering style (satori option). Default "twemoji". */
14
+ emoji?: "twemoji" | "blobmoji" | "noto" | "openmoji";
15
+ /** Render debug outlines (satori option). */
16
+ debug?: boolean;
17
+ }
18
+ //#endregion
19
+ export { ImageResponseOptions };
package/dist/types.js ADDED
File without changes
@@ -0,0 +1,4 @@
1
+ import { OG_HEADERS, OgFont, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ import { ImageResponseOptions } from "./types.js";
3
+ import { ImageResponse } from "workers-og";
4
+ export { ImageResponse, type ImageResponseOptions, OG_HEADERS, type OgFont, hasCJK, loadDefaultFonts, loadGoogleFont };
@@ -0,0 +1,3 @@
1
+ import { OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont } from "./fonts.js";
2
+ import { ImageResponse } from "workers-og";
3
+ export { ImageResponse, OG_HEADERS, hasCJK, loadDefaultFonts, loadGoogleFont };
package/package.json CHANGED
@@ -1,20 +1,41 @@
1
1
  {
2
2
  "name": "@junejs/og",
3
- "version": "0.0.4",
3
+ "version": "0.0.6-dev.0",
4
4
  "type": "module",
5
5
  "description": "June — cross-platform OG image generation. Cloudflare Workers, Vercel Edge, and Node.js dev all share one import; the right backend is selected at build time via export conditions.",
6
6
  "exports": {
7
7
  ".": {
8
- "workerd": "./src/workerd.ts",
9
- "edge-light": "./src/edge.ts",
10
- "default": "./src/node.ts"
8
+ "source": {
9
+ "workerd": "./src/workerd.ts",
10
+ "edge-light": "./src/edge.ts",
11
+ "default": "./src/node.ts"
12
+ },
13
+ "bun": {
14
+ "workerd": "./src/workerd.ts",
15
+ "edge-light": "./src/edge.ts",
16
+ "default": "./src/node.ts"
17
+ },
18
+ "workerd": {
19
+ "types": "./dist/workerd.d.ts",
20
+ "default": "./dist/workerd.js"
21
+ },
22
+ "edge-light": {
23
+ "types": "./dist/edge.d.ts",
24
+ "default": "./dist/edge.js"
25
+ },
26
+ "default": {
27
+ "types": "./dist/node.d.ts",
28
+ "default": "./dist/node.js"
29
+ }
11
30
  }
12
31
  },
13
32
  "files": [
33
+ "dist",
14
34
  "src"
15
35
  ],
16
36
  "scripts": {
17
- "typecheck": "tsc --noEmit"
37
+ "typecheck": "tsc --noEmit",
38
+ "build": "tsdown"
18
39
  },
19
40
  "keywords": [
20
41
  "june",
package/src/edge.ts CHANGED
@@ -1,6 +1,55 @@
1
- // Vercel Edge / edge-light backend — resolved when the build uses the "edge-light" condition.
2
- // @vercel/og bundles its own resvg WASM compatible with Vercel's Edge Runtime.
3
- export { ImageResponse } from "@vercel/og";
1
+ // Vercel / edge-light backend — resolved when the build uses the "edge-light" condition.
2
+ // @vercel/og renders OG images with its own resvg WASM (works on Vercel's Edge AND Node runtimes).
3
+ //
4
+ // @vercel/og is loaded LAZILY via `new Function("return import(m)")` (mirrors node.ts's satori/
5
+ // @resvg load) so the bundler never resolves it at build time. Its entry statically imports
6
+ // `./yoga.wasm?module`, which rolldown — June's worker bundler — can't bundle; a STATIC
7
+ // `export { ImageResponse } from "@vercel/og"` here dragged that WASM into EVERY worker carrying
8
+ // the OG route, breaking the build even when OG is prerendered to static files and @vercel/og is
9
+ // never called at runtime (externalizing doesn't help: an ESM static import is resolved at module
10
+ // load regardless of use). Lazy-loading defers it to first render — edge/Node OG works at runtime
11
+ // (the consumer installs @vercel/og), and a static-prerendered route, never invoked, pulls nothing.
12
+ import type { ReactElement } from "react";
4
13
  export type { ImageResponseOptions } from "./types";
5
14
  export { loadGoogleFont, loadDefaultFonts, hasCJK, OG_HEADERS } from "./fonts";
6
15
  export type { OgFont } from "./fonts";
16
+
17
+ type VercelImageResponse = new (element: ReactElement, options?: Record<string, unknown>) => Response;
18
+
19
+ // TypeScript cannot see through Function() — no static module resolution is attempted.
20
+ const _import = new Function("m", "return import(m)") as (m: string) => Promise<unknown>;
21
+
22
+ export class ImageResponse extends Response {
23
+ constructor(element: ReactElement, options: import("./types").ImageResponseOptions = {}) {
24
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
25
+ super(readable, {
26
+ status: options.status ?? 200,
27
+ headers: {
28
+ "cache-control": "public, max-age=86400, stale-while-revalidate=604800",
29
+ ...options.headers,
30
+ // Contract (types.ts): callers may merge/override any header EXCEPT content-type
31
+ // — set it last so it always wins and the body is always served as a PNG.
32
+ "content-type": "image/png",
33
+ },
34
+ });
35
+ (_import("@vercel/og") as Promise<{ ImageResponse: VercelImageResponse }>)
36
+ .then(({ ImageResponse: VercelOg }) => {
37
+ // Delegate the actual render to @vercel/og, then pipe its PNG body into ours
38
+ // (so our status/headers above win, matching node.ts's response shape). pipeTo
39
+ // handles backpressure, completion, and error propagation (it aborts `writable`
40
+ // if the source errors), so there's no hand-managed writer to get wrong.
41
+ const rendered = new VercelOg(element, {
42
+ width: options.width ?? 1200,
43
+ height: options.height ?? 630,
44
+ fonts: options.fonts,
45
+ emoji: options.emoji,
46
+ debug: options.debug,
47
+ });
48
+ return rendered.body ? rendered.body.pipeTo(writable) : writable.close();
49
+ })
50
+ // The lazy import or the render setup failed (a streaming error already aborted
51
+ // `writable` via pipeTo — the redundant abort is swallowed). Abort so the response
52
+ // errors instead of hanging.
53
+ .catch((err: unknown) => writable.abort(err).catch(() => {}));
54
+ }
55
+ }
package/src/node.ts CHANGED
@@ -22,9 +22,11 @@ export class ImageResponse extends Response {
22
22
  super(readable, {
23
23
  status: options.status ?? 200,
24
24
  headers: {
25
- "content-type": "image/png",
26
25
  "cache-control": "public, max-age=86400, stale-while-revalidate=604800",
27
26
  ...options.headers,
27
+ // Contract (types.ts): callers may merge/override any header EXCEPT content-type
28
+ // — set it last so it always wins and the body is always served as a PNG.
29
+ "content-type": "image/png",
28
30
  },
29
31
  });
30
32
  const writer = writable.getWriter();