Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for image helpers in nitro endpoints #1473

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 24 additions & 11 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import process from 'node:process'

import { parseURL, withLeadingSlash } from 'ufo'
import { defineNuxtModule, addTemplate, addImports, createResolver, addComponent, addPlugin } from '@nuxt/kit'
import { defineNuxtModule, addTemplate, addImports, addServerImports, createResolver, addComponent, addPlugin } from '@nuxt/kit'
import { resolve } from 'pathe'
import { resolveProviders, detectProvider, resolveProvider } from './provider'
import type { ImageProviders, ImageOptions, InputProvider, CreateImageOptions } from './types'
import type { ImageProviders, ImageOptions, InputProvider, CreateImageOptions, ImageModuleProvider } from './types'

export interface ModuleOptions extends ImageProviders {
inject: boolean
Expand Down Expand Up @@ -121,18 +121,17 @@ export default defineNuxtModule<ModuleOptions>({
addTemplate({
filename: 'image-options.mjs',
getContents() {
return `
${providers.map(p => `import * as ${p.importName} from '${p.runtime}'`).join('\n')}

export const imageOptions = ${JSON.stringify(imageOptions, null, 2)}

imageOptions.providers = {
${providers.map(p => ` ['${p.name}']: { provider: ${p.importName}, defaults: ${JSON.stringify(p.runtimeOptions)} }`).join(',\n')}
}
`
return generateImageOptions(providers, imageOptions)
},
})

addServerImports([
{
name: 'useImage',
from: resolver.resolve('runtime/server/utils/image'),
},
])

nuxt.hook('nitro:init', async (nitro) => {
if (!options.provider || options.provider === 'ipx' || options.provider === 'ipxStatic') {
const resolvedProvider = nitro.options.static || options.provider === 'ipxStatic'
Expand All @@ -152,6 +151,8 @@ ${providers.map(p => ` ['${p.name}']: { provider: ${p.importName}, defaults: ${
await p.setup(p, options, nuxt)
}
}
// runtime options to use in nitro environment
nitro.options.virtual['#image-options'] = generateImageOptions(providers, imageOptions)
})

if (options.inject) {
Expand All @@ -170,3 +171,15 @@ function pick<O extends Record<any, any>, K extends keyof O>(obj: O, keys: K[]):
}
return newobj
}

function generateImageOptions(providers: ImageModuleProvider[], imageOptions: Omit<CreateImageOptions, 'providers' | 'nuxt' | 'runtimeConfig'>): string {
return `
${providers.map(p => `import * as ${p.importName} from '${p.runtime}'`).join('\n')}

export const imageOptions = ${JSON.stringify(imageOptions, null, 2)}

imageOptions.providers = {
${providers.map(p => ` ['${p.name}']: { provider: ${p.importName}, defaults: ${JSON.stringify(p.runtimeOptions)} }`).join(',\n')}
}
`
}
5 changes: 2 additions & 3 deletions src/runtime/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ import { imageMeta } from './utils/meta'
import { checkDensities, parseDensities, parseSize, parseSizes } from './utils'
import { prerenderStaticImages } from './utils/prerender'

export function createImage(globalOptions: CreateImageOptions) {
export function createImage(globalOptions: CreateImageOptions, isCalledInNitro: boolean = false) {
const ctx: ImageCTX = {
options: globalOptions,
}

const getImage: $Img['getImage'] = (input: string, options = {}) => {
const image = resolveImage(ctx, input, options)

// Prerender static images
if (import.meta.server && import.meta.prerender) {
if (import.meta.server && import.meta.prerender && !isCalledInNitro) {
Copy link
Member

@danielroe danielroe Sep 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we not want to hint to prerender static images if called from a server endpoint?

maybe instead we use getEvent and prerender them if it's available?

Copy link
Author

@Afshar07 Afshar07 Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the hint, i have tried the generate command and i see that beside this, i have a lot of unhandled situations!
But my main problem is i do not have access to image-options virtual file in nitro when generating, i need to handle that.
I investigate the source code more precisely, review my code and come back with a solution ASAP.
Is there anything specific i need to know? like about writing tests or anything else?
Thanks for your time.

prerenderStaticImages(image.url)
}

Expand Down
18 changes: 18 additions & 0 deletions src/runtime/server/utils/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Img } from '../../../module'

import { createImage } from '../../image'
// @ts-expect-error virtual file
import { imageOptions } from '#image-options'
import { useRuntimeConfig } from '#imports'

export const useImage = (): Img => {
const config = useRuntimeConfig()

return createImage({
...imageOptions,
nuxt: {
baseURL: config.app.baseURL,
},
runtimeConfig: config,
}, true)
}