fix(vite, kit, nuxt): generate safe variable names using knitwork (#4906)

This commit is contained in:
Daniel Roe 2022-06-10 14:12:21 +01:00 committed by GitHub
parent 6947d30f01
commit 93f6a1e4ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 24 additions and 33 deletions

View File

@ -21,7 +21,7 @@
"hash-sum": "^2.0.0",
"ignore": "^5.2.0",
"jiti": "^1.13.0",
"knitwork": "^0.1.1",
"knitwork": "^0.1.2",
"lodash.template": "^4.5.0",
"mlly": "^0.5.2",
"pathe": "^0.3.0",

View File

@ -1,9 +1,6 @@
import { promises as fsp } from 'node:fs'
import lodashTemplate from 'lodash.template'
import hash from 'hash-sum'
import { camelCase } from 'scule'
import { basename, extname } from 'pathe'
import { genDynamicImport, genImport } from 'knitwork'
import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork'
import type { NuxtTemplate } from '@nuxt/schema'
@ -26,18 +23,16 @@ export async function compileTemplate (template: NuxtTemplate, ctx: any) {
const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, r => JSON.parse(r).replace(/^{(.*)}$/, '$1'))
const importName = (src: string) => `${camelCase(basename(src, extname(src))).replace(/[^a-zA-Z?\d\s:]/g, '')}_${hash(src)}`
const importSources = (sources: string | string[], { lazy = false } = {}) => {
if (!Array.isArray(sources)) {
sources = [sources]
}
return sources.map((src) => {
if (lazy) {
return `const ${importName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`
return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`
}
return genImport(src, importName(src))
return genImport(src, genSafeVariableName(src))
}).join('\n')
}
export const templateUtils = { serialize, importName, importSources }
export const templateUtils = { serialize, importName: genSafeVariableName, importSources }

View File

@ -49,7 +49,7 @@
"h3": "^0.7.8",
"hash-sum": "^2.0.0",
"hookable": "^5.1.1",
"knitwork": "^0.1.1",
"knitwork": "^0.1.2",
"magic-string": "^0.26.2",
"mlly": "^0.5.2",
"nitropack": "^0.4.4",

View File

@ -1,6 +1,6 @@
import { templateUtils } from '@nuxt/kit'
import type { Nuxt, NuxtApp, NuxtTemplate } from '@nuxt/schema'
import { genArrayFromRaw, genDynamicImport, genExport, genImport, genObjectFromRawEntries, genString } from 'knitwork'
import { genArrayFromRaw, genDynamicImport, genExport, genImport, genObjectFromRawEntries, genString, genSafeVariableName } from 'knitwork'
import { isAbsolute, join, relative } from 'pathe'
import { resolveSchema, generateTypes } from 'untyped'
@ -50,7 +50,7 @@ export const clientPluginTemplate = {
const clientPlugins = ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server')
return [
templateUtils.importSources(clientPlugins.map(p => p.src)),
`export default ${genArrayFromRaw(clientPlugins.map(p => templateUtils.importName(p.src)))}`
`export default ${genArrayFromRaw(clientPlugins.map(p => genSafeVariableName(p.src)))}`
].join('\n')
}
}
@ -64,7 +64,7 @@ export const serverPluginTemplate = {
templateUtils.importSources(serverPlugins.map(p => p.src)),
`export default ${genArrayFromRaw([
'preload',
...serverPlugins.map(p => templateUtils.importName(p.src))
...serverPlugins.map(p => genSafeVariableName(p.src))
])}`
].join('\n')
}

View File

@ -1,10 +1,10 @@
import { existsSync } from 'node:fs'
import { defineNuxtModule, addTemplate, addPlugin, addVitePlugin, addWebpackPlugin, findPath } from '@nuxt/kit'
import { resolve } from 'pathe'
import { genDynamicImport, genString, genArrayFromRaw, genImport, genObjectFromRawEntries } from 'knitwork'
import { genDynamicImport, genString, genArrayFromRaw, genImport, genObjectFromRawEntries, genSafeVariableName } from 'knitwork'
import escapeRE from 'escape-string-regexp'
import { distDir } from '../dirs'
import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils'
import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware } from './utils'
import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros'
export default defineNuxtModule({
@ -113,8 +113,8 @@ export default defineNuxtModule({
const namedMiddleware = middleware.filter(mw => !mw.global)
const namedMiddlewareObject = genObjectFromRawEntries(namedMiddleware.map(mw => [mw.name, genDynamicImport(mw.path)]))
return [
...globalMiddleware.map(mw => genImport(mw.path, getImportName(mw.name))),
`export const globalMiddleware = ${genArrayFromRaw(globalMiddleware.map(mw => getImportName(mw.name)))}`,
...globalMiddleware.map(mw => genImport(mw.path, genSafeVariableName(mw.name))),
`export const globalMiddleware = ${genArrayFromRaw(globalMiddleware.map(mw => genSafeVariableName(mw.name)))}`,
`export const namedMiddleware = ${namedMiddlewareObject}`
].join('\n')
}

View File

@ -2,8 +2,8 @@ import { basename, extname, normalize, relative, resolve } from 'pathe'
import { encodePath } from 'ufo'
import { NuxtMiddleware, NuxtPage } from '@nuxt/schema'
import { resolveFiles, useNuxt } from '@nuxt/kit'
import { kebabCase, pascalCase } from 'scule'
import { genImport, genDynamicImport, genArrayFromRaw } from 'knitwork'
import { kebabCase } from 'scule'
import { genImport, genDynamicImport, genArrayFromRaw, genSafeVariableName } from 'knitwork'
import escapeRE from 'escape-string-regexp'
enum SegmentParserState {
@ -233,7 +233,7 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
imports: metaImports,
routes: genArrayFromRaw(routes.map((route) => {
const file = normalize(route.file)
const metaImportName = getImportName(file) + 'Meta'
const metaImportName = genSafeVariableName(file) + 'Meta'
metaImports.add(genImport(`${file}?macro=true`, [{ name: 'meta', as: metaImportName }]))
return {
...Object.fromEntries(Object.entries(route).map(([key, value]) => [key, JSON.stringify(value)])),
@ -271,10 +271,6 @@ function hasSuffix (path: string, suffix: string) {
return basename(path).replace(extname(path), '').endsWith(suffix)
}
export function getImportName (name: string) {
return pascalCase(name).replace(/[^\w]/g, r => '_' + r.charCodeAt(0))
}
function uniqueBy <T, K extends keyof T> (arr: T[], key: K) {
const res: T[] = []
const seen = new Set<T[K]>()

View File

@ -33,7 +33,7 @@
"fs-extra": "^10.1.0",
"get-port-please": "^2.5.0",
"h3": "^0.7.8",
"knitwork": "^0.1.1",
"knitwork": "^0.1.2",
"magic-string": "^0.26.2",
"mlly": "^0.5.2",
"pathe": "^0.3.0",

View File

@ -1627,7 +1627,7 @@ __metadata:
hash-sum: ^2.0.0
ignore: ^5.2.0
jiti: ^1.13.0
knitwork: ^0.1.1
knitwork: ^0.1.2
lodash.template: ^4.5.0
mlly: ^0.5.2
pathe: ^0.3.0
@ -1766,7 +1766,7 @@ __metadata:
fs-extra: ^10.1.0
get-port-please: ^2.5.0
h3: ^0.7.8
knitwork: ^0.1.1
knitwork: ^0.1.2
magic-string: ^0.26.2
mlly: ^0.5.2
pathe: ^0.3.0
@ -8333,10 +8333,10 @@ __metadata:
languageName: node
linkType: hard
"knitwork@npm:^0.1.1":
version: 0.1.1
resolution: "knitwork@npm:0.1.1"
checksum: 63b6dbb858d220ee288465f9702bf58e01588fb1469e3664158ab63b32bbe439d9c089165c4cc00d5773416eb5682ca219c34e258e81e91cacc20f940496ed97
"knitwork@npm:^0.1.2":
version: 0.1.2
resolution: "knitwork@npm:0.1.2"
checksum: aadc6f150ff2b93c509553bf9e7a5884e67fd193eda12b265ea7f90742d6d461cc90b14059310f91f009dacd03103cea7ef4f5afaaf895a85007e3983b307ea7
languageName: node
linkType: hard
@ -9980,7 +9980,7 @@ __metadata:
h3: ^0.7.8
hash-sum: ^2.0.0
hookable: ^5.1.1
knitwork: ^0.1.1
knitwork: ^0.1.2
magic-string: ^0.26.2
mlly: ^0.5.2
nitropack: ^0.4.4