nuxt-og-image 3.0.0-beta.3 → 3.0.0-beta.30

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.
Files changed (124) hide show
  1. package/README.md +3 -3
  2. package/dist/client/200.html +5 -5
  3. package/dist/client/404.html +5 -5
  4. package/dist/client/_nuxt/{IconCSS.e8427024.js → IconCSS.157c2ef5.js} +1 -1
  5. package/dist/client/_nuxt/IconCSS.7e8f1f7b.css +1 -0
  6. package/dist/client/_nuxt/builds/latest.json +1 -1
  7. package/dist/client/_nuxt/builds/meta/2f3b82b2-c809-4818-a70e-0a9fa0dde8cb.json +1 -0
  8. package/dist/client/_nuxt/entry.74866e06.js +137 -0
  9. package/dist/client/_nuxt/entry.f47d0628.css +1 -0
  10. package/dist/client/_nuxt/{error-404.b1c8e4c8.js → error-404.d663cd65.js} +1 -1
  11. package/dist/client/_nuxt/{error-500.6b97e3ab.js → error-500.8c184504.js} +1 -1
  12. package/dist/client/index.html +5 -5
  13. package/dist/module.d.mts +43 -25
  14. package/dist/module.d.ts +43 -25
  15. package/dist/module.json +2 -2
  16. package/dist/module.mjs +146 -93
  17. package/dist/runtime/cache.d.ts +7 -10
  18. package/dist/runtime/cache.mjs +40 -27
  19. package/dist/runtime/components/OgImage/OgImage.d.ts +5 -0
  20. package/dist/runtime/components/OgImage/{index.mjs → OgImage.mjs} +1 -1
  21. package/dist/runtime/components/OgImage/OgImageScreenshot.d.ts +5 -0
  22. package/dist/runtime/components/OgImage/{Screenshot.mjs → OgImageScreenshot.mjs} +1 -1
  23. package/dist/runtime/components/Templates/{Official → Community}/BrandedLogo.vue +3 -2
  24. package/dist/runtime/components/Templates/Community/Nuxt.vue +6 -5
  25. package/dist/runtime/components/Templates/Community/NuxtSeo.vue +137 -0
  26. package/dist/runtime/components/Templates/{Official → Community}/SimpleBlog.vue +7 -5
  27. package/dist/runtime/components/Templates/Community/UnJs.vue +108 -0
  28. package/dist/runtime/components/Templates/{Official → Community}/Wave.vue +3 -2
  29. package/dist/runtime/components/Templates/{Official → Community}/WithEmoji.vue +3 -2
  30. package/dist/runtime/composables/defineOgImage.d.ts +2 -23
  31. package/dist/runtime/composables/defineOgImage.mjs +33 -116
  32. package/dist/runtime/composables/defineOgImageComponent.d.ts +3 -0
  33. package/dist/runtime/composables/defineOgImageComponent.mjs +8 -0
  34. package/dist/runtime/composables/defineOgImageScreenshot.d.ts +2 -0
  35. package/dist/runtime/composables/defineOgImageScreenshot.mjs +14 -0
  36. package/dist/runtime/core/bindings/css-inline/node.d.ts +2 -5
  37. package/dist/runtime/core/bindings/css-inline/node.mjs +2 -10
  38. package/dist/runtime/core/bindings/resvg/wasm.mjs +2 -3
  39. package/dist/runtime/core/bindings/satori/wasm.mjs +7 -0
  40. package/dist/runtime/core/cache/emojis.d.ts +1 -0
  41. package/dist/runtime/core/cache/emojis.mjs +5 -0
  42. package/dist/runtime/core/cache/htmlPayload.d.ts +5 -0
  43. package/dist/runtime/core/cache/htmlPayload.mjs +6 -0
  44. package/dist/runtime/core/cache/prerender.d.ts +1 -1
  45. package/dist/runtime/core/font/fetch.d.ts +2 -3
  46. package/dist/runtime/core/font/fetch.mjs +20 -8
  47. package/dist/runtime/core/html/applyEmojis.d.ts +3 -0
  48. package/dist/runtime/core/html/applyEmojis.mjs +37 -0
  49. package/dist/runtime/core/html/applyInlineCss.d.ts +3 -0
  50. package/dist/runtime/core/html/applyInlineCss.mjs +32 -0
  51. package/dist/runtime/core/html/devIframeTemplate.d.ts +2 -0
  52. package/dist/runtime/core/html/{fetch.mjs → devIframeTemplate.mjs} +33 -42
  53. package/dist/runtime/core/html/fetchIsland.d.ts +3 -0
  54. package/dist/runtime/core/html/fetchIsland.mjs +17 -0
  55. package/dist/runtime/core/options/fetch.d.ts +1 -1
  56. package/dist/runtime/core/options/fetch.mjs +10 -5
  57. package/dist/runtime/core/options/normalise.d.ts +2 -2
  58. package/dist/runtime/core/options/normalise.mjs +3 -2
  59. package/dist/runtime/core/renderers/chromium/index.mjs +6 -7
  60. package/dist/runtime/core/renderers/chromium/screenshot.d.ts +2 -3
  61. package/dist/runtime/core/renderers/chromium/screenshot.mjs +5 -4
  62. package/dist/runtime/core/renderers/satori/fonts.d.ts +2 -2
  63. package/dist/runtime/core/renderers/satori/fonts.mjs +2 -2
  64. package/dist/runtime/core/renderers/satori/index.d.ts +2 -3
  65. package/dist/runtime/core/renderers/satori/index.mjs +25 -22
  66. package/dist/runtime/core/renderers/satori/instances.d.ts +3 -0
  67. package/dist/runtime/core/renderers/satori/instances.mjs +15 -0
  68. package/dist/runtime/core/renderers/satori/plugins/emojis.mjs +15 -13
  69. package/dist/runtime/core/renderers/satori/plugins/imageSrc.mjs +8 -4
  70. package/dist/runtime/core/renderers/satori/plugins/unocss.d.ts +2 -0
  71. package/dist/runtime/core/renderers/satori/plugins/unocss.mjs +38 -0
  72. package/dist/runtime/core/renderers/satori/utils.d.ts +2 -3
  73. package/dist/runtime/core/renderers/satori/vnodes.d.ts +2 -3
  74. package/dist/runtime/core/renderers/satori/vnodes.mjs +16 -6
  75. package/dist/runtime/core/utils/resolveRendererContext.d.ts +2 -6
  76. package/dist/runtime/core/utils/resolveRendererContext.mjs +46 -23
  77. package/dist/runtime/core/utils/wasm.d.ts +1 -0
  78. package/dist/runtime/core/utils/wasm.mjs +10 -0
  79. package/dist/runtime/nitro/plugins/nuxt-content.mjs +3 -4
  80. package/dist/runtime/nitro/plugins/prerender.d.ts +1 -1
  81. package/dist/runtime/nitro/plugins/prerender.mjs +13 -5
  82. package/dist/runtime/nuxt/plugins/og-image-canonical-urls.server.mjs +31 -0
  83. package/dist/runtime/nuxt/plugins/route-rule-og-image.server.mjs +16 -50
  84. package/dist/runtime/nuxt/utils.d.ts +2 -0
  85. package/dist/runtime/nuxt/utils.mjs +53 -0
  86. package/dist/runtime/server/routes/__og-image__/debug.json.d.ts +1 -3
  87. package/dist/runtime/server/routes/__og-image__/debug.json.mjs +4 -8
  88. package/dist/runtime/server/routes/__og-image__/image.mjs +87 -0
  89. package/dist/runtime/types.d.ts +74 -25
  90. package/dist/runtime/utils.d.ts +4 -0
  91. package/dist/runtime/utils.mjs +11 -0
  92. package/dist/runtime/utils.pure.d.ts +5 -0
  93. package/dist/runtime/utils.pure.mjs +43 -0
  94. package/package.json +27 -29
  95. package/virtual.d.ts +49 -0
  96. package/dist/client/_nuxt/IconCSS.8f429b14.css +0 -1
  97. package/dist/client/_nuxt/builds/meta/af7b6f15-8224-4a19-bb3a-f685b2b145c3.json +0 -1
  98. package/dist/client/_nuxt/entry.434c2c45.css +0 -1
  99. package/dist/client/_nuxt/entry.8ea61ef1.js +0 -137
  100. package/dist/client/grid.png +0 -0
  101. package/dist/runtime/components/OgImage/Cached.d.ts +0 -5
  102. package/dist/runtime/components/OgImage/Cached.mjs +0 -10
  103. package/dist/runtime/components/OgImage/Dynamic.d.ts +0 -8
  104. package/dist/runtime/components/OgImage/Dynamic.mjs +0 -10
  105. package/dist/runtime/components/OgImage/Screenshot.d.ts +0 -6
  106. package/dist/runtime/components/OgImage/Static.d.ts +0 -8
  107. package/dist/runtime/components/OgImage/Static.mjs +0 -10
  108. package/dist/runtime/components/OgImage/WithoutCache.d.ts +0 -5
  109. package/dist/runtime/components/OgImage/WithoutCache.mjs +0 -10
  110. package/dist/runtime/components/OgImage/index.d.ts +0 -5
  111. package/dist/runtime/components/Templates/Official/Fallback.vue +0 -147
  112. package/dist/runtime/core/bindings/css-inline/mock.d.ts +0 -5
  113. package/dist/runtime/core/bindings/css-inline/mock.mjs +0 -3
  114. package/dist/runtime/core/bindings/satori/yoga-wasm.mjs +0 -7
  115. package/dist/runtime/core/bindings/sharp/wasm.d.ts +0 -2
  116. package/dist/runtime/core/bindings/sharp/wasm.mjs +0 -2
  117. package/dist/runtime/core/html/fetch.d.ts +0 -3
  118. package/dist/runtime/nuxt/plugins/nuxt-content-canonical-urls.mjs +0 -29
  119. package/dist/runtime/server/routes/__og-image__/image-[path]-og.[extension].mjs +0 -45
  120. package/dist/runtime/utilts.d.ts +0 -2
  121. package/dist/runtime/utilts.mjs +0 -8
  122. /package/dist/runtime/core/bindings/satori/{yoga-wasm.d.ts → wasm.d.ts} +0 -0
  123. /package/dist/runtime/nuxt/plugins/{nuxt-content-canonical-urls.d.ts → og-image-canonical-urls.server.d.ts} +0 -0
  124. /package/dist/runtime/server/routes/__og-image__/{image-[path]-og.[extension].d.ts → image.d.ts} +0 -0
