nuxt-og-image 7.1.1 → 7.2.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.
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import { pathToFileURL } from 'node:url';
3
3
  import { resolveModulePath } from 'exsolve';
4
4
  import { dirname, join } from 'pathe';
5
- import { e as extractVariantBaseClasses, r as resolveVariantPrefixes, h as resolveExtractedVars, l as resolveVarsDeep, s as simplifyCss, p as postProcessStyles, m as loadLightningCss, a as extractCssVars, c as extractUniversalVars, d as extractPerClassVars, g as extractVarsFromCss, f as extractClassStyles } from '../shared/nuxt-og-image.Dr6blNqj.mjs';
5
+ import { e as extractVariantBaseClasses, r as resolveVariantPrefixes, h as resolveExtractedVars, l as resolveVarsDeep, s as simplifyCss, p as postProcessStyles, m as loadLightningCss, a as extractCssVars, c as extractUniversalVars, d as extractPerClassVars, g as extractVarsFromCss, f as extractClassStyles } from '../shared/nuxt-og-image.7j0Ug7zJ.mjs';
6
6
  import 'node:fs';
7
7
  import '@nuxt/kit';
8
8
  import 'defu';
@@ -1,8 +1,8 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { defu } from 'defu';
3
3
  import { logger } from '../../dist/runtime/logger.js';
4
- import { e as extractVariantBaseClasses, s as simplifyCss, a as extractCssVars, b as extractPropertyInitialValues, c as extractUniversalVars, d as extractPerClassVars, f as extractClassStyles, p as postProcessStyles, r as resolveVariantPrefixes, i as importOptionalPeer, g as extractVarsFromCss, h as resolveExtractedVars } from '../shared/nuxt-og-image.Dr6blNqj.mjs';
5
- export { j as importResolvedModule, k as resolveOptionalModulePath } from '../shared/nuxt-og-image.Dr6blNqj.mjs';
4
+ import { e as extractVariantBaseClasses, s as simplifyCss, a as extractCssVars, b as extractPropertyInitialValues, c as extractUniversalVars, d as extractPerClassVars, f as extractClassStyles, p as postProcessStyles, r as resolveVariantPrefixes, i as importOptionalPeer, g as extractVarsFromCss, h as resolveExtractedVars } from '../shared/nuxt-og-image.7j0Ug7zJ.mjs';
5
+ export { j as importResolvedModule, k as resolveOptionalModulePath } from '../shared/nuxt-og-image.7j0Ug7zJ.mjs';
6
6
  import 'node:fs';
7
7
  import 'node:url';
8
8
  import '@nuxt/kit';
@@ -50,6 +50,8 @@ const PARAM_ALIASES: Record<string, string> = {
50
50
  p: '_path', // page path - needs alias since _path starts with underscore
51
51
  q: '_query', // query params - needs alias since _query starts with underscore
52
52
  ch: '_componentHash', // component template hash for cache busting prerendered URLs
53
+ // `video_` was an inline component prop before the option existed, so the option uses its own key.
54
+ mp4: 'video',
53
55
  }
54
56
 
55
57
  // Reverse mapping (param name -> alias)
