Skip to content

Commit

Permalink
fix: use oxc-parser builtin MagicString
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyinws committed Dec 11, 2024
1 parent cb15605 commit ecaa347
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 47 deletions.
3 changes: 2 additions & 1 deletion examples/vite-vue3/src/tsLog.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export function logTs() {
console.log('from ts')
const a = '你好'
console.log(a)
}
39 changes: 19 additions & 20 deletions src/core/transform/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context } from './../../types'
import MagicString from 'magic-string'
import { parseSync } from 'oxc-parser'
import { genConsoleString, getCompiler, getLineAndColumn, isConsoleExpression, isPluginDisable } from '../utils'
import { calculateStart, genConsoleString, getCompiler, isConsoleExpression, isPluginDisable } from '../utils'
import { walk } from '../utils/walker'
import { compilers } from './compilers'

Expand All @@ -25,18 +25,20 @@ export async function transform(context: Context) {

const compileResult = await compilers[compiler](context)

const ast = parseSync(id, compileResult.script, {
const oxcParsedResult = parseSync(id, compileResult.script, {
lang: (compileResult.lang || 'js') as 'js' | 'jsx' | 'ts' | 'tsx' | undefined,
sourceType: 'module',
})

const { program, comments = [], magicString: oxcMs } = oxcParsedResult

if (isPluginDisable({
comments: ast.comments || [],
comments,
originalLine: 1,
script: compileResult.script,
id,
type: 'top-file',
compiler,
oxcMs,
})) {
return {
code: magicString.toString(),
Expand All @@ -49,41 +51,38 @@ export async function transform(context: Context) {
}
}

walk(ast.program, {
walk(program, {
enter(node) {
if (isConsoleExpression(node)) {
const expressionStart = node.start
const expressionEnd = node.end

const originalExpression = magicString.slice(expressionStart, expressionEnd)
const originalExpression = oxcMs.getSourceText(node.start, node.end)

if (originalExpression.includes('%c'))
return false

const { line, column } = getLineAndColumn(compileResult.script, expressionStart)
const { line, column } = oxcMs.getLineColumnNumber(node.start)

const originalLine = line + compileResult.line
const originalLine = line + compileResult.line + 1
const originalColumn = column

if (isPluginDisable({
comments: ast.comments || [],
script: compileResult.script,
comments,
originalLine: line,
id,
type: 'inline-file',
compiler,
oxcMs,
})) {
return false
}

// @ts-expect-error any
const args = node.arguments
const args = (node as any).arguments

const argsStart = calculateStart(compileResult.script, oxcMs.getLineColumnNumber(args[0].start))
const argsEnd = calculateStart(compileResult.script, oxcMs.getLineColumnNumber(args[args.length - 1].end))

const argsStart = args[0].start! + compileResult.offset
const argsEnd = args[args.length - 1].end! + compileResult.offset
const argType = args[0].type

const argsName = magicString.slice(argsStart, argsEnd)
const argsName = oxcMs.getSourceText(args[0].start, args[args.length - 1].end)
.toString()
.replace(/`/g, '')
.replace(/\n/g, '')
Expand All @@ -98,8 +97,8 @@ export async function transform(context: Context) {
id,
})

consoleString && magicString.appendLeft(argsStart, consoleString)
_suffix && magicString.appendRight(argsEnd, `,"${_suffix}"`)
consoleString && magicString.appendLeft(argsStart + compileResult.offset, consoleString)
_suffix && magicString.appendRight(argsEnd + compileResult.offset, `,"${_suffix}"`)
}
},
})
Expand Down
46 changes: 26 additions & 20 deletions src/core/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Comment } from 'oxc-parser'
import type { Comment, MagicString } from 'oxc-parser'
import type { Compiler, Options } from '../../types'
import type { Node } from '../utils/walker'
import { createFilter } from '@rollup/pluginutils'
Expand Down Expand Up @@ -61,27 +61,32 @@ export function isPluginDisable(meta: {
originalLine: number
id: string
type: 'top-file' | 'inline-file'
script: string
compiler: Compiler
oxcMs: MagicString
}) {
const { comments, originalLine, type, compiler, script } = meta
const { comments, originalLine, type, compiler, oxcMs } = meta

if (comments?.length === 0)
return false

if (type === 'top-file') {
const startLine = compiler === 'vanilla' ? 1 : 2

const disablePluginComment = comments?.find(comment => comment.value.includes('turbo-console-disable'))

const disableLine = getLineAndColumn(script, disablePluginComment?.start || 0).line
const disablePluginComment = comments?.find(comment => comment.value.includes('turbo-console-disable') && !comment.value.includes('turbo-console-disable-'))

const disableLine = oxcMs.getLineColumnNumber(disablePluginComment?.start || 0).line
if (disablePluginComment && disableLine <= startLine)
return true
}
else if (type === 'inline-file') {
const currentLineComment = comments?.find(comment => comment.value.includes('turbo-console-disable-line') && getLineAndColumn(script, comment.start).line === originalLine)
const nextLineComment = comments?.find(comment => comment.value.includes('turbo-console-disable-next-line') && getLineAndColumn(script, comment.start).line === originalLine - 1)
const currentLineComment = comments?.find((comment) => {
const { line } = oxcMs.getLineColumnNumber(comment.start)
return comment.value.includes('turbo-console-disable-line') && line === originalLine
})
const nextLineComment = comments?.find((comment) => {
const { line } = oxcMs.getLineColumnNumber(comment.start)
return comment.value.includes('turbo-console-disable-next-line') && line === originalLine - 1
})

if (currentLineComment || nextLineComment)
return true
Expand Down Expand Up @@ -109,19 +114,20 @@ export async function loadPkg(pkg: string) {
}
}

export function getLineAndColumn(code: string, start: number) {
let line = 1
let column = 0
export function calculateStart(
source: string,
position: { line: number, column: number },
): number {
const lines = source.split('\n')
let start = 0

for (let i = 0; i < start; i++) {
if (code[i] === '\n') {
line++
column = 0
}
else {
column++
}
// 计算之前所有完整行的长度(包括换行符)
for (let i = 0; i < position.line; i++) {
start += lines[i].length + 1 // +1 是为了计入换行符
}

return { line, column }
// 加上当前行的列偏移
start += position.column

return start
}
10 changes: 6 additions & 4 deletions test/__snapshots__/transform.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -88,18 +88,20 @@ exports[`svelte transform > svelte 1`] = `
}
`;
exports[`utf-8 > on top of file 1`] = `
exports[`utf-8 > includes utf-8 1`] = `
{
"code": "console.log("%c🚀 main.js·1%c🔦 http://127.1:3070#mainjs,1,1",\`padding:2px 5px;border-radius:3px 0 0 3px;margin:0 0 5px 0;color:#111827;background:\${globalThis._UTC_DETECT_DARK && globalThis._UTC_DETECT_DARK() ? '#F7DF1E90;' : '#F7DF1E;'}\`,\`background:#00DC8250;padding:2px 5px;border-radius:0 3px 3px 0;margin:0 0 5px 0;\`,"\\n",'你好,世界!')",
"code": "const a = '你好'
console.log("%c🚀 main.js·2 ~ a%c🔦 http://127.1:3070#mainjs,2,1",\`padding:2px 5px;border-radius:3px 0 0 3px;margin:0 0 5px 0;color:#111827;background:\${globalThis._UTC_DETECT_DARK && globalThis._UTC_DETECT_DARK() ? '#F7DF1E90;' : '#F7DF1E;'}\`,\`background:#00DC8250;padding:2px 5px;border-radius:0 3px 3px 0;margin:0 0 5px 0;\`,"\\n",a)",
"map": SourceMap {
"file": "main.js",
"mappings": "AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,6TAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC",
"mappings": "AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACf,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,iUAAC,CAAC",
"names": [],
"sources": [
"main.js",
],
"sourcesContent": [
"console.log('你好,世界!')",
"const a = '你好'
console.log(a)",
],
"version": 3,
},
Expand Down
3 changes: 2 additions & 1 deletion test/fixtures/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export const WIN_PATH = {

export const UTF_8 = {
options: {},
code: `console.log('你好,世界!')`,
code: `const a = '你好'
console.log(a)`,
id: '/home/runner/main.js',
}
2 changes: 1 addition & 1 deletion test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ describe('edge case', () => {
})

describe('utf-8', () => {
it('on top of file', async () => {
it('includes utf-8', async () => {
UTF_8.options = resolveOptions(UTF_8.options)
expect(await transform(UTF_8)).toMatchSnapshot()
})
Expand Down

0 comments on commit ecaa347

Please sign in to comment.