@@ -6,8 +6,9 @@ import { toBase64Image } from "../../../env/assets.mjs";
6
6
  import { useNitroOrigin } from "#imports";
7
7
  export default defineSatoriTransformer({
8
8
  filter: (node) => node.type === "img",
9
- transform: async (node, e) => {
9
+ transform: async (node, { e }) => {
10
10
  const src = node.props?.src;
11
+ const isRelative = src?.startsWith("/");
11
12
  if (src) {
12
13
  let updated = false;
13
14
  let dimensions;
@@ -21,8 +22,11 @@ export default defineSatoriTransformer({
21
22
  });
22
23
  if (valid) {
23
24
  node.props.src = toBase64Image(src, response);
24
- const imageSize = sizeOf(Buffer.from(response));
25
- dimensions = { width: imageSize.width, height: imageSize.height };
25
+ try {
26
+ const imageSize = sizeOf(Buffer.from(response));
27
+ dimensions = { width: imageSize.width, height: imageSize.height };
28
+ } catch (e2) {
29
+ }
26
30
  updated = true;
27
31
  }
28
32
  }
@@ -37,7 +41,7 @@ export default defineSatoriTransformer({
37
41
  node.props.height = dimensions.height;
38
42
  }
39
43
  }
40
- if (!updated) {
44
+ if (!updated && isRelative) {
41
45
  node.props.src = `${withBase(src, `${useNitroOrigin(e)}`)}?${Date.now()}`;
42
46
  }
43
47
  }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../../../types").SatoriTransformer | import("../../../../types").SatoriTransformer[];
2
+ export default _default;
@@ -0,0 +1,38 @@
1
+ import { createGenerator } from "@unocss/core";
2
+ import presetWind from "@unocss/preset-wind";
3
+ import { defineSatoriTransformer } from "../utils.mjs";
4
+ import { theme } from "#nuxt-og-image/unocss-config.mjs";
5
+ const uno = createGenerator({ theme }, {
6
+ presets: [
7
+ presetWind()
8
+ ]
9
+ });
10
+ export default defineSatoriTransformer({
11
+ filter: (node) => !!node.props?.class,
12
+ transform: async (node) => {
13
+ const classes = node.props.class || "";
14
+ const styles = node.props.style || {};
15
+ const replacedClasses = /* @__PURE__ */ new Set();
16
+ for (const token of classes.split(" ").filter((c) => c.trim())) {
17
+ const parsedToken = await uno.parseToken(token);
18
+ if (parsedToken) {
19
+ const inlineStyles = parsedToken[0][2].split(";").filter((s) => !!s?.trim());
20
+ const vars = {};
21
+ inlineStyles.filter((s) => s.startsWith("--")).forEach((s) => {
22
+ const [key, value] = s.split(":");
23
+ vars[key] = value;
24
+ });
25
+ inlineStyles.filter((s) => !s.startsWith("--")).forEach((s) => {
26
+ const [key, value] = s.split(":");
27
+ const camelCasedKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
28
+ if (!styles[camelCasedKey])
29
+ styles[camelCasedKey] = value.replace(/var\((.*?)\)/g, (_, k) => vars[k.trim()]);
30
+ });
31
+ replacedClasses.add(token);
32
+ }
33
+ }
34
+ node.props.class = classes.split(" ").filter((c) => !replacedClasses.has(c)).join(" ");
35
+ node.props.tw = classes.split(" ").filter((c) => !replacedClasses.has(c)).join(" ");
36
+ node.props.style = styles;
37
+ }
38
+ });
@@ -1,4 +1,3 @@
1
- import type { H3Event } from 'h3';
2
- import type { SatoriTransformer, VNode } from '../../../types';
3
- export declare function walkSatoriTree(e: H3Event, node: VNode, plugins: (SatoriTransformer | SatoriTransformer[])[]): Promise<void>;
1
+ import type { H3EventOgImageRender, SatoriTransformer, VNode } from '../../../types';
2
+ export declare function walkSatoriTree(e: H3EventOgImageRender, node: VNode, plugins: (SatoriTransformer | SatoriTransformer[])[]): Promise<void>;
4
3
  export declare function defineSatoriTransformer(transformer: SatoriTransformer | SatoriTransformer[]): SatoriTransformer | SatoriTransformer[];
@@ -1,3 +1,2 @@
1
- import type { H3Event } from 'h3';
2
- import type { RendererOptions, VNode } from '../../../types';
3
- export declare function createVNodes(e: H3Event, options: RendererOptions): Promise<VNode>;
1
+ import type { H3EventOgImageRender, VNode } from '../../../types';
2
+ export declare function createVNodes(ctx: H3EventOgImageRender): Promise<VNode>;
@@ -1,16 +1,26 @@
1
1
  import { html as convertHtmlToSatori } from "satori-html";
2
- import { fetchHTML } from "../../html/fetch.mjs";
2
+ import { fetchIsland } from "../../html/fetchIsland.mjs";
3
+ import { applyInlineCss } from "../../html/applyInlineCss.mjs";
4
+ import { applyEmojis } from "../../html/applyEmojis.mjs";
3
5
  import { walkSatoriTree } from "./utils.mjs";
6
+ import unocss from "./plugins/unocss.mjs";
4
7
  import emojis from "./plugins/emojis.mjs";
5
8
  import twClasses from "./plugins/twClasses.mjs";
6
9
  import imageSrc from "./plugins/imageSrc.mjs";
7
10
  import flex from "./plugins/flex.mjs";
8
11
  import encoding from "./plugins/encoding.mjs";
9
- export async function createVNodes(e, options) {
10
- const html = options.html || await fetchHTML(e, options);
11
- const body = html.match(/<body[^>]*>([\s\S]*)<\/body>/)?.[1] || html;
12
- const satoriTree = convertHtmlToSatori(body);
13
- await walkSatoriTree(e, satoriTree, [
12
+ export async function createVNodes(ctx) {
13
+ let html = ctx.options.html;
14
+ if (!html) {
15
+ const island = await fetchIsland(ctx);
16
+ await applyInlineCss(ctx, island);
17
+ await applyEmojis(ctx, island);
18
+ html = island.html;
19
+ }
20
+ const template = `<div data-v-inspector-ignore="true" style="position: relative; display: flex; margin: 0 auto; width: ${ctx.options.width}px; height: ${ctx.options.height}px; overflow: hidden;">${html}</div>`;
21
+ const satoriTree = convertHtmlToSatori(template);
22
+ await walkSatoriTree(ctx, satoriTree, [
23
+ unocss,
14
24
  emojis,
15
25
  twClasses,
16
26
  imageSrc,
@@ -1,7 +1,3 @@
1
1
  import type { H3Error, H3Event } from 'h3';
2
- import type { Renderer, RuntimeOgImageOptions } from '../../types';
3
- export declare function resolveRendererContext(e: H3Event): Promise<H3Error | {
4
- extension: RuntimeOgImageOptions['extension'];
5
- renderer: Renderer;
6
- options: RuntimeOgImageOptions;
7
- }>;
2
+ import type { H3EventOgImageRender } from '../../types';
3
+ export declare function resolveRendererContext(e: H3Event): Promise<H3Error | H3EventOgImageRender>;
@@ -2,13 +2,14 @@ import { parseURL, withoutBase, withoutLeadingSlash, withoutTrailingSlash } from
2
2
  import { createError, getQuery } from "h3";
3
3
  import { defu } from "defu";
4
4
  import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
5
+ import { hash } from "ohash";
5
6
  import { fetchPathHtmlAndExtractOptions } from "../options/fetch.mjs";
6
7
  import { prerenderCache } from "../cache/prerender.mjs";
7
- import { useRuntimeConfig } from "#imports";
8
- const satoriRendererInstance = { instance: void 0 };
9
- const chromiumRendererInstance = { instance: void 0 };
8
+ import { useChromiumRenderer, useSatoriRenderer } from "../renderers/satori/instances.mjs";
9
+ import { separateProps, useOgImageRuntimeConfig } from "../../utils.mjs";
10
+ import { useRuntimeConfig, useSiteConfig } from "#imports";
10
11
  export async function resolveRendererContext(e) {
11
- const runtimeConfig = useRuntimeConfig()["nuxt-og-image"];
12
+ const runtimeConfig = useOgImageRuntimeConfig();
12
13
  const path = parseURL(e.path).pathname;
13
14
  const extension = path.split(".").pop();
14
15
  if (!extension) {
@@ -17,22 +18,37 @@ export async function resolveRendererContext(e) {
17
18
  statusMessage: `Missing OG Image type.`
18
19
  });
19
20
  }
21
+ if (!["png", "jpeg", "jpg", "svg", "html", "json"].includes(extension)) {
22
+ return createError({
23
+ statusCode: 400,
24
+ statusMessage: `Unknown OG Image type ${extension}.`
25
+ });
26
+ }
20
27
  const basePath = withoutTrailingSlash(
21
- path.replace("/__og-image__/image", "").replace(`/og.${extension}`, "")
28
+ path.replace(`/__og-image__/image`, "").replace(`/og.${extension}`, "")
22
29
  );
23
- const queryParams = { ...getQuery(e) };
30
+ let queryParams = { ...getQuery(e) };
31
+ queryParams.props = JSON.parse(queryParams.props || "{}");
32
+ queryParams = separateProps(queryParams);
33
+ const isDebugJsonPayload = extension === "json" && runtimeConfig.debug;
34
+ const siteConfig = useSiteConfig(e);
35
+ const key = [
36
+ withoutLeadingSlash(basePath === "/" || !basePath ? "index" : basePath).replaceAll("/", "-"),
37
+ hash([
38
+ basePath,
39
+ siteConfig.url,
40
+ hash(queryParams)
41
+ ])
42
+ ].join(":");
24
43
  let options = queryParams.options;
25
44
  if (!options) {
26
45
  if (import.meta.prerender) {
27
- const key = [
28
- withoutLeadingSlash(basePath === "/" || !basePath ? "index" : basePath).replaceAll("/", "-")
29
- ].join(":");
30
46
  options = await prerenderCache?.getItem(key);
31
47
  } else {
32
- const payloadOptions = await fetchPathHtmlAndExtractOptions(e, basePath);
33
- if (payloadOptions instanceof Error)
34
- return payloadOptions;
35
- options = payloadOptions;
48
+ const payload = await fetchPathHtmlAndExtractOptions(e, basePath, key);
49
+ if (payload instanceof Error)
50
+ return payload;
51
+ options = payload;
36
52
  }
37
53
  }
38
54
  delete queryParams.options;
@@ -41,8 +57,15 @@ export async function resolveRendererContext(e) {
41
57
  );
42
58
  const routeRules = defu({}, ..._routeRulesMatcher.matchAll(
43
59
  withoutBase(basePath.split("?")[0], useRuntimeConfig().app.baseURL)
44
- ).reverse()).ogImage;
45
- options = defu(queryParams, routeRules, options, runtimeConfig.defaults);
60
+ ).reverse());
61
+ if (typeof routeRules.ogImage === "undefined" && !options) {
62
+ return createError({
63
+ statusCode: 400,
64
+ statusMessage: "The route is missing the Nuxt OG Image payload or route rules."
65
+ });
66
+ }
67
+ const ogImageRouteRules = separateProps(routeRules.ogImage);
68
+ options = defu(queryParams, ogImageRouteRules, options, runtimeConfig.defaults);
46
69
  if (!options) {
47
70
  return createError({
48
71
  statusCode: 404,
@@ -52,25 +75,25 @@ export async function resolveRendererContext(e) {
52
75
  let renderer;
53
76
  switch (options.renderer) {
54
77
  case "satori":
55
- renderer = satoriRendererInstance.instance = satoriRendererInstance.instance || await import("#nuxt-og-image/renderers/satori").then((m) => Object.keys(m.default).length ? m.default : false);
78
+ renderer = await useSatoriRenderer();
56
79
  break;
57
80
  case "chromium":
58
- renderer = chromiumRendererInstance.instance = chromiumRendererInstance.instance || await import("#nuxt-og-image/renderers/chromium").then((m) => Object.keys(m.default).length ? m.default : false);
81
+ renderer = await useChromiumRenderer();
59
82
  break;
60
83
  }
61
- if (!renderer) {
84
+ if (!renderer || renderer.__unenv__) {
62
85
  throw createError({
63
86
  statusCode: 400,
64
87
  statusMessage: `Renderer ${options.renderer} is missing.`
65
88
  });
66
89
  }
67
90
  return {
91
+ e,
92
+ key,
68
93
  renderer,
94
+ isDebugJsonPayload,
69
95
  extension,
70
- options: {
71
- ...options,
72
- extension: extension === "json" ? options.extension : extension,
73
- path: basePath
74
- }
96
+ basePath,
97
+ options
75
98
  };
76
99
  }
@@ -0,0 +1 @@
1
+ export declare function importWasm(input: any): Promise<any>;
@@ -0,0 +1,10 @@
1
+ export async function importWasm(input) {
2
+ const _input = await input;
3
+ const _module = _input.default || _input;
4
+ if (typeof _module === "function") {
5
+ const fnRes = await _module();
6
+ const _instance = fnRes.instance || fnRes;
7
+ return _instance.exports || _instance || _module;
8
+ }
9
+ return _module;
10
+ }
@@ -1,16 +1,15 @@
1
1
  import { defineNitroPlugin } from "nitropack/dist/runtime/plugin";
2
2
  import { defu } from "defu";
3
- import { getOgImagePath } from "../../utilts.mjs";
4
- import { useRuntimeConfig } from "#imports";
3
+ import { getOgImagePath, useOgImageRuntimeConfig } from "../../utils.mjs";
5
4
  export default defineNitroPlugin((nitroApp) => {
6
5
  nitroApp.hooks.hook("content:file:afterParse", async (content) => {
7
6
  if (content._draft || content._extension !== "md" || content._partial || content.indexable === false || content.index === false)
8
7
  return;
9
8
  if (content.path && content.ogImage) {
10
9
  const ogImageConfig = typeof content.ogImage === "object" ? content.ogImage : {};
11
- const { defaults } = useRuntimeConfig()["nuxt-og-image"];
10
+ const { defaults } = useOgImageRuntimeConfig();
12
11
  const optionsWithDefault = defu(ogImageConfig, defaults);
13
- const src = getOgImagePath(content.path, optionsWithDefault.extension);
12
+ const src = getOgImagePath(content.path, optionsWithDefault);
14
13
  const payload = {
15
14
  title: content.title,
16
15
  excerpt: content.description || content.excerpt,
@@ -1,2 +1,2 @@
1
- declare const _default: import("nitropack/dist/runtime/plugin").NitroAppPlugin;
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
2
  export default _default;
@@ -1,9 +1,11 @@
1
- import { parseURL, withoutLeadingSlash } from "ufo";
2
- import { getRouteRules } from "nitropack/dist/runtime/route-rules";
1
+ import { parseURL, withoutBase, withoutLeadingSlash } from "ufo";
2
+ import { defineNitroPlugin } from "nitropack/dist/runtime/plugin";
3
+ import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
4
+ import { defu } from "defu";
3
5
  import { extractAndNormaliseOgImageOptions } from "../../core/options/extract.mjs";
4
6
  import { prerenderCache, prerenderChromiumContext } from "../../core/cache/prerender.mjs";
5
- import { isInternalRoute } from "../../utilts.mjs";
6
- import { defineNitroPlugin } from "nitropack/dist/runtime/plugin";
7
+ import { isInternalRoute } from "../../utils.pure.mjs";
8
+ import { useRuntimeConfig } from "#imports";
7
9
  export default defineNitroPlugin(async (nitro) => {
8
10
  if (!import.meta.prerender)
9
11
  return;
@@ -11,7 +13,13 @@ export default defineNitroPlugin(async (nitro) => {
11
13
  const path = parseURL(e.event.path).pathname;
12
14
  if (isInternalRoute(path))
13
15
  return;
14
- const routeRules = getRouteRules(e)?.ogImage || {};
16
+ const runtimeConfig = useRuntimeConfig();
17
+ const _routeRulesMatcher = toRouteMatcher(
18
+ createRadixRouter({ routes: runtimeConfig.nitro?.routeRules })
19
+ );
20
+ const routeRules = defu({}, ..._routeRulesMatcher.matchAll(
21
+ withoutBase(path.split("?")[0], runtimeConfig.app.baseURL)
22
+ ).reverse()).ogImage;
15
23
  if (routeRules === false)
16
24
  return;
17
25
  const options = extractAndNormaliseOgImageOptions([
@@ -0,0 +1,31 @@
1
+ import { parseURL } from "ufo";
2
+ import { toValue } from "vue";
3
+ import { isInternalRoute } from "../../utils.pure.mjs";
4
+ import { defineNuxtPlugin, useRequestEvent, withSiteUrl } from "#imports";
5
+ export default defineNuxtPlugin({
6
+ setup(nuxtApp) {
7
+ nuxtApp.hooks.hook("app:rendered", async (ctx) => {
8
+ const { ssrContext } = ctx;
9
+ const e = useRequestEvent();
10
+ const path = parseURL(e.path).pathname;
11
+ if (isInternalRoute(path))
12
+ return;
13
+ ssrContext?.head.use({
14
+ key: "nuxt-og-image:canonical-urls",
15
+ hooks: {
16
+ "tags:resolve": async ({ tags }) => {
17
+ for (const tag of tags) {
18
+ if (tag.tag === "meta" && (tag.props.property === "og:image" || tag.props.name === "twitter:image:src")) {
19
+ if (!tag.props.content.startsWith("https")) {
20
+ await nuxtApp.runWithContext(() => {
21
+ tag.props.content = toValue(withSiteUrl(tag.props.content));
22
+ });
23
+ }
24
+ }
25
+ }
26
+ }
27
+ }
28
+ });
29
+ });
30
+ }
31
+ });
@@ -2,8 +2,9 @@ import { defu } from "defu";
2
2
  import { parseURL, withoutBase } from "ufo";
3
3
  import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
4
4
  import { normaliseOptions } from "../../core/options/normalise.mjs";
5
- import { getOgImagePath, isInternalRoute } from "../../utilts.mjs";
6
- import { defineNuxtPlugin, useRequestEvent, useRuntimeConfig } from "#imports";
5
+ import { getOgImagePath, isInternalRoute, useOgImageRuntimeConfig } from "../../utils.mjs";
6
+ import { createOgImageMeta } from "../utils.mjs";
7
+ import { defineNuxtPlugin, useRequestEvent } from "#imports";
7
8
  export default defineNuxtPlugin((nuxtApp) => {
8
9
  nuxtApp.hooks.hook("app:rendered", async (ctx) => {
9
10
  const { ssrContext } = ctx;
@@ -14,59 +15,24 @@ export default defineNuxtPlugin((nuxtApp) => {
14
15
  const _routeRulesMatcher = toRouteMatcher(
15
16
  createRadixRouter({ routes: ssrContext?.runtimeConfig?.nitro?.routeRules })
16
17
  );
17
- const routeRules = defu({}, ..._routeRulesMatcher.matchAll(
18
+ let routeRules = defu({}, ..._routeRulesMatcher.matchAll(
18
19
  withoutBase(path.split("?")[0], ssrContext?.runtimeConfig?.app.baseURL)
19
20
  ).reverse()).ogImage;
20
21
  if (typeof routeRules === "undefined")
21
22
  return;
22
- const payloadIndex = ssrContext.head.headEntries().findIndex((entry) => {
23
- return entry.input?.script?.[0]?.id === "nuxt-og-image-options";
24
- });
25
- if (payloadIndex >= 0 && routeRules === false) {
26
- ssrContext.head.headEntries().splice(payloadIndex, 1);
23
+ const ogImageInstances = nuxtApp.ssrContext._ogImageInstances || [];
24
+ if (routeRules === false) {
25
+ ogImageInstances?.forEach((e2) => {
26
+ e2.dispose();
27
+ });
28
+ nuxtApp.ssrContext._ogImagePayload = void 0;
29
+ nuxtApp.ssrContext._ogImageInstances = void 0;
27
30
  return;
28
31
  }
29
- if (payloadIndex >= 0)
30
- return;
31
- const options = normaliseOptions(routeRules);
32
- const { defaults } = useRuntimeConfig()["nuxt-og-image"];
33
- const optionsWithDefault = normaliseOptions(defu(options, defaults));
34
- const src = getOgImagePath(ssrContext.url, optionsWithDefault.extension);
35
- ssrContext?.head.push({
36
- script: [
37
- {
38
- id: "nuxt-og-image-options",
39
- type: "application/json",
40
- processTemplateParams: true,
41
- innerHTML: () => {
42
- const payload = {
43
- title: "%s"
44
- };
45
- Object.entries(options).forEach(([key, val]) => {
46
- payload[key.replace(/-([a-z])/g, (g) => g[1].toUpperCase())] = val;
47
- });
48
- return payload;
49
- },
50
- // we want this to be last in our head
51
- tagPosition: "bodyClose"
52
- }
53
- ],
54
- meta: [
55
- { property: "og:image", content: src },
56
- { property: "og:image:width", content: optionsWithDefault.width },
57
- { property: "og:image:height", content: optionsWithDefault.height },
58
- { property: "og:image:type", content: `image/${optionsWithDefault.extension}` },
59
- { property: "og:image:alt", content: optionsWithDefault.alt },
60
- // twitter
61
- { name: "twitter:card", content: "summary_large_image" },
62
- { name: "twitter:image:src", content: src },
63
- { name: "twitter:image:width", content: optionsWithDefault.width },
64
- { name: "twitter:image:height", content: optionsWithDefault.height },
65
- { name: "twitter:image:alt", content: optionsWithDefault.alt }
66
- ]
67
- }, {
68
- mode: "server",
69
- tagPriority: 35
70
- });
32
+ routeRules = defu(nuxtApp.ssrContext?.event.context._nitro?.routeRules?.ogImage, routeRules);
33
+ const { defaults } = useOgImageRuntimeConfig();
34
+ const resolvedOptions = normaliseOptions(defu(routeRules, defaults));
35
+ const src = getOgImagePath(ssrContext.url, resolvedOptions);
36
+ createOgImageMeta(src, routeRules, resolvedOptions, nuxtApp.ssrContext);
71
37
  });
72
38
  });
@@ -0,0 +1,2 @@
1
+ import type { OgImageOptions, OgImagePrebuilt } from '../types';
2
+ export declare function createOgImageMeta(src: string | null, input: OgImageOptions | OgImagePrebuilt, resolvedOptions: OgImageOptions, ssrContext: Record<string, any>): void;
@@ -0,0 +1,53 @@
1
+ import { defu } from "defu";
2
+ import { separateProps } from "../utils.mjs";
3
+ import { useServerHead } from "#imports";
4
+ export function createOgImageMeta(src, input, resolvedOptions, ssrContext) {
5
+ const _input = separateProps(defu(input, ssrContext._ogImagePayload));
6
+ const url = src || input.url || resolvedOptions.url;
7
+ let urlExtension = (url.split("/").pop() || url).split(".").pop() || resolvedOptions.extension;
8
+ if (urlExtension === "jpg")
9
+ urlExtension = "jpeg";
10
+ const meta = [
11
+ { property: "og:image", content: url },
12
+ { property: "og:image:type", content: `image/${urlExtension}` },
13
+ { name: "twitter:card", content: "summary_large_image" },
14
+ { name: "twitter:image:src", content: url }
15
+ ];
16
+ if (resolvedOptions.width) {
17
+ meta.push({ property: "og:image:width", content: resolvedOptions.width });
18
+ meta.push({ name: "twitter:image:width", content: resolvedOptions.width });
19
+ }
20
+ if (resolvedOptions.height) {
21
+ meta.push({ property: "og:image:height", content: resolvedOptions.height });
22
+ meta.push({ name: "twitter:image:height", content: resolvedOptions.height });
23
+ }
24
+ if (resolvedOptions.alt) {
25
+ meta.push({ property: "og:image:alt", content: resolvedOptions.alt });
26
+ meta.push({ name: "twitter:image:alt", content: resolvedOptions.alt });
27
+ }
28
+ ssrContext._ogImageInstances = ssrContext._ogImageInstances || [];
29
+ const script = [];
30
+ if (src) {
31
+ script.push({
32
+ id: "nuxt-og-image-options",
33
+ type: "application/json",
34
+ processTemplateParams: true,
35
+ innerHTML: () => {
36
+ if (!_input.props.title)
37
+ _input.props.title = "%s";
38
+ delete _input.url;
39
+ return _input;
40
+ },
41
+ // we want this to be last in our head
42
+ tagPosition: "bodyClose"
43
+ });
44
+ }
45
+ const instance = useServerHead({
46
+ script,
47
+ meta
48
+ }, {
49
+ tagPriority: 35
50
+ });
51
+ ssrContext._ogImagePayload = _input;
52
+ ssrContext._ogImageInstances.push(instance);
53
+ }
@@ -4,8 +4,6 @@ declare const _default: import("h3").EventHandler<import("h3").EventHandlerReque
4
4
  source: any;
5
5
  };
6
6
  componentNames: any;
7
- runtimeConfig: any;
8
- baseCacheKey: string;
9
- cachedKeys: string[];
7
+ runtimeConfig: import("../../../types").OgImageRuntimeConfig;
10
8
  }>>;
11
9
  export default _default;
@@ -1,21 +1,17 @@
1
1
  import { defineEventHandler, setHeader } from "h3";
2
- import { prefixStorage } from "unstorage";
3
- import { useRuntimeConfig, useSiteConfig, useStorage } from "#imports";
2
+ import { useOgImageRuntimeConfig } from "../../../utils.mjs";
3
+ import { useSiteConfig } from "#imports";
4
4
  import { componentNames } from "#nuxt-og-image/component-names.mjs";
5
5
  export default defineEventHandler(async (e) => {
6
6
  setHeader(e, "Content-Type", "application/json");
7
- const runtimeConfig = useRuntimeConfig()["nuxt-og-image"];
7
+ const runtimeConfig = useOgImageRuntimeConfig();
8
8
  const siteConfig = await useSiteConfig(e, { debug: true });
9
- const baseCacheKey = runtimeConfig.runtimeCacheStorage === "default" ? `/cache/nuxt-og-image@${runtimeConfig.version}` : `/nuxt-og-image@${runtimeConfig.version}`;
10
- const cache = prefixStorage(useStorage(), `${baseCacheKey}/`);
11
9
  return {
12
10
  siteConfigUrl: {
13
11
  value: siteConfig.url,
14
12
  source: siteConfig._context.url || "unknown"
15
13
  },
16
14
  componentNames,
17
- runtimeConfig,
18
- baseCacheKey,
19
- cachedKeys: await cache.getKeys()
15
+ runtimeConfig
20
16
  };
21
17
  });
@@ -0,0 +1,87 @@
1
+ import { H3Error, createError, defineEventHandler, getQuery, setHeader } from "h3";
2
+ import { resolveRendererContext } from "../../../core/utils/resolveRendererContext.mjs";
3
+ import { fetchIsland } from "../../../core/html/fetchIsland.mjs";
4
+ import { devIframeTemplate } from "../../../core/html/devIframeTemplate.mjs";
5
+ import { applyInlineCss } from "../../../core/html/applyInlineCss.mjs";
6
+ import { useOgImageBufferCache } from "../../../cache.mjs";
7
+ import { useOgImageRuntimeConfig } from "../../../utils.mjs";
8
+ import { useSiteConfig } from "#imports";
9
+ export default defineEventHandler(async (e) => {
10
+ const ctx = await resolveRendererContext(e);
11
+ if (ctx instanceof H3Error)
12
+ return ctx;
13
+ const { isDebugJsonPayload, extension, options, renderer } = ctx;
14
+ const { debug, baseCacheKey } = useOgImageRuntimeConfig();
15
+ const compatibility = [];
16
+ if (isDebugJsonPayload) {
17
+ const queryExtension = getQuery(e).extension || ctx.options.extension;
18
+ if (["jpeg", "jpg"].includes(queryExtension) && options.renderer === "satori")
19
+ compatibility.push("Converting PNGs to JPEGs requires Sharp which only runs on Node based systems.");
20
+ if (options.renderer === "chromium")
21
+ compatibility.push("Using Chromium to generate images is only supported in Node based environments. It's recommended to only use this if you're prerendering");
22
+ if (await applyInlineCss(ctx, await fetchIsland(ctx)))
23
+ compatibility.push("Inlining CSS is only supported in Node based environments.");
24
+ setHeader(e, "Content-Type", "application/json");
25
+ return {
26
+ compatibility,
27
+ ...ctx,
28
+ siteConfig: useSiteConfig(e),
29
+ ...options.renderer === "satori" ? await renderer.debug(ctx) : void 0
30
+ };
31
+ }
32
+ switch (extension) {
33
+ case "html":
34
+ setHeader(e, "Content-Type", `text/html`);
35
+ return devIframeTemplate(ctx);
36
+ case "svg":
37
+ if (!debug && !import.meta.dev) {
38
+ return createError({
39
+ statusCode: 404
40
+ });
41
+ }
42
+ if (ctx.renderer.name !== "satori") {
43
+ return createError({
44
+ statusCode: 400,
45
+ statusMessage: `Generating ${extension}'s with ${renderer.name} is not supported.`
46
+ });
47
+ }
48
+ setHeader(e, "Content-Type", `image/svg+xml`);
49
+ return (await ctx.renderer.debug(ctx)).svg;
50
+ case "png":
51
+ case "jpeg":
52
+ case "jpg":
53
+ if (!renderer.supportedFormats.includes(extension)) {
54
+ return createError({
55
+ statusCode: 400,
56
+ statusMessage: `Generating ${extension}'s with ${renderer.name} is not supported.`
57
+ });
58
+ }
59
+ setHeader(e, "Content-Type", `image/${extension === "jpg" ? "jpeg" : extension}`);
60
+ break;
61
+ default:
62
+ return createError({
63
+ statusCode: 400,
64
+ statusMessage: `Invalid request for og.${extension}.`
65
+ });
66
+ }
67
+ const cacheApi = await useOgImageBufferCache(ctx, {
68
+ cacheMaxAgeSeconds: ctx.options.cacheMaxAgeSeconds,
69
+ baseCacheKey
70
+ });
71
+ if (typeof cacheApi === "undefined")
72
+ return;
73
+ let image = cacheApi.cachedItem;
74
+ if (!image) {
75
+ image = await renderer.createImage(ctx);
76
+ if (image instanceof H3Error)
77
+ return image;
78
+ if (!image) {
79
+ return createError({
80
+ statusCode: 500,
81
+ statusMessage: `Failed to generate og.${extension}.`
82
+ });
83
+ }
84
+ await cacheApi.update(image);
85
+ }
86
+ return image;
87
+ });