Fixed custom OG image using old extension

This commit is contained in:
Stephen Tse 2025-04-26 19:26:37 -07:00
parent e80ade76be
commit 17e922b8c5
2 changed files with 26 additions and 0 deletions

View File

@ -12,6 +12,8 @@ import { BuildCtx } from "../../util/ctx"
import { QuartzPluginData } from "../vfile" import { QuartzPluginData } from "../vfile"
import fs from "node:fs/promises" import fs from "node:fs/promises"
import chalk from "chalk" import chalk from "chalk"
import { getExtFromUrl } from "../../util/url"
import { imageExtsToOptimize, targetOptimizedImageExt } from "./assets"
const defaultOptions: SocialImageOptions = { const defaultOptions: SocialImageOptions = {
colorScheme: "lightMode", colorScheme: "lightMode",
@ -151,6 +153,17 @@ export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> =
userDefinedOgImagePath = isAbsoluteURL(userDefinedOgImagePath) userDefinedOgImagePath = isAbsoluteURL(userDefinedOgImagePath)
? userDefinedOgImagePath ? userDefinedOgImagePath
: `https://${baseUrl}/static/${userDefinedOgImagePath}` : `https://${baseUrl}/static/${userDefinedOgImagePath}`
// Replace extension of eligible image files with target extension if image optimization is enabled.
if (ctx.cfg.configuration.optimizeImages) {
const ext = getExtFromUrl(userDefinedOgImagePath)?.toLowerCase()
if (ext && imageExtsToOptimize.has(ext)) {
userDefinedOgImagePath = userDefinedOgImagePath.replace(
ext,
targetOptimizedImageExt,
)
}
}
} }
const generatedOgImagePath = isRealFile const generatedOgImagePath = isRealFile

13
quartz/util/url.ts Normal file
View File

@ -0,0 +1,13 @@
/**
* Extracts file extension from a file resource URL.
*
* @param url - URL to extract the file extension from
* @returns The file extension (with a preceding dot) or undefined if none found
*/
export function getExtFromUrl(url: string): string | undefined {
const urlObj = new URL(url)
const pathname = urlObj.pathname
// Remove any query parameters or hash first
const ext = pathname.split(/[#?]/)[0].split(".").pop()?.trim()
return ext === pathname ? undefined : "." + ext
}