From 1840b9633535b43631c6a57ef3e45799ca062a96 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 12 Jul 2022 11:55:32 +0100 Subject: [PATCH] refactor(nuxt): add import protection to nitro config (#5847) --- packages/nuxt/src/core/nitro.ts | 22 +++++++++---------- .../src/core/plugins/import-protection.ts | 4 ++++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/packages/nuxt/src/core/nitro.ts b/packages/nuxt/src/core/nitro.ts index 1d67b63524..f1e383a54b 100644 --- a/packages/nuxt/src/core/nitro.ts +++ b/packages/nuxt/src/core/nitro.ts @@ -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 }) diff --git a/packages/nuxt/src/core/plugins/import-protection.ts b/packages/nuxt/src/core/plugins/import-protection.ts index 6237a579c6..3826ff6b6b 100644 --- a/packages/nuxt/src/core/plugins/import-protection.ts +++ b/packages/nuxt/src/core/plugins/import-protection.ts @@ -10,6 +10,7 @@ const _require = createRequire(import.meta.url) interface ImportProtectionOptions { rootDir: string patterns: [importPattern: string | RegExp, warning?: string][] + exclude?: Array } export const vueAppPatterns = (nuxt: Nuxt) => [ @@ -25,10 +26,13 @@ export const vueAppPatterns = (nuxt: Nuxt) => [ export const ImportProtectionPlugin = createUnplugin(function (options: ImportProtectionOptions) { const cache: Record> = {} + 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) {