mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 08:33:53 +00:00
refactor(nuxt): add import protection to nitro config (#5847)
This commit is contained in:
parent
2d70507d1c
commit
1840b96335
@ -106,6 +106,16 @@ export async function initNitro (nuxt: Nuxt) {
|
||||
nitroConfig.virtual['#build/dist/server/server.mjs'] = 'export default () => {}'
|
||||
}
|
||||
|
||||
// Register nuxt protection patterns
|
||||
nitroConfig.rollupConfig.plugins.push(ImportProtectionPlugin.rollup({
|
||||
rootDir: nuxt.options.rootDir,
|
||||
patterns: [
|
||||
...['#app', /^#build(\/|$)/]
|
||||
.map(p => [p, 'Vue app aliases are not allowed in server routes.']) as [RegExp | string, string][]
|
||||
],
|
||||
exclude: [/core[\\/]runtime[\\/]nitro[\\/]renderer/]
|
||||
}))
|
||||
|
||||
// Extend nitro config with hook
|
||||
await nuxt.callHook('nitro:config', nitroConfig)
|
||||
|
||||
@ -121,18 +131,6 @@ export async function initNitro (nuxt: Nuxt) {
|
||||
// Connect hooks
|
||||
nuxt.hook('close', () => nitro.hooks.callHook('close'))
|
||||
|
||||
// Register nuxt protection patterns
|
||||
nitro.hooks.hook('rollup:before', (nitro) => {
|
||||
const plugin = ImportProtectionPlugin.rollup({
|
||||
rootDir: nuxt.options.rootDir,
|
||||
patterns: [
|
||||
...['#app', /^#build(\/|$)/]
|
||||
.map(p => [p, 'Vue app aliases are not allowed in server routes.']) as [RegExp | string, string][]
|
||||
]
|
||||
})
|
||||
nitro.options.rollupConfig.plugins.push(plugin)
|
||||
})
|
||||
|
||||
// Setup handlers
|
||||
const devMidlewareHandler = dynamicEventHandler()
|
||||
nitro.options.devHandlers.unshift({ handler: devMidlewareHandler })
|
||||
|
@ -10,6 +10,7 @@ const _require = createRequire(import.meta.url)
|
||||
interface ImportProtectionOptions {
|
||||
rootDir: string
|
||||
patterns: [importPattern: string | RegExp, warning?: string][]
|
||||
exclude?: Array<RegExp | string>
|
||||
}
|
||||
|
||||
export const vueAppPatterns = (nuxt: Nuxt) => [
|
||||
@ -25,10 +26,13 @@ export const vueAppPatterns = (nuxt: Nuxt) => [
|
||||
|
||||
export const ImportProtectionPlugin = createUnplugin(function (options: ImportProtectionOptions) {
|
||||
const cache: Record<string, Map<string | RegExp, boolean>> = {}
|
||||
const importersToExclude = options?.exclude || []
|
||||
return {
|
||||
name: 'nuxt:import-protection',
|
||||
enforce: 'pre',
|
||||
resolveId (id, importer) {
|
||||
if (importersToExclude.some(p => typeof p === 'string' ? importer === p : p.test(importer))) { return }
|
||||
|
||||
const invalidImports = options.patterns.filter(([pattern]) => pattern instanceof RegExp ? pattern.test(id) : pattern === id)
|
||||
let matched: boolean
|
||||
for (const match of invalidImports) {
|
||||
|
Loading…
Reference in New Issue
Block a user