Skip to content

Commit

Permalink
feat: add emitFile & expose unpluginContext
Browse files Browse the repository at this point in the history
closes #28
  • Loading branch information
sxzz committed Mar 3, 2024
1 parent 88faf74 commit 7cbf9b1
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
40 changes: 31 additions & 9 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,21 @@ import {
walkImportDeclaration,
} from 'ast-kit'
import { MagicString, generateTransform } from 'magic-string-ast'
import type { UnpluginBuildContext, UnpluginContext } from 'unplugin'
import type { ImportAttribute, Node } from '@babel/types'
import type { ViteNodeRunner } from 'vite-node/client'

export * from './options'
export interface MacroContext {
id: string
source: string
emitFile: UnpluginBuildContext['emitFile']
/**
* **Use with caution.**
*
* This is an experimental feature and may be changed at any time.
*/
unpluginContext: UnpluginBuildContext & UnpluginContext
}

interface MacroBase {
Expand All @@ -36,17 +45,26 @@ interface IdentifierMacro extends MacroBase {
}
type Macro = CallMacro | IdentifierMacro

export async function transformMacros(
code: string,
id: string,
getRunner: () => Promise<ViteNodeRunner>,
deps: Map<string, Set<string>>,
attrs: Record<string, string>,
) {
const program = babelParse(code, getLang(id), {
export async function transformMacros({
source,
id,
unpluginContext,
getRunner,
deps,
attrs,
}: {
id: string
source: string
unpluginContext: UnpluginBuildContext & UnpluginContext

getRunner: () => Promise<ViteNodeRunner>
deps: Map<string, Set<string>>
attrs: Record<string, string>
}) {
const program = babelParse(source, getLang(id), {
plugins: [['importAttributes', { deprecatedAssertSyntax: true }]],
})
const s = new MagicString(code)
const s = new MagicString(source)

const imports = new Map(Object.entries(recordImports()))
const macros = collectMacros()
Expand Down Expand Up @@ -89,6 +107,10 @@ export async function transformMacros(
if (macro.type === 'call') {
const ctx: MacroContext = {
id,
source,
emitFile: unpluginContext.emitFile,

unpluginContext,
}
ret = (exported as Function).apply(ctx, macro.args)
} else {
Expand Down
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,15 @@ export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {
return filter(id)
},

transform(code, id) {
return transformMacros(code, id, getRunner, deps, options.attrs)
transform(source, id) {
return transformMacros({
source,
id,
getRunner,
deps,
attrs: options.attrs,
unpluginContext: this,
})
},

vite: {
Expand Down

0 comments on commit 7cbf9b1

Please sign in to comment.