refactor: goodbye ts-morph

This commit is contained in:
zernonia 2024-06-18 22:17:01 +08:00
parent 42d6cfd252
commit 7033b4b02f
11 changed files with 253 additions and 327 deletions

View File

@ -1,14 +1,11 @@
import { promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'pathe'
import { Project, ScriptKind, type SourceFile } from 'ts-morph'
import type * as z from 'zod'
import { transform as metaTransform } from 'vue-metamorph'
import { transformTwPrefix } from './transform-tw-prefix'
import type { Config } from '@/src/utils/get-config'
import type { registryBaseColorSchema } from '@/src/utils/registry/schema'
import { transformCssVars } from '@/src/utils/transformers/transform-css-vars'
import { transformImport } from '@/src/utils/transformers/transform-import'
import { transformSFC } from '@/src/utils/transformers/transform-sfc'
import { transformTwPrefixes } from '@/src/utils/transformers/transform-tw-prefix'
export interface TransformOpts {
filename: string
@ -17,38 +14,12 @@ export interface TransformOpts {
baseColor?: z.infer<typeof registryBaseColorSchema>
}
export type Transformer<Output = SourceFile> = (
opts: TransformOpts & {
sourceFile: SourceFile
}
) => Promise<Output>
const transformers: Transformer[] = [
transformCssVars,
transformImport,
transformTwPrefixes,
]
const project = new Project({
compilerOptions: {},
})
async function createTempSourceFile(filename: string) {
const dir = await fs.mkdtemp(path.join(tmpdir(), 'shadcn-'))
return path.join(dir, filename)
}
export async function transform(opts: TransformOpts) {
const tempFile = await createTempSourceFile(opts.filename)
const sourceFile = project.createSourceFile(tempFile, opts.raw, {
scriptKind: ScriptKind.Unknown,
})
const source = await transformSFC(opts)
for (const transformer of transformers)
transformer({ sourceFile, ...opts })
return await transformSFC({
sourceFile,
...opts,
})
return metaTransform(source, opts.filename, [
transformImport(opts),
transformCssVars(opts),
transformTwPrefix(opts),
]).code
}

View File

@ -1,108 +0,0 @@
import { transform as metaTransform } from 'vue-metamorph'
import type { AST, CodemodPlugin } from 'vue-metamorph'
import type * as z from 'zod'
import { splitClassName } from './transform-css-vars'
import type { Config } from '@/src/utils/get-config'
import type { registryBaseColorSchema } from '@/src/utils/registry/schema'
export interface TransformOpts {
filename: string
raw: string
config: Config
baseColor?: z.infer<typeof registryBaseColorSchema>
}
function transformTwPrefix(config: Config): CodemodPlugin {
return {
type: 'codemod',
name: 'change string literals to hello, world',
// eslint-disable-next-line unused-imports/no-unused-vars
transform({ scriptASTs, sfcAST, styleASTs, filename, utils: { traverseScriptAST, traverseTemplateAST } }) {
// codemod plugins self-report the number of transforms it made
// this is only used to print the stats in CLI output
let transformCount = 0
// scriptASTs is an array of Program ASTs
// in a js/ts file, this array will only have one item
// in a vue file, this array will have one item for each <script> block
for (const scriptAST of scriptASTs) {
// traverseScriptAST is an alias for the ast-types 'visit' function
// see: https://github.com/benjamn/ast-types#ast-traversal
traverseScriptAST(scriptAST, {
visitLiteral(path) {
if (path.parent.value.type !== 'ImportDeclaration' && typeof path.node.value === 'string') {
// mutate the node
path.node.value = applyPrefix(path.node.value, config.tailwind.prefix)
transformCount++
}
return this.traverse(path)
},
})
}
if (sfcAST) {
// traverseTemplateAST is an alias for the vue-eslint-parser 'AST.traverseNodes' function
// see: https://github.com/vuejs/vue-eslint-parser/blob/master/src/ast/traverse.ts#L118
traverseTemplateAST(sfcAST, {
enterNode(node) {
if (node.type === 'Literal' && typeof node.value === 'string') {
if (!['BinaryExpression', 'Property'].includes(node.parent?.type ?? '')) {
node.value = applyPrefix(node.value, config.tailwind.prefix)
transformCount++
}
}
// handle class attribute without binding
else if (node.type === 'VLiteral' && typeof node.value === 'string') {
if (node.parent.key.name === 'class') {
node.value = `"${applyPrefix(node.value, config.tailwind.prefix)}"`
transformCount++
}
}
},
leaveNode() {
},
})
}
return transformCount
},
}
}
export function transform(opt: TransformOpts) {
return metaTransform(opt.raw, opt.filename, [transformTwPrefix(opt.config)]).code
}
export function applyPrefix(input: string, prefix: string = '') {
const classNames = input.split(' ')
const prefixed: string[] = []
for (const className of classNames) {
const [variant, value, modifier] = splitClassName(className)
if (variant) {
modifier
? prefixed.push(`${variant}:${prefix}${value}/${modifier}`)
: prefixed.push(`${variant}:${prefix}${value}`)
}
else {
modifier
? prefixed.push(`${prefix}${value}/${modifier}`)
: prefixed.push(`${prefix}${value}`)
}
}
return prefixed.join(' ')
}
export function applyPrefixesCss(css: string, prefix: string) {
const lines = css.split('\n')
for (const line of lines) {
if (line.includes('@apply')) {
const originalTWCls = line.replace('@apply', '').trim()
const prefixedTwCls = applyPrefix(originalTWCls, prefix)
css = css.replace(originalTWCls, prefixedTwCls)
}
}
return css
}

View File

@ -1,52 +1,69 @@
import type * as z from 'zod'
import MagicString from 'magic-string'
import type { SFCTemplateBlock } from '@vue/compiler-sfc'
import { parse } from '@vue/compiler-sfc'
import { SyntaxKind } from 'ts-morph'
import type { CodemodPlugin } from 'vue-metamorph'
import type { TransformOpts } from '.'
import type { registryBaseColorSchema } from '@/src/utils/registry/schema'
import type { Transformer } from '@/src/utils/transformers'
export const transformCssVars: Transformer = async ({
sourceFile,
config,
baseColor,
}) => {
const isVueFile = sourceFile.getFilePath().endsWith('vue')
// No transform if using css variables.
export function transformCssVars(opts: TransformOpts): CodemodPlugin {
return {
type: 'codemod',
name: 'add prefix to tailwind classes',
// eslint-disable-next-line unused-imports/no-unused-vars
transform({ scriptASTs, sfcAST, styleASTs, filename, utils: { traverseScriptAST, traverseTemplateAST } }) {
// codemod plugins self-report the number of transforms it made
// this is only used to print the stats in CLI output
let transformCount = 0
const { baseColor, config } = opts
if (config.tailwind?.cssVariables || !baseColor?.inlineColors)
return sourceFile
return transformCount
let template: SFCTemplateBlock | null = null
if (isVueFile) {
const parsed = parse(sourceFile.getText())
template = parsed.descriptor.template
if (!template)
return sourceFile
// scriptASTs is an array of Program ASTs
// in a js/ts file, this array will only have one item
// in a vue file, this array will have one item for each <script> block
for (const scriptAST of scriptASTs) {
// traverseScriptAST is an alias for the ast-types 'visit' function
// see: https://github.com/benjamn/ast-types#ast-traversal
traverseScriptAST(scriptAST, {
visitLiteral(path) {
if (path.parent.value.type !== 'ImportDeclaration' && typeof path.node.value === 'string') {
// mutate the node
path.node.value = applyColorMapping(path.node.value.replace(/"/g, ''), baseColor.inlineColors)
transformCount++
}
sourceFile.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach((node) => {
if (template && template.loc.start.offset >= node.getPos())
return sourceFile
const value = node.getText()
const hasClosingDoubleQuote = value.match(/"/g)?.length === 2
if (value.search('\'') === -1 && hasClosingDoubleQuote) {
const mapped = applyColorMapping(value.replace(/"/g, ''), baseColor.inlineColors)
node.replaceWithText(`"${mapped}"`)
}
else {
const s = new MagicString(value)
s.replace(/'(.*?)'/g, (substring) => {
return `'${applyColorMapping(substring.replace(/'/g, ''), baseColor.inlineColors)}'`
return this.traverse(path)
},
})
node.replaceWithText(s.toString())
}
})
return sourceFile
if (sfcAST) {
// traverseTemplateAST is an alias for the vue-eslint-parser 'AST.traverseNodes' function
// see: https://github.com/vuejs/vue-eslint-parser/blob/master/src/ast/traverse.ts#L118
traverseTemplateAST(sfcAST, {
enterNode(node) {
if (node.type === 'Literal' && typeof node.value === 'string') {
if (!['BinaryExpression', 'Property'].includes(node.parent?.type ?? '')) {
node.value = applyColorMapping(node.value.replace(/"/g, ''), baseColor.inlineColors)
transformCount++
}
}
// handle class attribute without binding
else if (node.type === 'VLiteral' && typeof node.value === 'string') {
if (node.parent.key.name === 'class') {
node.value = applyColorMapping(node.value.replace(/"/g, ''), baseColor.inlineColors)
transformCount++
}
}
},
leaveNode() {
},
})
}
return transformCount
},
}
}
// Splits a className into variant-name-alpha.

View File

@ -1,39 +1,56 @@
import type { Transformer } from '@/src/utils/transformers'
import type { CodemodPlugin } from 'vue-metamorph'
import type { TransformOpts } from '.'
import type { Config } from '@/src/utils/get-config'
export const transformImport: Transformer = async ({ sourceFile, config }) => {
const importDeclarations = sourceFile.getImportDeclarations()
export function transformImport(opts: TransformOpts): CodemodPlugin {
return {
type: 'codemod',
name: 'modify import based on user config',
for (const importDeclaration of importDeclarations) {
const moduleSpecifier = importDeclaration.getModuleSpecifierValue()
// eslint-disable-next-line unused-imports/no-unused-vars
transform({ scriptASTs, sfcAST, styleASTs, filename, utils: { traverseScriptAST, traverseTemplateAST } }) {
// codemod plugins self-report the number of transforms it made
// this is only used to print the stats in CLI output
const transformCount = 0
const { config } = opts
// scriptASTs is an array of Program ASTs
// in a js/ts file, this array will only have one item
// in a vue file, this array will have one item for each <script> block
for (const scriptAST of scriptASTs) {
// traverseScriptAST is an alias for the ast-types 'visit' function
// see: https://github.com/benjamn/ast-types#ast-traversal
traverseScriptAST(scriptAST, {
visitImportDeclaration(path) {
if (typeof path.node.source.value === 'string') {
const sourcePath = path.node.source.value
// Replace @/lib/registry/[style] with the components alias.
if (moduleSpecifier.startsWith('@/lib/registry/')) {
if (sourcePath.startsWith('@/lib/registry/')) {
if (config.aliases.ui) {
importDeclaration.setModuleSpecifier(
moduleSpecifier.replace(/^@\/lib\/registry\/[^/]+\/ui/, config.aliases.ui),
)
path.node.source.value = sourcePath.replace(/^@\/lib\/registry\/[^/]+\/ui/, config.aliases.ui)
}
else {
importDeclaration.setModuleSpecifier(
moduleSpecifier.replace(
/^@\/lib\/registry\/[^/]+/,
config.aliases.components,
),
)
path.node.source.value = sourcePath.replace(/^@\/lib\/registry\/[^/]+/, config.aliases.components)
}
}
// Replace `import { cn } from "@/lib/utils"`
if (moduleSpecifier === '@/lib/utils') {
const namedImports = importDeclaration.getNamedImports()
const cnImport = namedImports.find(i => i.getName() === 'cn')
if (sourcePath === '@/lib/utils') {
const namedImports = path.node.specifiers?.map(node => node.local?.name ?? '') ?? []
// const namedImports = importDeclaration.getNamedImports()
const cnImport = namedImports.find(i => i === 'cn')
if (cnImport) {
importDeclaration.setModuleSpecifier(
moduleSpecifier.replace(/^@\/lib\/utils/, config.aliases.utils),
)
path.node.source.value = sourcePath.replace(/^@\/lib\/utils/, config.aliases.utils)
}
}
}
return this.traverse(path)
},
})
}
return sourceFile
return transformCount
},
}
}

View File

@ -1,20 +1,19 @@
import { createRequire } from 'node:module'
import type { Transformer } from '@/src/utils/transformers'
import type { TransformOpts } from '.'
// required cause Error: Dynamic require of "@babel/core" is not supported
const require = createRequire(import.meta.url)
const { transform } = require('detype')
export async function transformSFC(opts: TransformOpts) {
if (opts.config?.typescript || opts.filename.includes('.ts'))
return opts.raw
return await transformByDetype(opts.raw, opts.filename).then(res => res as string)
}
export async function transformByDetype(content: string, filename: string) {
return await transform(content, filename, {
removeTsComments: true,
})
}
export const transformSFC: Transformer<string> = async ({ sourceFile, config, filename }) => {
const output = sourceFile?.getFullText()
if (config?.typescript)
return output
return await transformByDetype(output, filename)
}

View File

@ -1,56 +1,67 @@
import { SyntaxKind } from 'ts-morph'
import { MagicString, parse } from '@vue/compiler-sfc'
import type { SFCTemplateBlock } from '@vue/compiler-sfc'
import type { CodemodPlugin } from 'vue-metamorph'
import { splitClassName } from './transform-css-vars'
import type { Transformer } from '@/src/utils/transformers'
import type { TransformOpts } from '.'
import type { Config } from '@/src/utils/get-config'
export const transformTwPrefixes: Transformer = async ({
sourceFile,
config,
}) => {
const isVueFile = sourceFile.getFilePath().endsWith('vue')
if (!config.tailwind?.prefix)
return sourceFile
export function transformTwPrefix(opts: TransformOpts): CodemodPlugin {
return {
type: 'codemod',
name: 'add prefix to tailwind classes',
let template: SFCTemplateBlock | null = null
// eslint-disable-next-line unused-imports/no-unused-vars
transform({ scriptASTs, sfcAST, styleASTs, filename, utils: { traverseScriptAST, traverseTemplateAST } }) {
// codemod plugins self-report the number of transforms it made
// this is only used to print the stats in CLI output
let transformCount = 0
const { config } = opts
if (isVueFile) {
const parsed = parse(sourceFile.getText())
template = parsed.descriptor.template
if (!template)
return sourceFile
// scriptASTs is an array of Program ASTs
// in a js/ts file, this array will only have one item
// in a vue file, this array will have one item for each <script> block
for (const scriptAST of scriptASTs) {
// traverseScriptAST is an alias for the ast-types 'visit' function
// see: https://github.com/benjamn/ast-types#ast-traversal
traverseScriptAST(scriptAST, {
visitLiteral(path) {
if (path.parent.value.type !== 'ImportDeclaration' && typeof path.node.value === 'string') {
// mutate the node
path.node.value = applyPrefix(path.node.value, config.tailwind.prefix)
transformCount++
}
sourceFile.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach((node) => {
if (template && template.loc.start.offset >= node.getPos())
return sourceFile
const value = node.getText()
const attrName = sourceFile.getDescendantAtPos(node.getPos() - 2)?.getText()
if (isVueFile && attrName !== 'class')
return sourceFile
// Do not parse imported packages/files
if (node.getParent().getKind() === SyntaxKind.ImportDeclaration)
return
const hasClosingDoubleQuote = value.match(/"/g)?.length === 2
const hasFunction = value.startsWith('"cn(')
if (value.search('\'') === -1 && hasClosingDoubleQuote && !hasFunction) {
const mapped = applyPrefix(value.replace(/"/g, ''), config.tailwind.prefix)
node.replaceWithText(`"${mapped}"`)
}
else {
const s = new MagicString(value)
s.replace(/'(.*?)'/g, (substring) => {
return `'${applyPrefix(substring.replace(/'/g, ''), config.tailwind.prefix)}'`
return this.traverse(path)
},
})
node.replaceWithText(s.toString())
}
})
return sourceFile
if (sfcAST) {
// traverseTemplateAST is an alias for the vue-eslint-parser 'AST.traverseNodes' function
// see: https://github.com/vuejs/vue-eslint-parser/blob/master/src/ast/traverse.ts#L118
traverseTemplateAST(sfcAST, {
enterNode(node) {
if (node.type === 'Literal' && typeof node.value === 'string') {
if (!['BinaryExpression', 'Property'].includes(node.parent?.type ?? '')) {
node.value = applyPrefix(node.value, config.tailwind.prefix)
transformCount++
}
}
// handle class attribute without binding
else if (node.type === 'VLiteral' && typeof node.value === 'string') {
if (node.parent.key.name === 'class') {
node.value = `"${applyPrefix(node.value, config.tailwind.prefix)}"`
transformCount++
}
}
},
leaveNode() {
},
})
}
return transformCount
},
}
}
export function applyPrefix(input: string, prefix: string = '') {

View File

@ -33,8 +33,7 @@ exports[`transform css vars 3`] = `
:class="
cn(
'bg-white hover:bg-stone-100 dark:bg-stone-950 dark:hover:bg-stone-800',
true &&
'text-stone-50 sm:focus:text-stone-900 dark:text-stone-900 dark:sm:focus:text-stone-50',
true && 'text-stone-50 sm:focus:text-stone-900 dark:text-stone-900 dark:sm:focus:text-stone-50',
)
"
>

View File

@ -1,22 +1,33 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`transform import 1`] = `
"import { Foo } from "bar" import { Button } from "@/components/ui/button" import
{ Label} from "ui/label" import { Box } from "@/components/box" import { cn }
from "@/lib/utils"
"import { Foo } from 'bar'
import { Button } from '@/components/ui/button'
import { Label} from 'ui/label'
import { Box } from '@/components/box'
import { cn } from '@/lib/utils'
"
`;
exports[`transform import 2`] = `
"import { Foo } from "bar" import { Button } from "~/src/components/ui/button"
import { Label} from "ui/label" import { Box } from "~/src/components/box"
import { cn, foo, bar } from "~/lib" import { bar } from "@/lib/utils/bar"
"import { Foo } from 'bar'
import { Button } from '~/src/components/ui/button'
import { Label} from 'ui/label'
import { Box } from '~/src/components/box'
import { cn, foo } from '~/lib'
import { bar } from '@/lib/utils/bar'
"
`;
exports[`transform import 3`] = `
"import { Foo } from "bar" import { Button } from "~/src/components/ui/button"
import { Label} from "ui/label" import { Box } from "~/src/components/box"
import { cn } from "~/src/utils" import { bar } from "@/lib/utils/bar"
"import { Foo } from 'bar'
import { Button } from '~/src/components/ui/button'
import { Label} from 'ui/label'
import { Box } from '~/src/components/box'
import { cn } from '~/src/utils'
import { bar } from '@/lib/utils/bar'
"
`;

View File

@ -21,47 +21,56 @@ export const testVariants = cva(
exports[`transform tailwind prefix 2`] = `
"<template>
<div class="tw-bg-background hover:tw-bg-muted tw-text-primary-foreground sm:focus:tw-text-accent-foreground">
<div
class="tw-bg-background hover:tw-bg-muted tw-text-primary-foreground sm:focus:tw-text-accent-foreground"
>
foo
</div>
</template>
"
</template>
"
`;
exports[`transform tailwind prefix 3`] = `
"<template>
<div class="tw-bg-background hover:tw-bg-muted tw-text-primary-foreground sm:focus:tw-text-accent-foreground">
<div
class="tw-bg-background hover:tw-bg-muted tw-text-primary-foreground sm:focus:tw-text-accent-foreground"
>
foo
</div>
</template>
"
</template>
"
`;
exports[`transform tailwind prefix 4`] = `
"<template>
<div
id="testing" v-bind="props" @click="handleSomething" :data-test="true"
id="testing"
v-bind="props"
@click="handleSomething"
:data-test="true"
class="tw-mt-4"
:class="cn('tw-bg-background hover:tw-bg-muted', true && 'tw-text-primary-foreground sm:focus:tw-text-accent-foreground')"
:class="cn(buttonVariants({ variant, size }), props.class)"
:class="
cn(
buttonVariants({ variant: 'outline' }),
props.class,
'tw-bg-background'
'tw-bg-background hover:tw-bg-muted',
true && 'tw-text-primary-foreground sm:focus:tw-text-accent-foreground',
)
"
:class="cn(buttonVariants({ variant, size }), props.class)"
:class="
cn(buttonVariants({ variant: 'outline' }), props.class, 'tw-bg-background')
"
:class="
cn(
'tw-flex',
orientation === 'horizontal' ? 'tw--ml-4' : 'tw--mt-4 tw-flex-col',
props.class,
)"
)
"
>
foo
</div>
</template>
"
</template>
"
`;
exports[`transform tailwind prefix 5`] = `

View File

@ -4,7 +4,7 @@ import { transform } from '../../src/utils/transformers'
it('transform import', async () => {
expect(
await transform({
filename: 'app.vue',
filename: 'app.ts',
raw: `import { Foo } from "bar"
import { Button } from "@/lib/registry/new-york/ui/button"
import { Label} from "ui/label"
@ -27,13 +27,13 @@ it('transform import', async () => {
expect(
await transform({
filename: 'app.vue',
filename: 'app.ts',
raw: `import { Foo } from "bar"
import { Button } from "@/lib/registry/new-york/ui/button"
import { Label} from "ui/label"
import { Box } from "@/lib/registry/new-york/box"
import { cn, foo, bar } from "@/lib/utils"
import { cn, foo } from "@/lib/utils"
import { bar } from "@/lib/utils/bar"
`,
config: {
@ -47,7 +47,7 @@ it('transform import', async () => {
expect(
await transform({
filename: 'app.vue',
filename: 'app.ts',
raw: `import { Foo } from "bar"
import { Button } from "@/lib/registry/new-york/ui/button"
import { Label} from "ui/label"

View File

@ -1,10 +1,10 @@
import { expect, it } from 'vitest'
import { transform } from '../../src/utils/transformers/new'
import { transform } from '../../src/utils/transformers'
import { applyPrefixesCss } from '../../src/utils/transformers/transform-tw-prefix'
it('transform tailwind prefix', async () => {
expect(
transform({
await transform({
filename: 'test.ts',
raw: `import { cva } from "class-variance-authority"
@ -36,7 +36,7 @@ it('transform tailwind prefix', async () => {
).toMatchSnapshot()
expect(
transform({
await transform({
filename: 'app.vue',
raw: `<template>
<div class="bg-background hover:bg-muted text-primary-foreground sm:focus:text-accent-foreground">
@ -59,7 +59,7 @@ it('transform tailwind prefix', async () => {
).toMatchSnapshot()
expect(
transform({
await transform({
filename: 'app.vue',
raw: `<template>
<div class="bg-background hover:bg-muted text-primary-foreground sm:focus:text-accent-foreground">
@ -83,7 +83,7 @@ it('transform tailwind prefix', async () => {
).toMatchSnapshot()
expect(
transform({
await transform({
filename: 'app.vue',
raw: `<template>
<div