refactor(nuxt): add import protection to nitro config (#5847)

This commit is contained in:
Daniel Roe 2022-07-12 11:55:32 +01:00 committed by GitHub
parent 2d70507d1c
commit 1840b96335
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 12 deletions

View File

@ -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 })

View File

@ -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) {