@@ -75,6 +77,7 @@ const KNOWN_PARAMS = new Set([
75
77
  'sharp',
76
78
  'screenshot',
77
79
  'takumi',
80
+ 'video',
78
81
  'fonts',
79
82
  '_query',
80
83
  '_hash',
@@ -85,7 +88,7 @@ const KNOWN_PARAMS = new Set([
85
88
  ])
86
89
 
87
90
  // Params that need base64 encoding (complex objects, or values with slashes)
88
- const COMPLEX_PARAMS = new Set(['satori', 'resvg', 'sharp', 'screenshot', 'takumi', 'fonts', '_query', '_path'])
91
+ const COMPLEX_PARAMS = new Set(['satori', 'resvg', 'sharp', 'screenshot', 'takumi', 'video', 'fonts', '_query', '_path'])
89
92
 
90
93
  // URL-safe base64 encode/decode helpers (works in both browser and Node, handles Unicode)
91
94
  // Uses ~ instead of / and - instead of + to avoid breaking URL path segments
@@ -168,7 +171,9 @@ export function encodeOgImageParams(options: Record<string, any>, defaults?: Rec
168
171
  for (const [propKey, propValue] of Object.entries(value)) {
169
172
  if (propValue === undefined || propValue === null)
170
173
  continue
171
- if (typeof propValue === 'string' || typeof propValue === 'number' || typeof propValue === 'boolean') {
174
+ // A prop named like an option or alias would decode as that option, so it goes in the props blob.
175
+ const canEncodeInline = !KNOWN_PARAMS.has(propKey) && !(propKey in PARAM_ALIASES)
176
+ if (canEncodeInline && (typeof propValue === 'string' || typeof propValue === 'number' || typeof propValue === 'boolean')) {
172
177
  flattened[propKey] = propValue
173
178
  }
174
179
  else {
@@ -183,6 +188,11 @@ export function encodeOgImageParams(options: Record<string, any>, defaults?: Rec
183
188
  }
184
189
  }
185
190
 
191
+ // `video: {}` and settings that are all undefined opt in with the defaults. Encode them as `true`,
192
+ // because an object that serializes to `{}` is dropped below.
193
+ if (flattened.video && typeof flattened.video === 'object' && JSON.stringify(flattened.video) === '{}')
194
+ flattened.video = true
195
+
186
196
  for (const [key, value] of Object.entries(flattened)) {
187
197
  if (value === undefined || value === null || value === '') {
188
198
  continue
@@ -314,8 +324,10 @@ export function decodeOgImageParams(encoded: string): Record<string, any> {
314
324
 
315
325
  // Resolve alias to full param name
316
326
  const paramName = PARAM_ALIASES[alias] || alias
327
+ // An inline `video_` param is a component prop from a URL older than the `video` option.
328
+ const isOption = alias !== 'video'
317
329
 
318
- if (COMPLEX_PARAMS.has(paramName)) {
330
+ if (isOption && COMPLEX_PARAMS.has(paramName)) {
319
331
  // Base64 decode complex objects
320
332
  try {
321
333
  const json = b64Decode(value)
@@ -335,7 +347,7 @@ export function decodeOgImageParams(encoded: string): Record<string, any> {
335
347
  // ignore
336
348
  }
337
349
  }
338
- else if (KNOWN_PARAMS.has(paramName)) {
350
+ else if (isOption && KNOWN_PARAMS.has(paramName)) {
339
351
  // Known OgImageOptions param - decode value
340
352
  value = decodeSimpleValue(value)
341
353
  // Try to parse as number or boolean
@@ -6,7 +6,7 @@ import { defu } from 'defu'
6
6
  export { encodeOgImageParams } from './shared/urlEncoding'
7
7
 
8
8
  const RE_KEBAB_CASE = /-([a-z])/g
9
- const OG_IMAGE_OPTION_KEYS: string[] = ['url', 'extension', 'width', 'height', 'alt', 'props', 'renderer', 'component', 'emojis', '_query', '_hash', 'fonts', 'satori', 'resvg', 'sharp', 'screenshot', 'takumi', 'cacheMaxAgeSeconds', 'cacheKey', 'key']
9
+ const OG_IMAGE_OPTION_KEYS: string[] = ['url', 'extension', 'width', 'height', 'alt', 'props', 'renderer', 'component', 'emojis', '_query', '_hash', 'fonts', 'satori', 'resvg', 'sharp', 'screenshot', 'takumi', 'video', 'cacheMaxAgeSeconds', 'cacheKey', 'key']
10
10
 
11
11
  function filterIsOgImageOption(key: string): boolean {
12
12
  return OG_IMAGE_OPTION_KEYS.includes(key)
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": "^4.6.1 || ^5.0.0-0"
5
5
  },
6
6
  "configKey": "ogImage",
7
- "version": "7.1.1",
7
+ "version": "7.2.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -6,7 +6,7 @@ import 'defu';
6
6
  import 'fnv1a-64';
7
7
  import 'nuxtseo-shared/kit';
8
8
  import 'pathe';
9
- export { n as default } from './shared/nuxt-og-image.Dr6blNqj.mjs';
9
+ export { n as default } from './shared/nuxt-og-image.7j0Ug7zJ.mjs';
10
10
  import '../dist/runtime/logger.js';
11
11
  import '../dist/runtime/shared/publish.js';
12
12
  import 'node:crypto';
@@ -5,7 +5,7 @@ import { toValue } from "vue";
5
5
  import { hasServerRuntime } from "#build/nuxt-og-image/client-config.mjs";
6
6
  import { componentHashes, defaultComponentName } from "#build/nuxt-og-image/component-hashes.mjs";
7
7
  import { createSitePathResolver } from "#site-config/app";
8
- import { buildOgImageUrl, generateMeta, separateProps } from "../shared.js";
8
+ import { buildOgImageUrl, generateMeta, separateProps, withoutVideo } from "../shared.js";
9
9
  const clientEntriesByHead = /* @__PURE__ */ new WeakMap();
10
10
  const HYDRATION_KEY = Symbol("og-image:hydration");
11
11
  function registerClientOgHead(ogKey, input, options) {
@@ -101,13 +101,13 @@ export function clientProcessOgImageOptions(input, route, basePath, isHydrating
101
101
  if (validOptions.url) {
102
102
  const url = validOptions.url;
103
103
  const absoluteUrl = /^https?:\/\//.test(url) ? url : toValue(resolveImageUrl(url));
104
- registerClientOgHead(ogKey, { meta: generateMeta(absoluteUrl, validOptions, metaOptions) });
104
+ registerClientOgHead(ogKey, { meta: generateMeta(absoluteUrl, withoutVideo(validOptions), metaOptions) });
105
105
  paths.push(url);
106
106
  continue;
107
107
  }
108
108
  if (hasServerRuntime) {
109
109
  const finalUrl2 = buildResolverUrl(baseURL, basePath, ogKey, route.query);
110
- registerClientOgHead(ogKey, { meta: generateMeta(toValue(resolveImageUrl(finalUrl2)), validOptions, metaOptions) });
110
+ registerClientOgHead(ogKey, { meta: generateMeta(toValue(resolveImageUrl(finalUrl2)), withoutVideo(validOptions), metaOptions) });
111
111
  paths.push(finalUrl2);
112
112
  continue;
113
113
  }
@@ -123,7 +123,7 @@ export function clientProcessOgImageOptions(input, route, basePath, isHydrating
123
123
  const query = opts._query && Object.keys(opts._query).length ? { _query: opts._query } : {};
124
124
  const finalUrl = withQuery(resolvedUrl, query);
125
125
  const imageUrl = rc.app.cdnURL ? withQuery(joinURL(rc.app.cdnURL, result.url), query) : toValue(resolveImageUrl(finalUrl));
126
- registerClientOgHead(ogKey, { meta: generateMeta(imageUrl, opts, metaOptions) }, { processTemplateParams: true });
126
+ registerClientOgHead(ogKey, { meta: generateMeta(imageUrl, withoutVideo(opts), metaOptions) }, { processTemplateParams: true });
127
127
  paths.push(finalUrl);
128
128
  }
129
129
  return paths;
@@ -5,7 +5,7 @@ import { joinURL, withQuery } from "ufo";
5
5
  import { isRef, toValue } from "vue";
6
6
  import { componentNames } from "#build/nuxt-og-image/components.mjs";
7
7
  import { createSitePathResolver, withSiteUrl } from "#site-config/app";
8
- import { buildOgImageUrl, generateMeta, separateProps } from "../shared.js";
8
+ import { buildOgImageUrl, generateMeta, separateProps, toVideoUrl, withoutVideo } from "../shared.js";
9
9
  function resolveUnrefHeadInput(input) {
10
10
  if (input == null)
11
11
  return input;
@@ -96,6 +96,9 @@ export function createOgImageMeta(src, input, ssrContext, pagePath, head) {
96
96
  const resolvedComponentName = rawComponentName ? resolveComponentName(rawComponentName) : void 0;
97
97
  const resolvedComponent = resolvedComponentName ? componentNames?.find((c) => c.pascalName === resolvedComponentName || c.kebabName === resolvedComponentName) : void 0;
98
98
  const declaredProps = resolvedComponent?.propNames;
99
+ const renderVideo = !!opts.video && resolvedComponent?.renderer === "takumi";
100
+ if (opts.video && !renderVideo && import.meta.dev)
101
+ console.warn(`[nuxt-og-image] The \`video\` option needs a Takumi component. "${resolvedComponentName}" renders with ${resolvedComponent?.renderer || "an unknown renderer"}, so the page gets no og:video.`);
99
102
  if (seo) {
100
103
  if (seo.title && typeof opts.props.title === "undefined" && (!declaredProps || declaredProps.includes("title")))
101
104
  opts.props.title = seo.title;
@@ -104,6 +107,7 @@ export function createOgImageMeta(src, input, ssrContext, pagePath, head) {
104
107
  }
105
108
  const extension = opts.extension || defaults?.extension || "png";
106
109
  const isStatic = import.meta.prerender && !(ogImageConfig.security?.secret && ogImageConfig.security?.strict);
110
+ const videoAvailable = renderVideo && (isStatic || import.meta.dev || !!ogImageConfig.security?.secret);
107
111
  const urlOpts = { ...opts, _path: payloadBasePath };
108
112
  const componentName = opts.component || componentNames?.[0]?.pascalName;
109
113
  const component = componentNames?.find((c) => c.pascalName === componentName || c.kebabName === componentName);
@@ -120,10 +124,13 @@ export function createOgImageMeta(src, input, ssrContext, pagePath, head) {
120
124
  const prerenderPaths = ssrContext.event.context._ogImagePrerenderPaths;
121
125
  if (prerenderPaths) {
122
126
  const ogKey = opts.key || "og";
123
- prerenderPaths.set(ogKey, (finalUrl.split("?")[0] || finalUrl).replace(/,/g, "%2C"));
127
+ const prerenderPath = (finalUrl.split("?")[0] || finalUrl).replace(/,/g, "%2C");
128
+ prerenderPaths.set(ogKey, prerenderPath);
129
+ if (videoAvailable)
130
+ prerenderPaths.set(`${ogKey}:video`, toVideoUrl(prerenderPath));
124
131
  }
125
132
  }
126
- const meta = generateMeta(toValue(resolveImageUrl(finalUrl)), opts, { includeTwitter: ogImageConfig.includeTwitter });
133
+ const meta = generateMeta(toValue(resolveImageUrl(finalUrl)), videoAvailable ? opts : withoutVideo(opts), { includeTwitter: ogImageConfig.includeTwitter });
127
134
  hydrationMeta.value[opts.key || "og"] = resolveUnrefHeadInput(meta);
128
135
  return meta;
129
136
  });
@@ -27,7 +27,7 @@ export async function resolveContext(e) {
27
27
  });
28
28
  const path = resolvePathWithBase(parseURL(e.path).pathname);
29
29
  let extension = path.split(".").pop();
30
- if (!extension || !path.includes(".") || extension.includes("/") || !["png", "jpeg", "jpg", "webp", "svg", "html", "json"].includes(extension)) {
30
+ if (!extension || !path.includes(".") || extension.includes("/") || !["png", "jpeg", "jpg", "webp", "svg", "html", "json", "mp4"].includes(extension)) {
31
31
  extension = "png";
32
32
  }
33
33
  const encodedSegment = extractEncodedSegment(path, extension);
@@ -160,7 +160,7 @@ export async function resolveContext(e) {
160
160
  }
161
161
  const rendererType = normalised.renderer;
162
162
  const identity = normalised.options.cacheKey ? ["cacheKey", String(normalised.options.cacheKey)] : hashMatch ? ["hash", hashMatch[1]] : ["page", basePathWithQuery, import.meta.prerender ? "" : getSiteConfig(e, { resolveRefs: true }).url, normalised.options];
163
- const key = digestCanonical([...identity, componentHash]);
163
+ const key = digestCanonical([...identity, extension, componentHash]);
164
164
  let renderer;
165
165
  switch (rendererType) {
166
166
  case "satori":
@@ -58,11 +58,12 @@ async function doResolveSrcToBuffer(src, kind, { e, publicStoragePath, runtimeCo
58
58
  const srcWithoutBase = src.replace(runtimeConfig.app.baseURL, "/");
59
59
  buffer2 = await resolveLocalFilePathImage(publicStoragePath, srcWithoutBase);
60
60
  }
61
- if (!buffer2 && !import.meta.prerender) {
61
+ if (!buffer2) {
62
62
  const ab = await timings.measure("image-fetch", () => fetchLocalAsset(e, src, {
63
63
  fetchTimeout,
64
64
  headers: SUBREQUEST_HEADERS,
65
- includeExternalFallback: true,
65
+ // No server answers on the site origin while prerendering, and it may be the live site.
66
+ includeExternalFallback: !import.meta.prerender,
66
67
  onStepFailure: logFailure
67
68
  }));
68
69
  if (ab)
@@ -0,0 +1,8 @@
1
+ import type { OgImageComponent } from '../../types.js';
2
+ /**
3
+ * Development only. Component metadata (propNames, hash, credits) can change when an OG image
4
+ * component is edited after Nitro is built; the module rewrites this file instead of rebuilding
5
+ * Nitro. Parsed again only when the file changes.
6
+ */
7
+ export declare function readDevComponentNames(path: string): OgImageComponent[] | undefined;
8
+ export declare function createDevComponentNamesProxy(path: string, fallback: OgImageComponent[]): OgImageComponent[];
@@ -0,0 +1,42 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ let cachedPath;
3
+ let cachedVersion;
4
+ let cached;
5
+ export function readDevComponentNames(path) {
6
+ try {
7
+ const { ino, mtimeNs, size } = statSync(path, { bigint: true });
8
+ const version = `${ino}:${mtimeNs}:${size}`;
9
+ if (path !== cachedPath || version !== cachedVersion) {
10
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
11
+ if (!Array.isArray(parsed))
12
+ return void 0;
13
+ cached = parsed;
14
+ cachedPath = path;
15
+ cachedVersion = version;
16
+ }
17
+ return cached;
18
+ } catch {
19
+ return void 0;
20
+ }
21
+ }
22
+ export function createDevComponentNamesProxy(path, fallback) {
23
+ const getCurrent = () => readDevComponentNames(path) ?? fallback;
24
+ return new Proxy(fallback, {
25
+ get(_target, prop) {
26
+ const current = getCurrent();
27
+ if (prop === "toJSON")
28
+ return () => current;
29
+ const value = Reflect.get(current, prop, current);
30
+ return typeof value === "function" ? value.bind(current) : value;
31
+ },
32
+ has(_target, prop) {
33
+ return Reflect.has(getCurrent(), prop);
34
+ },
35
+ ownKeys() {
36
+ return Reflect.ownKeys(getCurrent());
37
+ },
38
+ getOwnPropertyDescriptor(_target, prop) {
39
+ return Reflect.getOwnPropertyDescriptor(getCurrent(), prop);
40
+ }
41
+ });
42
+ }
@@ -7,6 +7,7 @@ import { TAKUMI_FORMATS } from "../font-source.js";
7
7
  import { getDefaultFontFamily, loadFontsForRenderer, parseUnicodeRange, selectLazyFonts } from "../fonts.js";
8
8
  import { getTakumi } from "./instances.js";
9
9
  import { createTakumiNodes } from "./nodes.js";
10
+ import { createMp4Encoder, resolveVideoOptions, videoFrameTimes } from "./video.js";
10
11
  async function getTakumiRenderer(event) {
11
12
  const nitro = event._nitro;
12
13
  if (!nitro._takumiRenderer) {
@@ -83,12 +84,13 @@ function normalizeImageSources(images) {
83
84
  data: image.data instanceof Uint8Array ? image.data : new Uint8Array(image.data)
84
85
  }));
85
86
  }
86
- async function createImage(event, format) {
87
+ async function createTakumiScene(event, { evenDimensions }) {
87
88
  const { options, timings } = event;
89
+ const renderTimeout = event.runtimeConfig.security?.renderTimeout ?? 15e3;
90
+ const signal = AbortSignal.timeout(renderTimeout);
88
91
  const { fontFamilyOverride, defaultFont } = getDefaultFontFamily(options);
89
92
  const nodes = await createTakumiNodes(event);
90
93
  const fontEntries = dedupeFontsByBinary(selectLazyFonts(event.e, { supportedFormats: TAKUMI_FORMATS, component: options.component, fontFamilyOverride: fontFamilyOverride || defaultFont }));
91
- const renderTimeout = event.runtimeConfig.security?.renderTimeout ?? 15e3;
92
94
  await withTimeout(
93
95
  event._nitro.hooks.callHook("nuxt-og-image:takumi:nodes", nodes, event),
94
96
  renderTimeout,
@@ -102,19 +104,37 @@ async function createImage(event, format) {
102
104
  const maxDpr = event.runtimeConfig.security?.maxDpr || 2;
103
105
  const maxDim = event.runtimeConfig.security?.maxDimension || 2048;
104
106
  const dpr = Math.min(Math.max(1, options.takumi?.devicePixelRatio ?? 1), maxDpr);
107
+ const dimension = (size) => {
108
+ const pixels = Math.floor(Math.min(Number(size) * dpr, maxDim));
109
+ return evenDimensions ? pixels - pixels % 2 : pixels;
110
+ };
111
+ const width = dimension(options.width);
112
+ const height = dimension(options.height);
105
113
  const fetchTimeout = getFetchTimeout(event.runtimeConfig);
106
114
  const failedFontKeys = /* @__PURE__ */ new Set();
107
- const fontLoaders = fontEntries.map((entry) => createFontLoader(entry, failedFontKeys));
108
- const signal = AbortSignal.timeout(renderTimeout);
109
- const prepare = (loaders) => renderer.prepare(nodes, {
110
- width: Math.min(Number(options.width) * dpr, maxDim),
111
- height: Math.min(Number(options.height) * dpr, maxDim),
115
+ let fontLoaders = fontEntries.map((entry) => createFontLoader(entry, failedFontKeys));
116
+ const imageBytes = /* @__PURE__ */ new Map();
117
+ const fetchImageOnce = async (src) => {
118
+ let bytes = imageBytes.get(src);
119
+ if (!bytes) {
120
+ bytes = fetchImage(event, src, fetchTimeout).then((res) => res.arrayBuffer());
121
+ imageBytes.set(src, bytes);
122
+ }
123
+ return new Response(await bytes);
124
+ };
125
+ const prepareWith = (loaders, timeMs) => renderer.prepare(nodes, {
126
+ width,
127
+ height,
112
128
  devicePixelRatio: dpr,
113
129
  fonts: loaders,
114
130
  fontFamilies: [...loadedFamilies],
131
+ // The rules come from the image URL. Takumi parses them and rejects an invalid rule.
132
+ css: options.takumi?.css,
133
+ // Takumi accepts whole milliseconds only.
134
+ timeMs: timeMs === void 0 ? void 0 : Math.round(Number(timeMs)) || 0,
115
135
  images: {
116
136
  sources: normalizeImageSources(options.takumi?.images),
117
- fetch: (src) => fetchImage(event, src, fetchTimeout),
137
+ fetch: fetchImageOnce,
118
138
  // Defense-in-depth: any URL surviving the imageSrc transformer is re-validated here.
119
139
  allowUrl: (src) => src.startsWith("/") || (import.meta.dev ? RE_HTTP_URL.test(src) : !isBlockedUrl(src)),
120
140
  timeout: fetchTimeout,
@@ -122,20 +142,67 @@ async function createImage(event, format) {
122
142
  },
123
143
  signal
124
144
  });
125
- return await withTimeout((async () => {
126
- try {
127
- const prepared = await timings.measure("takumi-prepare", () => prepare(fontLoaders).catch((err) => {
145
+ return {
146
+ renderer,
147
+ width,
148
+ height,
149
+ signal,
150
+ renderTimeout,
151
+ prepare(timeMs) {
152
+ fontLoaders = fontLoaders.filter((loader) => !failedFontKeys.has(loader.key));
153
+ return prepareWith(fontLoaders, timeMs).catch((err) => {
128
154
  if (failedFontKeys.size === 0) {
129
155
  throw err;
130
156
  }
131
- return prepare(fontLoaders.filter((loader) => !failedFontKeys.has(loader.key)));
132
- }));
133
- return await timings.measure("render-takumi", () => renderer.render(prepared, { format: options.takumi?.format ?? format, signal }));
134
- } catch (err) {
157
+ fontLoaders = fontLoaders.filter((loader) => !failedFontKeys.has(loader.key));
158
+ return prepareWith(fontLoaders, timeMs);
159
+ });
160
+ },
161
+ /** Start from a fresh Renderer after a failure, so a trapped WASM instance is not reused. */
162
+ discardRenderer() {
135
163
  delete event._nitro._takumiRenderer;
164
+ }
165
+ };
166
+ }
167
+ async function createImage(event, format) {
168
+ const { options, timings } = event;
169
+ const scene = await createTakumiScene(event, { evenDimensions: false });
170
+ return await withTimeout((async () => {
171
+ try {
172
+ const prepared = await timings.measure("takumi-prepare", () => scene.prepare(options.takumi?.timeMs));
173
+ return await timings.measure("render-takumi", () => scene.renderer.render(prepared, { format: options.takumi?.format ?? format, signal: scene.signal }));
174
+ } catch (err) {
175
+ scene.discardRenderer();
176
+ throw err;
177
+ }
178
+ })(), scene.renderTimeout, "takumi render");
179
+ }
180
+ async function createVideo(event) {
181
+ const { options, timings } = event;
182
+ const video = resolveVideoOptions(options.video);
183
+ const scene = await createTakumiScene(event, { evenDimensions: true });
184
+ return await withTimeout((async () => {
185
+ const encoder = await createMp4Encoder({
186
+ ffmpeg: globalThis.process?.env.NUXT_OG_IMAGE_FFMPEG || "ffmpeg",
187
+ width: scene.width,
188
+ height: scene.height,
189
+ fps: video.fps,
190
+ signal: scene.signal
191
+ });
192
+ try {
193
+ await timings.measure("render-takumi", async () => {
194
+ for (const timeMs of videoFrameTimes(video)) {
195
+ const prepared = await scene.prepare(timeMs);
196
+ await encoder.write(await scene.renderer.render(prepared, { format: "raw", signal: scene.signal }));
197
+ }
198
+ });
199
+ return await timings.measure("encode-mp4", () => encoder.finish());
200
+ } catch (err) {
201
+ await encoder.abort();
202
+ scene.discardRenderer();
136
203
  throw err;
137
204
  }
138
- })(), renderTimeout, "takumi render");
205
+ })(), scene.renderTimeout, "takumi video render");
139
206
  }
140
207
  async function fetchImage(event, src, fetchTimeout) {
141
208
  const headers = { "x-nuxt-og-image": "1" };
@@ -163,7 +230,7 @@ async function fetchImage(event, src, fetchTimeout) {
163
230
  }
164
231
  const TakumiRenderer = {
165
232
  name: "takumi",
166
- supportedFormats: ["png", "jpeg", "jpg", "webp", "json"],
233
+ supportedFormats: ["png", "jpeg", "jpg", "webp", "json", "mp4"],
167
234
  async createImage(e) {
168
235
  switch (e.extension) {
169
236
  case "png":
@@ -173,6 +240,8 @@ const TakumiRenderer = {
173
240
  return createImage(e, "jpeg");
174
241
  case "webp":
175
242
  return createImage(e, "webp");
243
+ case "mp4":
244
+ return createVideo(e);
176
245
  }
177
246
  },
178
247
  async debug(e) {
@@ -0,0 +1,30 @@
1
+ import type { OgImageOptions, OgImageVideoOptions } from '../../../types.js';
2
+ export declare const MAX_VIDEO_DURATION_MS = 10000;
3
+ export declare const MAX_VIDEO_FPS = 60;
4
+ /**
5
+ * Bound the `video` option from the image URL. An unsigned URL can carry any value,
6
+ * so each field falls back to its default or clamps to the documented range.
7
+ */
8
+ export declare function resolveVideoOptions(video: OgImageOptions['video']): Required<OgImageVideoOptions>;
9
+ /** The timeline position of each frame, in whole milliseconds, which is what Takumi accepts. */
10
+ export declare function videoFrameTimes({ durationMs, fps }: Required<OgImageVideoOptions>): number[];
11
+ export interface Mp4EncoderOptions {
12
+ /** The ffmpeg binary to run. */
13
+ ffmpeg: string;
14
+ width: number;
15
+ height: number;
16
+ fps: number;
17
+ /** Aborting it stops ffmpeg. */
18
+ signal: AbortSignal;
19
+ }
20
+ /**
21
+ * Stream raw RGBA frames into `ffmpeg` and get back an H.264 MP4.
22
+ * Output goes to a temp file because `+faststart` needs a seekable output, and
23
+ * Messages only plays MP4s it can stream from the start.
24
+ */
25
+ export declare function createMp4Encoder({ ffmpeg: bin, width, height, fps, signal }: Mp4EncoderOptions): Promise<{
26
+ write(frame: Uint8Array): Promise<void>;
27
+ finish(): Promise<Uint8Array>;
28
+ /** Stop ffmpeg after a failed render and remove its output. */
29
+ abort(): Promise<void>;
30
+ }>;
@@ -0,0 +1,98 @@
1
+ export const MAX_VIDEO_DURATION_MS = 1e4;
2
+ export const MAX_VIDEO_FPS = 60;
3
+ export function resolveVideoOptions(video) {
4
+ const options = video && typeof video === "object" ? video : {};
5
+ return {
6
+ durationMs: Math.min(Math.max(Number(options.durationMs) || 3e3, 100), MAX_VIDEO_DURATION_MS),
7
+ fps: Math.min(Math.max(Math.round(Number(options.fps)) || 30, 1), MAX_VIDEO_FPS)
8
+ };
9
+ }
10
+ export function videoFrameTimes({ durationMs, fps }) {
11
+ const count = Math.max(1, Math.round(durationMs / 1e3 * fps));
12
+ return Array.from({ length: count }, (_, i) => Math.round(i * 1e3 / fps));
13
+ }
14
+ export async function createMp4Encoder({ ffmpeg: bin, width, height, fps, signal }) {
15
+ const [{ spawn }, { mkdtemp, readFile, rm }, { tmpdir }, { join }] = await Promise.all([
16
+ import("node:child_process"),
17
+ import("node:fs/promises"),
18
+ import("node:os"),
19
+ import("node:path")
20
+ ]);
21
+ signal.throwIfAborted();
22
+ const dir = await mkdtemp(join(tmpdir(), "nuxt-og-image-"));
23
+ const output = join(dir, "og.mp4");
24
+ const ffmpeg = spawn(bin, [
25
+ "-y",
26
+ "-loglevel",
27
+ "error",
28
+ "-f",
29
+ "rawvideo",
30
+ "-pixel_format",
31
+ "rgba",
32
+ "-video_size",
33
+ `${width}x${height}`,
34
+ "-framerate",
35
+ String(fps),
36
+ "-i",
37
+ "pipe:0",
38
+ "-c:v",
39
+ "libx264",
40
+ "-preset",
41
+ "veryfast",
42
+ "-pix_fmt",
43
+ "yuv420p",
44
+ "-movflags",
45
+ "+faststart",
46
+ "-an",
47
+ output
48
+ ], { stdio: ["pipe", "ignore", "pipe"], signal });
49
+ let stderr = "";
50
+ ffmpeg.stderr.on("data", (chunk) => {
51
+ stderr += chunk;
52
+ });
53
+ ffmpeg.stdin.on("error", (err) => {
54
+ void err;
55
+ });
56
+ let failure;
57
+ const exited = new Promise((resolve, reject) => {
58
+ ffmpeg.on("error", (err) => {
59
+ failure ||= err.name === "AbortError" ? err : new Error(`[Nuxt OG Image] Could not run ffmpeg for og:video: ${err.message}. Install ffmpeg, or set NUXT_OG_IMAGE_FFMPEG to its path.`);
60
+ reject(failure);
61
+ });
62
+ ffmpeg.on("close", (code) => {
63
+ if (code === 0)
64
+ return resolve();
65
+ failure ||= new Error(`[Nuxt OG Image] ffmpeg exited with code ${code}: ${stderr.trim()}`);
66
+ reject(failure);
67
+ });
68
+ });
69
+ exited.catch((err) => {
70
+ void err;
71
+ });
72
+ const removeDir = () => rm(dir, { recursive: true, force: true });
73
+ return {
74
+ async write(frame) {
75
+ if (failure)
76
+ throw failure;
77
+ if (!ffmpeg.stdin.write(frame))
78
+ await Promise.race([new Promise((resolve) => ffmpeg.stdin.once("drain", resolve)), exited]);
79
+ },
80
+ async finish() {
81
+ ffmpeg.stdin.end();
82
+ try {
83
+ await exited;
84
+ return new Uint8Array(await readFile(output));
85
+ } finally {
86
+ await removeDir();
87
+ }
88
+ },
89
+ /** Stop ffmpeg after a failed render and remove its output. */
90
+ async abort() {
91
+ ffmpeg.kill();
92
+ await exited.catch((err) => {
93
+ void err;
94
+ });
95
+ await removeDir();
96
+ }
97
+ };
98
+ }
@@ -17,9 +17,9 @@ function getPayloadFromHtml(html) {
17
17
  const match = String(html).match(PAYLOAD_REGEX);
18
18
  return match ? String(match[1]) : null;
19
19
  }
20
- function replaceImageUrls(head, path, resolve) {
20
+ function replaceMediaUrls(head, path, resolve) {
21
21
  return head.map((entry) => entry.replace(/(<meta\b[^>]+\bcontent=")([^"]*)("[^>]*>)/g, (tag, start, url, end) => {
22
- if (!/\b(?:property|name)="(?:og:image(?::url|:secure_url)?|twitter:image(?::src)?)"/.test(tag))
22
+ if (!/\b(?:property|name)="(?:og:image(?::url|:secure_url)?|og:video(?::url|:secure_url)?|twitter:image(?::src)?)"/.test(tag))
23
23
  return tag;
24
24
  const source = url.replace(/&amp;/g, "&");
25
25
  const urlPath = parseURL(source).pathname;
@@ -87,7 +87,7 @@ export default defineNitroPlugin(async (nitro) => {
87
87
  }
88
88
  });
89
89
  if (result._tag === "Published") {
90
- html.head = replaceImageUrls(html.head, prerenderPath, () => result.url);
90
+ html.head = replaceMediaUrls(html.head, prerenderPath, () => result.url);
91
91
  prerenderPaths.delete(ogKey);
92
92
  } else if (!publishWarningShown) {
93
93
  publishWarningShown = true;
@@ -102,7 +102,7 @@ export default defineNitroPlugin(async (nitro) => {
102
102
  for (const prerenderPath of prerenderPaths.values()) {
103
103
  if (app.cdnURL && prerenderPath.includes("/_og/s/")) {
104
104
  const imageURL = joinURL(app.cdnURL, withoutBase(prerenderPath, app.baseURL));
105
- html.head = replaceImageUrls(html.head, prerenderPath, (source) => `${imageURL}${parseURL(source).search || ""}`);
105
+ html.head = replaceMediaUrls(html.head, prerenderPath, (source) => `${imageURL}${parseURL(source).search || ""}`);
106
106
  }
107
107
  appendResponseHeader(ctx.event, "x-nitro-prerender", prerenderPath);
108
108
  }
@@ -0,0 +1,15 @@
1
+ export type ByteRange = {
2
+ _tag: 'Full';
3
+ } | {
4
+ _tag: 'Partial';
5
+ start: number;
6
+ end: number;
7
+ } | {
8
+ _tag: 'Unsatisfiable';
9
+ };
10
+ /**
11
+ * Read a `Range` request header for a body of `size` bytes. Video players such as Safari's
12
+ * fetch an MP4 in byte ranges. A header this server does not serve, such as several ranges,
13
+ * gets the full body, which RFC 9110 allows.
14
+ */
15
+ export declare function parseByteRange(header: string | undefined, size: number): ByteRange;
@@ -0,0 +1,19 @@
1
+ const RE_SINGLE_BYTE_RANGE = /^bytes=(\d*)-(\d*)$/;
2
+ export function parseByteRange(header, size) {
3
+ const match = header?.trim().match(RE_SINGLE_BYTE_RANGE);
4
+ if (!match || !match[1] && !match[2])
5
+ return { _tag: "Full" };
6
+ if (!match[1]) {
7
+ const suffix = Number(match[2]);
8
+ if (suffix === 0)
9
+ return { _tag: "Unsatisfiable" };
10
+ return { _tag: "Partial", start: Math.max(0, size - suffix), end: size - 1 };
11
+ }
12
+ const start = Number(match[1]);
13
+ if (start >= size)
14
+ return { _tag: "Unsatisfiable" };
15
+ const end = match[2] ? Number(match[2]) : size - 1;
16
+ if (end < start)
17
+ return { _tag: "Full" };
18
+ return { _tag: "Partial", start, end: Math.min(end, size - 1) };
19
+ }
@@ -1,4 +1,4 @@
1
- import { appendResponseHeader, createError, getRequestHost, H3Error, sendRedirect, setHeader } from "#nuxtseo/h3";
1
+ import { appendResponseHeader, createError, getRequestHeader, getRequestHost, H3Error, sendRedirect, setHeader, setResponseStatus } from "#nuxtseo/h3";
2
2
  import { useStorage } from "#nuxtseo/nitro";
3
3
  import { getSiteConfig } from "#site-config/server/composables/getSiteConfig";
4
4
  import { logger } from "../../logger.js";
@@ -9,6 +9,7 @@ import { resolveContext } from "../og-image/context.js";
9
9
  import { fetchPathHtmlAndExtractOptions } from "../og-image/devtools.js";
10
10
  import { html } from "../og-image/templates/html.js";
11
11
  import { useOgImageRuntimeConfig } from "../utils.js";
12
+ import { parseByteRange } from "./byteRange.js";
12
13
  import { useOgImageBufferCache } from "./cache.js";
13
14
  import { warnPublishUnavailable } from "./publishWarnings.js";
14
15
  import { parsePurgeRequest } from "./purge.js";
@@ -120,6 +121,27 @@ async function renderOgImage(e, ctx) {
120
121
  }
121
122
  setHeader(e, "Content-Type", `image/${extension === "jpg" ? "jpeg" : extension}`);
122
123
  break;
124
+ case "mp4":
125
+ if (!renderer.supportedFormats.includes(extension)) {
126
+ return createError({
127
+ statusCode: 400,
128
+ statusMessage: `[Nuxt OG Image] Generating ${extension}'s with ${renderer.name} is not supported.`
129
+ });
130
+ }
131
+ if (!ctx.options.video) {
132
+ return createError({
133
+ statusCode: 400,
134
+ statusMessage: `[Nuxt OG Image] og:video is not enabled for this image. Set the \`video\` option in defineOgImage().`
135
+ });
136
+ }
137
+ if (!import.meta.prerender && !import.meta.dev && !security?.secret) {
138
+ return createError({
139
+ statusCode: 403,
140
+ statusMessage: `[Nuxt OG Image] og:video renders at runtime only with URL signing. Enable URL signing, or prerender the page.`
141
+ });
142
+ }
143
+ setHeader(e, "Content-Type", "video/mp4");
144
+ break;
123
145
  default:
124
146
  return createError({
125
147
  statusCode: 400,
@@ -131,7 +153,7 @@ async function renderOgImage(e, ctx) {
131
153
  timings.record("cache-hit", 0);
132
154
  return buildCachedImage;
133
155
  }
134
- let publication = publish && !import.meta.dev && !import.meta.prerender ? (() => {
156
+ let publication = publish && extension !== "mp4" && !import.meta.dev && !import.meta.prerender ? (() => {
135
157
  const key = getPublishKey(new URL(e.path, getSiteConfig(e).url).href, config.defaults, publish.cacheVersion);
136
158
  return {
137
159
  cache: getPublishedImageCache(ctx._nitro),
@@ -182,7 +204,7 @@ async function renderOgImage(e, ctx) {
182
204
  let timer;
183
205
  const endRender = timings.start("render-total");
184
206
  image = await Promise.race([
185
- renderer.createImage(ctx),
207
+ renderShared(ctx, timeout),
186
208
  new Promise((_, reject) => {
187
209
  timer = setTimeout(() => reject(new Error(`OG image render timed out after ${timeout}ms`)), timeout);
188
210
  })
@@ -237,5 +259,59 @@ async function renderOgImage(e, ctx) {
237
259
  e.waitUntil(task);
238
260
  }
239
261
  }
262
+ if (extension === "mp4")
263
+ return sendVideoRange(e, image);
240
264
  return image;
241
265
  }
266
+ const MAX_ACTIVE_VIDEO_RENDERS = 2;
267
+ const MAX_PENDING_VIDEO_RENDERS = 4;
268
+ function renderShared(ctx, timeout) {
269
+ if (ctx.extension !== "mp4")
270
+ return ctx.renderer.createImage(ctx);
271
+ const nitro = ctx._nitro;
272
+ const state = nitro._ogImageVideoRenders ||= { renders: /* @__PURE__ */ new Map(), active: 0, pending: [] };
273
+ const shared = state.renders.get(ctx.key);
274
+ if (shared)
275
+ return shared;
276
+ if (state.active >= MAX_ACTIVE_VIDEO_RENDERS && state.pending.length >= MAX_PENDING_VIDEO_RENDERS)
277
+ return Promise.resolve(createError({ statusCode: 503 }));
278
+ const render = new Promise((resolve, reject) => {
279
+ let queueTimer;
280
+ const start = () => {
281
+ clearTimeout(queueTimer);
282
+ state.active++;
283
+ Promise.resolve().then(() => ctx.renderer.createImage(ctx)).finally(() => {
284
+ state.active--;
285
+ state.pending.shift()?.();
286
+ }).then(resolve, reject);
287
+ };
288
+ if (state.active < MAX_ACTIVE_VIDEO_RENDERS) {
289
+ start();
290
+ } else {
291
+ state.pending.push(start);
292
+ queueTimer = setTimeout(() => {
293
+ state.pending.splice(state.pending.indexOf(start), 1);
294
+ reject(new Error(`OG image render timed out after ${timeout}ms`));
295
+ }, timeout);
296
+ }
297
+ }).finally(() => state.renders.delete(ctx.key));
298
+ state.renders.set(ctx.key, render);
299
+ return render;
300
+ }
301
+ function sendVideoRange(e, video) {
302
+ const bytes = ArrayBuffer.isView(video) ? new Uint8Array(video.buffer, video.byteOffset, video.byteLength) : new Uint8Array(video);
303
+ setHeader(e, "Accept-Ranges", "bytes");
304
+ const range = parseByteRange(getRequestHeader(e, "range"), bytes.byteLength);
305
+ switch (range._tag) {
306
+ case "Full":
307
+ return video;
308
+ case "Unsatisfiable":
309
+ setResponseStatus(e, 416);
310
+ setHeader(e, "Content-Range", `bytes */${bytes.byteLength}`);
311
+ return "";
312
+ case "Partial":
313
+ setResponseStatus(e, 206);
314
+ setHeader(e, "Content-Range", `bytes ${range.start}-${range.end}/${bytes.byteLength}`);
315
+ return bytes.subarray(range.start, range.end + 1);
316
+ }
317
+ }
@@ -39,8 +39,10 @@ const PARAM_ALIASES = {
39
39
  // page path - needs alias since _path starts with underscore
40
40
  q: "_query",
41
41
  // query params - needs alias since _query starts with underscore
42
- ch: "_componentHash"
42
+ ch: "_componentHash",
43
43
  // component template hash for cache busting prerendered URLs
44
+ // `video_` was an inline component prop before the option existed, so the option uses its own key.
45
+ mp4: "video"
44
46
  };
45
47
  const PARAM_TO_ALIAS = Object.fromEntries(
46
48
  Object.entries(PARAM_ALIASES).map(([alias, param]) => [param, alias])
@@ -62,6 +64,7 @@ const KNOWN_PARAMS = /* @__PURE__ */ new Set([
62
64
  "sharp",
63
65
  "screenshot",
64
66
  "takumi",
67
+ "video",
65
68
  "fonts",
66
69
  "_query",
67
70
  "_hash",
@@ -70,7 +73,7 @@ const KNOWN_PARAMS = /* @__PURE__ */ new Set([
70
73
  "props",
71
74
  "_path"
72
75
  ]);
73
- const COMPLEX_PARAMS = /* @__PURE__ */ new Set(["satori", "resvg", "sharp", "screenshot", "takumi", "fonts", "_query", "_path"]);
76
+ const COMPLEX_PARAMS = /* @__PURE__ */ new Set(["satori", "resvg", "sharp", "screenshot", "takumi", "video", "fonts", "_query", "_path"]);
74
77
  function b64Encode(str) {
75
78
  let encoded;
76
79
  if (typeof btoa === "function") {
@@ -136,7 +139,7 @@ export function encodeOgImageParams(options, defaults) {
136
139
  for (const [propKey, propValue] of Object.entries(value)) {
137
140
  if (propValue === void 0 || propValue === null || propValue === "")
138
141
  continue;
139
- const canEncodeInline = propKey !== "props" && RE_INLINE_PROP_NAME.test(propKey);
142
+ const canEncodeInline = propKey !== "props" && RE_INLINE_PROP_NAME.test(propKey) && !KNOWN_PARAMS.has(propKey) && !(propKey in PARAM_ALIASES);
140
143
  if (canEncodeInline && (typeof propValue === "string" || typeof propValue === "number" || typeof propValue === "boolean")) {
141
144
  flattened[propKey] = propValue;
142
145
  } else {
@@ -148,6 +151,8 @@ export function encodeOgImageParams(options, defaults) {
148
151
  flattened[key] = value;
149
152
  }
150
153
  }
154
+ if (flattened.video && typeof flattened.video === "object" && JSON.stringify(flattened.video) === "{}")
155
+ flattened.video = true;
151
156
  for (const [key, value] of Object.entries(flattened)) {
152
157
  if (value === void 0 || value === null || value === "") {
153
158
  continue;
@@ -224,7 +229,8 @@ export function decodeOgImageParams(encoded) {
224
229
  const alias = part.slice(0, idx);
225
230
  let value = part.slice(idx + 1);
226
231
  const paramName = PARAM_ALIASES[alias] || alias;
227
- if (COMPLEX_PARAMS.has(paramName)) {
232
+ const isOption = alias !== "video";
233
+ if (isOption && COMPLEX_PARAMS.has(paramName)) {
228
234
  try {
229
235
  const json = b64Decode(value);
230
236
  options[paramName] = JSON.parse(json);
@@ -237,7 +243,7 @@ export function decodeOgImageParams(encoded) {
237
243
  options.props = { ...options.props, ...JSON.parse(json) };
238
244
  } catch {
239
245
  }
240
- } else if (KNOWN_PARAMS.has(paramName)) {
246
+ } else if (isOption && KNOWN_PARAMS.has(paramName)) {
241
247
  value = decodeSimpleValue(value);
242
248
  if (value === "true") {
243
249
  options[paramName] = true;
@@ -2,6 +2,13 @@ import type { ResolvableMeta } from '@unhead/vue';
2
2
  import type { OgImageOptions, OgImagePrebuilt } from './types.js';
3
3
  export { extractSocialPreviewTags, toBase64Image } from './pure.js';
4
4
  export { buildOgImageUrl, decodeOgImageParams, encodeOgImageParams, extractEncodedSegment, hashOgImageOptions, parseOgImageUrl, signEncodedParams, verifyOgImageSignature } from './shared/urlEncoding.js';
5
+ /** The MP4 rendition of an OG image lives at the same URL with an `.mp4` extension. */
6
+ export declare function toVideoUrl(imageUrl: string): string;
7
+ /**
8
+ * The options without the `video` opt-in, for meta tags only. URL builders keep `video`, so every
9
+ * builder hashes the same options and points at the same file.
10
+ */
11
+ export declare function withoutVideo<T extends object>(options: T): T;
5
12
  export interface GenerateMetaOptions {
6
13
  /**
7
14
  * Emit Twitter card meta tags (`twitter:card`, `twitter:image`, etc) alongside
@@ -3,6 +3,14 @@ import { toValue } from "vue";
3
3
  export { extractSocialPreviewTags, toBase64Image } from "./pure.js";
4
4
  export { buildOgImageUrl, decodeOgImageParams, encodeOgImageParams, extractEncodedSegment, hashOgImageOptions, parseOgImageUrl, signEncodedParams, verifyOgImageSignature } from "./shared/urlEncoding.js";
5
5
  const RE_KEBAB_CASE = /-([a-z])/g;
6
+ const RE_IMAGE_EXTENSION = /\.(?:png|jpe?g|webp)(?=$|\?)/;
7
+ export function toVideoUrl(imageUrl) {
8
+ return imageUrl.replace(RE_IMAGE_EXTENSION, ".mp4");
9
+ }
10
+ export function withoutVideo(options) {
11
+ const { video: _video, ...rest } = options;
12
+ return rest;
13
+ }
6
14
  export function generateMeta(url, resolvedOptions, metaOptions = {}) {
7
15
  const key = resolvedOptions.key || "og";
8
16
  const isTwitterOnly = key === "twitter";
@@ -24,6 +32,17 @@ export function generateMeta(url, resolvedOptions, metaOptions = {}) {
24
32
  if (!isTwitterOnly)
25
33
  meta.push({ property: "og:image:height", content: resolvedOptions.height });
26
34
  }
35
+ const isPrebuilt = "url" in resolvedOptions && !!resolvedOptions.url;
36
+ if ("video" in resolvedOptions && resolvedOptions.video && !isTwitterOnly && !isPrebuilt) {
37
+ const videoUrl = () => toVideoUrl(toValue(url));
38
+ meta.push({ property: "og:video", content: videoUrl });
39
+ meta.push({ property: "og:video:secure_url", content: videoUrl });
40
+ meta.push({ property: "og:video:type", content: "video/mp4" });
41
+ if (resolvedOptions.width)
42
+ meta.push({ property: "og:video:width", content: resolvedOptions.width });
43
+ if (resolvedOptions.height)
44
+ meta.push({ property: "og:video:height", content: resolvedOptions.height });
45
+ }
27
46
  if (resolvedOptions.alt) {
28
47
  if (!isTwitterOnly)
29
48
  meta.push({ property: "og:image:alt", content: resolvedOptions.alt });
@@ -56,6 +75,7 @@ function filterIsOgImageOption(key) {
56
75
  "sharp",
57
76
  "screenshot",
58
77
  "takumi",
78
+ "video",
59
79
  "cacheMaxAgeSeconds",
60
80
  "cacheKey",
61
81
  "key"
@@ -8,7 +8,7 @@ import type { SameOriginPath } from './server/util/ssrf.js';
8
8
  import type { Timings } from './server/util/timings.js';
9
9
  export interface OgImageRenderEventContext {
10
10
  e: H3Event;
11
- extension: 'png' | 'jpeg' | 'jpg' | 'webp' | 'svg' | 'html' | 'json';
11
+ extension: 'png' | 'jpeg' | 'jpg' | 'webp' | 'svg' | 'html' | 'json' | 'mp4';
12
12
  key: string;
13
13
  basePath: SameOriginPath;
14
14
  renderer: Renderer;
@@ -151,6 +151,13 @@ export interface OgImageOptions {
151
151
  */
152
152
  props?: Record<string, any>;
153
153
  extension?: 'png' | 'jpeg' | 'jpg' | 'webp' | 'svg' | 'html';
154
+ /**
155
+ * Also render the template's CSS animations to an MP4 and emit `og:video` tags next to `og:image`.
156
+ *
157
+ * Messages on Apple platforms autoplay an MP4 `og:video` inline. Other clients fall back to `og:image`.
158
+ * Requires the takumi renderer and an `ffmpeg` binary on the server or at prerender.
159
+ */
160
+ video?: boolean | OgImageVideoOptions;
154
161
  emojis?: IconifyEmojiIconSets | false;
155
162
  /**
156
163
  * Provide a static HTML template to render the OG Image instead of a component.
@@ -170,6 +177,10 @@ export interface OgImageOptions {
170
177
  data: ArrayBuffer | Uint8Array;
171
178
  }>;
172
179
  devicePixelRatio?: number;
180
+ /** Point on the animation timeline to render for still images, in milliseconds. */
181
+ timeMs?: number;
182
+ /** Stylesheet text or CSS rules passed to takumi, e.g. `[{ keyframes: 'move', steps: [...] }]`. */
183
+ css?: Array<string | Record<string, any>>;
173
184
  };
174
185
  /** @deprecated Legacy font override — no longer used at runtime */
175
186
  fonts?: any;
@@ -254,9 +265,15 @@ export interface CompatibilityFlagEnvOverrides {
254
265
  export type RendererOptions = Omit<OgImageOptions, 'extension'> & {
255
266
  extension: Omit<OgImageOptions['extension'], 'html'>;
256
267
  };
268
+ export interface OgImageVideoOptions {
269
+ /** @default 3000 */
270
+ durationMs?: number;
271
+ /** @default 30 */
272
+ fps?: number;
273
+ }
257
274
  export interface Renderer {
258
275
  name: 'browser' | 'satori' | 'takumi';
259
- supportedFormats: Partial<RendererOptions['extension']>[];
276
+ supportedFormats: Partial<RendererOptions['extension'] | 'mp4'>[];
260
277
  createImage: (e: OgImageRenderEventContext) => Promise<H3Error | BufferSource | Buffer | Uint8Array | void | undefined>;
261
278
  debug: (e: OgImageRenderEventContext) => Promise<Record<string, any>>;
262
279
  }
@@ -6,7 +6,7 @@ import { resolvePath, useNuxt, getNuxtVersion, addTemplate, updateTemplates, dir
6
6
  import { defu } from 'defu';
7
7
  import { fnv1a64Base36 } from 'fnv1a-64';
8
8
  import { resolveNitroPreset, renderNitroTypeAugmentations, findPackageJSON, setupRuntimeAliases, setupNitroRuntimeCompatibility, getNuxtModuleOptions, isNuxtGenerate } from 'nuxtseo-shared/kit';
9
- import { join, basename, dirname, relative, isAbsolute, resolve } from 'pathe';
9
+ import { join, basename, dirname, relative, isAbsolute, resolve, normalize } from 'pathe';
10
10
  import { createHash } from 'node:crypto';
11
11
  import MagicString from 'magic-string';
12
12
  import { parseAndWalk } from 'oxc-walker';
@@ -3895,7 +3895,11 @@ const ICON_CLASS_RE = /^i-([a-z\d]+(?:-[a-z\d]+)*)[-:](.+)$/;
3895
3895
  function isIconClass(cls) {
3896
3896
  return ICON_CLASS_RE.test(cls);
3897
3897
  }
3898
- function isUnsupportedClass(cls) {
3898
+ const TAKUMI_ANIMATION_CLASS_RE = /^animate(?:-|$)/;
3899
+ const RE_TAKUMI_COMPONENT = /\.takumi\.vue$/;
3900
+ function isUnsupportedClass(cls, id) {
3901
+ if (RE_TAKUMI_COMPONENT.test(id) && TAKUMI_ANIMATION_CLASS_RE.test(cls))
3902
+ return false;
3899
3903
  return UNSUPPORTED_CLASS_PATTERNS.some((p) => p.test(cls));
3900
3904
  }
3901
3905
  function mergeThemePairs(classes, light, dark) {
@@ -4153,8 +4157,8 @@ const AssetTransformPlugin = createUnplugin((options) => {
4153
4157
  const fullCode = code.slice(0, templateStart) + template + code.slice(templateEnd);
4154
4158
  const result = await transformVueTemplate(fullCode, {
4155
4159
  resolveStyles: async (classes) => {
4156
- const supported = classes.filter((cls) => !isUnsupportedClass(cls) && !isIconClass(cls));
4157
- const unsupported = classes.filter((cls) => isUnsupportedClass(cls));
4160
+ const supported = classes.filter((cls) => !isUnsupportedClass(cls, id) && !isIconClass(cls));
4161
+ const unsupported = classes.filter((cls) => isUnsupportedClass(cls, id));
4158
4162
  if (unsupported.length > 0) {
4159
4163
  const componentName2 = id.split("/").pop();
4160
4164
  logger.warn(`[nuxt-og-image] ${componentName2}: Filtered unsupported classes: ${unsupported.join(", ")}`);
@@ -4680,6 +4684,40 @@ ${importStatements}
4680
4684
  };
4681
4685
  });
4682
4686
 
4687
+ function normalizeForCompare(path, caseInsensitive) {
4688
+ const normalized = normalize(path).replace(/\/+$/, "");
4689
+ return caseInsensitive ? normalized.toLowerCase() : normalized;
4690
+ }
4691
+ function isSamePath(a, b, caseInsensitive = process.platform === "win32") {
4692
+ return normalizeForCompare(a, caseInsensitive) === normalizeForCompare(b, caseInsensitive);
4693
+ }
4694
+ function isPathWithinDir(filePath, dirPath, caseInsensitive = process.platform === "win32") {
4695
+ const normalizedFile = normalizeForCompare(filePath, caseInsensitive);
4696
+ const normalizedDir = normalizeForCompare(dirPath, caseInsensitive);
4697
+ return normalizedFile === normalizedDir || normalizedFile.startsWith(`${normalizedDir}/`);
4698
+ }
4699
+ function resolveWatchedPath(relativePath, options) {
4700
+ if (isAbsolute(relativePath))
4701
+ return normalize(relativePath);
4702
+ const exists = options.exists ?? existsSync;
4703
+ const caseInsensitive = options.caseInsensitive ?? process.platform === "win32";
4704
+ const srcPath = join(options.srcDir, relativePath);
4705
+ const rootPath = join(options.rootDir, relativePath);
4706
+ if (exists(srcPath))
4707
+ return srcPath;
4708
+ if (exists(rootPath))
4709
+ return rootPath;
4710
+ if (isPathWithinDir(rootPath, options.srcDir, caseInsensitive))
4711
+ return rootPath;
4712
+ return srcPath;
4713
+ }
4714
+ function isOgImageComponentPath(absolutePath, srcDir, componentDirs, caseInsensitive = process.platform === "win32") {
4715
+ return componentDirs.some((dir) => {
4716
+ const componentDir = join(srcDir, "components", dir);
4717
+ return isPathWithinDir(absolutePath, componentDir, caseInsensitive);
4718
+ });
4719
+ }
4720
+
4683
4721
  const warnings = [];
4684
4722
  const counts = {
4685
4723
  config: /* @__PURE__ */ new Map(),
@@ -6018,6 +6056,43 @@ ${familyInfo}`);
6018
6056
  });
6019
6057
  }
6020
6058
  }
6059
+ const devComponentNamesPath = join(nuxt.options.buildDir, "cache", "og-image", "dev-component-names.json");
6060
+ if (nuxt.options.dev)
6061
+ fs.rmSync(devComponentNamesPath, { force: true });
6062
+ let devComponentNamesWrite;
6063
+ let devComponentNamesStale = false;
6064
+ async function writeDevComponentNames() {
6065
+ if (!nuxt.options.dev)
6066
+ return;
6067
+ if (devComponentNamesWrite) {
6068
+ devComponentNamesStale = true;
6069
+ await devComponentNamesWrite;
6070
+ return;
6071
+ }
6072
+ const writeOnce = async () => {
6073
+ const payload = JSON.stringify(ogImageComponentCtx.components);
6074
+ await mkdir(dirname(devComponentNamesPath), { recursive: true });
6075
+ const tmpPath = `${devComponentNamesPath}.${process.pid}.tmp`;
6076
+ try {
6077
+ await writeFile(tmpPath, payload);
6078
+ await rename(tmpPath, devComponentNamesPath);
6079
+ } catch (error) {
6080
+ fs.rmSync(tmpPath, { force: true });
6081
+ logger.warn(`Could not refresh OG image component metadata: ${error.message}`);
6082
+ }
6083
+ };
6084
+ devComponentNamesWrite = (async () => {
6085
+ do {
6086
+ devComponentNamesStale = false;
6087
+ await writeOnce();
6088
+ } while (devComponentNamesStale);
6089
+ })();
6090
+ try {
6091
+ await devComponentNamesWrite;
6092
+ } finally {
6093
+ devComponentNamesWrite = void 0;
6094
+ }
6095
+ }
6021
6096
  await loadSfcCompiler();
6022
6097
  nuxt.hook("components:extend", async (components) => {
6023
6098
  allNuxtComponents = components;
@@ -6124,6 +6199,7 @@ Run: npx nuxt-og-image migrate v6`;
6124
6199
  }
6125
6200
  }
6126
6201
  await nuxt.hooks.callHook("nuxt-og-image:components", ogImageComponentCtx);
6202
+ await writeDevComponentNames();
6127
6203
  });
6128
6204
  addTemplate({
6129
6205
  filename: "nuxt-og-image/components.mjs",
@@ -6151,8 +6227,11 @@ Run: npx nuxt-og-image migrate v6`;
6151
6227
  });
6152
6228
  nuxt.options.nitro.virtual = nuxt.options.nitro.virtual || {};
6153
6229
  nuxt.options.nitro.virtual["#og-image-virtual/component-names.mjs"] = () => {
6154
- const components = nuxt.options.dev ? ogImageComponentCtx.components : getServerComponents(ogImageComponentCtx.components);
6155
- return `export const componentNames = ${JSON.stringify(components)}`;
6230
+ if (nuxt.options.dev) {
6231
+ return `import { createDevComponentNamesProxy } from ${JSON.stringify(resolve("./runtime/server/og-image/dev-component-names"))}
6232
+ export const componentNames = createDevComponentNamesProxy(${JSON.stringify(devComponentNamesPath)}, ${JSON.stringify(ogImageComponentCtx.components)})`;
6233
+ }
6234
+ return `export const componentNames = ${JSON.stringify(getServerComponents(ogImageComponentCtx.components))}`;
6156
6235
  };
6157
6236
  nuxt.options.nitro.virtual["#og-image/island-hash"] = () => {
6158
6237
  const islandHashFile = join(nuxt.options.appDir, "island-hash.js");
@@ -6512,7 +6591,10 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6512
6591
  nuxt.hooks.hook("nitro:init", resolveNitro);
6513
6592
  });
6514
6593
  nuxt.hook("builder:watch", async (event, relativePath) => {
6515
- const absolutePath = isAbsolute(relativePath) ? relativePath : join(nuxt.options.rootDir, relativePath);
6594
+ const absolutePath = resolveWatchedPath(relativePath, {
6595
+ rootDir: nuxt.options.rootDir,
6596
+ srcDir: nuxt.options.srcDir
6597
+ });
6516
6598
  if (absolutePath.endsWith(".css") && nuxt.options.css.some((entry) => {
6517
6599
  const src = typeof entry === "string" ? entry : entry?.src;
6518
6600
  return src && absolutePath.endsWith(src.replace(RE_TILDE_PREFIX, ""));
@@ -6526,15 +6608,41 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6526
6608
  }
6527
6609
  if (!absolutePath.endsWith(".vue"))
6528
6610
  return;
6529
- const isOgImageComponent = config.componentDirs.some((dir) => {
6530
- const componentDir = join(nuxt.options.srcDir, "components", dir);
6531
- return absolutePath.startsWith(componentDir);
6532
- });
6533
- if (isOgImageComponent && (event === "add" || event === "unlink")) {
6611
+ const isOgImageComponent = isOgImageComponentPath(absolutePath, nuxt.options.srcDir, config.componentDirs);
6612
+ const existingComponent = ogImageComponentCtx.components.find((c) => c.path && isSamePath(c.path, absolutePath));
6613
+ if ((isOgImageComponent || existingComponent) && (event === "add" || event === "unlink")) {
6534
6614
  logger.debug(`HMR: OG image component ${event === "add" ? "added" : "removed"}`);
6535
6615
  await updateTemplates({ filter: (t) => t.filename.includes("nuxt-og-image") });
6536
6616
  const nitro = await useNitro;
6537
6617
  await nitro.hooks.callHook("rollup:reload");
6618
+ return;
6619
+ }
6620
+ if (event === "change" && existingComponent) {
6621
+ let content;
6622
+ try {
6623
+ content = await readFile(absolutePath, "utf-8");
6624
+ } catch {
6625
+ return;
6626
+ }
6627
+ await loadSfcCompiler();
6628
+ const nextHash = fnv1a64Base36(content);
6629
+ const nextPropNames = extractPropNamesFromVue(content);
6630
+ const nextCredits = content.split("\n").find((line) => line.startsWith(" * @credits"))?.replace("* @credits", "").trim();
6631
+ const propNamesChanged = nextPropNames.length !== (existingComponent.propNames?.length ?? 0) || nextPropNames.some((prop, idx) => prop !== existingComponent.propNames?.[idx]);
6632
+ const hashChanged = nextHash !== existingComponent.hash;
6633
+ const creditsChanged = nextCredits !== existingComponent.credits;
6634
+ if (!propNamesChanged && !hashChanged && !creditsChanged)
6635
+ return;
6636
+ existingComponent.hash = nextHash;
6637
+ existingComponent.propNames = nextPropNames;
6638
+ existingComponent.credits = nextCredits;
6639
+ logger.debug(`HMR: OG image component metadata updated (${existingComponent.pascalName})`);
6640
+ await writeDevComponentNames();
6641
+ if (propNamesChanged || hashChanged) {
6642
+ await updateTemplates({
6643
+ filter: (t) => t.filename.includes("nuxt-og-image/components.mjs") || t.filename.includes("nuxt-og-image/component-hashes.mjs")
6644
+ });
6645
+ }
6538
6646
  }
6539
6647
  });
6540
6648
  } else if (isNuxtGenerate()) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-og-image",
3
3
  "type": "module",
4
- "version": "7.1.1",
4
+ "version": "7.2.0",
5
5
  "description": "Enlightened OG Image generation for Nuxt.",
6
6
  "author": {
7
7
  "website": "https://harlanzw.com",