Skip to content

Commit 7a7d5a1

Browse files
committed
chore: new type issues
1 parent 1348648 commit 7a7d5a1

File tree

15 files changed

+73
-77
lines changed

15 files changed

+73
-77
lines changed

playground/nuxt.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ export default defineNuxtConfig({
151151
},
152152
},
153153
'/satori/route-rules/**': {
154+
// @ts-expect-error untyped
154155
site: {
155156
name: 'nuxt-og-image-route-rules',
156157
},

src/build/devtools.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@ export function setupDevToolsUI(options: ModuleOptions, resolve: Resolver['resol
4949
const rpc = extendServerRpc<ClientFunctions, ServerFunctions>('nuxt-og-image', {
5050
async ejectCommunityTemplate(path: string) {
5151
const [dirName, componentName] = path.split('/')
52-
const dir = resolve(nuxt.options.rootDir, 'components', dirName)
52+
const dir = resolve(nuxt.options.rootDir, 'components', dirName || '')
5353
if (!existsSync(dir)) {
5454
mkdirSync(dir)
5555
}
56-
const newPath = resolve(dir, componentName)
56+
const newPath = resolve(dir, componentName || '')
5757
const templatePath = resolve(`./runtime/app/components/Templates/Community/${componentName}`)
5858
// readFile, we need to modify it
5959
const template = (await readFile(templatePath, 'utf-8')).replace('{{ title }}', `{{ title }} - Ejected!`)

src/compatibility.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,9 @@ export function resolveNitroPreset(nitroConfig?: NitroConfig): string {
125125
}
126126

127127
export function getPresetNitroPresetCompatibility(target: string) {
128-
let compatibility: RuntimeCompatibilitySchema = RuntimeCompatibility[target as keyof typeof RuntimeCompatibility]
128+
let compatibility: RuntimeCompatibilitySchema = RuntimeCompatibility[target as keyof typeof RuntimeCompatibility]!
129129
if (!compatibility)
130-
compatibility = RuntimeCompatibility['nitro-dev']
130+
compatibility = RuntimeCompatibility['nitro-dev']!
131131
return compatibility
132132
}
133133

src/kit.ts

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { Nuxt, NuxtModule } from '@nuxt/schema'
2-
import { addTemplate, createResolver, loadNuxtModuleInstance, useNuxt } from '@nuxt/kit'
3-
import { relative } from 'pathe'
2+
import { loadNuxtModuleInstance, useNuxt } from '@nuxt/kit'
43

54
/**
65
* Get the user provided options for a Nuxt module.
@@ -33,33 +32,6 @@ export async function getNuxtModuleOptions(module: string | NuxtModule, nuxt: Nu
3332
return inlineOptions
3433
}
3534

36-
export function extendTypes(module: string, template: (options: { typesPath: string }) => string | Promise<string>) {
37-
const nuxt = useNuxt()
38-
const { resolve } = createResolver(import.meta.url)
39-
// paths.d.ts
40-
addTemplate({
41-
filename: `module/${module}.d.ts`,
42-
getContents: async () => {
43-
const typesPath = relative(resolve(nuxt!.options.rootDir, nuxt!.options.buildDir, 'module'), resolve('runtime/types'))
44-
const s = await template({ typesPath })
45-
return `// Generated by ${module}
46-
${s}
47-
export {}
48-
`
49-
},
50-
})
51-
52-
nuxt.hooks.hook('prepare:types', ({ references }) => {
53-
references.push({ path: resolve(nuxt.options.buildDir, `module/${module}.d.ts`) })
54-
})
55-
nuxt.hooks.hook('nitro:config', (config) => {
56-
config.typescript = config.typescript || {}
57-
config.typescript.tsConfig = config.typescript.tsConfig || {}
58-
config.typescript.tsConfig.include = config.typescript.tsConfig.include || []
59-
config.typescript.tsConfig.include.push(`./module/${module}.d.ts`)
60-
})
61-
}
62-
6335
export function isNuxtGenerate(nuxt: Nuxt = useNuxt()) {
6436
return (nuxt.options as any)._generate /* TODO: remove in future major */ || nuxt.options.nitro.static || nuxt.options.nitro.preset === 'static'
6537
}

src/module.ts

Lines changed: 37 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import type {
1717
import * as fs from 'node:fs'
1818
import { existsSync } from 'node:fs'
1919
import { readFile } from 'node:fs/promises'
20-
import { addBuildPlugin, addComponent, addComponentsDir, addImports, addPlugin, addServerHandler, addServerPlugin, addTemplate, createResolver, defineNuxtModule, hasNuxtModule, hasNuxtModuleCompatibility } from '@nuxt/kit'
20+
import { addBuildPlugin, addComponent, addComponentsDir, addImports, addPlugin, addServerHandler, addServerPlugin, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, hasNuxtModule, hasNuxtModuleCompatibility } from '@nuxt/kit'
2121
import { defu } from 'defu'
2222
import { installNuxtSiteConfig } from 'nuxt-site-config/kit'
2323
import { hash } from 'ohash'
@@ -38,7 +38,7 @@ import {
3838
getPresetNitroPresetCompatibility,
3939
resolveNitroPreset,
4040
} from './compatibility'
41-
import { extendTypes, getNuxtModuleOptions, isNuxtGenerate } from './kit'
41+
import { getNuxtModuleOptions, isNuxtGenerate } from './kit'
4242
import { normaliseFontInput } from './pure'
4343
import { logger } from './runtime/logger'
4444
import { checkLocalChrome, downloadFont, hasResolvableDependency, isUndefinedOrTruthy } from './util'
@@ -155,7 +155,6 @@ export default defineNuxtModule<ModuleOptions>({
155155
name: 'nuxt-og-image',
156156
compatibility: {
157157
nuxt: '>=3.16.0',
158-
bridge: false,
159158
},
160159
configKey: 'ogImage',
161160
},
@@ -222,7 +221,7 @@ export default defineNuxtModule<ModuleOptions>({
222221
const basePath = config.zeroRuntime ? './runtime/server/routes/__zero-runtime' : './runtime/server/routes'
223222
let publicDirAbs = nuxt.options.dir.public
224223
if (!isAbsolute(publicDirAbs)) {
225-
publicDirAbs = publicDirAbs in nuxt.options.alias ? nuxt.options.alias[publicDirAbs] : resolve(nuxt.options.rootDir, publicDirAbs)
224+
publicDirAbs = (publicDirAbs in nuxt.options.alias ? nuxt.options.alias[publicDirAbs] : resolve(nuxt.options.rootDir, publicDirAbs)) || ''
226225
}
227226
if (isProviderEnabledForEnv('satori', nuxt, config)) {
228227
let attemptSharpUsage = false
@@ -463,6 +462,8 @@ export default defineNuxtModule<ModuleOptions>({
463462
from: resolve(`./runtime/app/composables/${name}`),
464463
})
465464
if (!nuxt.options.dev) {
465+
nuxt.options.optimization.treeShake.composables.client = nuxt.options.optimization.treeShake.composables.client || {}
466+
nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'] = nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'] || []
466467
nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'].push(name)
467468
}
468469
})
@@ -578,23 +579,24 @@ export default defineNuxtModule<ModuleOptions>({
578579
return `export const theme = ${JSON.stringify(unoCssConfig)}`
579580
}
580581

581-
extendTypes('nuxt-og-image', ({ typesPath }) => {
582-
// need to map our components to types so we can import them
583-
const componentImports = ogImageComponentCtx.components.map((component) => {
584-
const relativeComponentPath = relative(resolve(nuxt!.options.rootDir, nuxt!.options.buildDir, 'module'), component.path!)
585-
// remove dirNames from component name
586-
const name = config.componentDirs
587-
// need to sort by longest first so we don't replace the wrong part of the string
588-
.sort((a, b) => b.length - a.length)
589-
.reduce((name, dir) => {
590-
// only replace from the start of the string
591-
return name.replace(new RegExp(`^${dir}`), '')
592-
}, component.pascalName)
593-
return ` '${name}': typeof import('${relativeComponentPath}')['default']`
594-
}).join('\n')
595-
return `
596-
declare module 'nitropack' {
597-
interface NitroRouteRules {
582+
addTypeTemplate({
583+
filename: 'module/nuxt-og-image.d.ts',
584+
getContents: (data) => {
585+
const typesPath = relative(resolve(data.nuxt!.options.rootDir, data.nuxt!.options.buildDir, 'module'), resolve('runtime/types'))
586+
// need to map our components to types so we can import them
587+
const componentImports = ogImageComponentCtx.components.map((component) => {
588+
const relativeComponentPath = relative(resolve(nuxt!.options.rootDir, nuxt!.options.buildDir, 'module'), component.path!)
589+
// remove dirNames from component name
590+
const name = config.componentDirs
591+
// need to sort by longest first so we don't replace the wrong part of the string
592+
.sort((a, b) => b.length - a.length)
593+
.reduce((name, dir) => {
594+
// only replace from the start of the string
595+
return name.replace(new RegExp(`^${dir}`), '')
596+
}, component.pascalName)
597+
return ` '${name}': typeof import('${relativeComponentPath}')['default']`
598+
}).join('\n')
599+
const types = `interface NitroRouteRules {
598600
ogImage?: false | import('${typesPath}').OgImageOptions & Record<string, any>
599601
}
600602
interface NitroRouteConfig {
@@ -603,7 +605,14 @@ declare module 'nitropack' {
603605
interface NitroRuntimeHooks {
604606
'nuxt-og-image:context': (ctx: import('${typesPath}').OgImageRenderEventContext) => void | Promise<void>
605607
'nuxt-og-image:satori:vnodes': (vnodes: import('${typesPath}').VNode, ctx: import('${typesPath}').OgImageRenderEventContext) => void | Promise<void>
606-
}
608+
}`
609+
return `
610+
declare module 'nitropack' {
611+
${types}
612+
}
613+
614+
declare module 'nitropack/types' {
615+
${types}
607616
}
608617
609618
declare module '#og-image/components' {
@@ -614,7 +623,13 @@ ${componentImports}
614623
declare module '#og-image/unocss-config' {
615624
export type theme = any
616625
}
626+
627+
export {}
617628
`
629+
},
630+
}, {
631+
nitro: true,
632+
nuxt: true,
618633
})
619634

620635
const cacheEnabled = typeof config.runtimeCacheStorage !== 'undefined' && config.runtimeCacheStorage !== false

src/runtime/app/utils/plugins.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ export function ogImageCanonicalUrls(nuxtApp: NuxtSSRContext['nuxt']) {
5151
ctx.tags = ctx.tags.filter(Boolean)
5252

5353
for (const tag of ctx.tags) {
54-
if (tag.tag === 'meta' && (tag.props.property === 'og:image' || ['twitter:image:src', 'twitter:image'].includes(tag.props.name))) {
54+
if (tag.tag === 'meta' && (tag.props.property === 'og:image' || ['twitter:image:src', 'twitter:image'].includes(tag.props.name || ''))) {
5555
if (!tag.props.content) {
5656
tag.props = {} // equivalent to removing
5757
continue
@@ -61,7 +61,7 @@ export function ogImageCanonicalUrls(nuxtApp: NuxtSSRContext['nuxt']) {
6161
// property twitter:image:src
6262
if (!tag.props.content?.startsWith('https')) {
6363
await nuxtApp.runWithContext(() => {
64-
tag.props.content = toValue(withSiteUrl(tag.props.content, {
64+
tag.props.content = toValue(withSiteUrl(tag.props.content || '', {
6565
withBase: true,
6666
}))
6767
})
@@ -91,7 +91,7 @@ export function routeRuleOgImage(nuxtApp: NuxtSSRContext['nuxt']) {
9191
createRadixRouter({ routes: ssrContext?.runtimeConfig?.nitro?.routeRules }),
9292
)
9393
const matchedRules = _routeRulesMatcher.matchAll(
94-
withoutBase(path.split('?')[0], ssrContext?.runtimeConfig?.app.baseURL || ''),
94+
withoutBase(path.split('?')?.[0] || '', ssrContext?.runtimeConfig?.app.baseURL || ''),
9595
).reverse()
9696
const combinedRules = defu({}, ...matchedRules) as any
9797
let routeRules = combinedRules?.ogImage as NitroRouteRules['ogImage']

src/runtime/server/og-image/context.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ const PAYLOAD_REGEX = /<script.+id="nuxt-og-image-options"[^>]*>(.+?)<\/script>/
171171

172172
function getPayloadFromHtml(html: string | unknown): string | null {
173173
const match = String(html).match(PAYLOAD_REGEX)
174-
return match ? match[1] : null
174+
return match ? String(match[1]) : null
175175
}
176176

177177
export function extractAndNormaliseOgImageOptions(html: string): OgImageOptions | false {

src/runtime/server/og-image/satori/plugins/unocss.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import type { VNode } from '../../../../types'
22
import { defineSatoriTransformer } from '../utils'
33

4+
function safeSplit(s: string) {
5+
const [key, value] = s.split(':')
6+
return [String(key || '').trim(), String(value || '').trim()] satisfies [string, string]
7+
}
8+
49
// convert classes to inline style using unocss, provides more robust API than satori
510
export default defineSatoriTransformer({
611
filter: (node: VNode) => !!node.props?.class,
@@ -13,7 +18,7 @@ export default defineSatoriTransformer({
1318
for (const token of classes.split(' ').filter(c => c.trim())) {
1419
const parsedToken = await ctx.unocss.parseToken(token)
1520
if (parsedToken) {
16-
const inlineStyles = parsedToken[0][2].split(';').filter(s => !!s?.trim())
21+
const inlineStyles = String(parsedToken?.[0]?.[2]).split(';').filter(s => !!s?.trim())
1722
const vars: Record<string, string> = {
1823
'--color-gray-50': '249 250 251',
1924
'--color-gray-100': '243 244 246',
@@ -29,27 +34,30 @@ export default defineSatoriTransformer({
2934
}
3035
inlineStyles.filter(s => s.startsWith('--'))
3136
.forEach((s) => {
32-
const [key, value] = s.split(':')
37+
const [key, value] = safeSplit(s)
3338
vars[key] = value
3439
})
3540
inlineStyles.filter(s => !s.startsWith('--'))
3641
.forEach((s) => {
37-
const [key, value] = s.split(':')
42+
const [key, value] = safeSplit(s)
3843
const camelCasedKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
3944
// we need to replace any occurances of a var key with the var values, avoid replacing existing inline styles
4045
if (!styles[camelCasedKey])
46+
// @ts-expect-error untyped
4147
styles[camelCasedKey] = value.replace(/var\((.*?)\)/g, (_, k) => vars[k.trim()])
4248

4349
// we need to replace this rgba syntax with either a regular rgb if opacity is 1
4450
// rgb(59 130 246 / 1) -> rgba(59, 130, 246)
4551
// rgba(59 130 246 / 0.5) -> rgba(59, 130, 246, 0.5)
4652
if (styles[camelCasedKey] && styles[camelCasedKey].includes('/')) {
4753
const [rgb, opacity] = styles[camelCasedKey].split('/')
48-
if (opacity.trim() === '1)')
49-
// eslint-disable-next-line regexp/optimal-quantifier-concatenation
50-
styles[camelCasedKey] = rgb.replace(/(\d+) (\d+) (\d+).*/, (_, r, g, b) => `${r}, ${g}, ${b})`)
51-
else
52-
styles[camelCasedKey] = `${rgb.replace('rgb', 'rgba').replaceAll(' ', ', ')}${opacity.trim()}`
54+
if (rgb && opacity) {
55+
if (opacity.trim() === '1)')
56+
// eslint-disable-next-line regexp/optimal-quantifier-concatenation
57+
styles[camelCasedKey] = rgb.replace(/(\d+) (\d+) (\d+).*/, (_, r, g, b) => `${r}, ${g}, ${b})`)
58+
else
59+
styles[camelCasedKey] = `${rgb.replace('rgb', 'rgba').replaceAll(' ', ', ')}${opacity.trim()}`
60+
}
5361
}
5462
})
5563
replacedClasses.add(token)

src/runtime/server/og-image/satori/renderer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ async function resolveFonts(event: OgImageRenderEventContext) {
3434
return _font
3535
})
3636
}
37-
localFontPromises.push(fontPromises[font.cacheKey])
37+
localFontPromises.push(fontPromises[font.cacheKey]!)
3838
}
3939
}
4040
}

src/runtime/server/plugins/prerender.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export default defineNitroPlugin(async (nitro) => {
3737
const index = html.bodyAppend.findIndex(script => script.includes('id="nuxt-og-image-options"'))
3838
if (index !== -1) {
3939
// we need to remove `<script id="nuxt-og-image-options" type="application/json">...anything...</script>`
40-
html.bodyAppend[index] = html.bodyAppend[index].replace(/<script id="nuxt-og-image-options" type="application\/json">[\s\S]*?<\/script>/, '')
40+
html.bodyAppend[index] = String(html.bodyAppend[index]).replace(/<script id="nuxt-og-image-options" type="application\/json">[\s\S]*?<\/script>/, '')
4141
html.bodyAppend[index] = html.bodyAppend[index].replace(/<script id="nuxt-og-image-overrides" type="application\/json">[\s\S]*?<\/script>/, '')
4242
}
4343
})

0 commit comments

Comments
 (0)