Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #4010: allow define key to start with import. #4013

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions internal/js_parser/global_name_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/evanw/esbuild/internal/logger"
)

func ParseGlobalName(log logger.Log, source logger.Source) (result []string, ok bool) {
func ParseGlobalName(log logger.Log, source logger.Source, allowImportMeta bool) (result []string, ok bool) {
ok = true
defer func() {
r := recover()
Expand All @@ -18,10 +18,24 @@ func ParseGlobalName(log logger.Log, source logger.Source) (result []string, ok
}()

lexer := js_lexer.NewLexerGlobalName(log, source)

// Start off with an identifier
result = append(result, lexer.Identifier.String)
lexer.Expect(js_lexer.TIdentifier)
// Start off with an identifier or `import`
if allowImportMeta {
if lexer.Token == js_lexer.TImport {
result = append(result, lexer.Identifier.String)
lexer.Next()
lexer.Expect(js_lexer.TDot)
result = append(result, lexer.Identifier.String)
lexer.Expect(js_lexer.TIdentifier)
Comment on lines +27 to +28
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't strictly limit to import.meta here. (import.foo is allowed and import['meta'] is not allowed)

} else if lexer.Token == js_lexer.TIdentifier {
result = append(result, lexer.Identifier.String)
lexer.Next()
} else {
lexer.Unexpected()
}
} else {
result = append(result, lexer.Identifier.String)
lexer.Expect(js_lexer.TIdentifier)
}

// Follow with dot or index expressions
for lexer.Token != js_lexer.TEndOfFile {
Expand Down
12 changes: 6 additions & 6 deletions pkg/api/api_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,15 +386,15 @@ func validateSupported(log logger.Log, supported map[string]bool) (
return
}

func validateGlobalName(log logger.Log, text string, path string) []string {
func validateGlobalName(log logger.Log, text string, path string, allowImportMeta bool) []string {
if text != "" {
source := logger.Source{
KeyPath: logger.Path{Text: path},
PrettyPath: path,
Contents: text,
}

if result, ok := js_parser.ParseGlobalName(log, source); ok {
if result, ok := js_parser.ParseGlobalName(log, source, allowImportMeta); ok {
return result
}
}
Expand Down Expand Up @@ -560,7 +560,7 @@ func validateDefines(

for _, key := range sortedKeys {
value := defines[key]
keyParts := validateGlobalName(log, key, "(define name)")
keyParts := validateGlobalName(log, key, "(define name)", true)
if keyParts == nil {
continue
}
Expand Down Expand Up @@ -669,7 +669,7 @@ func validateDefines(
}

for _, key := range pureFns {
keyParts := validateGlobalName(log, key, "(pure name)")
keyParts := validateGlobalName(log, key, "(pure name)", true)
if keyParts == nil {
continue
}
Expand Down Expand Up @@ -1271,7 +1271,7 @@ func validateBuildOptions(
ASCIIOnly: validateASCIIOnly(buildOpts.Charset),
IgnoreDCEAnnotations: buildOpts.IgnoreAnnotations,
TreeShaking: validateTreeShaking(buildOpts.TreeShaking, buildOpts.Bundle, buildOpts.Format),
GlobalName: validateGlobalName(log, buildOpts.GlobalName, "(global name)"),
GlobalName: validateGlobalName(log, buildOpts.GlobalName, "(global name)", false),
CodeSplitting: buildOpts.Splitting,
OutputFormat: validateFormat(buildOpts.Format),
AbsOutputFile: validatePath(log, realFS, buildOpts.Outfile, "outfile path"),
Expand Down Expand Up @@ -1715,7 +1715,7 @@ func transformImpl(input string, transformOpts TransformOptions) TransformResult
SourceRoot: transformOpts.SourceRoot,
ExcludeSourcesContent: transformOpts.SourcesContent == SourcesContentExclude,
OutputFormat: validateFormat(transformOpts.Format),
GlobalName: validateGlobalName(log, transformOpts.GlobalName, "(global name)"),
GlobalName: validateGlobalName(log, transformOpts.GlobalName, "(global name)", false),
MinifySyntax: transformOpts.MinifySyntax,
MinifyWhitespace: transformOpts.MinifyWhitespace,
MinifyIdentifiers: transformOpts.MinifyIdentifiers,
Expand Down
19 changes: 19 additions & 0 deletions scripts/js-api-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -6137,6 +6137,14 @@ class Foo {
assert.strictEqual(code, `(() => {\n const import_meta = {};\n console.log(import_meta, import_meta.foo);\n})();\n`)
},

async defineImportMetaAsIdentifier({ esbuild }) {
const { code: code1 } = await esbuild.transform(`console.log(import.meta); export {}`, { define: { 'import.meta': 'import_meta' }, format: 'esm' })
assert.strictEqual(code1, `console.log(import_meta);\n`)

const { code: code2 } = await esbuild.transform(`console.log(import.meta.aaa); export {}`, { define: { 'import.meta.aaa': 'import_meta_url' }, format: 'esm' })
assert.strictEqual(code2, `console.log(import_meta_url);\n`)
},

async defineIdentifierVsStringWarningIssue466Transform({ esbuild }) {
const { warnings } = await esbuild.transform(``, { define: { 'process.env.NODE_ENV': 'production' } })
const formatted = await esbuild.formatMessages(warnings, { kind: 'warning' })
Expand Down Expand Up @@ -6180,6 +6188,9 @@ class Foo {

const { code: code5 } = await esbuild.transform(`foo(x['y'].z, x.y['z'], x['y']['z'])`, { define: { 'x["y"][\'z\']': 'true' } })
assert.strictEqual(code5, `foo(true, true, true);\n`)

const { code: code6 } = await esbuild.transform(`foo(import.meta['y'].z, import.meta.y['z'], import.meta['y']['z'])`, { define: { 'import.meta["y"].z': 'true' } })
assert.strictEqual(code6, `foo(true, true, true);\n`)
},

async defineQuotedPropertyNameBuild({ esbuild }) {
Expand Down Expand Up @@ -6526,6 +6537,14 @@ class Foo {
assert.strictEqual(code2, `foo;\n`)
},

async pureImportMeta({ esbuild }) {
const { code: code1 } = await esbuild.transform(`import.meta.foo(123, foo)`, { minifySyntax: true, pure: [] })
assert.strictEqual(code1, `import.meta.foo(123, foo);\n`)

const { code: code2 } = await esbuild.transform(`import.meta.foo(123, foo)`, { minifySyntax: true, pure: ['import.meta.foo'] })
assert.strictEqual(code2, `foo;\n`)
},

async nameCollisionEvalRename({ esbuild }) {
const { code } = await esbuild.transform(`
// "arg" must not be renamed to "arg2"
Expand Down
Loading