From 376f925b4f16f8a1bc3dddf70d7f259ce1826d32 Mon Sep 17 00:00:00 2001 From: Mihail Stoykov Date: Thu, 27 Apr 2023 18:04:34 +0300 Subject: [PATCH 1/7] Update goja to modules branch --- go.mod | 2 +- go.sum | 4 +- js/bundle_test.go | 8 - .../grafana/sobek/.tc39_test262_checkout.sh | 2 +- vendor/github.com/grafana/sobek/README.md | 2 +- vendor/github.com/grafana/sobek/ast/node.go | 91 +++ .../grafana/sobek/builtin_object.go | 23 +- vendor/github.com/grafana/sobek/compiler.go | 287 +++++++- .../github.com/grafana/sobek/compiler_expr.go | 62 +- .../github.com/grafana/sobek/compiler_stmt.go | 164 ++++- vendor/github.com/grafana/sobek/modules.go | 518 ++++++++++++++ .../grafana/sobek/modules_namespace.go | 182 +++++ .../grafana/sobek/modules_sourcetext.go | 661 ++++++++++++++++++ vendor/github.com/grafana/sobek/object.go | 10 +- .../grafana/sobek/parser/expression.go | 87 ++- .../github.com/grafana/sobek/parser/parser.go | 9 +- .../github.com/grafana/sobek/parser/scope.go | 26 +- .../grafana/sobek/parser/statement.go | 394 ++++++++++- vendor/github.com/grafana/sobek/runtime.go | 9 + .../grafana/sobek/token/token_const.go | 15 +- vendor/github.com/grafana/sobek/vm.go | 208 +++++- vendor/modules.txt | 2 +- 22 files changed, 2658 insertions(+), 108 deletions(-) create mode 100644 vendor/github.com/grafana/sobek/modules.go create mode 100644 vendor/github.com/grafana/sobek/modules_namespace.go create mode 100644 vendor/github.com/grafana/sobek/modules_sourcetext.go diff --git a/go.mod b/go.mod index 0973704ef90b..d461720cf894 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/go-sourcemap/sourcemap v2.1.4+incompatible github.com/golang/protobuf v1.5.4 github.com/gorilla/websocket v1.5.1 - github.com/grafana/sobek v0.0.0-20240611084759-1a77bdaf1a4a + github.com/grafana/sobek v0.0.0-20240624162318-afbc13aa071b github.com/grafana/xk6-browser v1.6.0 github.com/grafana/xk6-dashboard v0.7.4 github.com/grafana/xk6-output-prometheus-remote v0.4.0 diff --git a/go.sum b/go.sum index 1083c3eb94f8..8e3e4d7d80d9 100644 --- a/go.sum +++ b/go.sum @@ -82,8 +82,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= -github.com/grafana/sobek v0.0.0-20240611084759-1a77bdaf1a4a h1:RE9WtCdu6yQ5kfHA5ophYdf2FSchssXt85USln9eks0= -github.com/grafana/sobek v0.0.0-20240611084759-1a77bdaf1a4a/go.mod h1:tUEHKWaMrxFGrMgjeAH85OEceCGQiSl6a/6Wckj/Vf4= +github.com/grafana/sobek v0.0.0-20240624162318-afbc13aa071b h1:CX/3ThBRroXW/4sLbyfXtHPBdzQFFESeWlkHO6/JvWw= +github.com/grafana/sobek v0.0.0-20240624162318-afbc13aa071b/go.mod h1:tUEHKWaMrxFGrMgjeAH85OEceCGQiSl6a/6Wckj/Vf4= github.com/grafana/xk6-browser v1.6.0 h1:x8ZfBwiUJRRKNEw+Asr5ae9o2gFvYU1Ll/4dDMNIPZ8= github.com/grafana/xk6-browser v1.6.0/go.mod h1:xLaGGhTMHIRsMvkVWFYh9RPy87kG2n4L4Or6DeI8U+o= github.com/grafana/xk6-dashboard v0.7.4 h1:0ZRPTAXW+6A3Xqq/a/OaIZhxUt1SOMwUFff0IPwBHrs= diff --git a/js/bundle_test.go b/js/bundle_test.go index 934171aa9ba3..567d6b8d7786 100644 --- a/js/bundle_test.go +++ b/js/bundle_test.go @@ -189,11 +189,6 @@ func TestNewBundle(t *testing.T) { "InvalidCompat", "es1", `export default function() {};`, `invalid compatibility mode "es1". Use: "extended", "base", "experimental_enhanced"`, }, - // ES2015 modules are not supported - { - "Modules", "base", `export default function() {};`, - "file:///script.js: Line 1:28 Unexpected reserved word (and 2 more errors)", - }, // BigInt is not supported { "BigInt", "base", @@ -532,7 +527,6 @@ func TestNewBundleFromArchive(t *testing.T) { checkArchive(t, arc, lib.RuntimeOptions{}, "") // default options checkArchive(t, arc, extCompatModeRtOpts, "") - checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word") }) t.Run("es6_script_explicit", func(t *testing.T) { @@ -543,7 +537,6 @@ func TestNewBundleFromArchive(t *testing.T) { checkArchive(t, arc, lib.RuntimeOptions{}, "") checkArchive(t, arc, extCompatModeRtOpts, "") - checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word") }) t.Run("es5_script_with_extended", func(t *testing.T) { @@ -582,7 +575,6 @@ func TestNewBundleFromArchive(t *testing.T) { arc.CompatibilityMode = "blah" // intentionally break the archive checkArchive(t, arc, lib.RuntimeOptions{}, "invalid compatibility mode") // fails when it uses the archive one checkArchive(t, arc, extCompatModeRtOpts, "") // works when I force the compat mode - checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word") // failes because of ES6 }) t.Run("script_options_dont_overwrite_metadata", func(t *testing.T) { diff --git a/vendor/github.com/grafana/sobek/.tc39_test262_checkout.sh b/vendor/github.com/grafana/sobek/.tc39_test262_checkout.sh index 65dedfc68aff..a72fc1563224 100644 --- a/vendor/github.com/grafana/sobek/.tc39_test262_checkout.sh +++ b/vendor/github.com/grafana/sobek/.tc39_test262_checkout.sh @@ -1,6 +1,6 @@ #!/bin/sh # this is just the commit it was last tested with -sha=926b0960d737b9f1dfd0ec0c1dfd95d836016d33 +sha=634933a489f1bb8cf074a2a9b8616ade5f2f5cac mkdir -p testdata/test262 cd testdata/test262 diff --git a/vendor/github.com/grafana/sobek/README.md b/vendor/github.com/grafana/sobek/README.md index 70dc1cdb3f71..51b669c4efc6 100644 --- a/vendor/github.com/grafana/sobek/README.md +++ b/vendor/github.com/grafana/sobek/README.md @@ -12,7 +12,7 @@ This project is a fork of [goja](/~https://github.com/dop251/goja). This project was largely inspired by [otto](/~https://github.com/robertkrimen/otto). -The minimum required Go version is 1.20. +The minimum required Go version is 1.21. Features -------- diff --git a/vendor/github.com/grafana/sobek/ast/node.go b/vendor/github.com/grafana/sobek/ast/node.go index 0663ba8daea9..538a4f89aba8 100644 --- a/vendor/github.com/grafana/sobek/ast/node.go +++ b/vendor/github.com/grafana/sobek/ast/node.go @@ -288,6 +288,9 @@ type ( SuperExpression struct { Idx file.Idx } + DynamicImportExpression struct { + Idx file.Idx + } UnaryExpression struct { Operator token.Token @@ -336,6 +339,8 @@ func (*ObjectPattern) _expressionNode() {} func (*ArrayPattern) _expressionNode() {} func (*Binding) _expressionNode() {} +func (*DynamicImportExpression) _expressionNode() {} + func (*PropertyShort) _expressionNode() {} func (*PropertyKeyed) _expressionNode() {} @@ -485,6 +490,69 @@ type ( Function *FunctionLiteral } + ImportDeclaration struct { + Idx file.Idx + ImportClause *ImportClause + FromClause *FromClause + ModuleSpecifier unistring.String + } + + ImportClause struct { + ImportedDefaultBinding *Identifier + NameSpaceImport *NameSpaceImport + NamedImports *NamedImports + } + + NameSpaceImport struct { + ImportedBinding unistring.String + } + + NamedImports struct { + ImportsList []*ImportSpecifier + } + + ImportSpecifier struct { + IdentifierName unistring.String + Alias unistring.String + } + + ExportDeclaration struct { + Idx file.Idx + Variable *VariableStatement + AssignExpression Expression + LexicalDeclaration *LexicalDeclaration + ClassDeclaration *ClassDeclaration + NamedExports *NamedExports + ExportFromClause *ExportFromClause + FromClause *FromClause + HoistableDeclaration *HoistableDeclaration + IsDefault bool + } + + FromClause struct { + ModuleSpecifier unistring.String + } + ExportFromClause struct { + IsWildcard bool + Alias unistring.String + NamedExports *NamedExports + } + + NamedExports struct { + ExportsList []*ExportSpecifier + } + + ExportSpecifier struct { + IdentifierName unistring.String + Alias unistring.String + } + + HoistableDeclaration struct { + FunctionDeclaration *FunctionDeclaration + // GeneratorDeclaration + // AsyncFunc and AsyncGenerator + } + ClassDeclaration struct { Class *ClassLiteral } @@ -517,6 +585,9 @@ func (*LexicalDeclaration) _statementNode() {} func (*FunctionDeclaration) _statementNode() {} func (*ClassDeclaration) _statementNode() {} +func (*ExportDeclaration) _statementNode() {} +func (*ImportDeclaration) _statementNode() {} + // =========== // // Declaration // // =========== // @@ -633,6 +704,10 @@ type Program struct { Body []Statement DeclarationList []*VariableDeclaration + ImportEntries []*ImportDeclaration + ExportEntries []*ExportDeclaration + + HasTLA bool File *file.File } @@ -679,6 +754,8 @@ func (self *UnaryExpression) Idx0() file.Idx { } func (self *MetaProperty) Idx0() file.Idx { return self.Idx } +func (self *DynamicImportExpression) Idx0() file.Idx { return self.Idx } + func (self *BadStatement) Idx0() file.Idx { return self.From } func (self *BlockStatement) Idx0() file.Idx { return self.LeftBrace } func (self *BranchStatement) Idx0() file.Idx { return self.Idx } @@ -713,6 +790,9 @@ func (self *PropertyShort) Idx0() file.Idx { return self.Name.Id func (self *PropertyKeyed) Idx0() file.Idx { return self.Key.Idx0() } func (self *ExpressionBody) Idx0() file.Idx { return self.Expression.Idx0() } +func (self *ExportDeclaration) Idx0() file.Idx { return self.Idx } +func (self *ImportDeclaration) Idx0() file.Idx { return self.Idx } + func (self *VariableDeclaration) Idx0() file.Idx { return self.Var } func (self *FieldDefinition) Idx0() file.Idx { return self.Idx } func (self *MethodDefinition) Idx0() file.Idx { return self.Idx } @@ -767,10 +847,13 @@ func (self *UnaryExpression) Idx1() file.Idx { } return self.Operand.Idx1() } + func (self *MetaProperty) Idx1() file.Idx { return self.Property.Idx1() } +func (self *DynamicImportExpression) Idx1() file.Idx { return self.Idx + 6 } + func (self *BadStatement) Idx1() file.Idx { return self.To } func (self *BlockStatement) Idx1() file.Idx { return self.RightBrace + 1 } func (self *BranchStatement) Idx1() file.Idx { @@ -841,6 +924,14 @@ func (self *PropertyKeyed) Idx1() file.Idx { return self.Value.Idx1() } func (self *ExpressionBody) Idx1() file.Idx { return self.Expression.Idx1() } +func (self *ExportDeclaration) Idx1() file.Idx { + return self.Idx + file.Idx(len(token.EXPORT.String())) +} + +func (self *ImportDeclaration) Idx1() file.Idx { + return self.Idx + file.Idx(len(token.IMPORT.String())) +} + func (self *VariableDeclaration) Idx1() file.Idx { if len(self.List) > 0 { return self.List[len(self.List)-1].Idx1() diff --git a/vendor/github.com/grafana/sobek/builtin_object.go b/vendor/github.com/grafana/sobek/builtin_object.go index d7c5aa922acb..957ef6391122 100644 --- a/vendor/github.com/grafana/sobek/builtin_object.go +++ b/vendor/github.com/grafana/sobek/builtin_object.go @@ -284,23 +284,16 @@ func (r *Runtime) object_freeze(call FunctionCall) Value { obj.self.preventExtensions(true) for item, next := obj.self.iterateKeys()(); next != nil; item, next = next() { - if prop, ok := item.value.(*valueProperty); ok { - prop.configurable = false - if !prop.accessor { - prop.writable = false - } + prop := obj.getOwnProp(item.name) + descr := PropertyDescriptor{ + Configurable: FLAG_FALSE, + } + if prop, ok := prop.(*valueProperty); ok && prop.accessor { + // no-op } else { - prop := obj.getOwnProp(item.name) - descr := PropertyDescriptor{ - Configurable: FLAG_FALSE, - } - if prop, ok := prop.(*valueProperty); ok && prop.accessor { - // no-op - } else { - descr.Writable = FLAG_FALSE - } - obj.defineOwnProperty(item.name, descr, true) + descr.Writable = FLAG_FALSE } + obj.defineOwnProperty(item.name, descr, true) } return obj } else { diff --git a/vendor/github.com/grafana/sobek/compiler.go b/vendor/github.com/grafana/sobek/compiler.go index edebf8c6ce9c..b0378249509b 100644 --- a/vendor/github.com/grafana/sobek/compiler.go +++ b/vendor/github.com/grafana/sobek/compiler.go @@ -2,11 +2,11 @@ package sobek import ( "fmt" - "github.com/grafana/sobek/token" "sort" "github.com/grafana/sobek/ast" "github.com/grafana/sobek/file" + "github.com/grafana/sobek/token" "github.com/grafana/sobek/unistring" ) @@ -29,8 +29,9 @@ const ( maskVar = 1 << 30 maskDeletable = 1 << 29 maskStrict = maskDeletable + maskIndirect = 1 << 28 - maskTyp = maskConst | maskVar | maskDeletable + maskTyp = maskConst | maskVar | maskDeletable | maskIndirect ) type varType byte @@ -72,6 +73,8 @@ type Program struct { funcName unistring.String src *file.File srcMap []srcMapItem + + scriptOrModule interface{} } type compiler struct { @@ -79,6 +82,9 @@ type compiler struct { scope *scope block *block + hostResolveImportedModule HostResolveImportedModuleFunc + module *SourceTextModuleRecord + classScope *classScope enumGetExpr compiledEnumGetExpr @@ -91,10 +97,18 @@ type compiler struct { stringCache map[unistring.String]Value } +func (c *compiler) getScriptOrModule() interface{} { + if c.module != nil { + return c.module + } + return c.p // TODO figure comething better +} + type binding struct { scope *scope name unistring.String accessPoints map[*scope]*[]int + getIndirect func(vm *vm) Value isConst bool isStrict bool isArg bool @@ -134,7 +148,9 @@ func (b *binding) markAccessPoint() { func (b *binding) emitGet() { b.markAccessPoint() - if b.isVar && !b.isArg { + if b.getIndirect != nil { + b.scope.c.emit(loadIndirect(b.getIndirect)) + } else if b.isVar && !b.isArg { b.scope.c.emit(loadStack(0)) } else { b.scope.c.emit(loadStackLex(0)) @@ -143,7 +159,9 @@ func (b *binding) emitGet() { func (b *binding) emitGetAt(pos int) { b.markAccessPointAt(pos) - if b.isVar && !b.isArg { + if b.getIndirect != nil { + b.scope.c.p.code[pos] = loadIndirect(b.getIndirect) + } else if b.isVar && !b.isArg { b.scope.c.p.code[pos] = loadStack(0) } else { b.scope.c.p.code[pos] = loadStackLex(0) @@ -151,8 +169,11 @@ func (b *binding) emitGetAt(pos int) { } func (b *binding) emitGetP() { - if b.isVar && !b.isArg { - // no-op + if b.getIndirect != nil { + b.markAccessPoint() + b.scope.c.emit(loadIndirect(b.getIndirect), pop) + } else if b.isVar && !b.isArg { + // noop } else { // make sure TDZ is checked b.markAccessPoint() @@ -237,7 +258,9 @@ func (b *binding) emitInitPAtScope(scope *scope, pos int) { func (b *binding) emitGetVar(callee bool) { b.markAccessPoint() - if b.isVar && !b.isArg { + if b.getIndirect != nil { + b.scope.c.emit(loadIndirect(b.getIndirect)) + } else if b.isVar && !b.isArg { b.scope.c.emit(&loadMixed{name: b.name, callee: callee}) } else { b.scope.c.emit(&loadMixedLex{name: b.name, callee: callee}) @@ -676,6 +699,18 @@ func (s *scope) finaliseVarAlloc(stackOffset int) (stashSize, stackSize int) { switch i := (*ap).(type) { case loadStack: *ap = loadStash(idx) + case initIndirect: + *ap = initIndirect{idx: idx, getter: i.getter} + case export: + *ap = export{ + idx: idx, + callback: i.callback, + } + case exportLex: + *ap = exportLex{ + idx: idx, + callback: i.callback, + } case storeStack: *ap = storeStash(idx) case storeStackP: @@ -696,6 +731,8 @@ func (s *scope) finaliseVarAlloc(stackOffset int) (stashSize, stackSize int) { i.idx = idx case *resolveMixed: i.idx = idx + case loadIndirect: + // do nothing default: s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i) } @@ -871,6 +908,9 @@ func (s *scope) makeNamesMap() map[unistring.String]uint32 { if b.isVar { idx |= maskVar } + if b.getIndirect != nil { + idx |= maskIndirect + } names[b.name] = idx } return names @@ -901,6 +941,185 @@ found: s.bindings = s.bindings[:l] } +func (c *compiler) compileModule(module *SourceTextModuleRecord) { + oldModule := c.module + c.module = module + oldResolve := c.hostResolveImportedModule + c.hostResolveImportedModule = module.hostResolveImportedModule + defer func() { + c.module = oldModule + c.hostResolveImportedModule = oldResolve + }() + in := module.body + c.p.scriptOrModule = module + c.p.src = in.File + + c.newScope() + scope := c.scope + scope.dynamic = true + scope.strict = true + c.newBlockScope() + scope = c.scope + scope.funcType = funcModule + // scope.variable = true + c.emit(&enterFunc{ + funcType: funcModule, + }) + c.block = &block{ + outer: c.block, + typ: blockScope, + + // needResult: true, + } + var enter *enterBlock + c.emit(&enterFuncBody{ + funcType: funcModule, + extensible: true, + adjustStack: true, + }) + for _, in := range module.indirectExportEntries { + v, ambiguous := module.ResolveExport(in.exportName) + if v == nil || ambiguous { + c.compileAmbiguousImport(unistring.NewFromString(in.importName)) + } + } + + for _, in := range module.importEntries { + c.compileImportEntry(in) + } + funcs := c.extractFunctions(in.Body) + c.createFunctionBindings(funcs) + c.compileDeclList(in.DeclarationList, false) + vars := make([]unistring.String, len(scope.bindings)) + for i, b := range scope.bindings { + vars[i] = b.name + } + if len(vars) > 0 { + c.emit(&bindVars{names: vars, deletable: false}) + } + if c.compileLexicalDeclarations(in.Body, true) { + c.block = &block{ + outer: c.block, + typ: blockScope, + needResult: true, + } + enter = &enterBlock{} + c.emit(enter) + } + for _, exp := range in.Body { + if imp, ok := exp.(*ast.ImportDeclaration); ok { + c.compileImportDeclaration(imp) + } + } + for _, entry := range module.localExportEntries { + c.compileLocalExportEntry(entry) + } + for _, entry := range module.indirectExportEntries { + c.compileIndirectExportEntry(entry) + } + + c.compileFunctions(funcs) + + c.emit(&loadModulePromise{moduleCore: module}) + c.emit(await) // this to stop us execute once after we initialize globals + c.emit(pop) + + c.compileStatements(in.Body, true) + c.emit(loadUndef) + c.emit(ret) + if enter != nil { + c.leaveScopeBlock(enter) + c.popScope() + } + + scope.finaliseVarAlloc(0) + m := &newModule{ + moduleCore: module, + newAsyncFunc: newAsyncFunc{ + newFunc: newFunc{ + prg: c.p, + name: unistring.String(in.File.Name()), + source: in.File.Source(), + length: 0, + strict: true, + }, + }, + } + c.p = &Program{ + src: in.File, + scriptOrModule: m, + } + c.emit(_loadUndef{}, m, call(0), &setModulePromise{moduleCore: module}) +} + +func (c *compiler) compileImportEntry(in importEntry) { + importedModule, err := c.hostResolveImportedModule(c.module, in.moduleRequest) + if err != nil { + panic(fmt.Errorf("previously resolved module returned error %w", err)) + } + if in.importName != "*" { + resolution, ambiguous := importedModule.ResolveExport(in.importName) + if resolution == nil || ambiguous { + c.compileAmbiguousImport(unistring.NewFromString(in.importName)) + return + } + } + b, _ := c.scope.bindName(unistring.NewFromString(in.localName)) + b.inStash = true + b.isConst = true +} + +func (c *compiler) compileLocalExportEntry(entry exportEntry) { + name := unistring.NewFromString(entry.localName) + b, ok := c.scope.boundNames[name] + if !ok { + if entry.localName != "default" { + c.throwSyntaxError(entry.offset, "exporting unknown binding: %q", name) + } + b, _ = c.scope.bindName(name) + } + + b.inStash = true + b.markAccessPoint() + + exportName := unistring.NewFromString(entry.localName) + module := c.module + callback := func(vm *vm, getter func() Value) { + vm.r.modules[module].(*SourceTextModuleInstance).exportGetters[exportName.String()] = getter + } + + if entry.lex || !c.scope.boundNames[exportName].isVar { + c.emit(exportLex{callback: callback}) + } else { + c.emit(export{callback: callback}) + } +} + +func (c *compiler) compileIndirectExportEntry(entry exportEntry) { + otherModule, err := c.hostResolveImportedModule(c.module, entry.moduleRequest) + if err != nil { + panic(fmt.Errorf("previously resolved module returned error %w", err)) + } + if entry.importName == "*" { + return + } + b, ambiguous := otherModule.ResolveExport(entry.importName) + if ambiguous || b == nil { + c.compileAmbiguousImport(unistring.NewFromString(entry.importName)) + return + } + + exportName := unistring.NewFromString(entry.exportName).String() + importName := unistring.NewFromString(b.BindingName).String() + module := c.module + c.emit(exportIndirect{callback: func(vm *vm) { + m := vm.r.modules[module] + m.(*SourceTextModuleInstance).exportGetters[exportName] = func() Value { + return vm.r.modules[b.Module].GetBindingValue(importName) + } + }}) +} + func (c *compiler) compile(in *ast.Program, strict, inGlobal bool, evalVm *vm) { c.ctxVM = evalVm @@ -997,6 +1216,10 @@ func (c *compiler) compile(in *ast.Program, strict, inGlobal bool, evalVm *vm) { c.stringCache = nil } +func (c *compiler) compileAmbiguousImport(name unistring.String) { + c.emit(ambiguousImport(name)) +} + func (c *compiler) compileDeclList(v []*ast.VariableDeclaration, inFunc bool) { for _, value := range v { c.createVarBindings(value, inFunc) @@ -1022,6 +1245,13 @@ func (c *compiler) extractFunctions(list []ast.Statement) (funcs []*ast.Function } else { continue } + case *ast.ExportDeclaration: + if st.HoistableDeclaration == nil { + continue + } + if st.HoistableDeclaration.FunctionDeclaration != nil { + decl = st.HoistableDeclaration.FunctionDeclaration + } default: continue } @@ -1203,19 +1433,42 @@ func (c *compiler) createLexicalBindings(lex *ast.LexicalDeclaration) { } func (c *compiler) compileLexicalDeclarations(list []ast.Statement, scopeDeclared bool) bool { + declareScope := func() { + if !scopeDeclared { + c.newBlockScope() + scopeDeclared = true + } + } for _, st := range list { - if lex, ok := st.(*ast.LexicalDeclaration); ok { - if !scopeDeclared { - c.newBlockScope() - scopeDeclared = true - } + switch lex := st.(type) { + case *ast.LexicalDeclaration: + declareScope() c.createLexicalBindings(lex) - } else if cls, ok := st.(*ast.ClassDeclaration); ok { - if !scopeDeclared { - c.newBlockScope() - scopeDeclared = true + case *ast.ClassDeclaration: + declareScope() + c.createLexicalIdBinding(lex.Class.Name.Name, false, int(lex.Class.Name.Idx)-1) + case *ast.ExportDeclaration: + if lex.LexicalDeclaration != nil { + declareScope() + c.createLexicalBindings(lex.LexicalDeclaration) + } else if lex.ClassDeclaration != nil { + declareScope() + if lex.IsDefault { + c.createLexicalIdBinding("default", false, int(lex.Idx0())-1) + } else { + cls := lex.ClassDeclaration + c.createLexicalIdBinding(cls.Class.Name.Name, false, int(cls.Class.Name.Idx)-1) + } + } else if lex.IsDefault { + switch { + case lex.HoistableDeclaration != nil: + s := c.scope + + unique := !s.isFunction() && !s.variable && s.strict + + s.bindNameLexical("default", unique, int(lex.HoistableDeclaration.FunctionDeclaration.Function.Name.Idx1())-1) + } } - c.createLexicalIdBinding(cls.Class.Name.Name, false, int(cls.Class.Name.Idx)-1) } } return scopeDeclared diff --git a/vendor/github.com/grafana/sobek/compiler_expr.go b/vendor/github.com/grafana/sobek/compiler_expr.go index 69d37153cd5c..ffac6e76f142 100644 --- a/vendor/github.com/grafana/sobek/compiler_expr.go +++ b/vendor/github.com/grafana/sobek/compiler_expr.go @@ -134,6 +134,7 @@ const ( funcClsInit funcCtor funcDerivedCtor + funcModule ) type compiledFunctionLiteral struct { @@ -169,6 +170,9 @@ type compiledNewTarget struct { baseCompiledExpr } +type compiledImportMeta struct { + baseCompiledExpr +} type compiledSequenceExpr struct { baseCompiledExpr sequence []compiledExpr @@ -230,6 +234,9 @@ type compiledOptional struct { baseCompiledExpr expr compiledExpr } +type compiledDynamicImport struct { + baseCompiledExpr +} func (e *defaultDeleteExpr) emitGetter(putOnStack bool) { e.expr.emitGetter(false) @@ -1373,9 +1380,10 @@ func (e *compiledFunctionLiteral) compile() (prg *Program, name unistring.String savedPrg := e.c.p preambleLen := 8 // enter, boxThis, loadStack(0), initThis, createArgs, set, loadCallee, init e.c.p = &Program{ - src: e.c.p.src, - code: e.c.newCode(preambleLen, 16), - srcMap: []srcMapItem{{srcPos: e.offset}}, + src: e.c.p.src, + code: e.c.newCode(preambleLen, 16), + srcMap: []srcMapItem{{srcPos: e.offset}}, + scriptOrModule: e.c.getScriptOrModule(), } e.c.newScope() s := e.c.scope @@ -1983,7 +1991,7 @@ func (e *compiledClassLiteral) emitGetter(putOnStack bool) { DeclarationList: elt.DeclarationList, }, true) f.typ = funcClsInit - //f.lhsName = "" + // f.lhsName = "" f.homeObjOffset = 1 staticElements = append(staticElements, clsElement{ body: f, @@ -2198,9 +2206,10 @@ func (e *compiledClassLiteral) compileFieldsAndStaticBlocks(elements []clsElemen } e.c.p = &Program{ - src: savedPrg.src, - funcName: funcName, - code: e.c.newCode(2, 16), + src: savedPrg.src, + funcName: funcName, + code: e.c.newCode(2, 16), + scriptOrModule: e.c.getScriptOrModule(), } e.c.newScope() @@ -2240,7 +2249,7 @@ func (e *compiledClassLiteral) compileFieldsAndStaticBlocks(elements []clsElemen } } } - //e.c.emit(halt) + // e.c.emit(halt) if s.isDynamic() || thisBinding.useCount() > 0 { if s.isDynamic() || thisBinding.inStash { thisBinding.emitInitAt(1) @@ -2327,6 +2336,12 @@ func (c *compiler) compileArrowFunctionLiteral(v *ast.ArrowFunctionLiteral) *com func (c *compiler) emitLoadThis() { b, eval := c.scope.lookupThis() + + if c.module != nil && c.scope.outer != nil && c.scope.outer.outer == nil { // modules don't have this defined + // TODO maybe just add isTopLevel and rewrite the rest of the code + c.emit(_loadUndef{}) + return + } if b != nil { b.emitGet() } else { @@ -2407,12 +2422,25 @@ func (e *compiledNewTarget) emitGetter(putOnStack bool) { } } +func (e *compiledImportMeta) emitGetter(putOnStack bool) { + if putOnStack { + e.addSrcMap() + e.c.emit(loadImportMeta) + } +} + func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr { - if v.Meta.Name == "new" || v.Property.Name != "target" { + if v.Meta.Name == "new" && v.Property.Name == "target" { r := &compiledNewTarget{} r.init(c, v.Idx0()) return r } + if v.Meta.Name == "import" && v.Property.Name == "meta" { + r := &compiledImportMeta{} + r.init(c, v.Idx0()) + return r + } + c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name) return nil } @@ -2799,7 +2827,6 @@ func (e *compiledBinaryExpr) emitGetter(putOnStack bool) { } func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr { - switch v.Operator { case token.LOGICAL_OR: return c.compileLogicalOr(v.Left, v.Right, v.Idx0()) @@ -3179,11 +3206,16 @@ func (c *compiler) compileCallee(v ast.Expression) compiledExpr { c.throwSyntaxError(int(v.Idx0())-1, "'super' keyword unexpected here") panic("unreachable") } + if imp, ok := v.(*ast.DynamicImportExpression); ok { + r := &compiledDynamicImport{} + r.init(c, imp.Idx) + return r + } return c.compileExpression(v) } func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr { - + // fmt.Printf("%+v %+v %T\n", v, v.Callee, v.Callee) args := make([]compiledExpr, len(v.ArgumentList)) isVariadic := false for i, argExpr := range v.ArgumentList { @@ -3278,8 +3310,6 @@ func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr { } func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr { - // log.Printf("compileAssignExpression(): %+v", v) - r := &compiledAssignExpr{ left: c.compileExpression(v.Left), right: c.compileExpression(v.Right), @@ -3579,6 +3609,12 @@ func (e *compiledOptional) emitGetter(putOnStack bool) { } } +func (e *compiledDynamicImport) emitGetter(putOnStack bool) { + if putOnStack { + e.c.emit(dynamicImport) + } +} + func (e *compiledAwaitExpression) emitGetter(putOnStack bool) { e.arg.emitGetter(true) e.c.emit(await) diff --git a/vendor/github.com/grafana/sobek/compiler_stmt.go b/vendor/github.com/grafana/sobek/compiler_stmt.go index f9599b7e329e..7d654d913ad2 100644 --- a/vendor/github.com/grafana/sobek/compiler_stmt.go +++ b/vendor/github.com/grafana/sobek/compiler_stmt.go @@ -8,7 +8,6 @@ import ( ) func (c *compiler) compileStatement(v ast.Statement, needResult bool) { - switch v := v.(type) { case *ast.BlockStatement: c.compileBlockStatement(v, needResult) @@ -52,6 +51,10 @@ func (c *compiler) compileStatement(v ast.Statement, needResult bool) { case *ast.WithStatement: c.compileWithStatement(v, needResult) case *ast.DebuggerStatement: + case *ast.ImportDeclaration: + // this is already done, earlier + case *ast.ExportDeclaration: + c.compileExportDeclaration(v) default: c.assert(false, int(v.Idx0())-1, "Unknown statement type: %T", v) panic("unreachable") @@ -780,6 +783,165 @@ func (c *compiler) emitVarAssign(name unistring.String, offset int, init compile } } +func (c *compiler) compileExportDeclaration(expr *ast.ExportDeclaration) { + switch { + case expr.Variable != nil: + c.compileVariableStatement(expr.Variable) + case expr.LexicalDeclaration != nil: + c.compileLexicalDeclaration(expr.LexicalDeclaration) + case expr.ClassDeclaration != nil: + cls := expr.ClassDeclaration + if expr.IsDefault { + c.emitLexicalAssign("default", int(cls.Class.Class)-1, c.compileClassLiteral(cls.Class, false)) + } else { + c.compileClassDeclaration(cls) + } + case expr.HoistableDeclaration != nil: // already handled + case expr.AssignExpression != nil: + assign := expr.AssignExpression + c.compileLexicalDeclaration(&ast.LexicalDeclaration{ + Idx: assign.Idx0(), + Token: token.CONST, + List: []*ast.Binding{ + { + Target: &ast.Identifier{ + Name: unistring.String("default"), + Idx: assign.Idx0(), + }, + Initializer: assign, + }, + }, + }) + case expr.ExportFromClause != nil: + from := expr.ExportFromClause + module, err := c.hostResolveImportedModule(c.module, expr.FromClause.ModuleSpecifier.String()) + if err != nil { + c.throwSyntaxError(int(expr.Idx0()), err.Error()) + } + if from.NamedExports == nil { // star export - nothing to do + return + } + for _, name := range from.NamedExports.ExportsList { + value, ambiguous := module.ResolveExport(name.IdentifierName.String()) + + if ambiguous || value == nil { // also ambiguous + continue // ambiguous import already reported + } + + n := name.Alias + if n.String() == "" { + n = name.IdentifierName + } + localB, _ := c.scope.lookupName(n) + if localB == nil { + c.throwSyntaxError(int(expr.Idx0()), "couldn't lookup %s", n) + } + identifier := name.IdentifierName.String() + localB.getIndirect = func(vm *vm) Value { + return vm.r.modules[module].GetBindingValue(identifier) + } + } + } +} + +func (c *compiler) compileImportDeclaration(expr *ast.ImportDeclaration) { + if expr.FromClause == nil { + return // import "specifier"; + } + module, err := c.hostResolveImportedModule(c.module, expr.FromClause.ModuleSpecifier.String()) + if err != nil { + c.throwSyntaxError(int(expr.Idx0()), err.Error()) + } + if expr.ImportClause != nil { + if namespace := expr.ImportClause.NameSpaceImport; namespace != nil { + idx := expr.Idx + c.emitLexicalAssign( + namespace.ImportedBinding, + int(idx), + c.compileEmitterExpr(func() { + c.emit(importNamespace{ + module: module, + }) + }, idx), + ) + } + if named := expr.ImportClause.NamedImports; named != nil { + for _, name := range named.ImportsList { + value, ambiguous := module.ResolveExport(name.IdentifierName.String()) + + if ambiguous || value == nil { + continue // ambiguous import already reports + } + n := name.Alias + if n.String() == "" { + n = name.IdentifierName + } + if value.BindingName == "*namespace*" { + idx := expr.Idx + c.emitLexicalAssign( + n, + int(idx), + c.compileEmitterExpr(func() { + c.emit(importNamespace{ + module: value.Module, + }) + }, idx), + ) + continue + } + + c.checkIdentifierLName(n, int(expr.Idx)) + localB, _ := c.scope.lookupName(n) + if localB == nil { + c.throwSyntaxError(int(expr.Idx0()), "couldn't lookup %s", n) + } + identifier := unistring.NewFromString(value.BindingName).String() + localB.getIndirect = func(vm *vm) Value { + m := vm.r.modules[value.Module] + return m.GetBindingValue(identifier) + } + localB.markAccessPoint() + c.emit(initIndirect{getter: localB.getIndirect}) + + } + } + + if def := expr.ImportClause.ImportedDefaultBinding; def != nil { + value, ambiguous := module.ResolveExport("default") + + if ambiguous || value == nil { + return // already handled + } + + localB, _ := c.scope.lookupName(def.Name) + if localB == nil { + c.throwSyntaxError(int(expr.Idx0()), "couldn't lookup %s", def.Name) + } + if value.BindingName == "*namespace*" { + idx := expr.Idx + c.emitLexicalAssign( + def.Name, + int(idx), + c.compileEmitterExpr(func() { + c.emit(importNamespace{ + module: value.Module, + }) + }, idx), + ) + } else { + identifier := unistring.NewFromString(value.BindingName).String() + localB.getIndirect = func(vm *vm) Value { + m := vm.r.modules[value.Module] + v := m.GetBindingValue(identifier) + return v + } + localB.markAccessPoint() + c.emit(initIndirect{getter: localB.getIndirect}) + } + } + } +} + func (c *compiler) compileVarBinding(expr *ast.Binding) { switch target := expr.Target.(type) { case *ast.Identifier: diff --git a/vendor/github.com/grafana/sobek/modules.go b/vendor/github.com/grafana/sobek/modules.go new file mode 100644 index 000000000000..e570166776d0 --- /dev/null +++ b/vendor/github.com/grafana/sobek/modules.go @@ -0,0 +1,518 @@ +package sobek + +import ( + "errors" + "sort" +) + +type HostResolveImportedModuleFunc func(referencingScriptOrModule interface{}, specifier string) (ModuleRecord, error) + +// TODO most things here probably should be unexported and names should be revised before merged in master +// Record should probably be dropped from everywhere + +// ModuleRecord is the common interface for module record as defined in the EcmaScript specification +type ModuleRecord interface { + // GetExportedNames gets it result on the callback and returns wether it has done so or not. + // This is currently a hack in order to support ModuleRecords who can not return the exported names right away. + // This happens when you need CommonJS modules to be importable or more accurately to use `export * as something ...`. + // + // Experimental: This is very likely to be changed in the future + GetExportedNames(callback func([]string), resolveset ...ModuleRecord) bool + ResolveExport(exportName string, resolveset ...ResolveSetElement) (*ResolvedBinding, bool) + Link() error + Evaluate(*Runtime) *Promise +} + +type CyclicModuleRecordStatus uint8 + +const ( + Unlinked CyclicModuleRecordStatus = iota + Linking + Linked + Evaluating + Evaluating_Async + Evaluated +) + +type CyclicModuleRecord interface { + ModuleRecord + RequestedModules() []string + InitializeEnvironment() error + Instantiate(rt *Runtime) (CyclicModuleInstance, error) +} + +type ( + ModuleInstance interface { + GetBindingValue(string) Value + } + CyclicModuleInstance interface { + ModuleInstance + HasTLA() bool + ExecuteModule(rt *Runtime, res, rej func(interface{})) (CyclicModuleInstance, error) + } +) + +type linkState struct { + status map[ModuleRecord]CyclicModuleRecordStatus + dfsIndex map[ModuleRecord]uint + dfsAncestorIndex map[ModuleRecord]uint +} + +func newLinkState() *linkState { + return &linkState{ + status: make(map[ModuleRecord]CyclicModuleRecordStatus), + dfsIndex: make(map[ModuleRecord]uint), + dfsAncestorIndex: make(map[ModuleRecord]uint), + } +} + +func (c *compiler) CyclicModuleRecordConcreteLink(module ModuleRecord) error { + stack := []CyclicModuleRecord{} + if _, err := c.innerModuleLinking(newLinkState(), module, &stack, 0); err != nil { + return err + } + return nil +} + +func (c *compiler) innerModuleLinking(state *linkState, m ModuleRecord, stack *[]CyclicModuleRecord, index uint) (uint, error) { + var module CyclicModuleRecord + var ok bool + if module, ok = m.(CyclicModuleRecord); !ok { + return index, m.Link() + } + if status := state.status[module]; status == Linking || status == Linked || status == Evaluated { + return index, nil + } else if status != Unlinked { + return 0, errors.New("bad status on link") // TODO fix + } + state.status[module] = Linking + state.dfsIndex[module] = index + state.dfsAncestorIndex[module] = index + index++ + *stack = append(*stack, module) + var err error + var requiredModule ModuleRecord + for _, required := range module.RequestedModules() { + requiredModule, err = c.hostResolveImportedModule(module, required) + if err != nil { + return 0, err + } + index, err = c.innerModuleLinking(state, requiredModule, stack, index) + if err != nil { + return 0, err + } + if requiredC, ok := requiredModule.(CyclicModuleRecord); ok { + if state.status[requiredC] == Linking { + if ancestorIndex := state.dfsAncestorIndex[module]; state.dfsAncestorIndex[requiredC] > ancestorIndex { + state.dfsAncestorIndex[requiredC] = ancestorIndex + } + } + } + } + err = module.InitializeEnvironment() + if err != nil { + return 0, err + } + if state.dfsAncestorIndex[module] == state.dfsIndex[module] { + for i := len(*stack) - 1; i >= 0; i-- { + requiredModule := (*stack)[i] + *stack = (*stack)[:i] + state.status[requiredModule] = Linked + if requiredModule == module { + break + } + } + } + return index, nil +} + +type evaluationState struct { + status map[ModuleInstance]CyclicModuleRecordStatus + dfsIndex map[ModuleInstance]uint + dfsAncestorIndex map[ModuleInstance]uint + pendingAsyncDependancies map[ModuleInstance]uint + cycleRoot map[ModuleInstance]CyclicModuleInstance + asyncEvaluation map[CyclicModuleInstance]uint64 + asyncParentModules map[CyclicModuleInstance][]CyclicModuleInstance + evaluationError map[CyclicModuleInstance]interface{} + topLevelCapability map[CyclicModuleRecord]*promiseCapability + + asyncEvaluationCounter uint64 +} + +func newEvaluationState() *evaluationState { + return &evaluationState{ + status: make(map[ModuleInstance]CyclicModuleRecordStatus), + dfsIndex: make(map[ModuleInstance]uint), + dfsAncestorIndex: make(map[ModuleInstance]uint), + pendingAsyncDependancies: make(map[ModuleInstance]uint), + cycleRoot: make(map[ModuleInstance]CyclicModuleInstance), + asyncEvaluation: make(map[CyclicModuleInstance]uint64), + asyncParentModules: make(map[CyclicModuleInstance][]CyclicModuleInstance), + evaluationError: make(map[CyclicModuleInstance]interface{}), + topLevelCapability: make(map[CyclicModuleRecord]*promiseCapability), + } +} + +// TODO have resolve as part of runtime +func (r *Runtime) CyclicModuleRecordEvaluate(c CyclicModuleRecord, resolve HostResolveImportedModuleFunc) *Promise { + if r.modules == nil { + r.modules = make(map[ModuleRecord]ModuleInstance) + } + stackInstance := []CyclicModuleInstance{} + + if r.evaluationState == nil { + r.evaluationState = newEvaluationState() + } + if cap, ok := r.evaluationState.topLevelCapability[c]; ok { + return cap.promise.Export().(*Promise) + } + capability := r.newPromiseCapability(r.getPromise()) + r.evaluationState.topLevelCapability[c] = capability + state := r.evaluationState + _, err := r.innerModuleEvaluation(state, c, &stackInstance, 0, resolve) + if err != nil { + for _, m := range stackInstance { + state.status[m] = Evaluated + state.evaluationError[m] = err + } + + capability.reject(r.ToValue(err)) + } else { + if state.asyncEvaluation[r.modules[c].(CyclicModuleInstance)] == 0 { + state.topLevelCapability[c].resolve(_undefined) + } + } + if len(r.vm.callStack) == 0 { + r.leave() + } + return state.topLevelCapability[c].promise.Export().(*Promise) +} + +func (r *Runtime) innerModuleEvaluation( + state *evaluationState, + m ModuleRecord, stack *[]CyclicModuleInstance, index uint, + resolve HostResolveImportedModuleFunc, +) (idx uint, err error) { + if len(*stack) > 100000 { + panic("too deep dependancy stack of 100000") + } + var cr CyclicModuleRecord + var ok bool + var c CyclicModuleInstance + if cr, ok = m.(CyclicModuleRecord); !ok { + p := m.Evaluate(r) + if p.state == PromiseStateRejected { + return index, p.Result().Export().(error) + } + r.modules[m] = p.Result().Export().(ModuleInstance) // TODO fix this cast ... somehow + return index, nil + } + if _, ok = r.modules[m]; ok { + return index, nil + } + c, err = cr.Instantiate(r) + if err != nil { + // state.evaluationError[cr] = err + // TODO handle this somehow - maybe just panic + return index, err + } + + r.modules[m] = c + if status := state.status[c]; status == Evaluated { + return index, nil + } else if status == Evaluating || status == Evaluating_Async { + // maybe check evaluation error + return index, nil + } + state.status[c] = Evaluating + state.dfsIndex[c] = index + state.dfsAncestorIndex[c] = index + state.pendingAsyncDependancies[c] = 0 + index++ + + *stack = append(*stack, c) + var requiredModule ModuleRecord + for _, required := range cr.RequestedModules() { + requiredModule, err = resolve(m, required) + if err != nil { + state.evaluationError[c] = err + return index, err + } + index, err = r.innerModuleEvaluation(state, requiredModule, stack, index, resolve) + if err != nil { + return index, err + } + requiredInstance := r.GetModuleInstance(requiredModule) + if requiredC, ok := requiredInstance.(CyclicModuleInstance); ok { + if state.status[requiredC] == Evaluating { + if ancestorIndex := state.dfsAncestorIndex[c]; state.dfsAncestorIndex[requiredC] > ancestorIndex { + state.dfsAncestorIndex[requiredC] = ancestorIndex + } + } else { + requiredC = state.cycleRoot[requiredC] + // check stuff + } + if state.asyncEvaluation[requiredC] != 0 { + state.pendingAsyncDependancies[c]++ + state.asyncParentModules[requiredC] = append(state.asyncParentModules[requiredC], c) + } + } + } + if state.pendingAsyncDependancies[c] > 0 || c.HasTLA() { + state.asyncEvaluationCounter++ + state.asyncEvaluation[c] = state.asyncEvaluationCounter + if state.pendingAsyncDependancies[c] == 0 { + r.executeAsyncModule(state, c) + } + } else { + c, err = c.ExecuteModule(r, nil, nil) + if err != nil { + state.evaluationError[c] = err + return index, err + } + } + + if state.dfsAncestorIndex[c] == state.dfsIndex[c] { + for i := len(*stack) - 1; i >= 0; i-- { + requiredModuleInstance := (*stack)[i] + *stack = (*stack)[:i] + if state.asyncEvaluation[requiredModuleInstance] == 0 { + state.status[requiredModuleInstance] = Evaluated + } else { + state.status[requiredModuleInstance] = Evaluating_Async + } + state.cycleRoot[requiredModuleInstance] = c + if requiredModuleInstance == c { + break + } + } + } + return index, nil +} + +func (r *Runtime) executeAsyncModule(state *evaluationState, c CyclicModuleInstance) { + // implement https://262.ecma-international.org/13.0/#sec-execute-async-module + p, res, rej := r.NewPromise() + r.performPromiseThen(p, r.ToValue(func(call FunctionCall) Value { + r.asyncModuleExecutionFulfilled(state, c) + return nil + }), r.ToValue(func(call FunctionCall) Value { + // we use this signature so that sobek doesn't try to infer types and wrap them + err := call.Argument(0) + r.asyncModuleExecutionRejected(state, c, err) + return nil + }), nil) + _, _ = c.ExecuteModule(r, res, rej) +} + +func (r *Runtime) asyncModuleExecutionFulfilled(state *evaluationState, c CyclicModuleInstance) { + if state.status[c] == Evaluated { + return + } + state.asyncEvaluation[c] = 0 + // TODO fix this + for m, i := range r.modules { + if i == c { + if cap := state.topLevelCapability[m.(CyclicModuleRecord)]; cap != nil { + cap.resolve(_undefined) + } + break + } + } + execList := make([]CyclicModuleInstance, 0) + r.gatherAvailableAncestors(state, c, &execList) + sort.Slice(execList, func(i, j int) bool { + return state.asyncEvaluation[execList[i]] < state.asyncEvaluation[execList[j]] + }) + for _, m := range execList { + if state.status[m] == Evaluated { + continue + } + if m.HasTLA() { + r.executeAsyncModule(state, m) + } else { + result, err := m.ExecuteModule(r, nil, nil) + if err != nil { + r.asyncModuleExecutionRejected(state, m, err) + continue + } + state.status[m] = Evaluated + if cap := state.topLevelCapability[r.findModuleRecord(result).(CyclicModuleRecord)]; cap != nil { + // TODO having the module instances going through Values and back is likely not a *great* idea + cap.resolve(_undefined) + } + } + } +} + +func (r *Runtime) gatherAvailableAncestors(state *evaluationState, c CyclicModuleInstance, execList *[]CyclicModuleInstance) { + contains := func(m CyclicModuleInstance) bool { + for _, l := range *execList { + if l == m { + return true + } + } + return false + } + for _, m := range state.asyncParentModules[c] { + if contains(m) || state.evaluationError[m] != nil { + continue + } + state.pendingAsyncDependancies[m]-- + if state.pendingAsyncDependancies[m] == 0 { + *execList = append(*execList, m) + if !m.HasTLA() { + r.gatherAvailableAncestors(state, m, execList) + } + } + } +} + +func (r *Runtime) asyncModuleExecutionRejected(state *evaluationState, c CyclicModuleInstance, ex interface{}) { + if state.status[c] == Evaluated { + return + } + state.evaluationError[c] = ex + state.status[c] = Evaluated + for _, m := range state.asyncParentModules[c] { + r.asyncModuleExecutionRejected(state, m, ex) + } + // TODO handle top level capabiltiy better + if cap := state.topLevelCapability[r.findModuleRecord(c).(CyclicModuleRecord)]; cap != nil { + cap.reject(r.ToValue(ex)) + } +} + +// TODO fix this whole thing +func (r *Runtime) findModuleRecord(i ModuleInstance) ModuleRecord { + for m, mi := range r.modules { + if mi == i { + return m + } + } + panic("this should never happen") +} + +func (r *Runtime) GetActiveScriptOrModule() interface{} { // have some better type + if r.vm.prg != nil && r.vm.prg.scriptOrModule != nil { + return r.vm.prg.scriptOrModule + } + for i := len(r.vm.callStack) - 1; i >= 0; i-- { + prg := r.vm.callStack[i].prg + if prg != nil && prg.scriptOrModule != nil { + return prg.scriptOrModule + } + } + return nil +} + +func (r *Runtime) getImportMetaFor(m ModuleRecord) *Object { + if r.importMetas == nil { + r.importMetas = make(map[ModuleRecord]*Object) + } + if o, ok := r.importMetas[m]; ok { + return o + } + o := r.NewObject() + _ = o.SetPrototype(nil) + + var properties []MetaProperty + if r.getImportMetaProperties != nil { + properties = r.getImportMetaProperties(m) + } + + for _, property := range properties { + o.Set(property.Key, property.Value) + } + + if r.finalizeImportMeta != nil { + r.finalizeImportMeta(o, m) + } + + r.importMetas[m] = o + return o +} + +type MetaProperty struct { + Key string + Value Value +} + +func (r *Runtime) SetGetImportMetaProperties(fn func(ModuleRecord) []MetaProperty) { + r.getImportMetaProperties = fn +} + +func (r *Runtime) SetFinalImportMeta(fn func(*Object, ModuleRecord)) { + r.finalizeImportMeta = fn +} + +// TODO fix signature +type ImportModuleDynamicallyCallback func(referencingScriptOrModule interface{}, specifier Value, promiseCapability interface{}) + +func (r *Runtime) SetImportModuleDynamically(callback ImportModuleDynamicallyCallback) { + r.importModuleDynamically = callback +} + +// TODO figure out whether Result should be an Option thing :shrug: +func (r *Runtime) FinishLoadingImportModule(referrer interface{}, specifier Value, payload interface{}, result ModuleRecord, err interface{}) { + // https://262.ecma-international.org/14.0/#sec-FinishLoadingImportedModule + // if err == nil { + // a. a. If referrer.[[LoadedModules]] contains a Record whose [[Specifier]] is specifier, then + // i. i. Assert: That Record's [[Module]] is result.[[Value]]. + // b. b. Else, append the Record { [[Specifier]]: specifier, [[Module]]: result.[[Value]] } to referrer.[[LoadedModules]]. + + // } + // 2. 2. If payload is a GraphLoadingState Record, then + // a. a. Perform ContinueModuleLoading(payload, result). + // 3. 3. Else, + // a. a. Perform ContinueDynamicImport(payload, result). + r.continueDynamicImport(payload.(*promiseCapability), result, err) // TODO better type inferance +} + +func (r *Runtime) continueDynamicImport(promiseCapability *promiseCapability, result ModuleRecord, err interface{}) { + // https://262.ecma-international.org/14.0/#sec-ContinueDynamicImport + if err != nil { + promiseCapability.reject(r.ToValue(err)) + return + } + // 2. 2. Let module be moduleCompletion.[[Value]]. + module := result + // 3. 3. Let loadPromise be module.LoadRequestedModules(). + loadPromise := r.promiseResolve(r.getPromise(), _undefined) // TODO fix + + rejectionClosure := r.ToValue(func(call FunctionCall) Value { + promiseCapability.reject(call.Argument(0)) + return nil + }) + linkAndEvaluateClosure := r.ToValue(func(call FunctionCall) Value { + // a. a. Let link be Completion(module.Link()). + err := module.Link() + if err != nil { + if err != nil { + switch x1 := err.(type) { + case *CompilerSyntaxError: + err = &Exception{ + val: r.builtin_new(r.getSyntaxError(), []Value{newStringValue(x1.Error())}), + } + case *CompilerReferenceError: + err = &Exception{ + val: r.newError(r.getReferenceError(), x1.Message), + } // TODO proper message + } + } + promiseCapability.reject(r.ToValue(err)) + return nil + } + evaluationPromise := module.Evaluate(r) + onFullfill := r.ToValue(func(call FunctionCall) Value { + namespace := r.NamespaceObjectFor(module) + promiseCapability.resolve(namespace) + return nil + }) + r.performPromiseThen(evaluationPromise, onFullfill, rejectionClosure, nil) + return nil + }) + + r.performPromiseThen(loadPromise.Export().(*Promise), linkAndEvaluateClosure, rejectionClosure, nil) +} diff --git a/vendor/github.com/grafana/sobek/modules_namespace.go b/vendor/github.com/grafana/sobek/modules_namespace.go new file mode 100644 index 000000000000..af00bc322fa1 --- /dev/null +++ b/vendor/github.com/grafana/sobek/modules_namespace.go @@ -0,0 +1,182 @@ +package sobek + +import ( + "sort" + + "github.com/grafana/sobek/unistring" +) + +type namespaceObject struct { + baseObject + m ModuleRecord + exports map[unistring.String]struct{} + exportsNames []unistring.String +} + +func (r *Runtime) NamespaceObjectFor(m ModuleRecord) *Object { + if r.moduleNamespaces == nil { + r.moduleNamespaces = make(map[ModuleRecord]*namespaceObject) + } + if o, ok := r.moduleNamespaces[m]; ok { + return o.val + } + o := r.createNamespaceObject(m) + r.moduleNamespaces[m] = o + return o.val +} + +func (r *Runtime) createNamespaceObject(m ModuleRecord) *namespaceObject { + o := &Object{runtime: r} + no := &namespaceObject{m: m} + no.val = o + no.extensible = true + no.defineOwnPropertySym(SymToStringTag, PropertyDescriptor{ + Value: newStringValue("Module"), + }, true) + no.extensible = false + o.self = no + no.init() + no.exports = make(map[unistring.String]struct{}) + m.GetExportedNames(func(names []string) { + for _, exportName := range names { + v, ambiguous := no.m.ResolveExport(exportName) + if ambiguous || v == nil { + continue + } + no.exports[unistring.NewFromString(exportName)] = struct{}{} + no.exportsNames = append(no.exportsNames, unistring.NewFromString(exportName)) + } + }) + return no +} + +func (no *namespaceObject) stringKeys(all bool, accum []Value) []Value { + for name := range no.exports { + if !all { // TODO this seems off + _ = no.getOwnPropStr(name) + } + accum = append(accum, stringValueFromRaw(name)) + } + // TODO optimize this + sort.Slice(accum, func(i, j int) bool { + return accum[i].String() < accum[j].String() + }) + return accum +} + +type namespacePropIter struct { + no *namespaceObject + idx int +} + +func (no *namespaceObject) iterateStringKeys() iterNextFunc { + return (&namespacePropIter{ + no: no, + }).next +} + +func (no *namespaceObject) iterateKeys() iterNextFunc { + return no.iterateStringKeys() +} + +func (i *namespacePropIter) next() (propIterItem, iterNextFunc) { + for i.idx < len(i.no.exportsNames) { + name := i.no.exportsNames[i.idx] + i.idx++ + prop := i.no.getOwnPropStr(name) + if prop != nil { + return propIterItem{name: stringValueFromRaw(name), value: prop}, i.next + } + } + return propIterItem{}, nil +} + +func (no *namespaceObject) getOwnPropStr(name unistring.String) Value { + if _, ok := no.exports[name]; !ok { + return nil + } + v, ambiguous := no.m.ResolveExport(name.String()) + if ambiguous || v == nil { + no.val.runtime.throwReferenceError((name)) + } + if v.BindingName == "*namespace*" { + return &valueProperty{ + value: no.val.runtime.NamespaceObjectFor(v.Module), + writable: true, + configurable: false, + enumerable: true, + } + } + + mi := no.val.runtime.modules[v.Module] + b := mi.GetBindingValue(v.BindingName) + if b == nil { + // TODO figure this out - this is needed as otherwise valueproperty is thought to not have a value + // which isn't really correct in a particular test around isFrozen + b = _null + } + return &valueProperty{ + value: b, + writable: true, + configurable: false, + enumerable: true, + } +} + +func (no *namespaceObject) hasOwnPropertyStr(name unistring.String) bool { + _, ok := no.exports[name] + return ok +} + +func (no *namespaceObject) getStr(name unistring.String, receiver Value) Value { + prop := no.getOwnPropStr(name) + if prop, ok := prop.(*valueProperty); ok { + if receiver == nil { + return prop.get(no.val) + } + return prop.get(receiver) + } + return prop +} + +func (no *namespaceObject) setOwnStr(name unistring.String, val Value, throw bool) bool { + no.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name) + return false +} + +func (no *namespaceObject) deleteStr(name unistring.String, throw bool) bool { + if _, exists := no.exports[name]; exists { + no.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name) + return false + } + return true +} + +func (no *namespaceObject) defineOwnPropertyStr(name unistring.String, desc PropertyDescriptor, throw bool) bool { + returnFalse := func() bool { + if throw { + no.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name) + } + return false + } + if !no.hasOwnPropertyStr(name) { + return returnFalse() + } + if desc.Empty() { + return true + } + if desc.Writable == FLAG_FALSE { + return returnFalse() + } + if desc.Configurable == FLAG_TRUE { + return returnFalse() + } + if desc.Enumerable == FLAG_FALSE { + return returnFalse() + } + if desc.Value != nil && desc.Value != no.getOwnPropStr(name) { + return returnFalse() + } + // TODO more checks + return true +} diff --git a/vendor/github.com/grafana/sobek/modules_sourcetext.go b/vendor/github.com/grafana/sobek/modules_sourcetext.go new file mode 100644 index 000000000000..61e8a9abeb3f --- /dev/null +++ b/vendor/github.com/grafana/sobek/modules_sourcetext.go @@ -0,0 +1,661 @@ +package sobek + +import ( + "fmt" + "sort" + "sync" + + "github.com/grafana/sobek/ast" + "github.com/grafana/sobek/parser" +) + +var ( + _ CyclicModuleRecord = &SourceTextModuleRecord{} + _ CyclicModuleInstance = &SourceTextModuleInstance{} +) + +type SourceTextModuleInstance struct { + moduleRecord *SourceTextModuleRecord + // TODO figure out omething less idiotic + exportGetters map[string]func() Value + pcap *promiseCapability + asyncPromise *Promise +} + +func (s *SourceTextModuleInstance) ExecuteModule(rt *Runtime, res, rej func(interface{})) (CyclicModuleInstance, error) { + promiseP := s.pcap.promise.self.(*Promise) + if len(promiseP.fulfillReactions) == 1 { + ar := promiseP.fulfillReactions[0].asyncRunner + _ = ar.onFulfilled(FunctionCall{Arguments: []Value{_undefined}}) + } + + promise := s.asyncPromise + if !s.HasTLA() { + if res != nil { + panic("sobek bug where a not async module was executed as async on") + } + switch s.asyncPromise.state { + case PromiseStateFulfilled: + return s, nil + case PromiseStateRejected: + return nil, rt.vm.exceptionFromValue(promise.result) + case PromiseStatePending: + panic("sobek bug where an sync module was not executed synchronously") + default: + panic("Somehow promise from a module execution is in invalid state") + } + } + if res == nil { + panic("sobek bug where an async module was not executed as async") + } + rt.performPromiseThen(s.asyncPromise, rt.ToValue(func(call FunctionCall) Value { + // fmt.Println("!!!!res") + res(call.Argument(0)) + return nil + }), rt.ToValue(func(call FunctionCall) Value { + v := call.Argument(0) + rej(rt.vm.exceptionFromValue(v)) + return nil + }), nil) + return nil, nil +} + +func (s *SourceTextModuleInstance) GetBindingValue(name string) Value { + getter, ok := s.exportGetters[name] + if !ok { // let's not panic in case somebody asks for a binding that isn't exported + return nil + } + return getter() +} + +func (s *SourceTextModuleInstance) HasTLA() bool { + return s.moduleRecord.hasTLA +} + +type SourceTextModuleRecord struct { + body *ast.Program + p *Program + // context + // importmeta + hasTLA bool + requestedModules []string + importEntries []importEntry + localExportEntries []exportEntry + indirectExportEntries []exportEntry + starExportEntries []exportEntry + + hostResolveImportedModule HostResolveImportedModuleFunc + + once *sync.Once +} + +type importEntry struct { + moduleRequest string + importName string + localName string + offset int +} + +type exportEntry struct { + exportName string + moduleRequest string + importName string + localName string + offset int + + // not standard + lex bool +} + +func importEntriesFromAst(declarations []*ast.ImportDeclaration) ([]importEntry, error) { + var result []importEntry + names := make(map[string]struct{}, len(declarations)) + for _, importDeclarion := range declarations { + importClause := importDeclarion.ImportClause + if importDeclarion.FromClause == nil { + continue // no entry in this case + } + moduleRequest := importDeclarion.FromClause.ModuleSpecifier.String() + if named := importClause.NamedImports; named != nil { + for _, el := range named.ImportsList { + localName := el.Alias.String() + if localName == "" { + localName = el.IdentifierName.String() + } + if _, ok := names[localName]; ok { + return nil, fmt.Errorf("duplicate bounded name %s", localName) + } + names[localName] = struct{}{} + result = append(result, importEntry{ + moduleRequest: moduleRequest, + importName: el.IdentifierName.String(), + localName: localName, + offset: int(importDeclarion.Idx0()), + }) + } + } + if def := importClause.ImportedDefaultBinding; def != nil { + localName := def.Name.String() + if _, ok := names[localName]; ok { + return nil, fmt.Errorf("duplicate bounded name %s", localName) + } + names[localName] = struct{}{} + result = append(result, importEntry{ + moduleRequest: moduleRequest, + importName: "default", + localName: localName, + offset: int(importDeclarion.Idx0()), + }) + } + if namespace := importClause.NameSpaceImport; namespace != nil { + localName := namespace.ImportedBinding.String() + if _, ok := names[localName]; ok { + return nil, fmt.Errorf("duplicate bounded name %s", localName) + } + names[localName] = struct{}{} + result = append(result, importEntry{ + moduleRequest: moduleRequest, + importName: "*", + localName: namespace.ImportedBinding.String(), + offset: int(importDeclarion.Idx0()), + }) + } + } + return result, nil +} + +func exportEntryFromIdentifier(id *ast.Identifier, lex bool) exportEntry { + name := id.Name.String() + return exportEntry{localName: name, exportName: name, lex: lex} +} + +func exportEntriesFromObjectPatter(op *ast.ObjectPattern, lex bool) []exportEntry { + result := make([]exportEntry, 0, len(op.Properties)) + for _, p := range op.Properties { + switch p := p.(type) { + case *ast.PropertyShort: + name := p.Name.Name.String() + result = append(result, exportEntry{ + localName: name, + exportName: name, + lex: lex, + offset: int(op.Idx0()), + }) + case *ast.PropertyKeyed: + panic("exported of keyed destructuring is not supported at this time.") + case *ast.SpreadElement: + panic("exported of spread element destructuring is not supported at this time.") + default: + panic("exported of destructing with unknown type is not supported at this time.") + } + } + return result +} + +func exportEntriesFromAst(declarations []*ast.ExportDeclaration) []exportEntry { + var result []exportEntry + for _, exportDeclaration := range declarations { + if exportDeclaration.ExportFromClause != nil { + exportFromClause := exportDeclaration.ExportFromClause + if namedExports := exportFromClause.NamedExports; namedExports != nil { + for _, spec := range namedExports.ExportsList { + result = append(result, exportEntry{ + localName: spec.IdentifierName.String(), + exportName: spec.Alias.String(), + offset: int(exportDeclaration.Idx0()), + }) + } + } else if exportFromClause.IsWildcard { + if from := exportDeclaration.FromClause; from != nil { + result = append(result, exportEntry{ + exportName: exportFromClause.Alias.String(), + importName: "*", + moduleRequest: from.ModuleSpecifier.String(), + offset: int(exportDeclaration.Idx0()), + }) + } else { + result = append(result, exportEntry{ + exportName: exportFromClause.Alias.String(), + importName: "*", + offset: int(exportDeclaration.Idx0()), + }) + } + } else { + panic("wat") + } + } else if variableDeclaration := exportDeclaration.Variable; variableDeclaration != nil { + for _, l := range variableDeclaration.List { + switch i := l.Target.(type) { + case *ast.Identifier: + result = append(result, exportEntryFromIdentifier(i, false)) + case *ast.ObjectPattern: + result = append(result, exportEntriesFromObjectPatter(i, false)...) + default: + panic("target for variable declaration export isn't supported. this is sobek bug.") + } + } + } else if LexicalDeclaration := exportDeclaration.LexicalDeclaration; LexicalDeclaration != nil { + for _, l := range LexicalDeclaration.List { + switch i := l.Target.(type) { + case *ast.Identifier: + result = append(result, exportEntryFromIdentifier(i, true)) + case *ast.ObjectPattern: + result = append(result, exportEntriesFromObjectPatter(i, true)...) + default: + panic("target for lexical declaration export isn't supported. this is sobek bug.") + } + } + } else if hoistable := exportDeclaration.HoistableDeclaration; hoistable != nil { + localName := "default" + exportName := "default" + if hoistable.FunctionDeclaration != nil { + if hoistable.FunctionDeclaration.Function.Name != nil { + localName = string(hoistable.FunctionDeclaration.Function.Name.Name.String()) + } + } + if !exportDeclaration.IsDefault { + exportName = localName + } + result = append(result, exportEntry{ + localName: localName, + exportName: exportName, + lex: true, + offset: int(exportDeclaration.Idx0()), + }) + } else if fromClause := exportDeclaration.FromClause; fromClause != nil { + if namedExports := exportDeclaration.NamedExports; namedExports != nil { + for _, spec := range namedExports.ExportsList { + alias := spec.IdentifierName.String() + if spec.Alias != "" { + alias = spec.Alias.String() + } + result = append(result, exportEntry{ + importName: spec.IdentifierName.String(), + exportName: alias, + moduleRequest: fromClause.ModuleSpecifier.String(), + offset: int(exportDeclaration.Idx0()), + }) + } + } else { + panic("wat") + } + } else if namedExports := exportDeclaration.NamedExports; namedExports != nil { + for _, spec := range namedExports.ExportsList { + alias := spec.IdentifierName.String() + if spec.Alias != "" { + alias = spec.Alias.String() + } + result = append(result, exportEntry{ + localName: spec.IdentifierName.String(), + exportName: alias, + offset: int(exportDeclaration.Idx0()), + }) + } + } else if exportDeclaration.AssignExpression != nil { + result = append(result, exportEntry{ + exportName: "default", + localName: "default", + lex: true, + offset: int(exportDeclaration.Idx0()), + }) + } else if exportDeclaration.ClassDeclaration != nil { + cls := exportDeclaration.ClassDeclaration.Class + if exportDeclaration.IsDefault { + result = append(result, exportEntry{ + exportName: "default", + localName: "default", + lex: true, + offset: int(exportDeclaration.Idx0()), + }) + } else { + result = append(result, exportEntry{ + exportName: cls.Name.Name.String(), + localName: cls.Name.Name.String(), + lex: true, + offset: int(exportDeclaration.Idx0()), + }) + } + } else { + panic("wat") + } + } + return result +} + +func requestedModulesFromAst(statements []ast.Statement) []string { + var result []string + for _, st := range statements { + switch imp := st.(type) { + case *ast.ImportDeclaration: + if imp.FromClause != nil { + result = append(result, imp.FromClause.ModuleSpecifier.String()) + } else { + result = append(result, imp.ModuleSpecifier.String()) + } + case *ast.ExportDeclaration: + if imp.FromClause != nil { + result = append(result, imp.FromClause.ModuleSpecifier.String()) + } + } + } + return result +} + +func findImportByLocalName(importEntries []importEntry, name string) (importEntry, bool) { + for _, i := range importEntries { + if i.localName == name { + return i, true + } + } + + return importEntry{}, false +} + +// This should probably be part of Parse +// TODO arguments to this need fixing +func ParseModule(name, sourceText string, resolveModule HostResolveImportedModuleFunc, opts ...parser.Option) (*SourceTextModuleRecord, error) { + // TODO asserts + opts = append(opts, parser.IsModule) + body, err := Parse(name, sourceText, opts...) + _ = body + if err != nil { + return nil, err + } + return ModuleFromAST(body, resolveModule) +} + +func ModuleFromAST(body *ast.Program, resolveModule HostResolveImportedModuleFunc) (*SourceTextModuleRecord, error) { + requestedModules := requestedModulesFromAst(body.Body) + importEntries, err := importEntriesFromAst(body.ImportEntries) + if err != nil { + // TODO create a separate error type + return nil, &CompilerSyntaxError{CompilerError: CompilerError{ + Message: err.Error(), + }} + } + // 6. Let importedBoundNames be ImportedLocalNames(importEntries). + // ^ is skipped as we don't need it. + + var indirectExportEntries []exportEntry + var localExportEntries []exportEntry + var starExportEntries []exportEntry + exportEntries := exportEntriesFromAst(body.ExportEntries) + for _, ee := range exportEntries { + if ee.moduleRequest == "" { // technically nil + ie, ok := findImportByLocalName(importEntries, ee.localName) + if !ok { + localExportEntries = append(localExportEntries, ee) + continue + } + if ie.importName == "*" { + localExportEntries = append(localExportEntries, ee) + } else { + indirectExportEntries = append(indirectExportEntries, exportEntry{ + moduleRequest: ie.moduleRequest, + importName: ie.importName, + exportName: ee.exportName, + }) + } + } else { + if ee.importName == "*" && ee.exportName == "" { + starExportEntries = append(starExportEntries, ee) + } else { + indirectExportEntries = append(indirectExportEntries, ee) + } + } + } + + s := &SourceTextModuleRecord{ + // realm isn't implement + // environment is undefined + // namespace is undefined + hasTLA: body.HasTLA, + requestedModules: requestedModules, + // hostDefined TODO + body: body, + // Context empty + // importMeta empty + importEntries: importEntries, + localExportEntries: localExportEntries, + indirectExportEntries: indirectExportEntries, + starExportEntries: starExportEntries, + + hostResolveImportedModule: resolveModule, + once: &sync.Once{}, + } + + names := s.getExportedNamesWithotStars() // we use this as the other one loops but wee need to early errors here + sort.Strings(names) + for i := 1; i < len(names); i++ { + if names[i] == names[i-1] { + return nil, &CompilerSyntaxError{ + CompilerError: CompilerError{ + Message: fmt.Sprintf("Duplicate export name %s", names[i]), + }, + } + } + // TODO other checks + } + + return s, nil +} + +func (module *SourceTextModuleRecord) getExportedNamesWithotStars() []string { + exportedNames := make([]string, 0, len(module.localExportEntries)+len(module.indirectExportEntries)) + for _, e := range module.localExportEntries { + exportedNames = append(exportedNames, e.exportName) + } + for _, e := range module.indirectExportEntries { + exportedNames = append(exportedNames, e.exportName) + } + return exportedNames +} + +func (module *SourceTextModuleRecord) GetExportedNames(callback func([]string), exportStarSet ...ModuleRecord) bool { + for _, el := range exportStarSet { + if el == module { // better check + // TODO assert + callback(nil) + return true + } + } + exportStarSet = append(exportStarSet, module) + var exportedNames []string + for _, e := range module.localExportEntries { + exportedNames = append(exportedNames, e.exportName) + } + for _, e := range module.indirectExportEntries { + exportedNames = append(exportedNames, e.exportName) + } + if len(module.starExportEntries) == 0 { + callback(exportedNames) + return true + } + + for i, e := range module.starExportEntries { + requestedModule, err := module.hostResolveImportedModule(module, e.moduleRequest) + if err != nil { + panic(err) + } + ch := make(chan struct{}) + newCallback := func(names []string) { + for _, n := range names { + if n != "default" { + // TODO check if n i exportedNames and don't include it + exportedNames = append(exportedNames, n) + } + } + close(ch) + } + + isSync := requestedModule.GetExportedNames(newCallback, exportStarSet...) + if !isSync { + go func() { + <-ch + module.handleAsyncGeteExportNames(exportedNames, module.starExportEntries[i:], callback, exportStarSet...) + }() + return false + } + } + callback(exportedNames) + return true +} + +func (module *SourceTextModuleRecord) handleAsyncGeteExportNames( + exportedNames []string, remaining []exportEntry, callback func([]string), exportStarSet ...ModuleRecord, +) { + for _, e := range remaining { + requestedModule, err := module.hostResolveImportedModule(module, e.moduleRequest) + if err != nil { + panic(err) + } + ch := make(chan struct{}) + newCallback := func(names []string) { + for _, n := range names { + if n != "default" { + // TODO check if n i exportedNames and don't include it + exportedNames = append(exportedNames, n) + } + } + close(ch) + } + + _ = requestedModule.GetExportedNames(newCallback, exportStarSet...) + <-ch + } + callback(exportedNames) +} + +func (module *SourceTextModuleRecord) InitializeEnvironment() (err error) { + module.once.Do(func() { + c := newCompiler() + defer func() { + if x := recover(); x != nil { + switch x1 := x.(type) { + case *CompilerSyntaxError: + err = x1 + default: + panic(x) + } + } + }() + + c.compileModule(module) + module.p = c.p + }) + return +} + +type ResolveSetElement struct { + Module ModuleRecord + ExportName string +} + +type ResolvedBinding struct { + Module ModuleRecord + BindingName string +} + +// GetModuleInstance returns an instance of an already instanciated module. +// If the ModuleRecord was not instanciated at this time it will return nil +func (r *Runtime) GetModuleInstance(m ModuleRecord) ModuleInstance { + return r.modules[m] +} + +func (module *SourceTextModuleRecord) ResolveExport(exportName string, resolveset ...ResolveSetElement) (*ResolvedBinding, bool) { + // TODO this whole algorithm can likely be used for not source module records a well + if exportName == "" { + panic("wat") + } + for _, r := range resolveset { + if r.Module == module && exportName == r.ExportName { // TODO better + return nil, false + } + } + resolveset = append(resolveset, ResolveSetElement{Module: module, ExportName: exportName}) + for _, e := range module.localExportEntries { + if exportName == e.exportName { + // ii. ii. Return ResolvedBinding Record { [[Module]]: module, [[BindingName]]: e.[[LocalName]] }. + return &ResolvedBinding{ + Module: module, + BindingName: e.localName, + }, false + } + } + + for _, e := range module.indirectExportEntries { + if exportName == e.exportName { + importedModule, err := module.hostResolveImportedModule(module, e.moduleRequest) + if err != nil { + panic(err) // TODO return err + } + if e.importName == "*" { + // 2. 2. Return ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: "*namespace*" }. + return &ResolvedBinding{ + Module: importedModule, + BindingName: "*namespace*", + }, false + } else { + return importedModule.ResolveExport(e.importName, resolveset...) + } + } + } + if exportName == "default" { + // This actually should've been caught above, but as it didn't it actually makes it s so the `default` export + // doesn't resolve anything that is `export * ...` + return nil, false + } + var starResolution *ResolvedBinding + + for _, e := range module.starExportEntries { + importedModule, err := module.hostResolveImportedModule(module, e.moduleRequest) + if err != nil { + panic(err) // TODO return err + } + resolution, ambiguous := importedModule.ResolveExport(exportName, resolveset...) + if ambiguous { + return nil, true + } + if resolution != nil { + if starResolution == nil { + starResolution = resolution + } else if resolution.Module != starResolution.Module || resolution.BindingName != starResolution.BindingName { + return nil, true + } + } + } + return starResolution, false +} + +func (module *SourceTextModuleRecord) Instantiate(rt *Runtime) (CyclicModuleInstance, error) { + // fmt.Println("Instantiate", module.p.src.Name()) + mi := &SourceTextModuleInstance{ + moduleRecord: module, + exportGetters: make(map[string]func() Value), + pcap: rt.newPromiseCapability(rt.getPromise()), + } + rt.modules[module] = mi + rt.vm.callStack = append(rt.vm.callStack, context{}) + _, ex := rt.RunProgram(module.p) + rt.vm.callStack = rt.vm.callStack[:len(rt.vm.callStack)-1] + if ex != nil { + mi.pcap.reject(rt.ToValue(ex)) + return nil, ex + } + + return mi, nil +} + +func (module *SourceTextModuleRecord) Evaluate(rt *Runtime) *Promise { + return rt.CyclicModuleRecordEvaluate(module, module.hostResolveImportedModule) +} + +func (module *SourceTextModuleRecord) Link() error { + c := newCompiler() + c.hostResolveImportedModule = module.hostResolveImportedModule + return c.CyclicModuleRecordConcreteLink(module) +} + +func (module *SourceTextModuleRecord) RequestedModules() []string { + return module.requestedModules +} diff --git a/vendor/github.com/grafana/sobek/object.go b/vendor/github.com/grafana/sobek/object.go index 906fe42e9ce5..c4a00f97051e 100644 --- a/vendor/github.com/grafana/sobek/object.go +++ b/vendor/github.com/grafana/sobek/object.go @@ -1452,14 +1452,8 @@ func (o *Object) getOwnProp(p Value) Value { } func (o *Object) hasOwnProperty(p Value) bool { - switch p := p.(type) { - case valueInt: - return o.self.hasOwnPropertyIdx(p) - case *Symbol: - return o.self.hasOwnPropertySym(p) - default: - return o.self.hasOwnPropertyStr(p.string()) - } + // https: // 262.ecma-international.org/12.0/#sec-hasownproperty + return o.getOwnProp(p) != nil } func (o *Object) hasProperty(p Value) bool { diff --git a/vendor/github.com/grafana/sobek/parser/expression.go b/vendor/github.com/grafana/sobek/parser/expression.go index 74d346a014c1..875b1c1577e2 100644 --- a/vendor/github.com/grafana/sobek/parser/expression.go +++ b/vendor/github.com/grafana/sobek/parser/expression.go @@ -110,6 +110,29 @@ func (self *_parser) parsePrimaryExpression() ast.Expression { return &ast.BadExpression{From: idx, To: self.idx} } +func (self *_parser) parseImportMeta() *ast.MetaProperty { + idx := self.expect(token.IMPORT) + self.expect(token.PERIOD) + if self.literal == "meta" { + return &ast.MetaProperty{ + Meta: &ast.Identifier{ + Name: unistring.String(token.IMPORT.String()), + Idx: idx, + }, + Idx: idx, + Property: self.parseIdentifier(), + } + } + self.errorUnexpectedToken(self.token) + return &ast.MetaProperty{ + Meta: &ast.Identifier{ + Name: unistring.String(token.IMPORT.String()), + Idx: idx, + }, + Idx: idx, + } +} + func (self *_parser) parseSuperProperty() ast.Expression { idx := self.idx self.next() @@ -219,7 +242,6 @@ func (self *_parser) parseParenthesisedExpression() ast.Expression { } func (self *_parser) parseRegExpLiteral() *ast.RegExpLiteral { - offset := self.chrOffset - 1 // Opening slash already gotten if self.token == token.QUOTIENT_ASSIGN { offset -= 1 // = @@ -370,6 +392,12 @@ func (self *_parser) parseObjectPropertyKey() (string, unistring.String, ast.Exp Value: num, } } + case token.EXPORT, token.IMPORT: + value = &ast.StringLiteral{ + Idx: idx, + Literal: literal, + Value: parsedLiteral, + } case token.PRIVATE_IDENTIFIER: value = &ast.PrivateIdentifier{ Identifier: ast.Identifier{ @@ -540,7 +568,6 @@ func (self *_parser) parseObjectLiteral() *ast.ObjectLiteral { } func (self *_parser) parseArrayLiteral() *ast.ArrayLiteral { - idx0 := self.expect(token.LEFT_BRACKET) var value []ast.Expression for self.token != token.RIGHT_BRACKET && self.token != token.EOF { @@ -632,7 +659,7 @@ func (self *_parser) parseArgumentList() (argumentList []ast.Expression, idx0, i return } -func (self *_parser) parseCallExpression(left ast.Expression) ast.Expression { +func (self *_parser) parseCallExpression(left ast.Expression) *ast.CallExpression { argumentList, idx0, idx1 := self.parseArgumentList() return &ast.CallExpression{ Callee: left, @@ -696,6 +723,9 @@ func (self *_parser) parseNewExpression() ast.Expression { if self.token == token.PERIOD { self.next() if self.literal == "target" { + if self.opts.module && self.scope.outer == nil { + self.errorUnexpectedToken(token.IDENTIFIER) // TODO better error + } return &ast.MetaProperty{ Meta: &ast.Identifier{ Name: unistring.String(token.NEW.String()), @@ -711,6 +741,14 @@ func (self *_parser) parseNewExpression() ast.Expression { bad.From = idx return bad } + + if call, ok := callee.(*ast.CallExpression); ok { + if _, ok := call.Callee.(*ast.DynamicImportExpression); ok { + self.error(idx, "You can't use new with import()") + return &ast.BadExpression{From: idx, To: self.idx} + } + } + node := &ast.NewExpression{ New: idx, Callee: callee, @@ -725,10 +763,11 @@ func (self *_parser) parseNewExpression() ast.Expression { } func (self *_parser) parseLeftHandSideExpression() ast.Expression { - var left ast.Expression if self.token == token.NEW { left = self.parseNewExpression() + } else if self.token == token.IMPORT { + left = self.parseImportExpression() } else { left = self.parsePrimaryExpression() } @@ -749,8 +788,32 @@ L: return left } -func (self *_parser) parseLeftHandSideExpressionAllowCall() ast.Expression { +func (self *_parser) parseImportExpression() ast.Expression { + idx := self.idx + if self.peek() == token.LEFT_PARENTHESIS { + self.expect(token.IMPORT) + cexp := self.parseCallExpression(&ast.DynamicImportExpression{}) + if len(cexp.ArgumentList) != 1 { + self.error(self.idx, "dynamic import requires exactly one argument") + return &ast.BadExpression{From: idx, To: self.idx} + } + if _, ok := cexp.ArgumentList[0].(*ast.SpreadElement); ok { + self.error(self.idx, "dynamic import can't use spread list") + return &ast.BadExpression{From: idx, To: self.idx} + } + + return cexp + } + if self.opts.module { + return self.parseImportMeta() + } + self.error(self.idx, "import not supported in script") + self.next() + return &ast.BadExpression{From: idx, To: self.idx} +} + +func (self *_parser) parseLeftHandSideExpressionAllowCall() ast.Expression { allowIn := self.scope.allowIn self.scope.allowIn = true defer func() { @@ -761,6 +824,8 @@ func (self *_parser) parseLeftHandSideExpressionAllowCall() ast.Expression { start := self.idx if self.token == token.NEW { left = self.parseNewExpression() + } else if self.token == token.IMPORT { + left = self.parseImportExpression() } else { left = self.parsePrimaryExpression() } @@ -851,7 +916,6 @@ func (self *_parser) parseUpdateExpression() ast.Expression { } func (self *_parser) parseUnaryExpression() ast.Expression { - switch self.token { case token.PLUS, token.MINUS, token.NOT, token.BITWISE_NOT: fallthrough @@ -878,6 +942,17 @@ func (self *_parser) parseUnaryExpression() ast.Expression { if self.scope.inFuncParams { self.error(idx, "Illegal await-expression in formal parameters of async function") } + scope := self.scope + for scope != nil { + if scope.inFunction { + break + } + if scope.outer == nil { + scope.hasTLA = true + break + } + scope = scope.outer + } return &ast.AwaitExpression{ Await: idx, Argument: self.parseUnaryExpression(), diff --git a/vendor/github.com/grafana/sobek/parser/parser.go b/vendor/github.com/grafana/sobek/parser/parser.go index 9adfe3ab8770..e68347604010 100644 --- a/vendor/github.com/grafana/sobek/parser/parser.go +++ b/vendor/github.com/grafana/sobek/parser/parser.go @@ -52,6 +52,7 @@ const ( ) type options struct { + module bool disableSourceMaps bool sourceMapLoader func(path string) ([]byte, error) } @@ -66,6 +67,10 @@ func WithDisableSourceMaps(opts *options) { opts.disableSourceMaps = true } +func IsModule(opts *options) { + opts.module = true +} + // WithSourceMapLoader is an option to set a custom source map loader. The loader will be given a path or a // URL from the sourceMappingURL. If sourceMappingURL is not absolute it is resolved relatively to the name // of the file being parsed. Any error returned by the loader will fail the parsing. @@ -186,7 +191,6 @@ func ParseFile(fileSet *file.FileSet, filename string, src interface{}, mode Mod // // The parameter list, if any, should be a comma-separated list of identifiers. func ParseFunction(parameterList, body string, options ...Option) (*ast.FunctionLiteral, error) { - src := "(function(" + parameterList + ") {\n" + body + "\n})" parser := _newParser("", src, 1, options...) @@ -212,6 +216,9 @@ func (self *_parser) parse() (*ast.Program, error) { self.openScope() defer self.closeScope() self.next() + if self.opts.module { + self.scope.allowAwait = true + } program := self.parseProgram() if false { self.errors.Sort() diff --git a/vendor/github.com/grafana/sobek/parser/scope.go b/vendor/github.com/grafana/sobek/parser/scope.go index f9936dafbfe1..d50e5c993d7b 100644 --- a/vendor/github.com/grafana/sobek/parser/scope.go +++ b/vendor/github.com/grafana/sobek/parser/scope.go @@ -6,17 +6,21 @@ import ( ) type _scope struct { - outer *_scope - allowIn bool - allowLet bool - inIteration bool - inSwitch bool - inFuncParams bool - inFunction bool - inAsync bool - allowAwait bool - allowYield bool - declarationList []*ast.VariableDeclaration + outer *_scope + allowIn bool + allowLet bool + allowImportExport bool + inIteration bool + inSwitch bool + inFuncParams bool + inFunction bool + inAsync bool + allowAwait bool + allowYield bool + declarationList []*ast.VariableDeclaration + importEntries []*ast.ImportDeclaration + exportEntries []*ast.ExportDeclaration + hasTLA bool labels []unistring.String } diff --git a/vendor/github.com/grafana/sobek/parser/statement.go b/vendor/github.com/grafana/sobek/parser/statement.go index 03e1de46632b..a28396904229 100644 --- a/vendor/github.com/grafana/sobek/parser/statement.go +++ b/vendor/github.com/grafana/sobek/parser/statement.go @@ -10,6 +10,7 @@ import ( "github.com/grafana/sobek/ast" "github.com/grafana/sobek/file" "github.com/grafana/sobek/token" + "github.com/grafana/sobek/unistring" ) func (self *_parser) parseBlockStatement() *ast.BlockStatement { @@ -36,12 +37,13 @@ func (self *_parser) parseStatementList() (list []ast.Statement) { } func (self *_parser) parseStatement() ast.Statement { - if self.token == token.EOF { self.errorUnexpectedToken(self.token) return &ast.BadStatement{From: self.idx, To: self.idx + 1} } + allowImportExport := self.scope.allowImportExport + self.scope.allowImportExport = false switch self.token { case token.SEMICOLON: return self.parseEmptyStatement() @@ -95,9 +97,47 @@ func (self *_parser) parseStatement() ast.Statement { return self.parseThrowStatement() case token.TRY: return self.parseTryStatement() + case token.EXPORT: + if !self.opts.module { + self.error(self.idx, "export not supported in script") + self.next() + return &ast.BadStatement{From: self.idx, To: self.idx + 1} + } + if !allowImportExport { + self.error(self.idx, "export only allowed in global scope") + self.next() + return &ast.BadStatement{From: self.idx, To: self.idx + 1} + } + exp := self.parseExportDeclaration() + if exp != nil { + // TODO this needs to be fixed + self.scope.exportEntries = append(self.scope.exportEntries, exp) + return exp + } + case token.IMPORT: + if self.peek() != token.LEFT_PARENTHESIS { + if !self.opts.module { + self.error(self.idx, "import not supported in script") + self.next() + return &ast.BadStatement{From: self.idx, To: self.idx + 1} + } + if self.peek() != token.PERIOD { + // this will be parsed as expression + if !allowImportExport { + self.error(self.idx, "import only allowed in global scope") + self.next() + return &ast.BadStatement{From: self.idx, To: self.idx + 1} + } + imp := self.parseImportDeclaration() + self.scope.importEntries = append(self.scope.importEntries, imp) + + return imp + } + } } expression := self.parseExpression() + // spew.Dump(expression) if identifier, isIdentifier := expression.(*ast.Identifier); isIdentifier && self.token == token.COLON { // LabelledStatement @@ -128,7 +168,6 @@ func (self *_parser) parseStatement() ast.Statement { } func (self *_parser) parseTryStatement() ast.Statement { - node := &ast.TryStatement{ Try: self.expect(token.TRY), Body: self.parseBlockStatement(), @@ -204,7 +243,6 @@ func (self *_parser) parseMaybeAsyncFunction(declaration bool) *ast.FunctionLite } func (self *_parser) parseFunction(declaration, async bool, start file.Idx) *ast.FunctionLiteral { - node := &ast.FunctionLiteral{ Function: start, Async: async, @@ -561,7 +599,6 @@ func (self *_parser) parseWithStatement() ast.Statement { } func (self *_parser) parseCaseStatement() *ast.CaseStatement { - node := &ast.CaseStatement{ Case: self.idx, } @@ -599,7 +636,6 @@ func (self *_parser) parseIterationStatement() ast.Statement { } func (self *_parser) parseForIn(idx file.Idx, into ast.ForInto) *ast.ForInStatement { - // Already have consumed " in" source := self.parseExpression() @@ -614,7 +650,6 @@ func (self *_parser) parseForIn(idx file.Idx, into ast.ForInto) *ast.ForInStatem } func (self *_parser) parseForOf(idx file.Idx, into ast.ForInto) *ast.ForOfStatement { - // Already have consumed " of" source := self.parseAssignmentExpression() @@ -629,7 +664,6 @@ func (self *_parser) parseForOf(idx file.Idx, into ast.ForInto) *ast.ForOfStatem } func (self *_parser) parseFor(idx file.Idx, initializer ast.ForLoopInitializer) *ast.ForStatement { - // Already have consumed " ;" var test, update ast.Expression @@ -780,7 +814,6 @@ func (self *_parser) ensurePatternInit(list []*ast.Binding) { } func (self *_parser) parseVariableStatement() *ast.VariableStatement { - idx := self.expect(token.VAR) list := self.parseVarDeclarationList(idx) @@ -877,6 +910,11 @@ func (self *_parser) parseIfStatement() ast.Statement { func (self *_parser) parseSourceElements() (body []ast.Statement) { for self.token != token.EOF { self.scope.allowLet = true + if self.opts.module { + self.scope.allowImportExport = true + self.scope.allowAwait = true + self.scope.inAsync = true + } body = append(body, self.parseStatement()) } @@ -887,6 +925,9 @@ func (self *_parser) parseProgram() *ast.Program { prg := &ast.Program{ Body: self.parseSourceElements(), DeclarationList: self.scope.declarationList, + ImportEntries: self.scope.importEntries, + ExportEntries: self.scope.exportEntries, + HasTLA: self.scope.hasTLA, File: self.file, } self.file.SetSourceMap(self.parseSourceMap()) @@ -1044,6 +1085,148 @@ illegal: return &ast.BadStatement{From: idx, To: self.idx} } +func (self *_parser) parseExportDeclaration() *ast.ExportDeclaration { + idx := self.expect(token.EXPORT) + + switch self.token { + case token.MULTIPLY: + exportFromClause := self.parseExportFromClause() + fromClause := self.parseFromClause() + self.semicolon() + return &ast.ExportDeclaration{ + Idx: idx, + ExportFromClause: exportFromClause, + FromClause: fromClause, + } + case token.LEFT_BRACE: + namedExports := self.parseNamedExports() + fromClause := self.parseFromClause() + self.semicolon() + return &ast.ExportDeclaration{ + Idx: idx, + NamedExports: namedExports, + FromClause: fromClause, + } + case token.VAR: + return &ast.ExportDeclaration{ + Idx: idx, + Variable: self.parseVariableStatement(), + } + case token.LET, token.CONST: + return &ast.ExportDeclaration{ + Idx: idx, + LexicalDeclaration: self.parseLexicalDeclaration(self.token), + } + case token.ASYNC: + return &ast.ExportDeclaration{ + Idx: idx, + HoistableDeclaration: &ast.HoistableDeclaration{ + FunctionDeclaration: &ast.FunctionDeclaration{ + Function: self.parseMaybeAsyncFunction(true), + }, + }, + } + case token.FUNCTION: + return &ast.ExportDeclaration{ + Idx: idx, + HoistableDeclaration: &ast.HoistableDeclaration{ + FunctionDeclaration: &ast.FunctionDeclaration{ + Function: self.parseFunction(true, false, idx), + }, + }, + } + case token.CLASS: + decl := &ast.ExportDeclaration{ + Idx: idx, + ClassDeclaration: &ast.ClassDeclaration{ + Class: self.parseClass(true), + }, + } + self.insertSemicolon = true + return decl + + case token.DEFAULT: + self.next() + var exp *ast.ExportDeclaration + + switch self.token { + case token.ASYNC: + f := self.parseMaybeAsyncFunction(false) + if f == nil { + exp = &ast.ExportDeclaration{ + Idx: idx, + AssignExpression: self.parseAssignmentExpression(), + IsDefault: true, + } + self.semicolon() + break + } + if f.Name == nil { + f.Name = &ast.Identifier{Name: unistring.String("default"), Idx: f.Idx0()} + } + exp = &ast.ExportDeclaration{ + Idx: idx, + HoistableDeclaration: &ast.HoistableDeclaration{ + FunctionDeclaration: &ast.FunctionDeclaration{Function: f}, + }, + IsDefault: true, + } + case token.FUNCTION: + f := self.parseFunction(false, false, idx) + if f.Name == nil { + f.Name = &ast.Identifier{Name: unistring.String("default"), Idx: f.Idx0()} + } + exp = &ast.ExportDeclaration{ + Idx: idx, + HoistableDeclaration: &ast.HoistableDeclaration{ + FunctionDeclaration: &ast.FunctionDeclaration{Function: f}, + }, + IsDefault: true, + } + case token.CLASS: + exp = &ast.ExportDeclaration{ + Idx: idx, + ClassDeclaration: &ast.ClassDeclaration{ + Class: self.parseClass(false), + }, + IsDefault: true, + } + self.insertSemicolon = true + default: + exp = &ast.ExportDeclaration{ + Idx: idx, + AssignExpression: self.parseAssignmentExpression(), + IsDefault: true, + } + self.semicolon() + } + return exp + default: + namedExports := self.parseNamedExports() + self.semicolon() + return &ast.ExportDeclaration{ + Idx: idx, + NamedExports: namedExports, + } + } +} + +func (self *_parser) parseImportDeclaration() *ast.ImportDeclaration { + idx := self.expect(token.IMPORT) + + if self.token == token.STRING { + moduleSpecifier := self.parseModuleSpecifier() + self.semicolon() + return &ast.ImportDeclaration{Idx: idx, ModuleSpecifier: moduleSpecifier} + } + + return &ast.ImportDeclaration{ + ImportClause: self.parseImportClause(), + FromClause: self.parseFromClause(), + Idx: idx, + } +} + // Find the next statement after an error (recover) func (self *_parser) nextStatement() { for { @@ -1076,3 +1259,198 @@ func (self *_parser) nextStatement() { self.next() } } + +func (self *_parser) parseFromClause() *ast.FromClause { + if self.literal == "from" { + self.next() + return &ast.FromClause{ + ModuleSpecifier: self.parseModuleSpecifier(), + } + } + return nil +} + +func (self *_parser) parseExportFromClause() *ast.ExportFromClause { + if self.token == token.MULTIPLY { + self.next() + + if self.token != token.IDENTIFIER { + return &ast.ExportFromClause{IsWildcard: true} + } + + if self.literal == "as" { + self.next() + alias := self.parseIdentifier() + return &ast.ExportFromClause{ + IsWildcard: true, + Alias: alias.Name, + } + } + + return &ast.ExportFromClause{ + IsWildcard: true, + } + } + + return &ast.ExportFromClause{ + IsWildcard: false, + NamedExports: self.parseNamedExports(), + } +} + +func (self *_parser) parseNamedExports() *ast.NamedExports { + _ = self.expect(token.LEFT_BRACE) + + exportsList := self.parseExportsList() + + self.expect(token.RIGHT_BRACE) + + return &ast.NamedExports{ + ExportsList: exportsList, + } +} + +func (self *_parser) parseExportsList() (exportsList []*ast.ExportSpecifier) { + if self.token == token.RIGHT_BRACE { + return + } + + for self.token != token.RIGHT_BRACE { + exportsList = append(exportsList, self.parseExportSpecifier()) + if self.token != token.COMMA { + break + } + + self.next() + } + + return +} + +func (self *_parser) parseExportSpecifier() *ast.ExportSpecifier { + identifier := self.parseIdentifier() + + if self.token != token.IDENTIFIER { + return &ast.ExportSpecifier{IdentifierName: identifier.Name} + } + + if self.literal != "as" { + self.error(self.idx, "Expected 'as' keyword, found '%s' instead", self.literal) + } + self.next() + + alias := self.parseIdentifier() + + return &ast.ExportSpecifier{ + IdentifierName: identifier.Name, + Alias: alias.Name, + } +} + +func (self *_parser) parseImportClause() *ast.ImportClause { + switch self.token { + case token.LEFT_BRACE: + return &ast.ImportClause{NamedImports: self.parseNamedImports()} + case token.MULTIPLY: + return &ast.ImportClause{NameSpaceImport: self.parseNameSpaceImport()} + case token.IDENTIFIER: + literal, _, _, _ := self.scanIdentifier() + if literal == "*" { + return &ast.ImportClause{NameSpaceImport: self.parseNameSpaceImport()} + } + + importClause := ast.ImportClause{ + ImportedDefaultBinding: self.parseImportedDefaultBinding(), + } + + if self.token == token.COMMA { + self.expect(token.COMMA) + + if self.token == token.MULTIPLY { + importClause.NameSpaceImport = self.parseNameSpaceImport() + } else if self.token == token.RIGHT_BRACE { + self.next() + return &importClause + } else { + importClause.NamedImports = self.parseNamedImports() + } + } + + return &importClause + } + + return nil // unreachable +} + +func (self *_parser) parseModuleSpecifier() unistring.String { + expression := self.parsePrimaryExpression() + stringLiteral, ok := expression.(*ast.StringLiteral) + if !ok { + self.error(self.idx, "expected module specifier") + return "" + } + + return stringLiteral.Value +} + +func (self *_parser) parseImportedDefaultBinding() *ast.Identifier { + return self.parseImportedBinding() +} + +func (self *_parser) parseNameSpaceImport() *ast.NameSpaceImport { + self.expect(token.MULTIPLY) + if self.literal != "as" { + self.error(self.idx, "Expected 'as' keyword, found '%s' instead", self.literal) + } + self.next() + + return &ast.NameSpaceImport{ImportedBinding: self.parseImportedBinding().Name} +} + +func (self *_parser) parseNamedImports() *ast.NamedImports { + _ = self.expect(token.LEFT_BRACE) + + importsList := self.parseImportsList() + + self.expect(token.RIGHT_BRACE) + + return &ast.NamedImports{ + ImportsList: importsList, + } +} + +func (self *_parser) parseImportsList() (importsList []*ast.ImportSpecifier) { + for self.token != token.RIGHT_BRACE { + importsList = append(importsList, self.parseImportSpecifier()) + if self.token != token.COMMA { + break + } + + self.next() + } + + return +} + +func (self *_parser) parseImportSpecifier() *ast.ImportSpecifier { + importSpecifier := &ast.ImportSpecifier{ + IdentifierName: self.parseImportedBinding().Name, + } + + if self.token == token.IDENTIFIER && self.literal == "as" { + self.next() // skip "as" + importSpecifier.Alias = self.parseIdentifier().Name + } + + return importSpecifier +} + +func (self *_parser) parseImportedBinding() *ast.Identifier { + return self.parseBindingIdentifier() +} + +func (self *_parser) parseBindingIdentifier() *ast.Identifier { + // FIXME: Ecma 262 defines yield and await as permitted binding identifier, + // but sobek does not support async/await nor generators yet? + return self.parseIdentifier() +} diff --git a/vendor/github.com/grafana/sobek/runtime.go b/vendor/github.com/grafana/sobek/runtime.go index 27404f594e06..745e7cdba9ca 100644 --- a/vendor/github.com/grafana/sobek/runtime.go +++ b/vendor/github.com/grafana/sobek/runtime.go @@ -192,6 +192,15 @@ type Runtime struct { hash *maphash.Hash idSeq uint64 + modules map[ModuleRecord]ModuleInstance + moduleNamespaces map[ModuleRecord]*namespaceObject + importMetas map[ModuleRecord]*Object + + getImportMetaProperties func(ModuleRecord) []MetaProperty + finalizeImportMeta func(*Object, ModuleRecord) + importModuleDynamically ImportModuleDynamicallyCallback + evaluationState *evaluationState + jobQueue []func() promiseRejectionTracker PromiseRejectionTracker diff --git a/vendor/github.com/grafana/sobek/token/token_const.go b/vendor/github.com/grafana/sobek/token/token_const.go index 25914273463e..819f1ca23370 100644 --- a/vendor/github.com/grafana/sobek/token/token_const.go +++ b/vendor/github.com/grafana/sobek/token/token_const.go @@ -122,6 +122,9 @@ const ( DEBUGGER INSTANCEOF + // ES6 Modules + EXPORT + IMPORT ESCAPED_RESERVED_WORD // Non-reserved keywords below @@ -235,6 +238,8 @@ var token2string = [...]string{ CONTINUE: "continue", DEBUGGER: "debugger", INSTANCEOF: "instanceof", + EXPORT: "export", + IMPORT: "import", } var keywordTable = map[string]_keyword{ @@ -329,16 +334,14 @@ var keywordTable = map[string]_keyword{ token: KEYWORD, futureKeyword: true, }, - "export": { - token: KEYWORD, - futureKeyword: true, + "import": { + token: IMPORT, }, "extends": { token: EXTENDS, }, - "import": { - token: KEYWORD, - futureKeyword: true, + "export": { + token: EXPORT, }, "super": { token: SUPER, diff --git a/vendor/github.com/grafana/sobek/vm.go b/vendor/github.com/grafana/sobek/vm.go index 8fa60e4c8a39..cfc4b574768e 100644 --- a/vendor/github.com/grafana/sobek/vm.go +++ b/vendor/github.com/grafana/sobek/vm.go @@ -3,6 +3,7 @@ package sobek import ( "fmt" "math" + "reflect" "strconv" "strings" "sync" @@ -27,6 +28,7 @@ type stash struct { obj *Object outer *stash + vm *vm // If this is a top-level function stash, sets the type of the function. If set, dynamic var declarations // created by direct eval go here. @@ -456,6 +458,10 @@ func (s *stash) getByName(name unistring.String) (v Value, exists bool) { } else { v = _undefined } + } else if idx&maskIndirect != 0 { + var f func(*vm) Value + _ = s.vm.r.ExportTo(v, &f) + v = f(s.vm) } return v, true } @@ -542,6 +548,7 @@ func (s *stash) deleteBinding(name unistring.String) { func (vm *vm) newStash() { vm.stash = &stash{ outer: vm.stash, + vm: vm, // TODO fix } vm.stashAllocs++ } @@ -755,8 +762,7 @@ func (vm *vm) handleThrow(arg interface{}) *Exception { } if int(tf.callStackLen) < len(vm.callStack) { ctx := &vm.callStack[tf.callStackLen] - vm.prg, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args = - ctx.prg, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args + vm.prg, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args = ctx.prg, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args vm.callStack = vm.callStack[:tf.callStackLen] } vm.sp = int(tf.sp) @@ -851,8 +857,7 @@ func (vm *vm) peek() Value { } func (vm *vm) saveCtx(ctx *context) { - ctx.prg, ctx.stash, ctx.privEnv, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args = - vm.prg, vm.stash, vm.privEnv, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args + ctx.prg, ctx.stash, ctx.privEnv, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args = vm.prg, vm.stash, vm.privEnv, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args } func (vm *vm) pushCtx() { @@ -867,8 +872,7 @@ func (vm *vm) pushCtx() { } func (vm *vm) restoreCtx(ctx *context) { - vm.prg, vm.stash, vm.privEnv, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args = - ctx.prg, ctx.stash, ctx.privEnv, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args + vm.prg, vm.stash, vm.privEnv, vm.newTarget, vm.result, vm.pc, vm.sb, vm.args = ctx.prg, ctx.stash, ctx.privEnv, ctx.newTarget, ctx.result, ctx.pc, ctx.sb, ctx.args } func (vm *vm) popCtx() { @@ -1161,6 +1165,66 @@ func (s initStack1P) exec(vm *vm) { vm.sp-- } +type importNamespace struct { + module ModuleRecord +} + +func (i importNamespace) exec(vm *vm) { + vm.push(vm.r.NamespaceObjectFor(i.module)) + vm.pc++ +} + +type export struct { + idx uint32 + callback func(*vm, func() Value) +} + +func (e export) exec(vm *vm) { + // from loadStash + level := int(e.idx >> 24) + idx := uint32(e.idx & 0x00FFFFFF) + stash := vm.stash + for i := 0; i < level; i++ { + stash = stash.outer + } + e.callback(vm, func() Value { + return stash.getByIdx(idx) + }) + vm.pc++ +} + +type exportLex struct { + idx uint32 + callback func(*vm, func() Value) +} + +func (e exportLex) exec(vm *vm) { + // from loadStashLex + level := int(e.idx >> 24) + idx := uint32(e.idx & 0x00FFFFFF) + stash := vm.stash + for i := 0; i < level; i++ { + stash = stash.outer + } + e.callback(vm, func() Value { + v := stash.getByIdx(idx) + if v == nil { + panic(errAccessBeforeInit) + } + return v + }) + vm.pc++ +} + +type exportIndirect struct { + callback func(*vm) +} + +func (e exportIndirect) exec(vm *vm) { + e.callback(vm) + vm.pc++ +} + type storeStackP int func (s storeStackP) exec(vm *vm) { @@ -2620,6 +2684,22 @@ func (s initStash) exec(vm *vm) { vm.initLocal(int(s)) } +type initIndirect struct { + idx uint32 + getter func(vm *vm) Value +} + +func (s initIndirect) exec(vm *vm) { + level := int(s.idx) >> 24 + idx := uint32(s.idx & 0x00FFFFFF) + stash := vm.stash + for i := 0; i < level; i++ { + stash = stash.outer + } + stash.initByIdx(idx, vm.r.ToValue(s.getter)) + vm.pc++ +} + type initStashP uint32 func (s initStashP) exec(vm *vm) { @@ -2768,6 +2848,15 @@ func (s setGlobalStrict) exec(vm *vm) { vm.pc++ } +// Load a var indirectly from another module +type loadIndirect func(vm *vm) Value + +func (g loadIndirect) exec(vm *vm) { + v := nilSafe(g(vm)) + vm.push(v) + vm.pc++ +} + // Load a var from stash type loadStash uint32 @@ -3374,11 +3463,15 @@ func (numargs call) exec(vm *vm) { n := int(numargs) v := vm.stack[vm.sp-n-1] // callee obj := vm.toCallee(v) + obj.self.vmCall(vm, n) } func (vm *vm) clearStack() { sp := vm.sp + if sp > len(vm.stack) { + time.Sleep(time.Second) + } stackTail := vm.stack[sp:] for i := range stackTail { stackTail[i] = nil @@ -3723,6 +3816,41 @@ func (n *newAsyncFunc) exec(vm *vm) { vm.pc++ } +type loadModulePromise struct { + moduleCore ModuleRecord +} + +func (n *loadModulePromise) exec(vm *vm) { + mi := vm.r.modules[n.moduleCore].(*SourceTextModuleInstance) + vm.push(mi.pcap.promise) + vm.pc++ +} + +type newModule struct { + newAsyncFunc + moduleCore ModuleRecord +} + +func (n *newModule) exec(vm *vm) { + obj := vm.r.newAsyncFunc(n.name, n.length, n.strict) + obj.prg = n.prg + obj.stash = vm.stash + obj.privEnv = vm.privEnv + obj.src = n.source + vm.push(obj.val) + vm.pc++ +} + +type setModulePromise struct { + moduleCore ModuleRecord +} + +func (n *setModulePromise) exec(vm *vm) { + mi := vm.r.modules[n.moduleCore].(*SourceTextModuleInstance) + mi.asyncPromise = vm.pop().Export().(*Promise) + vm.pc++ +} + type newGeneratorFunc struct { newFunc } @@ -3791,7 +3919,7 @@ func getFuncObject(v Value) *Object { } return o } - if v == _undefined { + if v == _undefined || v == _null { return nil } panic(typeError("Value is not an Object")) @@ -3829,6 +3957,12 @@ func (n *newArrowFunc) _exec(vm *vm, obj *arrowFuncObject) { vm.pc++ } +type ambiguousImport unistring.String + +func (a ambiguousImport) exec(vm *vm) { + panic(vm.r.newError(vm.r.getSyntaxError(), "Ambiguous import for name %s", a)) +} + func (n *newArrowFunc) exec(vm *vm) { n._exec(vm, vm.r.newArrowFunc(n.name, n.length, n.strict)) } @@ -4210,7 +4344,6 @@ end: return valueTrue } return valueFalse - } type _op_lt struct{} @@ -4539,6 +4672,65 @@ func (_loadNewTarget) exec(vm *vm) { vm.pc++ } +type _loadImportMeta struct{} + +var loadImportMeta _loadImportMeta + +func (_loadImportMeta) exec(vm *vm) { + // https://262.ecma-international.org/13.0/#sec-meta-properties-runtime-semantics-evaluation + t := vm.r.GetActiveScriptOrModule() + m := t.(ModuleRecord) // There should be now way for this to have compiled + vm.push(vm.r.getImportMetaFor(m)) + vm.pc++ +} + +type _loadDynamicImport struct{} + +var dynamicImport _loadDynamicImport + +func (_loadDynamicImport) exec(vm *vm) { + // https://262.ecma-international.org/13.0/#sec-import-call-runtime-semantics-evaluation + vm.push(vm.r.ToValue(func(specifier Value) Value { // TODO remove this function + t := vm.r.GetActiveScriptOrModule() + + pcap := vm.r.newPromiseCapability(vm.r.getPromise()) + var specifierStr String + err := vm.r.try(func() { + specifierStr = specifier.toString() + }) + if err != nil { + if ex, ok := err.(*Exception); ok { + pcap.reject(vm.r.ToValue(ex.val)) + } else { + pcap.reject(vm.r.ToValue(err)) + } + return pcap.promise + } + if vm.r.importModuleDynamically == nil { + pcap.reject(asciiString("dynamic modules not enabled in the host program")) + } else { + pcapInput := vm.r.newPromiseCapability(vm.r.getPromise()) + onFullfill := vm.r.ToValue(func(call FunctionCall) Value { + pcap.resolve(call.Argument(0)) + return nil + }) + rejectionClosure := vm.r.ToValue(func(call FunctionCall) Value { + v := call.Argument(0) + if v.ExportType() == reflect.TypeOf(&Exception{}) { + v = v.Export().(*Exception).Value() + } + + pcap.reject(v) + return nil + }) + vm.r.performPromiseThen(pcapInput.promise.Export().(*Promise), onFullfill, rejectionClosure, nil) + vm.r.importModuleDynamically(t, specifierStr, pcapInput) + } + return pcap.promise + })) + vm.pc++ +} + type _typeof struct{} var typeof _typeof diff --git a/vendor/modules.txt b/vendor/modules.txt index dccde99b1774..ee3c619386ad 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -163,7 +163,7 @@ github.com/google/uuid # github.com/gorilla/websocket v1.5.1 ## explicit; go 1.20 github.com/gorilla/websocket -# github.com/grafana/sobek v0.0.0-20240611084759-1a77bdaf1a4a +# github.com/grafana/sobek v0.0.0-20240624162318-afbc13aa071b ## explicit; go 1.20 github.com/grafana/sobek github.com/grafana/sobek/ast From 8963ef3c4e39910a3f8bb9c549e76803f6a506e2 Mon Sep 17 00:00:00 2001 From: Mihail Stoykov Date: Thu, 27 Jun 2024 08:55:01 +0300 Subject: [PATCH 2/7] js: Use the new ESM support in goja through k6 This is still very hackish and tries to preserve every observable behavior possible. This also specifically skips adding support for: 1. dynamic import 2. top level await 3. anything around the internal go modules Which will be added later. Also let us concentrate on making this change as not breaking as possible. --- cmd/tests/cmd_run_test.go | 22 +- cmd/tests/eventloop_test.go | 2 +- js/bundle.go | 148 ++++---- js/bundle_test.go | 6 +- js/compiler/compiler.go | 329 +++--------------- js/compiler/compiler_test.go | 155 ++------- js/compiler/enhanced.go | 2 +- js/compiler/enhanced_test.go | 10 +- js/compiler/lib/babel.min.js | 25 -- js/initcontext_test.go | 15 +- js/module_loading_test.go | 11 +- js/modules/cjsmodule.go | 126 +++++-- js/modules/gomodule.go | 124 ++++--- js/modules/gomodule_basic.go | 70 ++++ js/modules/k6/metrics/metrics.go | 2 +- js/modules/require_impl.go | 225 +++++++----- js/modules/resolution.go | 158 ++++++--- js/modulestest/runtime.go | 5 +- js/runner_test.go | 9 +- ...ing_test_errors-experimental_enhanced.json | 117 +++---- js/tc39/breaking_test_errors-extended.json | 149 +++----- js/tc39/tc39_test.go | 17 +- 22 files changed, 785 insertions(+), 942 deletions(-) delete mode 100644 js/compiler/lib/babel.min.js create mode 100644 js/modules/gomodule_basic.go diff --git a/cmd/tests/cmd_run_test.go b/cmd/tests/cmd_run_test.go index cbde1f175032..c706c258ac4e 100644 --- a/cmd/tests/cmd_run_test.go +++ b/cmd/tests/cmd_run_test.go @@ -944,8 +944,8 @@ func TestAbortedByScriptSetupErrorWithDependency(t *testing.T) { if runtime.GOOS == "windows" { rootPath += "c:/" } - assert.Contains(t, stdout, `level=error msg="Error: baz\n\tat baz (`+rootPath+`test/bar.js:6:9(3))\n\tat `+ - rootPath+`test/bar.js:3:3(3)\n\tat setup (`+rootPath+`test/test.js:5:3(9))\n" hint="script exception"`) + assert.Contains(t, stdout, `level=error msg="Error: baz\n\tat baz (`+rootPath+`test/bar.js:6:10(3))\n\tat default (`+ + rootPath+`test/bar.js:3:7(3))\n\tat setup (`+rootPath+`test/test.js:5:7(8))\n" hint="script exception"`) assert.Contains(t, stdout, `level=debug msg="Sending test finished" output=cloud ref=123 run_status=7 tainted=false`) assert.Contains(t, stdout, "bogus summary") } @@ -2105,10 +2105,10 @@ func TestEventSystemError(t *testing.T) { "got event Init with data ''", "got event TestStart with data ''", "got event IterStart with data '{Iteration:0 VUID:1 ScenarioName:default Error:}'", - "got event IterEnd with data '{Iteration:0 VUID:1 ScenarioName:default Error:test aborted: oops! at file:///-:11:16(6)}'", + "got event IterEnd with data '{Iteration:0 VUID:1 ScenarioName:default Error:test aborted: oops! at default (file:///-:11:16(5))}'", "got event TestEnd with data ''", - "got event Exit with data '&{Error:test aborted: oops! at file:///-:11:16(6)}'", - "test aborted: oops! at file:///-:11:16(6)", + "got event Exit with data '&{Error:test aborted: oops! at default (file:///-:11:16(5))}'", + "test aborted: oops! at default (file:///-:11:16(5))", }, expExitCode: exitcodes.ScriptAborted, }, @@ -2117,8 +2117,8 @@ func TestEventSystemError(t *testing.T) { script: "undefinedVar", expLog: []string{ "got event Exit with data '&{Error:could not initialize '-': could not load JS test " + - "'file:///-': ReferenceError: undefinedVar is not defined\n\tat file:///-:2:0(12)\n}'", - "ReferenceError: undefinedVar is not defined\n\tat file:///-:2:0(12)\n", + "'file:///-': ReferenceError: undefinedVar is not defined\n\tat file:///-:2:1(8)\n}'", + "ReferenceError: undefinedVar is not defined\n\tat file:///-:2:1(8)\n", }, expExitCode: exitcodes.ScriptException, }, @@ -2137,11 +2137,11 @@ func TestEventSystemError(t *testing.T) { "got event Init with data ''", "got event TestStart with data ''", "got event IterStart with data '{Iteration:0 VUID:1 ScenarioName:default Error:}'", - "got event IterEnd with data '{Iteration:0 VUID:1 ScenarioName:default Error:Error: oops!\n\tat file:///-:9:11(3)\n}'", - "Error: oops!\n\tat file:///-:9:11(3)\n", + "got event IterEnd with data '{Iteration:0 VUID:1 ScenarioName:default Error:Error: oops!\n\tat default (file:///-:9:12(3))\n}'", + "Error: oops!\n\tat default (file:///-:9:12(3))\n", "got event IterStart with data '{Iteration:1 VUID:1 ScenarioName:default Error:}'", - "got event IterEnd with data '{Iteration:1 VUID:1 ScenarioName:default Error:Error: oops!\n\tat file:///-:9:11(3)\n}'", - "Error: oops!\n\tat file:///-:9:11(3)\n", + "got event IterEnd with data '{Iteration:1 VUID:1 ScenarioName:default Error:Error: oops!\n\tat default (file:///-:9:12(3))\n}'", + "Error: oops!\n\tat default (file:///-:9:12(3))\n", "got event TestEnd with data ''", "got event Exit with data '&{Error:}'", }, diff --git a/cmd/tests/eventloop_test.go b/cmd/tests/eventloop_test.go index 03acebb3e743..1bf7579dea3f 100644 --- a/cmd/tests/eventloop_test.go +++ b/cmd/tests/eventloop_test.go @@ -113,7 +113,7 @@ func TestEventLoopDoesntCrossIterations(t *testing.T) { eventLoopTest(t, script, func(logLines []string) { require.Equal(t, []string{ "setTimeout 1 was stopped because the VU iteration was interrupted", - "just error\n\tat file:///-:13:4(15)\n", "1", + "just error\n\tat default (file:///-:13:5(14))\n", "1", }, logLines) }) } diff --git a/js/bundle.go b/js/bundle.go index 3f2db0602531..555fe4338e47 100644 --- a/js/bundle.go +++ b/js/bundle.go @@ -48,8 +48,9 @@ type BundleInstance struct { // TODO: maybe just have a reference to the Bundle? or save and pass rtOpts? env map[string]string - mainModuleExports *sobek.Object - moduleVUImpl *moduleVUImpl + mainModule sobek.ModuleRecord + mainModuleInstance sobek.ModuleInstance + moduleVUImpl *moduleVUImpl } func (bi *BundleInstance) getCallableExport(name string) sobek.Callable { @@ -59,7 +60,7 @@ func (bi *BundleInstance) getCallableExport(name string) sobek.Callable { } func (bi *BundleInstance) getExported(name string) sobek.Value { - return bi.mainModuleExports.Get(name) + return bi.mainModuleInstance.GetBindingValue(name) } // NewBundle creates a new bundle from a source file and a filesystem. @@ -94,7 +95,7 @@ func newBundle( } c := bundle.newCompiler(piState.Logger) - bundle.ModuleResolver = modules.NewModuleResolver(getJSModules(), generateFileLoad(bundle), c) + bundle.ModuleResolver = modules.NewModuleResolver(getJSModules(), generateFileLoad(bundle), c, bundle.pwd) // Instantiate the bundle into a new VM using a bound init context. This uses a context with a // runtime, but no state, to allow module-provided types to function within the init context. @@ -108,13 +109,13 @@ func newBundle( }, } vuImpl.eventLoop = eventloop.New(vuImpl) - exports, err := bundle.instantiate(vuImpl, 0) + bi, err := bundle.instantiate(vuImpl, 0) if err != nil { return nil, err } bundle.ModuleResolver.Lock() - err = bundle.populateExports(updateOptions, exports) + err = bundle.populateExports(updateOptions, bi) if err != nil { return nil, err } @@ -171,35 +172,50 @@ func (b *Bundle) makeArchive() *lib.Archive { } // populateExports validates and extracts exported objects -func (b *Bundle) populateExports(updateOptions bool, exports *sobek.Object) error { - for _, k := range exports.Keys() { - v := exports.Get(k) - if _, ok := sobek.AssertFunction(v); ok && k != consts.Options { - b.callableExports[k] = struct{}{} - continue - } - switch k { - case consts.Options: - if !updateOptions { +func (b *Bundle) populateExports(updateOptions bool, bi *BundleInstance) error { + var err error + ch := make(chan struct{}) + bi.mainModule.GetExportedNames(func(names []string) { + defer close(ch) + for _, k := range names { + v := bi.getExported(k) + if _, ok := sobek.AssertFunction(v); ok && k != consts.Options { + b.callableExports[k] = struct{}{} continue } - data, err := json.Marshal(v.Export()) - if err != nil { - return fmt.Errorf("error parsing script options: %w", err) - } - dec := json.NewDecoder(bytes.NewReader(data)) - dec.DisallowUnknownFields() - if err := dec.Decode(&b.Options); err != nil { - if uerr := json.Unmarshal(data, &b.Options); uerr != nil { - return uerr + switch k { + case consts.Options: + if !updateOptions { + continue + } + var data []byte + data, err = json.Marshal(v.Export()) + if err != nil { + err = fmt.Errorf("error parsing script options: %w", err) + return + } + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err = dec.Decode(&b.Options); err != nil { + if uerr := json.Unmarshal(data, &b.Options); uerr != nil { + err = uerr + return + } + b.preInitState.Logger.WithError(err).Warn("There were unknown fields in the options exported in the script") + err = nil } - b.preInitState.Logger.WithError(err).Warn("There were unknown fields in the options exported in the script") + case consts.SetupFn: + err = errors.New("exported 'setup' must be a function") + return + case consts.TeardownFn: + err = errors.New("exported 'teardown' must be a function") + return } - case consts.SetupFn: - return errors.New("exported 'setup' must be a function") - case consts.TeardownFn: - return errors.New("exported 'teardown' must be a function") } + }) + <-ch + if err != nil { + return err } if len(b.callableExports) == 0 { @@ -222,40 +238,34 @@ func (b *Bundle) Instantiate(ctx context.Context, vuID uint64) (*BundleInstance, }, } vuImpl.eventLoop = eventloop.New(vuImpl) - exports, err := b.instantiate(vuImpl, vuID) + bi, err := b.instantiate(vuImpl, vuID) if err != nil { return nil, err } - - bi := &BundleInstance{ - Runtime: vuImpl.runtime, - env: b.preInitState.RuntimeOptions.Env, - moduleVUImpl: vuImpl, - mainModuleExports: exports, + if err = bi.manipulateOptions(b.Options); err != nil { + return nil, err } + return bi, nil +} + +func (bi *BundleInstance) manipulateOptions(options lib.Options) error { // Grab any exported functions that could be executed. These were // already pre-validated in cmd.validateScenarioConfig(), just get them here. - jsOptions := exports.Get(consts.Options) + jsOptions := bi.getExported(consts.Options) var jsOptionsObj *sobek.Object if common.IsNullish(jsOptions) { - jsOptionsObj = vuImpl.runtime.NewObject() - err := exports.Set(consts.Options, jsOptionsObj) - if err != nil { - return nil, fmt.Errorf("couldn't set exported options with merged values: %w", err) - } - } else { - jsOptionsObj = jsOptions.ToObject(vuImpl.runtime) + return nil } + jsOptionsObj = jsOptions.ToObject(bi.Runtime) var instErr error - b.Options.ForEachSpecified("json", func(key string, val interface{}) { + options.ForEachSpecified("json", func(key string, val interface{}) { if err := jsOptionsObj.Set(key, val); err != nil { instErr = err } }) - - return bi, instErr + return instErr } func (b *Bundle) newCompiler(logger logrus.FieldLogger) *compiler.Compiler { @@ -268,7 +278,7 @@ func (b *Bundle) newCompiler(logger logrus.FieldLogger) *compiler.Compiler { return c } -func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*sobek.Object, error) { +func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*BundleInstance, error) { rt := vuImpl.runtime err := b.setupJSRuntime(rt, int64(vuID), b.preInitState.Logger) if err != nil { @@ -301,10 +311,25 @@ func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*sobek.Object, close(initDone) }() - var exportsV sobek.Value - err = vuImpl.eventLoop.Start(func() error { + bi := &BundleInstance{ + Runtime: vuImpl.runtime, + env: b.preInitState.RuntimeOptions.Env, + moduleVUImpl: vuImpl, + } + callback := func() error { // this exists so that sobek catches uncatchable panics such as Interrupt var err error - exportsV, err = modSys.RunSourceData(b.sourceData) + bi.mainModule, err = modSys.RunSourceData(b.sourceData) + if err != nil { + return err + } + bi.mainModuleInstance = rt.GetModuleInstance(bi.mainModule) + return nil + } + + call, _ := sobek.AssertFunction(vuImpl.runtime.ToValue(callback)) + + err = vuImpl.eventLoop.Start(func() error { + _, err := call(nil) return err }) @@ -317,14 +342,6 @@ func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*sobek.Object, } return nil, err } - if common.IsNullish(exportsV) { - return nil, errors.New("exports must not be set to null or undefined") - } - exports := exportsV.ToObject(vuImpl.runtime) - - if exports == nil { - return nil, errors.New("exports must be an object") - } // If we've already initialized the original VU init context, forbid // any subsequent VUs to open new files @@ -334,7 +351,7 @@ func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*sobek.Object, rt.SetRandSource(common.NewRandSource()) - return exports, nil + return bi, nil } func (b *Bundle) setupJSRuntime(rt *sobek.Runtime, vuID int64, logger logrus.FieldLogger) error { @@ -389,7 +406,7 @@ func (b *Bundle) setInitGlobals(rt *sobek.Runtime, vu *moduleVUImpl, modSys *mod impl := requireImpl{ inInitContext: func() bool { return vu.state == nil }, - internal: modules.NewLegacyRequireImpl(vu, modSys, *b.pwd), + internal: modules.NewLegacyRequireImpl(vu, modSys), } mustSet("require", impl.require) @@ -404,8 +421,11 @@ func (b *Bundle) setInitGlobals(rt *sobek.Runtime, vu *moduleVUImpl, modSys *mod return nil, errors.New("open() can't be used with an empty filename") } // This uses the pwd from the requireImpl - pwd := impl.internal.CurrentlyRequiredModule() - return openImpl(rt, b.filesystems["file"], &pwd, filename, args...) + pwd, err := impl.internal.CurrentlyRequiredModule() + if err != nil { + return nil, err + } + return openImpl(rt, b.filesystems["file"], pwd, filename, args...) }) } diff --git a/js/bundle_test.go b/js/bundle_test.go index 567d6b8d7786..d8a8c53f6620 100644 --- a/js/bundle_test.go +++ b/js/bundle_test.go @@ -112,7 +112,7 @@ func TestNewBundle(t *testing.T) { t.Parallel() _, err := getSimpleBundle(t, "/script.js", "\x00") require.NotNil(t, err) - require.Contains(t, err.Error(), "SyntaxError: file:///script.js: Unexpected character '\x00' (1:0)\n> 1 | \x00\n") + require.Contains(t, err.Error(), "file:///script.js: Line 1:1 Unexpected token ILLEGAL (and 1 more errors)") }) t.Run("Error", func(t *testing.T) { t.Parallel() @@ -124,7 +124,7 @@ func TestNewBundle(t *testing.T) { t.Run("InvalidExports", func(t *testing.T) { t.Parallel() _, err := getSimpleBundle(t, "/script.js", `module.exports = null`) - require.EqualError(t, err, "exports must be an object") + require.EqualError(t, err, "GoError: exports must be an object\n") // TODO: try to remove the GoError from herer }) t.Run("DefaultUndefined", func(t *testing.T) { t.Parallel() @@ -561,12 +561,14 @@ func TestNewBundleFromArchive(t *testing.T) { checkArchive(t, arc, baseCompatModeRtOpts, "") }) + /* TODO remove completely - this no longer makes sense t.Run("es6_archive_with_wrong_compat_mode", func(t *testing.T) { t.Parallel() arc, err := getArchive(t, es6Code, baseCompatModeRtOpts) require.Error(t, err) require.Nil(t, arc) }) + */ t.Run("messed_up_archive", func(t *testing.T) { t.Parallel() diff --git a/js/compiler/compiler.go b/js/compiler/compiler.go index 1fed51109a44..3ee5cd8fedbd 100644 --- a/js/compiler/compiler.go +++ b/js/compiler/compiler.go @@ -3,91 +3,26 @@ package compiler import ( - _ "embed" // we need this for embedding Babel "encoding/base64" "encoding/json" "errors" - "fmt" - "os" - "strconv" "strings" - "sync" - "time" "github.com/go-sourcemap/sourcemap" "github.com/grafana/sobek" + "github.com/grafana/sobek/ast" "github.com/grafana/sobek/parser" "github.com/sirupsen/logrus" "go.k6.io/k6/lib" ) -//go:embed lib/babel.min.js -var babelSrc string - -var ( - defaultOpts = map[string]interface{}{ //nolint:gochecknoglobals - // "presets": []string{"latest"}, - "plugins": []interface{}{ - // es2015 /~https://github.com/babel/babel/blob/v6.26.0/packages/babel-preset-es2015/src/index.js - // in Sobek - // []interface{}{"transform-es2015-template-literals", map[string]interface{}{"loose": false, "spec": false}}, - // "transform-es2015-literals", // in Sobek - // "transform-es2015-function-name", // in Sobek - // []interface{}{"transform-es2015-arrow-functions", map[string]interface{}{"spec": false}}, // in Sobek - // "transform-es2015-block-scoped-functions", // in Sobek - // []interface{}{"transform-es2015-classes", map[string]interface{}{"loose": false}}, // in Sobek - // "transform-es2015-object-super", // in Sobek - // "transform-es2015-shorthand-properties", // in Sobek - // "transform-es2015-duplicate-keys", // in Sobek - // []interface{}{"transform-es2015-computed-properties", map[string]interface{}{"loose": false}}, // in Sobek - // "transform-es2015-for-of", // in Sobek - // "transform-es2015-sticky-regex", // in Sobek - // "transform-es2015-unicode-regex", // in Sobek - // "check-es2015-constants", // in Sobek - // []interface{}{"transform-es2015-spread", map[string]interface{}{"loose": false}}, // in Sobek - // "transform-es2015-parameters", // in Sobek - // []interface{}{"transform-es2015-destructuring", map[string]interface{}{"loose": false}}, // in Sobek - // "transform-es2015-block-scoping", // in Sobek - // "transform-es2015-typeof-symbol", // in Sobek - // all the other module plugins are just dropped - []interface{}{"transform-es2015-modules-commonjs", map[string]interface{}{"loose": false}}, - // "transform-regenerator", // Doesn't really work unless regeneratorRuntime is also added - - // es2016 /~https://github.com/babel/babel/blob/v6.26.0/packages/babel-preset-es2016/src/index.js - // "transform-exponentiation-operator", - - // es2017 /~https://github.com/babel/babel/blob/v6.26.0/packages/babel-preset-es2017/src/index.js - // "syntax-trailing-function-commas", // in Sobek - // "transform-async-to-generator", // Doesn't really work unless regeneratorRuntime is also added - }, - "ast": false, - "sourceMaps": false, - "babelrc": false, - "compact": false, - "retainLines": true, - "highlightCode": false, - } - - maxSrcLenForBabelSourceMap = 250 * 1024 //nolint:gochecknoglobals - maxSrcLenForBabelSourceMapOnce sync.Once //nolint:gochecknoglobals - - onceBabelCode sync.Once //nolint:gochecknoglobals - globalBabelCode *sobek.Program //nolint:gochecknoglobals - errGlobalBabelCode error //nolint:gochecknoglobals - onceBabel sync.Once //nolint:gochecknoglobals - globalBabel *babel //nolint:gochecknoglobals -) - -const ( - maxSrcLenForBabelSourceMapVarName = "K6_DEBUG_SOURCEMAP_FILESIZE_LIMIT" - sourceMapURLFromBabel = "k6://internal-should-not-leak/file.map" -) +// A Compiler compiles JavaScript source code (ES5.1 or ES6) into a sobek.Program +const sourceMapURLFromBabel = "k6://internal-should-not-leak/file.map" // A Compiler compiles JavaScript source code (ES5.1 or ES6) into a sobek.Program type Compiler struct { logger logrus.FieldLogger - babel *babel Options Options } @@ -96,62 +31,6 @@ func New(logger logrus.FieldLogger) *Compiler { return &Compiler{logger: logger} } -// initializeBabel initializes a separate (non-global) instance of babel specifically for this Compiler. -// An error is returned only if babel itself couldn't be parsed/run which should never be possible. -func (c *Compiler) initializeBabel() error { - var err error - if c.babel == nil { - c.babel, err = newBabel() - } - return err -} - -// Transform the given code into ES5 -func (c *Compiler) Transform(src, filename string, inputSrcMap []byte) (code string, srcMap []byte, err error) { - if c.babel == nil { - onceBabel.Do(func() { - globalBabel, err = newBabel() - }) - c.babel = globalBabel - } - if err != nil { - return "", nil, err - } - - sourceMapEnabled := c.Options.SourceMapLoader != nil - maxSrcLenForBabelSourceMapOnce.Do(func() { - // TODO: drop this code and everything it's connected to when babel is dropped - v := os.Getenv(maxSrcLenForBabelSourceMapVarName) //nolint:forbidigo - if len(v) > 0 { - i, err := strconv.Atoi(v) - if err != nil { - c.logger.Warnf("Tried to parse %q from %s as integer but couldn't %s\n", - v, maxSrcLenForBabelSourceMapVarName, err) - return - } - maxSrcLenForBabelSourceMap = i - } - }) - if sourceMapEnabled && len(src) > maxSrcLenForBabelSourceMap { - sourceMapEnabled = false - c.logger.Warnf("The source for `%s` needs to go through babel but is over %d bytes. "+ - "For performance reasons source map support will be disabled for this particular file.", - filename, maxSrcLenForBabelSourceMap) - } - - // check that babel will likely be able to parse the inputSrcMap - if sourceMapEnabled && len(inputSrcMap) != 0 { - if err = verifySourceMapForBabel(inputSrcMap); err != nil { - sourceMapEnabled = false - inputSrcMap = nil - c.logger.WithError(err).Warnf( - "The source for `%s` needs to be transpiled by Babel, but its source map will"+ - " not be accepted by Babel, so it was disabled", filename) - } - } - return c.babel.transformImpl(c.logger, src, filename, sourceMapEnabled, inputSrcMap) -} - // Options are options to the compiler type Options struct { CompatibilityMode lib.CompatibilityMode @@ -168,7 +47,12 @@ type compilationState struct { srcMapError error wrapped bool // whether the original source is wrapped in a function to make it a commonjs module - compiler *Compiler + loader func(string) ([]byte, error) +} + +// Parse the program in the given CompatibilityMode, wrapping it between pre and post code +func (c *Compiler) Parse(src, filename string, wrap bool) (*ast.Program, bool, error) { + return c.parseImpl(src, filename, wrap) } // Compile the program in the given CompatibilityMode, wrapping it between pre and post code @@ -181,13 +65,7 @@ func (c *Compiler) Compile(src, filename string, isESM bool) (*sobek.Program, st // it not only gets the file from disk in the simple case, but also returns it if the map was generated from babel // additioanlly it fixes off by one error in commonjs dependencies due to having to wrap them in a function. func (c *compilationState) sourceMapLoader(path string) ([]byte, error) { - if path == sourceMapURLFromBabel { - if c.wrapped { - return c.increaseMappingsByOne(c.srcMap) - } - return c.srcMap, nil - } - c.srcMap, c.srcMapError = c.compiler.Options.SourceMapLoader(path) + c.srcMap, c.srcMapError = c.loader(path) if c.srcMapError != nil { c.couldntLoadSourceMap = true return nil, c.srcMapError @@ -204,12 +82,53 @@ func (c *compilationState) sourceMapLoader(path string) ([]byte, error) { return c.srcMap, nil } +func (c *Compiler) parseImpl(src, filename string, wrap bool) (*ast.Program, bool, error) { + code := src + state := compilationState{loader: c.Options.SourceMapLoader, wrapped: wrap} + if state.wrapped { // the lines in the sourcemap (if available) will be fixed by increaseMappingsByOne + conditionalNewLine := "" + if index := strings.LastIndex(code, "//# sourceMappingURL="); index != -1 { + // the lines in the sourcemap (if available) will be fixed by increaseMappingsByOne + conditionalNewLine = "\n" + newCode, err := state.updateInlineSourceMap(code, index) + if err != nil { + c.logger.Warnf("while compiling %q, couldn't update its inline sourcemap which might lead "+ + "to some line numbers being off: %s", filename, err) + } else { + code = newCode + } + + // if there is no sourcemap - bork only the first line of code, but leave the remaining ones. + } + code = "(function(module, exports){" + conditionalNewLine + code + "\n})\n" + } + opts := parser.WithDisableSourceMaps + if c.Options.SourceMapLoader != nil { + opts = parser.WithSourceMapLoader(state.sourceMapLoader) + } + ast, err := parser.ParseFile(nil, filename, code, 0, opts, parser.IsModule) + + if state.couldntLoadSourceMap { + state.couldntLoadSourceMap = false // reset + // we probably don't want to abort scripts which have source maps but they can't be found, + // this also will be a breaking change, so if we couldn't we retry with it disabled + c.logger.WithError(state.srcMapError).Warnf("Couldn't load source map for %s", filename) + ast, err = parser.ParseFile(nil, filename, code, 0, parser.WithDisableSourceMaps, parser.IsModule) + } + + if err != nil { + return nil, false, err + } + isModule := len(ast.ExportEntries) > 0 || len(ast.ImportEntries) > 0 || ast.HasTLA + return ast, isModule, nil +} + func (c *Compiler) compileImpl( src, filename string, wrap bool, compatibilityMode lib.CompatibilityMode, srcMap []byte, ) (*sobek.Program, string, error) { code := src - state := compilationState{srcMap: srcMap, compiler: c, wrapped: wrap} - if wrap { + state := compilationState{loader: c.Options.SourceMapLoader, wrapped: wrap, srcMap: srcMap} + if state.wrapped { // the lines in the sourcemap (if available) will be fixed by increaseMappingsByOne conditionalNewLine := "" if index := strings.LastIndex(code, "//# sourceMappingURL="); index != -1 { // the lines in the sourcemap (if available) will be fixed by increaseMappingsByOne @@ -230,14 +149,14 @@ func (c *Compiler) compileImpl( if c.Options.SourceMapLoader != nil { opts = parser.WithSourceMapLoader(state.sourceMapLoader) } - ast, err := parser.ParseFile(nil, filename, code, 0, opts) + ast, err := parser.ParseFile(nil, filename, code, 0, opts, parser.IsModule) if state.couldntLoadSourceMap { state.couldntLoadSourceMap = false // reset // we probably don't want to abort scripts which have source maps but they can't be found, // this also will be a breaking change, so if we couldn't we retry with it disabled c.logger.WithError(state.srcMapError).Warnf("Couldn't load source map for %s", filename) - ast, err = parser.ParseFile(nil, filename, code, 0, parser.WithDisableSourceMaps) + ast, err = parser.ParseFile(nil, filename, code, 0, parser.WithDisableSourceMaps, parser.IsModule) } if err == nil { @@ -245,25 +164,6 @@ func (c *Compiler) compileImpl( return pgm, code, err } - if compatibilityMode == lib.CompatibilityModeExtended { - code, state.srcMap, err = c.Transform(src, filename, state.srcMap) - if err != nil { - return nil, code, err - } - // the compatibility mode "decreases" here as we shouldn't transform twice - var prg *sobek.Program - prg, code, err = c.compileImpl(code, filename, wrap, lib.CompatibilityModeBase, state.srcMap) - if err == nil && strings.Contains(src, "module.exports") { - c.logger.Warningf( - "During the compilation of %q, it has been detected that the file combines ECMAScript modules (ESM) "+ - "import/export syntax with commonJS module.exports. "+ - "Mixing these two module systems is non-standard and will not be supported anymore in future releases. "+ - "Please ensure to use solely one or the other syntax.", - filename) - } - return prg, code, err - } - if compatibilityMode == lib.CompatibilityModeExperimentalEnhanced { code, state.srcMap, err = esbuildTransform(src, filename) if err != nil { @@ -278,36 +178,6 @@ func (c *Compiler) compileImpl( return nil, code, err } -type babel struct { - vm *sobek.Runtime - this sobek.Value - transform sobek.Callable - m sync.Mutex -} - -func newBabel() (*babel, error) { - onceBabelCode.Do(func() { - globalBabelCode, errGlobalBabelCode = sobek.Compile("", babelSrc, false) - }) - if errGlobalBabelCode != nil { - return nil, errGlobalBabelCode - } - vm := sobek.New() - _, err := vm.RunProgram(globalBabelCode) - if err != nil { - return nil, err - } - - this := vm.Get("Babel") - bObj := this.ToObject(vm) - result := &babel{vm: vm, this: this} - if err = vm.ExportTo(bObj.Get("transform"), &result.transform); err != nil { - return nil, err - } - - return result, err -} - func (c *compilationState) updateInlineSourceMap(code string, index int) (string, error) { nextnewline := strings.Index(code[index:], "\n") if nextnewline == -1 { @@ -326,7 +196,7 @@ func (c *compilationState) updateInlineSourceMap(code string, index int) (string return code, err } encoded := base64.StdEncoding.EncodeToString(b) - code = code[:index] + "//# sourcemappingurl=data:application/json;base64," + encoded + code[nextnewline:] + code = code[:index] + "//# sourceMappingURL=data:application/json;base64," + encoded + code[index+nextnewline:] } return code, nil } @@ -363,65 +233,6 @@ func (c *compilationState) increaseMappingsByOne(sourceMap []byte) ([]byte, erro return json.Marshal(m) } -// transformImpl the given code into ES5, while synchronizing to ensure only a single -// bundle instance / Goja VM is in use at a time. -func (b *babel) transformImpl( - logger logrus.FieldLogger, src, filename string, sourceMapsEnabled bool, inputSrcMap []byte, -) (string, []byte, error) { - b.m.Lock() - defer b.m.Unlock() - opts := make(map[string]interface{}) - for k, v := range defaultOpts { - opts[k] = v - } - if sourceMapsEnabled { - // given that the source map should provide accurate lines(and columns), this option isn't needed - // it also happens to make very long and awkward lines, especially around import/exports and definitely a lot - // less readable overall. Hopefully it also has some performance improvement not trying to keep the same lines - opts["retainLines"] = false - opts["sourceMaps"] = true - if inputSrcMap != nil { - srcMap := new(map[string]interface{}) - if err := json.Unmarshal(inputSrcMap, &srcMap); err != nil { - return "", nil, err - } - opts["inputSourceMap"] = srcMap - } - } - opts["filename"] = filename - - startTime := time.Now() - v, err := b.transform(b.this, b.vm.ToValue(src), b.vm.ToValue(opts)) - if err != nil { - return "", nil, err - } - logger.WithField("t", time.Since(startTime)).Debug("Babel: Transformed") - - vO := v.ToObject(b.vm) - var code string - if err = b.vm.ExportTo(vO.Get("code"), &code); err != nil { - return code, nil, err - } - if !sourceMapsEnabled { - return code, nil, nil - } - - // this is to make Sobek try to load a sourcemap. - // it is a special url as it should never leak outside of this code - // additionally the alternative support from babel is to embed *the whole* sourcemap at the end - code += "\n//# sourceMappingURL=" + sourceMapURLFromBabel - stringify, err := b.vm.RunString("(function(m) { return JSON.stringify(m)})") - if err != nil { - return code, nil, err - } - c, _ := sobek.AssertFunction(stringify) - mapAsJSON, err := c(sobek.Undefined(), vO.Get("map")) - if err != nil { - return code, nil, err - } - return code, []byte(mapAsJSON.String()), nil -} - // Pool is a pool of compilers so it can be used easier in parallel tests as they have their own babel. type Pool struct { c chan *Compiler @@ -437,10 +248,6 @@ func NewPool(logger logrus.FieldLogger, count int) *Pool { for i := 0; i < count; i++ { go func() { co := New(logger) - err := co.initializeBabel() - if err != nil { - panic(err) - } c.Put(co) }() } @@ -458,27 +265,3 @@ func (c *Pool) Get() *Compiler { func (c *Pool) Put(co *Compiler) { c.c <- co } - -func verifySourceMapForBabel(srcMap []byte) error { - // this function exists to do what babel checks in sourcemap before we give it to it. - m := make(map[string]json.RawMessage) - err := json.Unmarshal(srcMap, &m) - if err != nil { - return fmt.Errorf("source map is not valid json: %w", err) - } - // there are no checks on it's value in babel - // we technically only support v3 though - if _, ok := m["version"]; !ok { - return fmt.Errorf("source map missing required 'version' field") - } - - // This actually gets checked by the go implementation so it's not really necessary - if _, ok := m["mappings"]; !ok { - return fmt.Errorf("source map missing required 'mappings' field") - } - // the go implementation checks the value even if it doesn't require it exists - if _, ok := m["sources"]; !ok { - return fmt.Errorf("source map missing required 'sources' field") - } - return nil -} diff --git a/js/compiler/compiler_test.go b/js/compiler/compiler_test.go index 89b44cc971d1..699578765922 100644 --- a/js/compiler/compiler_test.go +++ b/js/compiler/compiler_test.go @@ -1,12 +1,11 @@ package compiler import ( - "errors" "io" - "strings" "testing" "github.com/grafana/sobek" + "github.com/grafana/sobek/parser" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -15,55 +14,6 @@ import ( "go.k6.io/k6/lib/testutils" ) -func TestTransform(t *testing.T) { - t.Parallel() - t.Run("blank", func(t *testing.T) { - t.Parallel() - c := New(testutils.NewLogger(t)) - src, _, err := c.Transform("", "test.js", nil) - assert.NoError(t, err) - assert.Equal(t, `"use strict";`, src) - }) - t.Run("double-arrow", func(t *testing.T) { - t.Parallel() - c := New(testutils.NewLogger(t)) - src, _, err := c.Transform("()=> true", "test.js", nil) - assert.NoError(t, err) - assert.Equal(t, `"use strict";() => true;`, src) - }) - t.Run("longer", func(t *testing.T) { - t.Parallel() - c := New(testutils.NewLogger(t)) - src, _, err := c.Transform(strings.Join([]string{ - `function add(a, b) {`, - ` return a + b;`, - `};`, - ``, - `let res = add(1, 2);`, - }, "\n"), "test.js", nil) - assert.NoError(t, err) - assert.Equal(t, strings.Join([]string{ - `"use strict";function add(a, b) {`, - ` return a + b;`, - `};`, - ``, - `let res = add(1, 2);`, - }, "\n"), src) - }) - - t.Run("double-arrow with sourceMap", func(t *testing.T) { - t.Parallel() - c := New(testutils.NewLogger(t)) - c.Options.SourceMapLoader = func(string) ([]byte, error) { return nil, errors.New("shouldn't be called") } - src, _, err := c.Transform("()=> true", "test.js", nil) - assert.NoError(t, err) - assert.Equal(t, `"use strict"; - -() => true; -//# sourceMappingURL=k6://internal-should-not-leak/file.map`, src) - }) -} - func TestCompile(t *testing.T) { t.Parallel() t.Run("ES5", func(t *testing.T) { @@ -87,51 +37,36 @@ func TestCompile(t *testing.T) { assert.Equal(t, "(function(module, exports){exports.d=1+(function() { return 2; })()\n})\n", code) rt := sobek.New() v, err := rt.RunProgram(pgm) - require.NoError(t, err) - fn, ok := sobek.AssertFunction(v) - require.True(t, ok, "not a function") - exp := make(map[string]sobek.Value) - _, err = fn(sobek.Undefined(), sobek.Undefined(), rt.ToValue(exp)) - require.NoError(t, err) - assert.Equal(t, int64(3), exp["d"].Export()) + if assert.NoError(t, err) { + fn, ok := sobek.AssertFunction(v) + if assert.True(t, ok, "not a function") { + exp := make(map[string]sobek.Value) + _, err := fn(sobek.Undefined(), sobek.Undefined(), rt.ToValue(exp)) + if assert.NoError(t, err) { + assert.Equal(t, int64(3), exp["d"].Export()) + } + } + } }) - t.Run("ES5 Invalid", func(t *testing.T) { - t.Parallel() - c := New(testutils.NewLogger(t)) - src := `1+(function() { return 2; )()` - c.Options.CompatibilityMode = lib.CompatibilityModeExtended - _, _, err := c.Compile(src, "script.js", false) - assert.IsType(t, &sobek.Exception{}, err) - assert.Contains(t, err.Error(), `SyntaxError: script.js: Unexpected token (1:26) -> 1 | 1+(function() { return 2; )()`) - }) t.Run("ES6", func(t *testing.T) { t.Parallel() c := New(testutils.NewLogger(t)) c.Options.CompatibilityMode = lib.CompatibilityModeExtended - pgm, code, err := c.Compile(`import "something"`, "script.js", true) - require.NoError(t, err) - assert.Equal(t, `"use strict";require("something");`, - code) - rt := sobek.New() - var requireCalled bool - require.NoError(t, rt.Set("require", func(s string) { - assert.Equal(t, "something", s) - requireCalled = true - })) - _, err = rt.RunProgram(pgm) + _, code, err := c.Compile(`import "something"`, "script.js", true) require.NoError(t, err) - require.True(t, requireCalled) + assert.Equal(t, `import "something"`, code) + // TODO running this is a bit more involved :( }) t.Run("Wrap", func(t *testing.T) { + // This only works with `require` as wrapping means the import/export won't be top level and that is forbidden t.Parallel() c := New(testutils.NewLogger(t)) c.Options.CompatibilityMode = lib.CompatibilityModeExtended - pgm, code, err := c.Compile(`import "something";`, "script.js", false) + pgm, code, err := c.Compile(`require("something");`, "script.js", false) require.NoError(t, err) - assert.Equal(t, `(function(module, exports){"use strict";require("something"); + assert.Equal(t, `(function(module, exports){require("something"); }) `, code) var requireCalled bool @@ -154,9 +89,8 @@ func TestCompile(t *testing.T) { c := New(testutils.NewLogger(t)) c.Options.CompatibilityMode = lib.CompatibilityModeExtended _, _, err := c.Compile(`1+(=>2)()`, "script.js", true) - assert.IsType(t, &sobek.Exception{}, err) - assert.Contains(t, err.Error(), `SyntaxError: script.js: Unexpected token (1:3) -> 1 | 1+(=>2)()`) + assert.IsType(t, parser.ErrorList{}, err) + assert.ErrorContains(t, err, `script.js: Line 1:4 Unexpected token => (and 1 more errors)`) }) } @@ -167,8 +101,10 @@ func TestCorruptSourceMap(t *testing.T) { logger := logrus.New() logger.SetLevel(logrus.DebugLevel) logger.Out = io.Discard - hook := testutils.NewLogHook(logrus.InfoLevel, logrus.WarnLevel) - logger.AddHook(hook) + hook := testutils.SimpleLogrusHook{ + HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + } + logger.AddHook(&hook) compiler := New(logger) compiler.Options = Options{ @@ -190,14 +126,17 @@ func TestCorruptSourceMap(t *testing.T) { func TestCorruptSourceMapOnlyForBabel(t *testing.T) { t.Parallel() + // This test is now kind of pointless // this a valid source map for the go implementation but babel doesn't like it corruptSourceMap := []byte(`{"mappings": ";"}`) logger := logrus.New() logger.SetLevel(logrus.DebugLevel) logger.Out = io.Discard - hook := testutils.NewLogHook(logrus.InfoLevel, logrus.WarnLevel) - logger.AddHook(hook) + hook := testutils.SimpleLogrusHook{ + HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + } + logger.AddHook(&hook) compiler := New(logger) compiler.Options = Options{ @@ -207,15 +146,10 @@ func TestCorruptSourceMapOnlyForBabel(t *testing.T) { return corruptSourceMap, nil }, } - _, _, err := compiler.Compile("import 'something';\n//# sourceMappingURL=somefile", "somefile", false) + _, _, err := compiler.Compile("import 'something';\n//# sourceMappingURL=somefile", "somefile", true) require.NoError(t, err) entries := hook.Drain() - require.Len(t, entries, 1) - msg, err := entries[0].String() // we need this in order to get the field error - require.NoError(t, err) - - require.Contains(t, msg, `needs to be transpiled by Babel, but its source map will not be accepted by Babel`) - require.Contains(t, msg, `source map missing required 'version' field`) + require.Empty(t, entries) } func TestMinimalSourceMap(t *testing.T) { @@ -226,8 +160,10 @@ func TestMinimalSourceMap(t *testing.T) { logger := logrus.New() logger.SetLevel(logrus.DebugLevel) logger.Out = io.Discard - hook := testutils.NewLogHook(logrus.InfoLevel, logrus.WarnLevel) - logger.AddHook(hook) + hook := testutils.SimpleLogrusHook{ + HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + } + logger.AddHook(&hook) compiler := New(logger) compiler.Options = Options{ @@ -241,26 +177,3 @@ func TestMinimalSourceMap(t *testing.T) { require.NoError(t, err) require.Empty(t, hook.Drain()) } - -func TestMixingImportExport(t *testing.T) { - t.Parallel() - logger := logrus.New() - logger.SetLevel(logrus.DebugLevel) - logger.Out = io.Discard - hook := testutils.NewLogHook(logrus.InfoLevel, logrus.WarnLevel) - logger.AddHook(hook) - - compiler := New(logger) - compiler.Options = Options{ - CompatibilityMode: lib.CompatibilityModeExtended, - Strict: true, - } - _, _, err := compiler.Compile("export let s = 5;\nmodule.exports = 'something';", "somefile", false) - require.NoError(t, err) - entries := hook.Drain() - require.Len(t, entries, 1) - msg, err := entries[0].String() // we need this in order to get the field error - require.NoError(t, err) - - require.Contains(t, msg, `it has been detected that the file combines`) -} diff --git a/js/compiler/enhanced.go b/js/compiler/enhanced.go index 0841448c417b..14154a5fed4c 100644 --- a/js/compiler/enhanced.go +++ b/js/compiler/enhanced.go @@ -13,7 +13,7 @@ func esbuildTransform(src, filename string) (code string, srcMap []byte, err err Sourcefile: filename, Loader: api.LoaderJS, Target: api.ESNext, - Format: api.FormatCommonJS, + Format: api.FormatDefault, Sourcemap: api.SourceMapExternal, SourcesContent: api.SourcesContentInclude, LegalComments: api.LegalCommentsNone, diff --git a/js/compiler/enhanced_test.go b/js/compiler/enhanced_test.go index e1c8bd55390b..8d35e8616f30 100644 --- a/js/compiler/enhanced_test.go +++ b/js/compiler/enhanced_test.go @@ -69,9 +69,10 @@ func TestCompile_experimental_enhanced(t *testing.T) { t.Parallel() c := New(testutils.NewLogger(t)) c.Options.CompatibilityMode = lib.CompatibilityModeExperimentalEnhanced - pgm, code, err := c.Compile(`import "something"`, "script.js", true) + pgm, code, err := c.Compile(`let t :string = "something"; require(t);`, "script.ts", true) require.NoError(t, err) - assert.Equal(t, `var import_something = require("something"); + assert.Equal(t, `let t = "something"; +require(t); `, code) rt := sobek.New() var requireCalled bool @@ -88,9 +89,10 @@ func TestCompile_experimental_enhanced(t *testing.T) { c := New(testutils.NewLogger(t)) c.Options.CompatibilityMode = lib.CompatibilityModeExperimentalEnhanced c.Options.SourceMapLoader = func(_ string) ([]byte, error) { return nil, nil } - _, code, err := c.Compile(`import "something"`, "script.js", true) + _, code, err := c.Compile(`let t :string = "something"; require(t);`, "script.ts", true) require.NoError(t, err) - assert.Equal(t, `var import_something = require("something"); + assert.Equal(t, `let t = "something"; +require(t); //# sourceMappingURL=k6://internal-should-not-leak/file.map`, code) }) diff --git a/js/compiler/lib/babel.min.js b/js/compiler/lib/babel.min.js deleted file mode 100644 index 10757768a26a..000000000000 --- a/js/compiler/lib/babel.min.js +++ /dev/null @@ -1,25 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Babel=t():e.Babel=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var r=t.slice(1),n=e[t[0]];return function(e,t,i){n.apply(this,[e,t,i].concat(r))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,r){"use strict";function n(e,t){return g(t)&&"string"==typeof t[0]?e.hasOwnProperty(t[0])?[e[t[0]]].concat(t.slice(1)):void 0:"string"==typeof t?e[t]:t}function i(e){var t=(e.presets||[]).map(function(e){var t=n(E,e);if(!t)throw new Error('Invalid preset specified in Babel options: "'+e+'"');return g(t)&&"object"===h(t[0])&&t[0].hasOwnProperty("buildPreset")&&(t[0]=d({},t[0],{buildPreset:t[0].buildPreset})),t}),r=(e.plugins||[]).map(function(e){var t=n(b,e);if(!t)throw new Error('Invalid plugin specified in Babel options: "'+e+'"');return t});return d({babelrc:!1},e,{presets:t,plugins:r})}function s(e,t){return y.transform(e,i(t))}function a(e,t,r){return y.transformFromAst(e,t,i(r))}function o(e,t){b.hasOwnProperty(e)&&console.warn('A plugin named "'+e+'" is already registered, it will be overridden'),b[e]=t}function u(e){Object.keys(e).forEach(function(t){return o(t,e[t])})}function l(e,t){E.hasOwnProperty(e)&&console.warn('A preset named "'+e+'" is already registered, it will be overridden'),E[e]=t}function c(e){Object.keys(e).forEach(function(t){return l(t,e[t])})}function f(e){(0,v.runScripts)(s,e)}function p(){window.removeEventListener("DOMContentLoaded",f)}Object.defineProperty(t,"__esModule",{value:!0}),t.version=t.buildExternalHelpers=t.availablePresets=t.availablePlugins=void 0;var d=Object.assign||function(e){for(var t=1;t=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}if(e===a)return!0}}return!1}function o(e,t,r){if(e){var n=z.NODE_FIELDS[e.type];if(n){var i=n[t];i&&i.validate&&(i.optional&&null==r||i.validate(e,t,r))}}}function u(e,t){for(var r=(0,B.default)(t),n=r,i=Array.isArray(n),s=0,n=i?n:(0,T.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;if(e[o]!==t[o])return!1}return!0}function l(e,t,r){return e.object=z.memberExpression(e.object,e.property,e.computed),e.property=t,e.computed=!!r,e}function c(e,t){return e.object=z.memberExpression(t,e.object),e}function f(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"body";return e[t]=z.toBlock(e[t],e)}function p(e){if(!e)return e;var t={};for(var r in e)"_"!==r[0]&&(t[r]=e[r]);return t}function d(e){var t=p(e);return delete t.loc,t}function h(e){if(!e)return e;var t={};for(var r in e)if("_"!==r[0]){var n=e[r];n&&(n.type?n=z.cloneDeep(n):Array.isArray(n)&&(n=n.map(z.cloneDeep))),t[r]=n}return t}function m(e,t){var r=e.split(".");return function(e){if(!z.isMemberExpression(e))return!1;for(var n=[e],i=0;n.length;){var s=n.shift();if(t&&i===r.length)return!0;if(z.isIdentifier(s)){if(r[i]!==s.name)return!1}else{if(!z.isStringLiteral(s)){if(z.isMemberExpression(s)){if(s.computed&&!z.isStringLiteral(s.property))return!1;n.push(s.object),n.push(s.property);continue}return!1}if(r[i]!==s.value)return!1}if(++i>r.length)return!1}return!0}}function y(e){for(var t=z.COMMENT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,T.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}delete e[i]}return e}function v(e,t){return g(e,t),b(e,t),E(e,t),e}function g(e,t){x("trailingComments",e,t)}function b(e,t){x("leadingComments",e,t)}function E(e,t){x("innerComments",e,t)}function x(e,t,r){t&&r&&(t[e]=(0,K.default)([].concat(t[e],r[e]).filter(Boolean)))}function A(e,t){if(!e||!t)return e;for(var r=z.INHERIT_KEYS.optional,n=Array.isArray(r),i=0,r=n?r:(0,T.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;null==e[a]&&(e[a]=t[a])}for(var o in t)"_"===o[0]&&(e[o]=t[o]);for(var u=z.INHERIT_KEYS.force,l=Array.isArray(u),c=0,u=l?u:(0,T.default)(u);;){var f;if(l){if(c>=u.length)break;f=u[c++]}else{if(c=u.next(),c.done)break;f=c.value}var p=f;e[p]=t[p]}return z.inheritsComments(e,t),e}function S(e){if(!_(e))throw new TypeError("Not a valid node "+(e&&e.type))}function _(e){return!(!e||!H.VISITOR_KEYS[e.type])}function D(e,t,r){if(e){var n=z.VISITOR_KEYS[e.type];if(n){r=r||{},t(e,r);for(var i=n,s=Array.isArray(i),a=0,i=s?i:(0,T.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o,l=e[u];if(Array.isArray(l))for(var c=l,f=Array.isArray(c),p=0,c=f?c:(0,T.default)(c);;){var d;if(f){if(p>=c.length)break;d=c[p++]}else{if(p=c.next(),p.done)break;d=p.value}var h=d;D(h,t,r)}else D(l,t,r)}}}}function C(e,t){t=t||{};for(var r=t.preserveComments?Z:ee,n=r,i=Array.isArray(n),s=0,n=i?n:(0,T.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;null!=e[o]&&(e[o]=void 0)}for(var u in e)"_"===u[0]&&null!=e[u]&&(e[u]=void 0);for(var l=(0,k.default)(e),c=l,f=Array.isArray(c),p=0,c=f?c:(0,T.default)(c);;){var d;if(f){if(p>=c.length)break;d=c[p++]}else{if(p=c.next(),p.done)break;d=p.value}e[d]=null}}function w(e,t){return D(e,C,t),e}t.__esModule=!0,t.createTypeAnnotationBasedOnTypeof=t.removeTypeDuplicates=t.createUnionTypeAnnotation=t.valueToNode=t.toBlock=t.toExpression=t.toStatement=t.toBindingIdentifierName=t.toIdentifier=t.toKeyAlias=t.toSequenceExpression=t.toComputedKey=t.isNodesEquivalent=t.isImmutable=t.isScope=t.isSpecifierDefault=t.isVar=t.isBlockScoped=t.isLet=t.isValidIdentifier=t.isReferenced=t.isBinding=t.getOuterBindingIdentifiers=t.getBindingIdentifiers=t.TYPES=t.react=t.DEPRECATED_KEYS=t.BUILDER_KEYS=t.NODE_FIELDS=t.ALIAS_KEYS=t.VISITOR_KEYS=t.NOT_LOCAL_BINDING=t.BLOCK_SCOPED_SYMBOL=t.INHERIT_KEYS=t.UNARY_OPERATORS=t.STRING_UNARY_OPERATORS=t.NUMBER_UNARY_OPERATORS=t.BOOLEAN_UNARY_OPERATORS=t.BINARY_OPERATORS=t.NUMBER_BINARY_OPERATORS=t.BOOLEAN_BINARY_OPERATORS=t.COMPARISON_BINARY_OPERATORS=t.EQUALITY_BINARY_OPERATORS=t.BOOLEAN_NUMBER_BINARY_OPERATORS=t.UPDATE_OPERATORS=t.LOGICAL_OPERATORS=t.COMMENT_KEYS=t.FOR_INIT_KEYS=t.FLATTENABLE_KEYS=t.STATEMENT_OR_BLOCK_KEYS=void 0;var P=r(360),k=n(P),F=r(2),T=n(F),O=r(14),B=n(O),R=r(35),I=n(R),M=r(135);Object.defineProperty(t,"STATEMENT_OR_BLOCK_KEYS",{enumerable:!0,get:function(){return M.STATEMENT_OR_BLOCK_KEYS}}),Object.defineProperty(t,"FLATTENABLE_KEYS",{enumerable:!0,get:function(){return M.FLATTENABLE_KEYS}}),Object.defineProperty(t,"FOR_INIT_KEYS",{enumerable:!0,get:function(){return M.FOR_INIT_KEYS}}),Object.defineProperty(t,"COMMENT_KEYS",{enumerable:!0,get:function(){return M.COMMENT_KEYS}}),Object.defineProperty(t,"LOGICAL_OPERATORS",{enumerable:!0,get:function(){return M.LOGICAL_OPERATORS}}),Object.defineProperty(t,"UPDATE_OPERATORS",{enumerable:!0,get:function(){return M.UPDATE_OPERATORS}}),Object.defineProperty(t,"BOOLEAN_NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return M.BOOLEAN_NUMBER_BINARY_OPERATORS}}),Object.defineProperty(t,"EQUALITY_BINARY_OPERATORS",{enumerable:!0,get:function(){return M.EQUALITY_BINARY_OPERATORS}}),Object.defineProperty(t,"COMPARISON_BINARY_OPERATORS",{enumerable:!0,get:function(){return M.COMPARISON_BINARY_OPERATORS}}),Object.defineProperty(t,"BOOLEAN_BINARY_OPERATORS",{enumerable:!0,get:function(){return M.BOOLEAN_BINARY_OPERATORS}}),Object.defineProperty(t,"NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return M.NUMBER_BINARY_OPERATORS}}),Object.defineProperty(t,"BINARY_OPERATORS",{enumerable:!0,get:function(){return M.BINARY_OPERATORS}}),Object.defineProperty(t,"BOOLEAN_UNARY_OPERATORS",{enumerable:!0,get:function(){return M.BOOLEAN_UNARY_OPERATORS}}),Object.defineProperty(t,"NUMBER_UNARY_OPERATORS",{enumerable:!0,get:function(){return M.NUMBER_UNARY_OPERATORS}}),Object.defineProperty(t,"STRING_UNARY_OPERATORS",{enumerable:!0,get:function(){return M.STRING_UNARY_OPERATORS}}),Object.defineProperty(t,"UNARY_OPERATORS",{enumerable:!0,get:function(){return M.UNARY_OPERATORS}}),Object.defineProperty(t,"INHERIT_KEYS",{enumerable:!0,get:function(){return M.INHERIT_KEYS}}),Object.defineProperty(t,"BLOCK_SCOPED_SYMBOL",{enumerable:!0,get:function(){return M.BLOCK_SCOPED_SYMBOL}}),Object.defineProperty(t,"NOT_LOCAL_BINDING",{enumerable:!0,get:function(){return M.NOT_LOCAL_BINDING}}),t.is=s,t.isType=a,t.validate=o,t.shallowEqual=u,t.appendToMemberExpression=l,t.prependToMemberExpression=c,t.ensureBlock=f,t.clone=p,t.cloneWithoutLoc=d,t.cloneDeep=h,t.buildMatchMemberExpression=m,t.removeComments=y,t.inheritsComments=v,t.inheritTrailingComments=g,t.inheritLeadingComments=b,t.inheritInnerComments=E,t.inherits=A,t.assertNode=S,t.isNode=_,t.traverseFast=D,t.removeProperties=C,t.removePropertiesDeep=w;var N=r(226);Object.defineProperty(t,"getBindingIdentifiers",{enumerable:!0,get:function(){return N.getBindingIdentifiers}}),Object.defineProperty(t,"getOuterBindingIdentifiers",{enumerable:!0,get:function(){return N.getOuterBindingIdentifiers}});var L=r(395);Object.defineProperty(t,"isBinding",{enumerable:!0,get:function(){return L.isBinding}}),Object.defineProperty(t,"isReferenced",{enumerable:!0,get:function(){return L.isReferenced}}),Object.defineProperty(t,"isValidIdentifier",{enumerable:!0,get:function(){return L.isValidIdentifier}}),Object.defineProperty(t,"isLet",{enumerable:!0,get:function(){return L.isLet}}),Object.defineProperty(t,"isBlockScoped",{enumerable:!0,get:function(){return L.isBlockScoped}}),Object.defineProperty(t,"isVar",{enumerable:!0,get:function(){return L.isVar}}),Object.defineProperty(t,"isSpecifierDefault",{enumerable:!0,get:function(){return L.isSpecifierDefault}}),Object.defineProperty(t,"isScope",{enumerable:!0,get:function(){return L.isScope}}),Object.defineProperty(t,"isImmutable",{enumerable:!0,get:function(){return L.isImmutable}}),Object.defineProperty(t,"isNodesEquivalent",{enumerable:!0,get:function(){return L.isNodesEquivalent}});var j=r(385);Object.defineProperty(t,"toComputedKey",{enumerable:!0,get:function(){return j.toComputedKey}}),Object.defineProperty(t,"toSequenceExpression",{enumerable:!0,get:function(){return j.toSequenceExpression}}),Object.defineProperty(t,"toKeyAlias",{enumerable:!0,get:function(){return j.toKeyAlias}}),Object.defineProperty(t,"toIdentifier",{enumerable:!0,get:function(){return j.toIdentifier}}),Object.defineProperty(t,"toBindingIdentifierName",{enumerable:!0,get:function(){return j.toBindingIdentifierName}}),Object.defineProperty(t,"toStatement",{enumerable:!0,get:function(){return j.toStatement}}),Object.defineProperty(t,"toExpression",{enumerable:!0,get:function(){return j.toExpression}}),Object.defineProperty(t,"toBlock",{enumerable:!0,get:function(){return j.toBlock}}),Object.defineProperty(t,"valueToNode",{enumerable:!0,get:function(){return j.valueToNode}});var U=r(393);Object.defineProperty(t,"createUnionTypeAnnotation",{enumerable:!0,get:function(){return U.createUnionTypeAnnotation}}),Object.defineProperty(t,"removeTypeDuplicates",{enumerable:!0,get:function(){return U.removeTypeDuplicates}}),Object.defineProperty(t,"createTypeAnnotationBasedOnTypeof",{enumerable:!0,get:function(){return U.createTypeAnnotationBasedOnTypeof}});var V=r(624),G=n(V),W=r(109),Y=n(W),q=r(600),K=n(q);r(390);var H=r(26),J=r(394),X=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(J),z=t;t.VISITOR_KEYS=H.VISITOR_KEYS,t.ALIAS_KEYS=H.ALIAS_KEYS,t.NODE_FIELDS=H.NODE_FIELDS,t.BUILDER_KEYS=H.BUILDER_KEYS,t.DEPRECATED_KEYS=H.DEPRECATED_KEYS,t.react=X;for(var $ in z.VISITOR_KEYS)i($);z.FLIPPED_ALIAS_KEYS={},(0,B.default)(z.ALIAS_KEYS).forEach(function(e){z.ALIAS_KEYS[e].forEach(function(t){(z.FLIPPED_ALIAS_KEYS[t]=z.FLIPPED_ALIAS_KEYS[t]||[]).push(e)})}),(0,B.default)(z.FLIPPED_ALIAS_KEYS).forEach(function(e){z[e.toUpperCase()+"_TYPES"]=z.FLIPPED_ALIAS_KEYS[e],i(e)});t.TYPES=(0,B.default)(z.VISITOR_KEYS).concat((0,B.default)(z.FLIPPED_ALIAS_KEYS)).concat((0,B.default)(z.DEPRECATED_KEYS));(0,B.default)(z.BUILDER_KEYS).forEach(function(e){function t(){if(arguments.length>r.length)throw new Error("t."+e+": Too many arguments passed. Received "+arguments.length+" but can receive no more than "+r.length);var t={};t.type=e;for(var n=0,i=r,s=Array.isArray(i),a=0,i=s?i:(0,T.default)(i);;){var u;if(s){if(a>=i.length)break;u=i[a++]}else{if(a=i.next(),a.done)break;u=a.value}var l=u,c=z.NODE_FIELDS[e][l],f=arguments[n++];void 0===f&&(f=(0,Y.default)(c.default)),t[l]=f}for(var p in t)o(t,p,t[p]);return t}var r=z.BUILDER_KEYS[e];z[e]=t,z[e[0].toLowerCase()+e.slice(1)]=t});for(var Q in z.DEPRECATED_KEYS)!function(e){function t(t){return function(){return console.trace("The node type "+e+" has been renamed to "+r),t.apply(this,arguments)}}var r=z.DEPRECATED_KEYS[e];z[e]=z[e[0].toLowerCase()+e.slice(1)]=t(z[r]),z["is"+e]=t(z["is"+r]),z["assert"+e]=t(z["assert"+r])}(Q);(0,G.default)(z),(0,G.default)(z.VISITOR_KEYS);var Z=["tokens","start","end","loc","raw","rawValue"],ee=z.COMMENT_KEYS.concat(["comments"]).concat(Z)},function(e,t,r){"use strict";e.exports={default:r(404),__esModule:!0}},function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t){e=(0,l.default)(e);var r=e,n=r.program;return t.length&&(0,m.default)(e,A,null,t),n.body.length>1?n.body:n.body[0]}t.__esModule=!0;var a=r(10),o=i(a);t.default=function(e,t){var r=void 0;try{throw new Error}catch(e){e.stack&&(r=e.stack.split("\n").slice(1).join("\n"))}t=(0,f.default)({allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,preserveComments:!1},t);var n=function(){var i=void 0;try{i=v.parse(e,t),i=m.default.removeProperties(i,{preserveComments:t.preserveComments}),m.default.cheap(i,function(e){e[E]=!0})}catch(e){throw e.stack=e.stack+"from\n"+r,e}return n=function(){return i},i};return function(){for(var e=arguments.length,t=Array(e),r=0;r=l.length)break;p=l[f++]}else{if(f=l.next(),f.done)break;p=f.value}var h=p;if((!s||!s[h])&&o.visit(e,h))return}},s.clearNode=function(e,t){x.removeProperties(e,t),S.path.delete(e)},s.removeProperties=function(e,t){return x.traverseFast(e,s.clearNode,t),e},s.hasType=function(e,t,r,n){if((0,b.default)(n,e.type))return!1;if(e.type===r)return!0;var i={has:!1,type:r};return s(e,{blacklist:n,enter:a},t,i),i.has},s.clearCache=function(){S.clear()},s.clearCache.clearPath=S.clearPath,s.clearCache.clearScope=S.clearScope,s.copyCache=function(e,t){S.path.has(e)&&S.path.set(t,S.path.get(e))}},function(e,t){"use strict";function r(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function i(e){if(c===setTimeout)return setTimeout(e,0);if((c===r||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function s(e){if(f===clearTimeout)return clearTimeout(e);if((f===n||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(e);try{return f(e)}catch(t){try{return f.call(null,e)}catch(t){return f.call(this,e)}}}function a(){m&&d&&(m=!1,d.length?h=d.concat(h):y=-1,h.length&&o())}function o(){if(!m){var e=i(a);m=!0;for(var t=h.length;t;){for(d=h,h=[];++y1)for(var r=1;r=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n=-1&&!i;s--){var a=s>=0?arguments[s]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(t=a+"/"+t,i="/"===a.charAt(0))}return t=r(n(t.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+t||"."},t.normalize=function(e){var i=t.isAbsolute(e),s="/"===a(e,-1);return e=r(n(e.split("/"),function(e){return!!e}),!i).join("/"),e||i||(e="."),e&&s&&(e+="/"),(i?"/":"")+e},t.isAbsolute=function(e){return"/"===e.charAt(0)},t.join=function(){var e=Array.prototype.slice.call(arguments,0);return t.normalize(n(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},t.relative=function(e,r){function n(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=t.resolve(e).substr(1),r=t.resolve(r).substr(1);for(var i=n(e.split("/")),s=n(r.split("/")),a=Math.min(i.length,s.length),o=a,u=0;u1?t-1:0),n=1;n=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;if(b.is(l,n)){i=!0;break}}if(!i)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,m.default)(r)+" but instead got "+(0,m.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;if(i(n)===c||b.is(c,n)){s=!0;break}}if(!s)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,m.default)(r)+" but instead got "+(0,m.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=e.length)break;i=e[n++]}else{if(n=e.next(),n.done)break;i=n.value}i.apply(void 0,arguments)}}for(var t=arguments.length,r=Array(t),n=0;n1&&void 0!==arguments[1]?arguments[1]:{},r=t.inherits&&D[t.inherits]||{};t.fields=t.fields||r.fields||{},t.visitor=t.visitor||r.visitor||[],t.aliases=t.aliases||r.aliases||[],t.builder=t.builder||r.builder||t.visitor||[],t.deprecatedAlias&&(_[t.deprecatedAlias]=e);for(var n=t.visitor.concat(t.builder),s=Array.isArray(n),a=0,n=s?n:(0,d.default)(n);;){var o;if(s){if(a>=n.length)break;o=n[a++]}else{if(a=n.next(),a.done)break;o=a.value}var u=o;t.fields[u]=t.fields[u]||{}}for(var c in t.fields){var f=t.fields[c];-1===t.builder.indexOf(c)&&(f.optional=!0),void 0===f.default?f.default=null:f.validate||(f.validate=l(i(f.default)))}E[e]=t.visitor,S[e]=t.builder,A[e]=t.fields,x[e]=t.aliases,D[e]=t}t.__esModule=!0,t.DEPRECATED_KEYS=t.BUILDER_KEYS=t.NODE_FIELDS=t.ALIAS_KEYS=t.VISITOR_KEYS=void 0;var p=r(2),d=n(p),h=r(35),m=n(h),y=r(11),v=n(y);t.assertEach=s,t.assertOneOf=a,t.assertNodeType=o,t.assertNodeOrValueType=u,t.assertValueType=l,t.chain=c,t.default=f;var g=r(1),b=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(g),E=t.VISITOR_KEYS={},x=t.ALIAS_KEYS={},A=t.NODE_FIELDS={},S=t.BUILDER_KEYS={},_=t.DEPRECATED_KEYS={},D={}},function(e,t){"use strict";e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){"use strict";var r={}.hasOwnProperty;e.exports=function(e,t){return r.call(e,t)}},function(e,t,r){"use strict";var n=r(23),i=r(92);e.exports=r(22)?function(e,t,r){return n.f(e,t,i(1,r))}:function(e,t,r){return e[t]=r,e}},function(e,t,r){"use strict";function n(e){return null==e?void 0===e?u:o:l&&l in Object(e)?s(e):a(e)}var i=r(45),s=r(534),a=r(559),o="[object Null]",u="[object Undefined]",l=i?i.toStringTag:void 0;e.exports=n},function(e,t,r){"use strict";function n(e,t,r,n){var a=!r;r||(r={});for(var o=-1,u=t.length;++o=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;if(l.container===t)return l.plugin}var c=void 0;if(c="function"==typeof t?t(b):t,"object"===(void 0===c?"undefined":(0,m.default)(c))){var f=new x.default(c,i);return e.memoisedPlugins.push({container:t,plugin:f}),f}throw new TypeError(S.get("pluginNotObject",r,n,void 0===c?"undefined":(0,m.default)(c))+r+n)},e.createBareOptions=function(){var e={};for(var t in M.default){var r=M.default[t];e[t]=(0,O.default)(r.default)}return e},e.normalisePlugin=function(t,r,n,i){if(!((t=t.__esModule?t.default:t)instanceof x.default)){if("function"!=typeof t&&"object"!==(void 0===t?"undefined":(0,m.default)(t)))throw new TypeError(S.get("pluginNotFunction",r,n,void 0===t?"undefined":(0,m.default)(t)));t=e.memoisePluginContainer(t,r,n,i)}return t.init(r,n),t},e.normalisePlugins=function(t,n,i){return i.map(function(i,s){var a=void 0,o=void 0;if(!i)throw new TypeError("Falsy value found in plugins");Array.isArray(i)?(a=i[0],o=i[1]):a=i;var u="string"==typeof a?a:t+"$"+s;if("string"==typeof a){var l=(0,C.default)(a,n);if(!l)throw new ReferenceError(S.get("pluginUnknown",a,t,s,n));a=r(179)(l)}return a=e.normalisePlugin(a,t,s,u),[a,o]})},e.prototype.mergeOptions=function(t){var r=this,i=t.options,s=t.extending,a=t.alias,o=t.loc,u=t.dirname;if(a=a||"foreign",i){("object"!==(void 0===i?"undefined":(0,m.default)(i))||Array.isArray(i))&&this.log.error("Invalid options type for "+a,TypeError);var l=(0,F.default)(i,function(e){if(e instanceof x.default)return e});u=u||n.cwd(),o=o||a;for(var c in l){if(!M.default[c]&&this.log)if(L.default[c])this.log.error("Using removed Babel 5 option: "+a+"."+c+" - "+L.default[c].message,ReferenceError);else{var p="Unknown option: "+a+"."+c+". Check out http://babeljs.io/docs/usage/options/ for more information about options.";this.log.error(p+"\n\nA common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.",ReferenceError)}}(0,_.normaliseOptions)(l),l.plugins&&(l.plugins=e.normalisePlugins(o,u,l.plugins)),l.presets&&(l.passPerPreset?l.presets=this.resolvePresets(l.presets,u,function(e,t){r.mergeOptions({options:e,extending:e,alias:t,loc:t,dirname:u})}):(this.mergePresets(l.presets,u),delete l.presets)),i===s?(0,f.default)(s,l):(0,R.default)(s||this.options,l)}},e.prototype.mergePresets=function(e,t){var r=this;this.resolvePresets(e,t,function(e,t){r.mergeOptions({options:e,alias:t,loc:t,dirname:G.default.dirname(t||"")})})},e.prototype.resolvePresets=function(e,t,n){return e.map(function(e){var i=void 0;if(Array.isArray(e)){if(e.length>2)throw new Error("Unexpected extra options "+(0,l.default)(e.slice(2))+" passed to preset.");var s=e;e=s[0],i=s[1]}var a=void 0;try{if("string"==typeof e){if(!(a=(0,P.default)(e,t)))throw new Error("Couldn't find preset "+(0,l.default)(e)+" relative to directory "+(0,l.default)(t));e=r(179)(a)}if("object"===(void 0===e?"undefined":(0,m.default)(e))&&e.__esModule)if(e.default)e=e.default;else{var u=e,c=(u.__esModule,(0,o.default)(u,["__esModule"]));e=c}if("object"===(void 0===e?"undefined":(0,m.default)(e))&&e.buildPreset&&(e=e.buildPreset),"function"!=typeof e&&void 0!==i)throw new Error("Options "+(0,l.default)(i)+" passed to "+(a||"a preset")+" which does not accept options.");if("function"==typeof e&&(e=e(b,i,{dirname:t})),"object"!==(void 0===e?"undefined":(0,m.default)(e)))throw new Error("Unsupported preset format: "+e+".");n&&n(e,a)}catch(e){throw a&&(e.message+=" (While processing preset: "+(0,l.default)(a)+")"),e}return e})},e.prototype.normaliseOptions=function(){var e=this.options;for(var t in M.default){var r=M.default[t],n=e[t];!n&&r.optional||(r.alias?e[r.alias]=e[r.alias]||n:e[t]=n)}},e.prototype.init=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=(0,U.default)(e,this.log),r=Array.isArray(t),n=0,t=r?t:(0,d.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;this.mergeOptions(s)}return this.normaliseOptions(e),this.options},e}();t.default=W,W.memoisedPlugins=[],e.exports=t.default}).call(t,r(8))},function(e,t,r){"use strict";e.exports={default:r(405),__esModule:!0}},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var s=r(2),a=i(s),o=r(3),u=i(o),l=r(224),c=n(l),f=r(239),p=i(f),d=r(466),h=i(d),m=r(7),y=i(m),v=r(174),g=i(v),b=r(134),E=i(b),x=r(1),A=n(x),S=r(88),_=(0,p.default)("babel"),D=function(){function e(t,r){(0,u.default)(this,e),this.parent=r,this.hub=t,this.contexts=[],this.data={},this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.state=null,this.opts=null,this.skipKeys=null,this.parentPath=null,this.context=null,this.container=null,this.listKey=null,this.inList=!1,this.parentKey=null,this.key=null,this.node=null,this.scope=null,this.type=null,this.typeAnnotation=null}return e.get=function(t){var r=t.hub,n=t.parentPath,i=t.parent,s=t.container,a=t.listKey,o=t.key;!r&&n&&(r=n.hub),(0,h.default)(i,"To get a node path the parent needs to exist");var u=s[o],l=S.path.get(i)||[];S.path.has(i)||S.path.set(i,l);for(var c=void 0,f=0;f1&&void 0!==arguments[1]?arguments[1]:SyntaxError;return this.hub.file.buildCodeFrameError(this.node,e,t)},e.prototype.traverse=function(e,t){(0,y.default)(this.node,e,this.scope,t,this)},e.prototype.mark=function(e,t){this.hub.file.metadata.marked.push({type:e,message:t,loc:this.node.loc})},e.prototype.set=function(e,t){A.validate(this.node,e,t),this.node[e]=t},e.prototype.getPathLocation=function(){var e=[],t=this;do{var r=t.key;t.inList&&(r=t.listKey+"["+r+"]"),e.unshift(r)}while(t=t.parentPath);return e.join(".")},e.prototype.debug=function(e){_.enabled&&_(this.getPathLocation()+" "+this.type+": "+e())},e}();t.default=D,(0,g.default)(D.prototype,r(368)),(0,g.default)(D.prototype,r(374)),(0,g.default)(D.prototype,r(382)),(0,g.default)(D.prototype,r(372)),(0,g.default)(D.prototype,r(371)),(0,g.default)(D.prototype,r(377)),(0,g.default)(D.prototype,r(370)),(0,g.default)(D.prototype,r(381)),(0,g.default)(D.prototype,r(380)),(0,g.default)(D.prototype,r(373)),(0,g.default)(D.prototype,r(369));for(var C=A.TYPES,w=Array.isArray(C),P=0,C=w?C:(0,a.default)(C);;){var k;if("break"===function(){if(w){if(P>=C.length)return"break";k=C[P++]}else{if(P=C.next(),P.done)return"break";k=P.value}var e=k,t="is"+e;D.prototype[t]=function(e){return A[t](this.node,e)},D.prototype["assert"+e]=function(r){if(!this[t](r))throw new TypeError("Expected node path of type "+e)}}())break}for(var F in c){(function(e){if("_"===e[0])return"continue";A.TYPES.indexOf(e)<0&&A.TYPES.push(e);var t=c[e];D.prototype["is"+e]=function(e){return t.checkPath(this,e)}})(F)}e.exports=t.default},function(e,t,r){"use strict";var n=r(142),i=r(140);e.exports=function(e){return n(i(e))}},function(e,t,r){"use strict";function n(e,t){var r=s(e,t);return i(r)?r:void 0}var i=r(497),s=r(535);e.exports=n},function(e,t){"use strict";e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t,r,n){if(e.selfReference){if(!n.hasBinding(r.name)||n.hasGlobal(r.name)){if(!f.isFunction(t))return;var i=p;t.generator&&(i=d);var s=i({FUNCTION:t,FUNCTION_ID:r,FUNCTION_KEY:n.generateUidIdentifier(r.name)}).expression;s.callee._skipModulesRemap=!0;for(var a=s.callee.body.body[0].params,u=0,l=(0,o.default)(t);u0&&void 0!==arguments[0]?arguments[0]:{},r=arguments[1];(0,p.default)(this,n);var i=(0,h.default)(this,t.call(this));return i.pipeline=r,i.log=new L.default(i,e.filename||"unknown"),i.opts=i.initOptions(e),i.parserOpts={sourceType:i.opts.sourceType,sourceFileName:i.opts.filename,plugins:[]},i.pluginVisitors=[],i.pluginPasses=[],i.buildPluginsForOptions(i.opts),i.opts.passPerPreset&&(i.perPresetOpts=[],i.opts.presets.forEach(function(e){var t=(0,c.default)((0,u.default)(i.opts),e);i.perPresetOpts.push(t),i.buildPluginsForOptions(t)})),i.metadata={usedHelpers:[],marked:[],modules:{imports:[],exports:{exported:[],specifiers:[]}}},i.dynamicImportTypes={},i.dynamicImportIds={},i.dynamicImports=[],i.declarations={},i.usedHelpers={},i.path=null,i.ast={},i.code="",i.shebang="",i.hub=new w.Hub(i),i}return(0,y.default)(n,t),n.prototype.getMetadata=function(){for(var e=!1,t=this.ast.program.body,r=Array.isArray(t),n=0,t=r?t:(0,a.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;if(H.isModuleDeclaration(s)){e=!0;break}}e&&this.path.traverse(E,this)},n.prototype.initOptions=function(e){e=new _.default(this.log,this.pipeline).init(e),e.inputSourceMap&&(e.sourceMaps=!0),e.moduleId&&(e.moduleIds=!0),e.basename=q.default.basename(e.filename,q.default.extname(e.filename)),e.ignore=W.arrayify(e.ignore,W.regexify),e.only&&(e.only=W.arrayify(e.only,W.regexify)),(0,M.default)(e,{moduleRoot:e.sourceRoot}),(0,M.default)(e,{sourceRoot:e.moduleRoot}),(0,M.default)(e,{filenameRelative:e.filename});var t=q.default.basename(e.filenameRelative);return(0,M.default)(e,{sourceFileName:t,sourceMapTarget:t}),e},n.prototype.buildPluginsForOptions=function(e){if(Array.isArray(e.plugins)){for(var t=e.plugins.concat(te),r=[],n=[],i=t,s=Array.isArray(i),o=0,i=s?i:(0,a.default)(i);;){var u;if(s){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var l=u,c=l[0],f=l[1];r.push(c.visitor),n.push(new C.default(this,c,f)),c.manipulateOptions&&c.manipulateOptions(e,this.parserOpts,this)}this.pluginVisitors.push(r),this.pluginPasses.push(n)}},n.prototype.getModuleName=function(){var e=this.opts;if(!e.moduleIds)return null;if(null!=e.moduleId&&!e.getModuleId)return e.moduleId;var t=e.filenameRelative,r="";if(null!=e.moduleRoot&&(r=e.moduleRoot+"/"),!e.filenameRelative)return r+e.filename.replace(/^\//,"");if(null!=e.sourceRoot){var n=new RegExp("^"+e.sourceRoot+"/?");t=t.replace(n,"")}return t=t.replace(/\.(\w*?)$/,""),r+=t,r=r.replace(/\\/g,"/"),e.getModuleId?e.getModuleId(r)||r:r},n.prototype.resolveModuleSource=function(e){var t=this.opts.resolveModuleSource;return t&&(e=t(e,this.opts.filename)),e},n.prototype.addImport=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,n=e+":"+t,i=this.dynamicImportIds[n];if(!i){e=this.resolveModuleSource(e),i=this.dynamicImportIds[n]=this.scope.generateUidIdentifier(r);var s=[];"*"===t?s.push(H.importNamespaceSpecifier(i)):"default"===t?s.push(H.importDefaultSpecifier(i)):s.push(H.importSpecifier(i,H.identifier(t)));var a=H.importDeclaration(s,H.stringLiteral(e));a._blockHoist=3,this.path.unshiftContainer("body",a)}return i},n.prototype.addHelper=function(e){var t=this.declarations[e];if(t)return t;this.usedHelpers[e]||(this.metadata.usedHelpers.push(e),this.usedHelpers[e]=!0);var r=this.get("helperGenerator"),n=this.get("helpersNamespace");if(r){var i=r(e);if(i)return i}else if(n)return H.memberExpression(n,H.identifier(e));var s=(0,g.default)(e),a=this.declarations[e]=this.scope.generateUidIdentifier(e);return H.isFunctionExpression(s)&&!s.id?(s.body._compact=!0,s._generated=!0,s.id=a,s.type="FunctionDeclaration",this.path.unshiftContainer("body",s)):(s._compact=!0,this.scope.push({id:a,init:s,unique:!0})),a},n.prototype.addTemplateObject=function(e,t,r){var n=r.elements.map(function(e){return e.value}),i=e+"_"+r.elements.length+"_"+n.join(","),s=this.declarations[i];if(s)return s;var a=this.declarations[i]=this.scope.generateUidIdentifier("templateObject"),o=this.addHelper(e),u=H.callExpression(o,[t,r]);return u._compact=!0,this.scope.push({id:a,init:u,_blockHoist:1.9}),a},n.prototype.buildCodeFrameError=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:SyntaxError,n=e&&(e.loc||e._loc),i=new r(t);return n?i.loc=n.start:((0,P.default)(e,re,this.scope,i),i.message+=" (This is an error on an internal node. Probably an internal error",i.loc&&(i.message+=". Location has been estimated."),i.message+=")"),i},n.prototype.mergeSourceMap=function(e){var t=this.opts.inputSourceMap;if(t){var r=new F.default.SourceMapConsumer(t),n=new F.default.SourceMapConsumer(e),i=new F.default.SourceMapGenerator({file:r.file,sourceRoot:r.sourceRoot}),s=n.sources[0];r.eachMapping(function(e){var t=n.generatedPositionFor({line:e.generatedLine,column:e.generatedColumn,source:s});null!=t.column&&i.addMapping({source:e.source,original:null==e.source?null:{line:e.originalLine,column:e.originalColumn},generated:t})});var a=i.toJSON();return t.mappings=a.mappings,t}return e},n.prototype.parse=function(t){var n=V.parse,i=this.opts.parserOpts;if(i&&(i=(0,c.default)({},this.parserOpts,i),i.parser)){if("string"==typeof i.parser){var s=q.default.dirname(this.opts.filename)||e.cwd(),a=(0,X.default)(i.parser,s);if(!a)throw new Error("Couldn't find parser "+i.parser+' with "parse" method relative to directory '+s);n=r(178)(a).parse}else n=i.parser;i.parser={parse:function(e){return(0,V.parse)(e,i)}}}this.log.debug("Parse start");var o=n(t,i||this.parserOpts);return this.log.debug("Parse stop"),o},n.prototype._addAst=function(e){this.path=w.NodePath.get({hub:this.hub,parentPath:null,parent:e,container:e,key:"program"}).setContext(),this.scope=this.path.scope,this.ast=e,this.getMetadata()},n.prototype.addAst=function(e){this.log.debug("Start set AST"),this._addAst(e),this.log.debug("End set AST")},n.prototype.transform=function(){for(var e=0;e=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var o=s,u=o.plugin,l=u[e];l&&l.call(o,this)}},n.prototype.parseInputSourceMap=function(e){var t=this.opts;if(!1!==t.inputSourceMap){var r=A.default.fromSource(e);r&&(t.inputSourceMap=r.toObject(),e=A.default.removeComments(e))}return e},n.prototype.parseShebang=function(){var e=ee.exec(this.code);e&&(this.shebang=e[0],this.code=this.code.replace(ee,""))},n.prototype.makeResult=function(e){var t=e.code,r=e.map,n=e.ast,i=e.ignored,s={metadata:null,options:this.opts,ignored:!!i,code:null,ast:null,map:r||null};return this.opts.code&&(s.code=t),this.opts.ast&&(s.ast=n),this.opts.metadata&&(s.metadata=this.metadata),s},n.prototype.generate=function(){var t=this.opts,n=this.ast,i={ast:n};if(!t.code)return this.makeResult(i);var s=O.default;if(t.generatorOpts.generator&&"string"==typeof(s=t.generatorOpts.generator)){var a=q.default.dirname(this.opts.filename)||e.cwd(),o=(0,X.default)(s,a);if(!o)throw new Error("Couldn't find generator "+s+' with "print" method relative to directory '+a);s=r(178)(o).print}this.log.debug("Generation start");var u=s(n,t.generatorOpts?(0,c.default)(t,t.generatorOpts):t,this.code);return i.code=u.code,i.map=u.map,this.log.debug("Generation end"),this.shebang&&(i.code=this.shebang+"\n"+i.code),i.map&&(i.map=this.mergeSourceMap(i.map)),"inline"!==t.sourceMaps&&"both"!==t.sourceMaps||(i.code+="\n"+A.default.fromObject(i.map).toComment()),"inline"===t.sourceMaps&&(i.map=null),this.makeResult(i)},n}(U.default);t.default=ne,t.File=ne}).call(t,r(8))},function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=x[e];return null==t?x[e]=E.default.existsSync(e):t}function a(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],r=e.filename,n=new S(t);return!1!==e.babelrc&&n.findConfigs(r),n.mergeConfig({options:e,alias:"base",dirname:r&&g.default.dirname(r)}),n.configs}t.__esModule=!0;var o=r(87),u=i(o),l=r(3),c=i(l);t.default=a;var f=r(118),p=i(f),d=r(470),h=i(d),m=r(604),y=i(m),v=r(19),g=i(v),b=r(115),E=i(b),x={},A={},S=function(){function e(t){(0,c.default)(this,e),this.resolvedConfigs=[],this.configs=[],this.log=t}return e.prototype.findConfigs=function(e){if(e){(0,y.default)(e)||(e=g.default.join(n.cwd(),e));for(var t=!1,r=!1;e!==(e=g.default.dirname(e));){if(!t){var i=g.default.join(e,".babelrc");s(i)&&(this.addConfig(i),t=!0);var a=g.default.join(e,"package.json");!t&&s(a)&&(t=this.addConfig(a,"babel",JSON))}if(!r){var o=g.default.join(e,".babelignore");s(o)&&(this.addIgnoreConfig(o),r=!0)}if(r&&t)return}}},e.prototype.addIgnoreConfig=function(e){var t=E.default.readFileSync(e,"utf8"),r=t.split("\n");r=r.map(function(e){return e.replace(/#(.*?)$/,"").trim()}).filter(function(e){return!!e}),r.length&&this.mergeConfig({options:{ignore:r},alias:e,dirname:g.default.dirname(e)})},e.prototype.addConfig=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h.default;if(this.resolvedConfigs.indexOf(e)>=0)return!1 -;this.resolvedConfigs.push(e);var n=E.default.readFileSync(e,"utf8"),i=void 0;try{i=A[n]=A[n]||r.parse(n),t&&(i=i[t])}catch(t){throw t.message=e+": Error while parsing JSON - "+t.message,t}return this.mergeConfig({options:i,alias:e,dirname:g.default.dirname(e)}),!!i},e.prototype.mergeConfig=function(e){var t=e.options,r=e.alias,i=e.loc,s=e.dirname;if(!t)return!1;if(t=(0,u.default)({},t),s=s||n.cwd(),i=i||r,t.extends){var a=(0,p.default)(t.extends,s);a?this.addConfig(a):this.log&&this.log.error("Couldn't resolve extends clause of "+t.extends+" in "+r),delete t.extends}this.configs.push({options:t,alias:r,loc:i,dirname:s});var o=void 0,l=n.env.BABEL_ENV||"production"||"development";t.env&&(o=t.env[l],delete t.env),this.mergeConfig({options:o,alias:r+".env."+l,dirname:s})},e}();e.exports=t.default}).call(t,r(8))},function(e,t,r){"use strict";function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e){var r=e[t];if(null!=r){var n=o.default[t];if(n&&n.alias&&(n=o.default[n.alias]),n){var i=s[n.type];i&&(r=i(r)),e[t]=r}}}return e}t.__esModule=!0,t.config=void 0,t.normaliseOptions=n;var i=r(53),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(i),a=r(33),o=function(e){return e&&e.__esModule?e:{default:e}}(a);t.config=o.default},function(e,t,r){"use strict";function n(e){return!!e}function i(e){return l.booleanify(e)}function s(e){return l.list(e)}t.__esModule=!0,t.filename=void 0,t.boolean=n,t.booleanString=i,t.list=s;var a=r(284),o=function(e){return e&&e.__esModule?e:{default:e}}(a),u=r(122),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(u);t.filename=o.default},function(e,t){"use strict";e.exports={auxiliaryComment:{message:"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"},blacklist:{message:"Put the specific transforms you want in the `plugins` option"},breakConfig:{message:"This is not a necessary option in Babel 6"},experimental:{message:"Put the specific transforms you want in the `plugins` option"},externalHelpers:{message:"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"},extra:{message:""},jsxPragma:{message:"use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"},loose:{message:"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."},metadataUsedHelpers:{message:"Not required anymore as this is enabled by default"},modules:{message:"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"},nonStandard:{message:"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"},optional:{message:"Put the specific transforms you want in the `plugins` option"},sourceMapName:{message:"Use the `sourceMapTarget` option"},stage:{message:"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"},whitelist:{message:"Put the specific transforms you want in the `plugins` option"}}},function(e,t,r){"use strict";var n=r(43),i=r(428),s=r(427),a=r(21),o=r(153),u=r(238),l={},c={},f=e.exports=function(e,t,r,f,p){var d,h,m,y,v=p?function(){return e}:u(e),g=n(r,f,t?2:1),b=0;if("function"!=typeof v)throw TypeError(e+" is not iterable!");if(s(v)){for(d=o(e.length);d>b;b++)if((y=t?g(a(h=e[b])[0],h[1]):g(e[b]))===l||y===c)return y}else for(m=v.call(e);!(h=m.next()).done;)if((y=i(m,g,h.value,t))===l||y===c)return y};f.BREAK=l,f.RETURN=c},function(e,t){"use strict";e.exports={}},function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=r(95)("meta"),s=r(16),a=r(28),o=r(23).f,u=0,l=Object.isExtensible||function(){return!0},c=!r(27)(function(){return l(Object.preventExtensions({}))}),f=function(e){o(e,i,{value:{i:"O"+ ++u,w:{}}})},p=function(e,t){if(!s(e))return"symbol"==(void 0===e?"undefined":n(e))?e:("string"==typeof e?"S":"P")+e;if(!a(e,i)){if(!l(e))return"F";if(!t)return"E";f(e)}return e[i].i},d=function(e,t){if(!a(e,i)){if(!l(e))return!0;if(!t)return!1;f(e)}return e[i].w},h=function(e){return c&&m.NEED&&l(e)&&!a(e,i)&&f(e),e},m=e.exports={KEY:i,NEED:!1,fastKey:p,getWeak:d,onFreeze:h}},function(e,t,r){"use strict";var n=r(16);e.exports=function(e,t){if(!n(e)||e._t!==t)throw TypeError("Incompatible receiver, "+t+" required!");return e}},function(e,t,r){"use strict";r(440);for(var n=r(15),i=r(29),s=r(56),a=r(13)("toStringTag"),o="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u=0;c--)a=u[c],"."===a?u.splice(c,1):".."===a?l++:l>0&&(""===a?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=o?"/":"."),s?(s.path=r,i(s)):r}function a(e,t){""===e&&(e="."),""===t&&(t=".");var r=n(t),a=n(e);if(a&&(e=a.path||"/"),r&&!r.scheme)return a&&(r.scheme=a.scheme),i(r);if(r||t.match(v))return t;if(a&&!a.host&&!a.path)return a.host=t,i(a);var o="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return a?(a.path=o,i(a)):o}function o(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var n=e.lastIndexOf("/");if(n<0)return t;if(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)}function u(e){return e}function l(e){return f(e)?"$"+e:e}function c(e){return f(e)?e.slice(1):e}function f(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var r=t-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,t,r){var n=e.source-t.source;return 0!==n?n:0!==(n=e.originalLine-t.originalLine)?n:0!==(n=e.originalColumn-t.originalColumn)||r?n:0!==(n=e.generatedColumn-t.generatedColumn)?n:(n=e.generatedLine-t.generatedLine,0!==n?n:e.name-t.name)}function d(e,t,r){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!==(n=e.generatedColumn-t.generatedColumn)||r?n:0!==(n=e.source-t.source)?n:0!==(n=e.originalLine-t.originalLine)?n:(n=e.originalColumn-t.originalColumn,0!==n?n:e.name-t.name)}function h(e,t){return e===t?0:e>t?1:-1}function m(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!==(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=h(e.source,t.source))?r:0!==(r=e.originalLine-t.originalLine)?r:(r=e.originalColumn-t.originalColumn,0!==r?r:h(e.name,t.name))}t.getArg=r;var y=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,v=/^data:.+\,.+$/;t.urlParse=n,t.urlGenerate=i,t.normalize=s,t.join=a,t.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(y)},t.relative=o;var g=function(){return!("__proto__"in Object.create(null))}();t.toSetString=g?u:l,t.fromSetString=g?u:c,t.compareByOriginalPositions=p,t.compareByGeneratedPositionsDeflated=d,t.compareByGeneratedPositionsInflated=m},function(e,t,r){(function(t){"use strict";function n(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,i=0,s=Math.min(r,n);i=0;o--)if(u[o]!==l[o])return!1;for(o=u.length-1;o>=0;o--)if(a=u[o],!d(e[a],t[a],r,n))return!1;return!0}function y(e,t,r){d(e,t,!0)&&f(e,t,r,"notDeepStrictEqual",y)}function v(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function g(e){var t;try{e()}catch(e){t=e}return t}function b(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=g(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&f(i,r,"Missing expected exception"+n);var s="string"==typeof n,a=!e&&x.isError(i),o=!e&&i&&!r;if((a&&s&&v(i,r)||o)&&f(i,r,"Got unwanted exception"+n),e&&i&&r&&!v(i,r)||!e&&i)throw i}var E="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},x=r(117),A=Object.prototype.hasOwnProperty,S=Array.prototype.slice,_=function(){return"foo"===function(){}.name}(),D=e.exports=p,C=/\s*function\s+([^\(\s]*)\s*/;D.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=c(this),this.generatedMessage=!0);var t=e.stackStartFunction||f;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var r=new Error;if(r.stack){var n=r.stack,i=o(t),s=n.indexOf("\n"+i);if(s>=0){var a=n.indexOf("\n",s+1);n=n.substring(a+1)}this.stack=n}}},x.inherits(D.AssertionError,Error),D.fail=f,D.ok=p,D.equal=function(e,t,r){e!=t&&f(e,t,r,"==",D.equal)},D.notEqual=function(e,t,r){e==t&&f(e,t,r,"!=",D.notEqual)},D.deepEqual=function(e,t,r){d(e,t,!1)||f(e,t,r,"deepEqual",D.deepEqual)},D.deepStrictEqual=function(e,t,r){d(e,t,!0)||f(e,t,r,"deepStrictEqual",D.deepStrictEqual)},D.notDeepEqual=function(e,t,r){d(e,t,!1)&&f(e,t,r,"notDeepEqual",D.notDeepEqual)},D.notDeepStrictEqual=y,D.strictEqual=function(e,t,r){e!==t&&f(e,t,r,"===",D.strictEqual)},D.notStrictEqual=function(e,t,r){e===t&&f(e,t,r,"!==",D.notStrictEqual)},D.throws=function(e,t,r){b(!0,e,t,r)},D.doesNotThrow=function(e,t,r){b(!1,e,t,r)},D.ifError=function(e){if(e)throw e};var w=Object.keys||function(e){var t=[];for(var r in e)A.call(e,r)&&t.push(r);return t}}).call(t,function(){return this}())},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(2),s=n(i),a=r(3),o=n(a),u=r(42),l=n(u),c=r(41),f=n(c),p=r(34),d=n(p),h=r(20),m=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(h),y=r(119),v=n(y),g=r(7),b=n(g),E=r(174),x=n(E),A=r(109),S=n(A),_=["enter","exit"],D=function(e){function t(r,n){(0,o.default)(this,t);var i=(0,l.default)(this,e.call(this));return i.initialized=!1,i.raw=(0,x.default)({},r),i.key=i.take("name")||n,i.manipulateOptions=i.take("manipulateOptions"),i.post=i.take("post"),i.pre=i.take("pre"),i.visitor=i.normaliseVisitor((0,S.default)(i.take("visitor"))||{}),i}return(0,f.default)(t,e),t.prototype.take=function(e){var t=this.raw[e];return delete this.raw[e],t},t.prototype.chain=function(e,t){if(!e[t])return this[t];if(!this[t])return e[t];var r=[e[t],this[t]];return function(){for(var e=void 0,t=arguments.length,n=Array(t),i=0;i=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;if(c){var f=c.apply(this,n);null!=f&&(e=f)}}return e}},t.prototype.maybeInherit=function(e){var t=this.take("inherits");t&&(t=d.default.normalisePlugin(t,e,"inherits"),this.manipulateOptions=this.chain(t,"manipulateOptions"),this.post=this.chain(t,"post"),this.pre=this.chain(t,"pre"),this.visitor=b.default.visitors.merge([t.visitor,this.visitor]))},t.prototype.init=function(e,t){if(!this.initialized){this.initialized=!0,this.maybeInherit(e);for(var r in this.raw)throw new Error(m.get("pluginInvalidProperty",e,t,r))}},t.prototype.normaliseVisitor=function(e){for(var t=_,r=Array.isArray(t),n=0,t=r?t:(0,s.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}if(e[i])throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.")}return b.default.explode(e),e},t}(v.default);t.default=D,e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0;var n=r(2),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=e.messages;return{visitor:{Scope:function(e){var r=e.scope;for(var n in r.bindings){var s=r.bindings[n];if("const"===s.kind||"module"===s.kind)for(var a=s.constantViolations,o=Array.isArray(a),u=0,a=o?a:(0,i.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;throw c.buildCodeFrameError(t.get("readOnly",n))}}}}}},e.exports=t.default},function(e,t){"use strict";t.__esModule=!0,t.default=function(){return{manipulateOptions:function(e,t){t.plugins.push("asyncFunctions")}}},e.exports=t.default},function(e,t){"use strict";t.__esModule=!0,t.default=function(e){var t=e.types;return{visitor:{ArrowFunctionExpression:function(e,r){if(r.opts.spec){var n=e.node;if(n.shadow)return;n.shadow={this:!1},n.type="FunctionExpression";var i=t.thisExpression();i._forceShadow=e,e.ensureBlock(),e.get("body").unshiftContainer("body",t.expressionStatement(t.callExpression(r.addHelper("newArrowCheck"),[t.thisExpression(),i]))),e.replaceWith(t.callExpression(t.memberExpression(n,t.identifier("bind")),[t.thisExpression()]))}else e.arrowFunctionToShadowed()}}}},e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0;var n=r(2),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){function t(e,t){for(var n=t.get(e),s=n,a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u,c=l.node;if(l.isFunctionDeclaration()){var f=r.variableDeclaration("let",[r.variableDeclarator(c.id,r.toExpression(c))]);f._blockHoist=2,c.id=null,l.replaceWith(f)}}}var r=e.types;return{visitor:{BlockStatement:function(e){var n=e.node,i=e.parent;r.isFunction(i,{body:n})||r.isExportDeclaration(i)||t("body",e)},SwitchCase:function(e){t("consequent",e)}}}},e.exports=t.default},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return b.isLoop(e.parent)||b.isCatchClause(e.parent)}function s(e){return!!b.isVariableDeclaration(e)&&(!!e[b.BLOCK_SCOPED_SYMBOL]||("let"===e.kind||"const"===e.kind))}function a(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(t||(t=e.node),!b.isFor(r))for(var s=0;s0&&e.traverse(P,t),e.skip()}},v.visitor]),P=y.default.visitors.merge([{ReferencedIdentifier:function(e,t){var r=t.letReferences[e.node.name];if(r){var n=e.scope.getBindingIdentifier(e.node.name);n&&n!==r||(t.closurify=!0)}}},v.visitor]),k={enter:function(e,t){var r=e.node;e.parent;if(e.isForStatement()){if(o(r.init)){var n=t.pushDeclar(r.init);1===n.length?r.init=n[0]:r.init=b.sequenceExpression(n)}}else if(e.isFor())o(r.left)&&(t.pushDeclar(r.left),r.left=r.left.declarations[0].id);else if(o(r))e.replaceWithMultiple(t.pushDeclar(r).map(function(e){return b.expressionStatement(e)}));else if(e.isFunction())return e.skip()}},F={LabeledStatement:function(e,t){var r=e.node;t.innerLabels.push(r.label.name)}},T={enter:function(e,t){if(e.isAssignmentExpression()||e.isUpdateExpression()){var r=e.getBindingIdentifiers();for(var n in r)t.outsideReferences[n]===e.scope.getBindingIdentifier(n)&&(t.reassignments[n]=!0)}}},O={Loop:function(e,t){var r=t.ignoreLabeless;t.ignoreLabeless=!0,e.traverse(O,t),t.ignoreLabeless=r,e.skip()},Function:function(e){e.skip()},SwitchCase:function(e,t){var r=t.inSwitchCase;t.inSwitchCase=!0,e.traverse(O,t),t.inSwitchCase=r,e.skip()},"BreakStatement|ContinueStatement|ReturnStatement":function(e,t){var r=e.node,n=e.parent,i=e.scope;if(!r[this.LOOP_IGNORE]){var s=void 0,a=u(r);if(a){if(r.label){if(t.innerLabels.indexOf(r.label.name)>=0)return;a=a+"|"+r.label.name}else{if(t.ignoreLabeless)return;if(t.inSwitchCase)return;if(b.isBreakStatement(r)&&b.isSwitchCase(n))return}t.hasBreakContinue=!0,t.map[a]=r,s=b.stringLiteral(a)}e.isReturnStatement()&&(t.hasReturn=!0,s=b.objectExpression([b.objectProperty(b.identifier("v"),r.argument||i.buildUndefinedNode())])),s&&(s=b.returnStatement(s),s[this.LOOP_IGNORE]=!0,e.skip(),e.replaceWith(b.inherits(s,r)))}}},B=function(){function e(t,r,n,i,s){(0,h.default)(this,e),this.parent=n,this.scope=i,this.file=s,this.blockPath=r,this.block=r.node,this.outsideLetReferences=(0,p.default)(null),this.hasLetReferences=!1,this.letReferences=(0,p.default)(null),this.body=[],t&&(this.loopParent=t.parent,this.loopLabel=b.isLabeledStatement(this.loopParent)&&this.loopParent.label,this.loopPath=t,this.loop=t.node)}return e.prototype.run=function(){var e=this.block;if(!e._letDone){e._letDone=!0;var t=this.getLetReferences();if(b.isFunction(this.parent)||b.isProgram(this.block))return void this.updateScopeInfo();if(this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.updateScopeInfo(t),this.loopLabel&&!b.isLabeledStatement(this.loopParent)?b.labeledStatement(this.loopLabel,this.loop):void 0}},e.prototype.updateScopeInfo=function(e){var t=this.scope,r=t.getFunctionParent(),n=this.letReferences;for(var i in n){var s=n[i],a=t.getBinding(s.name);a&&("let"!==a.kind&&"const"!==a.kind||(a.kind="var",e?t.removeBinding(s.name):t.moveBindingTo(s.name,r)))}},e.prototype.remap=function(){var e=this.letReferences,t=this.scope;for(var r in e){var n=e[r];(t.parentHasBinding(r)||t.hasGlobal(r))&&(t.hasOwnBinding(r)&&t.rename(n.name),this.blockPath.scope.hasOwnBinding(r)&&this.blockPath.scope.rename(n.name))}},e.prototype.wrapClosure=function(){if(this.file.opts.throwIfClosureRequired)throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure (throwIfClosureRequired).");var e=this.block,t=this.outsideLetReferences;if(this.loop)for(var r in t){var n=t[r];(this.scope.hasGlobal(n.name)||this.scope.parentHasBinding(n.name))&&(delete t[n.name],delete this.letReferences[n.name],this.scope.rename(n.name),this.letReferences[n.name]=n,t[n.name]=n)}this.has=this.checkLoop(),this.hoistVarDeclarations();var i=(0,x.default)(t),s=(0,x.default)(t),a=this.blockPath.isSwitchStatement(),o=b.functionExpression(null,i,b.blockStatement(a?[e]:e.body));o.shadow=!0,this.addContinuations(o);var u=o;this.loop&&(u=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(b.variableDeclaration("var",[b.variableDeclarator(u,o)])));var l=b.callExpression(u,s),c=this.scope.generateUidIdentifier("ret");y.default.hasType(o.body,this.scope,"YieldExpression",b.FUNCTION_TYPES)&&(o.generator=!0,l=b.yieldExpression(l,!0)),y.default.hasType(o.body,this.scope,"AwaitExpression",b.FUNCTION_TYPES)&&(o.async=!0,l=b.awaitExpression(l)),this.buildClosure(c,l),a?this.blockPath.replaceWithMultiple(this.body):e.body=this.body},e.prototype.buildClosure=function(e,t){var r=this.has;r.hasReturn||r.hasBreakContinue?this.buildHas(e,t):this.body.push(b.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,T,t);for(var r=0;r=t.length)break;o=t[a++]}else{if(a=t.next(),a.done)break;o=a.value}var u=o;"get"===u.kind||"set"===u.kind?n(e,u):r(e.objId,u,e.body)}}function a(e){for(var s=e.objId,a=e.body,u=e.computedProps,l=e.state,c=u,f=Array.isArray(c),p=0,c=f?c:(0,i.default)(c);;){var d;if(f){if(p>=c.length)break;d=c[p++]}else{if(p=c.next(),p.done)break;d=p.value}var h=d,m=o.toComputedKey(h);if("get"===h.kind||"set"===h.kind)n(e,h);else if(o.isStringLiteral(m,{value:"__proto__"}))r(s,h,a);else{if(1===u.length)return o.callExpression(l.addHelper("defineProperty"),[e.initPropExpression,m,t(h)]);a.push(o.expressionStatement(o.callExpression(l.addHelper("defineProperty"),[s,m,t(h)])))}}}var o=e.types,u=e.template,l=u("\n MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};\n MUTATOR_MAP_REF[KEY].KIND = VALUE;\n ");return{visitor:{ObjectExpression:{exit:function(e,t){for(var r=e.node,n=e.parent,u=e.scope,l=!1,c=r.properties,f=Array.isArray(c),p=0,c=f?c:(0,i.default)(c);;){var d;if(f){if(p>=c.length)break;d=c[p++]}else{if(p=c.next(),p.done)break;d=p.value}if(l=!0===d.computed)break}if(l){for(var h=[],m=[],y=!1,v=r.properties,g=Array.isArray(v),b=0,v=g?v:(0,i.default)(v);;){var E;if(g){if(b>=v.length)break;E=v[b++]}else{if(b=v.next(),b.done)break;E=b.value}var x=E;x.computed&&(y=!0),y?m.push(x):h.push(x)}var A=u.generateUidIdentifierBasedOnNode(n),S=o.objectExpression(h),_=[];_.push(o.variableDeclaration("var",[o.variableDeclarator(A,S)]));var D=a;t.opts.loose&&(D=s);var C=void 0,w=function(){return C||(C=u.generateUidIdentifier("mutatorMap"),_.push(o.variableDeclaration("var",[o.variableDeclarator(C,o.objectExpression([]))]))),C},P=D({scope:u,objId:A,body:_,computedProps:m,initPropExpression:S,getMutatorId:w,state:t});C&&_.push(o.expressionStatement(o.callExpression(t.addHelper("defineEnumerableProperties"),[A,C]))),P?e.replaceWith(P):(_.push(o.expressionStatement(A)),e.replaceWithMultiple(_))}}}}}},e.exports=t.default},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(3),s=n(i),a=r(2),o=n(a);t.default=function(e){function t(e){for(var t=e.declarations,r=Array.isArray(t),i=0,t=r?t:(0,o.default)(t);;){var s;if(r){if(i>=t.length)break;s=t[i++]}else{if(i=t.next(),i.done)break;s=i.value}var a=s;if(n.isPattern(a.id))return!0}return!1}function r(e){for(var t=e.elements,r=Array.isArray(t),i=0,t=r?t:(0,o.default)(t);;){var s;if(r){if(i>=t.length)break;s=t[i++]}else{if(i=t.next(),i.done)break;s=i.value}var a=s;if(n.isRestElement(a))return!0}return!1}var n=e.types,i={ReferencedIdentifier:function(e,t){t.bindings[e.node.name]&&(t.deopt=!0,e.stop())}},a=function(){function e(t){(0,s.default)(this,e),this.blockHoist=t.blockHoist,this.operator=t.operator,this.arrays={},this.nodes=t.nodes||[],this.scope=t.scope,this.file=t.file,this.kind=t.kind} -return e.prototype.buildVariableAssignment=function(e,t){var r=this.operator;n.isMemberExpression(e)&&(r="=");var i=void 0;return i=r?n.expressionStatement(n.assignmentExpression(r,e,t)):n.variableDeclaration(this.kind,[n.variableDeclarator(e,t)]),i._blockHoist=this.blockHoist,i},e.prototype.buildVariableDeclaration=function(e,t){var r=n.variableDeclaration("var",[n.variableDeclarator(e,t)]);return r._blockHoist=this.blockHoist,r},e.prototype.push=function(e,t){n.isObjectPattern(e)?this.pushObjectPattern(e,t):n.isArrayPattern(e)?this.pushArrayPattern(e,t):n.isAssignmentPattern(e)?this.pushAssignmentPattern(e,t):this.nodes.push(this.buildVariableAssignment(e,t))},e.prototype.toArray=function(e,t){return this.file.opts.loose||n.isIdentifier(e)&&this.arrays[e.name]?e:this.scope.toArray(e,t)},e.prototype.pushAssignmentPattern=function(e,t){var r=this.scope.generateUidIdentifierBasedOnNode(t),i=n.variableDeclaration("var",[n.variableDeclarator(r,t)]);i._blockHoist=this.blockHoist,this.nodes.push(i);var s=n.conditionalExpression(n.binaryExpression("===",r,n.identifier("undefined")),e.right,r),a=e.left;if(n.isPattern(a)){var o=n.expressionStatement(n.assignmentExpression("=",r,s));o._blockHoist=this.blockHoist,this.nodes.push(o),this.push(a,r)}else this.nodes.push(this.buildVariableAssignment(a,s))},e.prototype.pushObjectRest=function(e,t,r,i){for(var s=[],a=0;a=i)break;if(!n.isRestProperty(o)){var u=o.key;n.isIdentifier(u)&&!o.computed&&(u=n.stringLiteral(o.key.name)),s.push(u)}}s=n.arrayExpression(s);var l=n.callExpression(this.file.addHelper("objectWithoutProperties"),[t,s]);this.nodes.push(this.buildVariableAssignment(r.argument,l))},e.prototype.pushObjectProperty=function(e,t){n.isLiteral(e.key)&&(e.computed=!0);var r=e.value,i=n.memberExpression(t,e.key,e.computed);n.isPattern(r)?this.push(r,i):this.nodes.push(this.buildVariableAssignment(r,i))},e.prototype.pushObjectPattern=function(e,t){if(e.properties.length||this.nodes.push(n.expressionStatement(n.callExpression(this.file.addHelper("objectDestructuringEmpty"),[t]))),e.properties.length>1&&!this.scope.isStatic(t)){var r=this.scope.generateUidIdentifierBasedOnNode(t);this.nodes.push(this.buildVariableDeclaration(r,t)),t=r}for(var i=0;it.elements.length)){if(e.elements.length=s.length)break;l=s[u++]}else{if(u=s.next(),u.done)break;l=u.value}var c=l;if(!c)return!1;if(n.isMemberExpression(c))return!1}for(var f=t.elements,p=Array.isArray(f),d=0,f=p?f:(0,o.default)(f);;){var h;if(p){if(d>=f.length)break;h=f[d++]}else{if(d=f.next(),d.done)break;h=d.value}var m=h;if(n.isSpreadElement(m))return!1;if(n.isCallExpression(m))return!1;if(n.isMemberExpression(m))return!1}var y=n.getBindingIdentifiers(e),v={deopt:!1,bindings:y};return this.scope.traverse(t,i,v),!v.deopt}},e.prototype.pushUnpackedArrayPattern=function(e,t){for(var r=0;r=y.length)break;b=y[g++]}else{if(g=y.next(),g.done)break;b=g.value}var E=b,x=m[m.length-1];if(x&&n.isVariableDeclaration(x)&&n.isVariableDeclaration(E)&&x.kind===E.kind){var A;(A=x.declarations).push.apply(A,E.declarations)}else m.push(E)}for(var S=m,_=Array.isArray(S),D=0,S=_?S:(0,o.default)(S);;){var C;if(_){if(D>=S.length)break;C=S[D++]}else{if(D=S.next(),D.done)break;C=D.value}var w=C;if(w.declarations)for(var P=w.declarations,k=Array.isArray(P),F=0,P=k?P:(0,o.default)(P);;){var T;if(k){if(F>=P.length)break;T=P[F++]}else{if(F=P.next(),F.done)break;T=F.value}var O=T,B=O.id.name;s.bindings[B]&&(s.bindings[B].kind=w.kind)}}1===m.length?e.replaceWith(m[0]):e.replaceWithMultiple(m)}}}}},e.exports=t.default},function(e,t){"use strict";t.__esModule=!0,t.default=function(e){function t(e){var t=e.node,r=e.scope,n=[],i=t.right;if(!a.isIdentifier(i)||!r.hasBinding(i.name)){var s=r.generateUidIdentifier("arr");n.push(a.variableDeclaration("var",[a.variableDeclarator(s,i)])),i=s}var u=r.generateUidIdentifier("i"),l=o({BODY:t.body,KEY:u,ARR:i});a.inherits(l,t),a.ensureBlock(l);var c=a.memberExpression(i,u,!0),f=t.left;return a.isVariableDeclaration(f)?(f.declarations[0].init=c,l.body.body.unshift(f)):l.body.body.unshift(a.expressionStatement(a.assignmentExpression("=",f,c))),e.parentPath.isLabeledStatement()&&(l=a.labeledStatement(e.parentPath.node.label,l)),n.push(l),n}function r(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,l=void 0,c=void 0;if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))c=o;else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));c=n.generateUidIdentifier("ref"),l=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,c)])}var f=n.generateUidIdentifier("iterator"),p=n.generateUidIdentifier("isArray"),d=u({LOOP_OBJECT:f,IS_ARRAY:p,OBJECT:r.right,INDEX:n.generateUidIdentifier("i"),ID:c});l||d.body.body.shift();var h=a.isLabeledStatement(s),m=void 0;return h&&(m=a.labeledStatement(s.label,d)),{replaceParent:h,declar:l,node:m||d,loop:d}}function n(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,u=void 0,c=n.generateUidIdentifier("step"),f=a.memberExpression(c,a.identifier("value"));if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))u=a.expressionStatement(a.assignmentExpression("=",o,f));else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));u=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,f)])}var p=n.generateUidIdentifier("iterator"),d=l({ITERATOR_HAD_ERROR_KEY:n.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:n.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:n.generateUidIdentifier("iteratorError"),ITERATOR_KEY:p,STEP_KEY:c,OBJECT:r.right,BODY:null}),h=a.isLabeledStatement(s),m=d[3].block.body,y=m[0];return h&&(m[0]=a.labeledStatement(s.label,y)),{replaceParent:h,declar:u,loop:y,node:d}}var i=e.messages,s=e.template,a=e.types,o=s("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "),u=s("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "),l=s("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n ");return{visitor:{ForOfStatement:function(e,i){if(e.get("right").isArrayExpression())return e.parentPath.isLabeledStatement()?e.parentPath.replaceWithMultiple(t(e)):e.replaceWithMultiple(t(e));var s=n;i.opts.loose&&(s=r);var o=e.node,u=s(e,i),l=u.declar,c=u.loop,f=c.body;e.ensureBlock(),l&&f.body.push(l),f.body=f.body.concat(o.body.body),a.inherits(c,o),a.inherits(c.body,o.body),u.replaceParent?(e.parentPath.replaceWithMultiple(u.node),e.remove()):e.replaceWithMultiple(u.node)}}}},e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0,t.default=function(){return{visitor:{FunctionExpression:{exit:function(e){if("value"!==e.key&&!e.parentPath.isObjectProperty()){var t=(0,i.default)(e);t&&e.replaceWith(t)}}},ObjectProperty:function(e){var t=e.get("value");if(t.isFunction()){var r=(0,i.default)(t);r&&t.replaceWith(r)}}}}};var n=r(40),i=function(e){return e&&e.__esModule?e:{default:e}}(n);e.exports=t.default},function(e,t){"use strict";t.__esModule=!0,t.default=function(){return{visitor:{NumericLiteral:function(e){var t=e.node;t.extra&&/^0[ob]/i.test(t.extra.raw)&&(t.extra=void 0)},StringLiteral:function(e){var t=e.node;t.extra&&/\\[u]/gi.test(t.extra.raw)&&(t.extra=void 0)}}}},e.exports=t.default},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=r(14),s=n(i),a=r(9),o=n(a),u=r(2),l=n(u),c=r(10),f=n(c);t.default=function(){var e=(0,f.default)(),t={ReferencedIdentifier:function(e){var t=e.node.name,r=this.remaps[t];if(r&&this.scope.getBinding(t)===e.scope.getBinding(t)){if(e.parentPath.isCallExpression({callee:e.node}))e.replaceWith(g.sequenceExpression([g.numericLiteral(0),r]));else if(e.isJSXIdentifier()&&g.isMemberExpression(r)){var n=r.object,i=r.property;e.replaceWith(g.JSXMemberExpression(g.JSXIdentifier(n.name),g.JSXIdentifier(i.name)))}else e.replaceWith(r);this.requeueInParent(e)}},AssignmentExpression:function(t){var r=t.node;if(!r[e]){var n=t.get("left");if(n.isIdentifier()){var i=n.node.name,s=this.exports[i];if(!s)return;if(this.scope.getBinding(i)!==t.scope.getBinding(i))return;r[e]=!0;for(var a=s,o=Array.isArray(a),u=0,a=o?a:(0,l.default)(a);;){var c;if(o){if(u>=a.length)break;c=a[u++]}else{if(u=a.next(),u.done)break;c=u.value}r=S(c,r).expression}t.replaceWith(r),this.requeueInParent(t)}else if(n.isObjectPattern())for(var f=n.node.properties,p=Array.isArray(f),d=0,f=p?f:(0,l.default)(f);;){var h;if(p){if(d>=f.length)break;h=f[d++]}else{if(d=f.next(),d.done)break;h=d.value}var m=h,y=m.value.name,v=this.exports[y];if(v){if(this.scope.getBinding(y)!==t.scope.getBinding(y))return;r[e]=!0,t.insertAfter(S(g.identifier(y),g.identifier(y)))}}else if(n.isArrayPattern())for(var b=n.node.elements,E=Array.isArray(b),x=0,b=E?b:(0,l.default)(b);;){var A;if(E){if(x>=b.length)break;A=b[x++]}else{if(x=b.next(),x.done)break;A=x.value}var _=A;if(_){var D=_.name,C=this.exports[D];if(C){if(this.scope.getBinding(D)!==t.scope.getBinding(D))return;r[e]=!0,t.insertAfter(S(g.identifier(D),g.identifier(D)))}}}}},UpdateExpression:function(e){var t=e.get("argument");if(t.isIdentifier()){var r=t.node.name;if(this.exports[r]&&this.scope.getBinding(r)===e.scope.getBinding(r)){var n=g.assignmentExpression(e.node.operator[0]+"=",t.node,g.numericLiteral(1));if(e.parentPath.isExpressionStatement()&&!e.isCompletionRecord()||e.node.prefix)return e.replaceWith(n),void this.requeueInParent(e);var i=[];i.push(n);var s=void 0;s="--"===e.node.operator?"+":"-",i.push(g.binaryExpression(s,t.node,g.numericLiteral(1))),e.replaceWithMultiple(g.sequenceExpression(i))}}}};return{inherits:y.default,visitor:{ThisExpression:function(e,t){this.ranCommonJS||!0===t.opts.allowTopLevelThis||e.findParent(function(e){return!e.is("shadow")&&D.indexOf(e.type)>=0})||e.replaceWith(g.identifier("undefined"))},Program:{exit:function(e){function r(t,r){var n=C[t];if(n)return n;var i=e.scope.generateUidIdentifier((0,p.basename)(t,(0,p.extname)(t))),s=g.variableDeclaration("var",[g.variableDeclarator(i,b(g.stringLiteral(t)).expression)]);return h[t]&&(s.loc=h[t].loc),"number"==typeof r&&r>0&&(s._blockHoist=r),v.push(s),C[t]=i}function n(e,t,r){var n=e[t]||[];e[t]=n.concat(r)}this.ranCommonJS=!0;var i=!!this.opts.strict,a=!!this.opts.noInterop,u=e.scope;u.rename("module"),u.rename("exports"),u.rename("require");for(var c=!1,f=!1,d=e.get("body"),h=(0,o.default)(null),m=(0,o.default)(null),y=(0,o.default)(null),v=[],D=(0,o.default)(null),C=(0,o.default)(null),w=d,P=Array.isArray(w),k=0,w=P?w:(0,l.default)(w);;){var F;if(P){if(k>=w.length)break;F=w[k++]}else{if(k=w.next(),k.done)break;F=k.value}var T=F;if(T.isExportDeclaration()){c=!0;for(var O=[].concat(T.get("declaration"),T.get("specifiers")),B=O,R=Array.isArray(B),I=0,B=R?B:(0,l.default)(B);;){var M;if(R){if(I>=B.length)break;M=B[I++]}else{if(I=B.next(),I.done)break;M=I.value}var N=M;if(N.getBindingIdentifiers().__esModule)throw N.buildCodeFrameError('Illegal export "__esModule"')}}if(T.isImportDeclaration()){var L;f=!0;var j=T.node.source.value,U=h[j]||{specifiers:[],maxBlockHoist:0,loc:T.node.loc};(L=U.specifiers).push.apply(L,T.node.specifiers),"number"==typeof T.node._blockHoist&&(U.maxBlockHoist=Math.max(T.node._blockHoist,U.maxBlockHoist)),h[j]=U,T.remove()}else if(T.isExportDefaultDeclaration()){var V=T.get("declaration");if(V.isFunctionDeclaration()){var G=V.node.id,W=g.identifier("default");G?(n(m,G.name,W),v.push(S(W,G)),T.replaceWith(V.node)):(v.push(S(W,g.toExpression(V.node))),T.remove())}else if(V.isClassDeclaration()){var Y=V.node.id,q=g.identifier("default");Y?(n(m,Y.name,q),T.replaceWithMultiple([V.node,S(q,Y)])):(T.replaceWith(S(q,g.toExpression(V.node))),T.parentPath.requeue(T.get("expression.left")))}else T.replaceWith(S(g.identifier("default"),V.node)),T.parentPath.requeue(T.get("expression.left"))}else if(T.isExportNamedDeclaration()){var K=T.get("declaration");if(K.node){if(K.isFunctionDeclaration()){var H=K.node.id;n(m,H.name,H),v.push(S(H,H)),T.replaceWith(K.node)}else if(K.isClassDeclaration()){var J=K.node.id;n(m,J.name,J),T.replaceWithMultiple([K.node,S(J,J)]),y[J.name]=!0}else if(K.isVariableDeclaration()){for(var X=K.get("declarations"),z=X,$=Array.isArray(z),Q=0,z=$?z:(0,l.default)(z);;){var Z;if($){if(Q>=z.length)break;Z=z[Q++]}else{if(Q=z.next(),Q.done)break;Z=Q.value}var ee=Z,te=ee.get("id"),re=ee.get("init"),ne=[];if(re.node||re.replaceWith(g.identifier("undefined")),te.isIdentifier())n(m,te.node.name,te.node),re.replaceWith(S(te.node,re.node).expression),y[te.node.name]=!0;else if(te.isObjectPattern())for(var ie=0;ie=he.length)break;ve=he[ye++]}else{if(ye=he.next(),ye.done)break;ve=ye.value}var ge=ve;ge.isExportNamespaceSpecifier()||ge.isExportDefaultSpecifier()||ge.isExportSpecifier()&&(a||"default"!==ge.node.local.name?v.push(x(g.stringLiteral(ge.node.exported.name),g.memberExpression(de,ge.node.local))):v.push(x(g.stringLiteral(ge.node.exported.name),g.memberExpression(g.callExpression(this.addHelper("interopRequireDefault"),[de]),ge.node.local))),y[ge.node.exported.name]=!0)}else for(var be=ce,Ee=Array.isArray(be),xe=0,be=Ee?be:(0,l.default)(be);;){var Ae;if(Ee){if(xe>=be.length)break;Ae=be[xe++]}else{if(xe=be.next(),xe.done)break;Ae=xe.value}var Se=Ae;Se.isExportSpecifier()&&(n(m,Se.node.local.name,Se.node.exported),y[Se.node.exported.name]=!0,fe.push(S(Se.node.exported,Se.node.local)))}T.replaceWithMultiple(fe)}else if(T.isExportAllDeclaration()){var _e=_({OBJECT:r(T.node.source.value,T.node._blockHoist)});_e.loc=T.node.loc,v.push(_e),T.remove()}}for(var De in h){var Ce=h[De],O=Ce.specifiers,we=Ce.maxBlockHoist;if(O.length){for(var Pe=r(De,we),ke=void 0,Fe=0;Fe0&&(Oe._blockHoist=we),v.push(Oe)}ke=Te.local}else g.isImportDefaultSpecifier(Te)&&(O[Fe]=g.importSpecifier(Te.local,g.identifier("default")))}for(var Be=O,Re=Array.isArray(Be),Ie=0,Be=Re?Be:(0,l.default)(Be);;){var Me;if(Re){if(Ie>=Be.length)break;Me=Be[Ie++]}else{if(Ie=Be.next(),Ie.done)break;Me=Ie.value}var Ne=Me;if(g.isImportSpecifier(Ne)){var Le=Pe;if("default"===Ne.imported.name)if(ke)Le=ke;else if(!a){Le=ke=e.scope.generateUidIdentifier(Pe.name);var je=g.variableDeclaration("var",[g.variableDeclarator(Le,g.callExpression(this.addHelper("interopRequireDefault"),[Pe]))]);we>0&&(je._blockHoist=we),v.push(je)}D[Ne.local.name]=g.memberExpression(Le,g.cloneWithoutLoc(Ne.imported))}}}else{var Ue=b(g.stringLiteral(De));Ue.loc=h[De].loc,v.push(Ue)}}if(f&&(0,s.default)(y).length)for(var Ve=(0,s.default)(y),Ge=0;Ge=l.length)break;p=l[f++]}else{if(f=l.next(),f.done)break;p=f.value}var d=p;d.isObjectProperty()&&(d=d.get("value")),t(d,d.node,e.scope,o,i)}a&&(e.scope.push({id:a}),e.replaceWith(r.assignmentExpression("=",a,e.node)))}}}}}};var u=r(193),l=n(u);e.exports=t.default},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}t.__esModule=!0;var i=r(2),s=function(e){return e&&e.__esModule?e:{default:e}}(i);t.default=function(){return{visitor:a.visitors.merge([{ArrowFunctionExpression:function(e){for(var t=e.get("params"),r=t,n=Array.isArray(r),i=0,r=n?r:(0,s.default)(r);;){var a;if(n){if(i>=r.length)break;a=r[i++]}else{if(i=r.next(),i.done)break;a=i.value}var o=a;if(o.isRestElement()||o.isAssignmentPattern()){e.arrowFunctionToShadowed();break}}}},u.visitor,p.visitor,c.visitor])}};var a=r(7),o=r(334),u=n(o),l=r(333),c=n(l),f=r(335),p=n(f);e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0,t.default=function(){return{visitor:{ObjectMethod:function(e){var t=e.node;if("method"===t.kind){var r=i.functionExpression(null,t.params,t.body,t.generator,t.async);r.returnType=t.returnType,e.replaceWith(i.objectProperty(t.key,r,t.computed))}},ObjectProperty:function(e){var t=e.node;t.shorthand&&(t.shorthand=!1)}}}};var n=r(1),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(n);e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0;var n=r(2),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){function t(e,t,r){return r.opts.loose&&!s.isIdentifier(e.argument,{name:"arguments"})?e.argument:t.toArray(e.argument,!0)}function r(e){for(var t=0;t=l.length)break;p=l[f++]}else{if(f=l.next(),f.done)break;p=f.value}var d=p;s.isSpreadElement(d)?(a(),o.push(t(d,r,n))):u.push(d)}return a(),o}var s=e.types;return{visitor:{ArrayExpression:function(e,t){var i=e.node,a=e.scope,o=i.elements;if(r(o)){var u=n(o,a,t),l=u.shift();s.isArrayExpression(l)||(u.unshift(l),l=s.arrayExpression([])),e.replaceWith(s.callExpression(s.memberExpression(l,s.identifier("concat")),u))}},CallExpression:function(e,t){var i=e.node,a=e.scope,o=i.arguments;if(r(o)){var u=e.get("callee");if(!u.isSuper()){var l=s.identifier("undefined");i.arguments=[];var c=void 0;c=1===o.length&&"arguments"===o[0].argument.name?[o[0].argument]:n(o,a,t);var f=c.shift();c.length?i.arguments.push(s.callExpression(s.memberExpression(f,s.identifier("concat")),c)):i.arguments.push(f);var p=i.callee;if(u.isMemberExpression()){var d=a.maybeGenerateMemoised(p.object);d?(p.object=s.assignmentExpression("=",d,p.object),l=d):l=p.object,s.appendToMemberExpression(p,s.identifier("apply"))}else i.callee=s.memberExpression(i.callee,s.identifier("apply"));s.isSuper(l)&&(l=s.thisExpression()),i.arguments.unshift(l)}}},NewExpression:function(e,t){var i=e.node,a=e.scope,o=i.arguments;if(r(o)){var u=n(o,a,t),l=s.arrayExpression([s.nullLiteral()]);o=s.callExpression(s.memberExpression(l,s.identifier("concat")),u),e.replaceWith(s.newExpression(s.callExpression(s.memberExpression(s.memberExpression(s.memberExpression(s.identifier("Function"),s.identifier("prototype")),s.identifier("bind")),s.identifier("apply")),[i.callee,o]),[]))}}}}},e.exports=t.default},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}t.__esModule=!0,t.default=function(){return{visitor:{RegExpLiteral:function(e){var t=e.node;s.is(t,"y")&&e.replaceWith(o.newExpression(o.identifier("RegExp"),[o.stringLiteral(t.pattern),o.stringLiteral(t.flags)]))}}}};var i=r(192),s=n(i),a=r(1),o=n(a);e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0;var n=r(2),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){function t(e){return n.isLiteral(e)&&"string"==typeof e.value}function r(e,t){return n.binaryExpression("+",e,t)}var n=e.types;return{visitor:{TaggedTemplateExpression:function(e,t){for(var r=e.node,s=r.quasi,a=[],o=[],u=[],l=s.quasis,c=Array.isArray(l),f=0,l=c?l:(0,i.default)(l);;){var p;if(c){if(f>=l.length)break;p=l[f++]}else{if(f=l.next(),f.done)break;p=f.value}var d=p;o.push(n.stringLiteral(d.value.cooked)),u.push(n.stringLiteral(d.value.raw))}o=n.arrayExpression(o),u=n.arrayExpression(u);var h="taggedTemplateLiteral";t.opts.loose&&(h+="Loose");var m=t.file.addTemplateObject(h,o,u);a.push(m),a=a.concat(s.expressions),e.replaceWith(n.callExpression(r.tag,a))},TemplateLiteral:function(e,s){for(var a=[],o=e.get("expressions"),u=e.node.quasis,l=Array.isArray(u),c=0,u=l?u:(0,i.default)(u);;){var f;if(l){if(c>=u.length)break;f=u[c++]}else{if(c=u.next(),c.done)break;f=c.value}var p=f;a.push(n.stringLiteral(p.value.cooked));var d=o.shift();d&&(!s.opts.spec||d.isBaseType("string")||d.isBaseType("number")?a.push(d.node):a.push(n.callExpression(n.identifier("String"),[d.node])))}if(a=a.filter(function(e){return!n.isLiteral(e,{value:""})}),t(a[0])||t(a[1])||a.unshift(n.stringLiteral("")),a.length>1){for(var h=r(a.shift(),a.shift()),m=a,y=Array.isArray(m),v=0,m=y?m:(0,i.default)(m);;){var g;if(y){if(v>=m.length)break;g=m[v++]}else{if(v=m.next(),v.done)break;g=v.value}h=r(h,g)}e.replaceWith(h)}else e.replaceWith(a[0])}}}},e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0;var n=r(10),i=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=e.types,r=(0,i.default)();return{visitor:{Scope:function(e){var t=e.scope;t.getBinding("Symbol")&&t.rename("Symbol")},UnaryExpression:function(e){var n=e.node,i=e.parent;if(!n[r]&&!e.find(function(e){return e.node&&!!e.node._generated})){if(e.parentPath.isBinaryExpression()&&t.EQUALITY_BINARY_OPERATORS.indexOf(i.operator)>=0){var s=e.getOpposite();if(s.isLiteral()&&"symbol"!==s.node.value&&"object"!==s.node.value)return}if("typeof"===n.operator){var a=t.callExpression(this.addHelper("typeof"),[n.argument]);if(e.get("argument").isIdentifier()){var o=t.stringLiteral("undefined"),u=t.unaryExpression("typeof",n.argument);u[r]=!0,e.replaceWith(t.conditionalExpression(t.binaryExpression("===",u,o),o,a))}else e.replaceWith(a)}}}}}},e.exports=t.default},function(e,t,r){"use strict";t.__esModule=!0,t.default=function(){return{visitor:{RegExpLiteral:function(e){var t=e.node;a.is(t,"u")&&(t.pattern=(0,i.default)(t.pattern,t.flags),a.pullFlag(t,"u"))}}}};var n=r(612),i=function(e){return e&&e.__esModule?e:{default:e}}(n),s=r(192),a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(s);e.exports=t.default},function(e,t,r){"use strict";e.exports=r(606)},function(e,t,r){"use strict";e.exports={default:r(408),__esModule:!0}},function(e,t,r){"use strict";function n(){i(),s()}function i(){t.path=u=new o.default}function s(){t.scope=l=new o.default}t.__esModule=!0,t.scope=t.path=void 0;var a=r(364),o=function(e){return e&&e.__esModule?e:{default:e}}(a);t.clear=n,t.clearPath=i,t.clearScope=s;var u=t.path=new o.default,l=t.scope=new o.default},function(e,t){"use strict";function r(e){return e=e.split(" "),function(t){return e.indexOf(t)>=0}}function n(e,t){for(var r=65536,n=0;ne)return!1;if((r+=t[n+1])>=e)return!0}}function i(e){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&x.test(String.fromCharCode(e)):n(e,S)))}function s(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&A.test(String.fromCharCode(e)):n(e,S)||n(e,_))))}function a(e){var t={};for(var r in D)t[r]=e&&r in e?e[r]:D[r];return t}function o(e){return 10===e||13===e||8232===e||8233===e}function u(e,t){for(var r=1,n=0;;){N.lastIndex=n;var i=N.exec(e);if(!(i&&i.index>10),56320+(e-65536&1023))}function c(e,t,r,n){return e.type=t,e.end=r,e.loc.end=n,this.processComment(e),e}function f(e){return e[e.length-1]}function p(e){return e&&"Property"===e.type&&"init"===e.kind&&!1===e.method}function d(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?d(e.object)+"."+d(e.property):void 0}function h(e,t){return new J(t,e).parse()}function m(e,t){var r=new J(t,e);return r.options.strictMode&&(r.state.strict=!0),r.getExpression()}var y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Object.defineProperty(t,"__esModule",{value:!0});var v={6:r("enum await"),strict:r("implements interface let package private protected public static yield"),strictBind:r("eval arguments") -},g=r("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"),b="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",E="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",x=new RegExp("["+b+"]"),A=new RegExp("["+b+E+"]");b=E=null;var S=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541],_=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239],D={sourceType:"script",sourceFilename:void 0,startLine:1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null},C="function"==typeof Symbol&&"symbol"===y(Symbol.iterator)?function(e){return void 0===e?"undefined":y(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":void 0===e?"undefined":y(e)},w=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},P=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":y(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},k=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":y(t))&&"function"!=typeof t?e:t},F=!0,T=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.rightAssociative=!!r.rightAssociative,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop||null,this.updateContext=null},O=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,t),n.keyword=r,k(this,e.call(this,r,n))}return P(t,e),t}(T),B=function(e){function t(r,n){return w(this,t),k(this,e.call(this,r,{beforeExpr:F,binop:n}))}return P(t,e),t}(T),R={num:new T("num",{startsExpr:!0}),regexp:new T("regexp",{startsExpr:!0}),string:new T("string",{startsExpr:!0}),name:new T("name",{startsExpr:!0}),eof:new T("eof"),bracketL:new T("[",{beforeExpr:F,startsExpr:!0}),bracketR:new T("]"),braceL:new T("{",{beforeExpr:F,startsExpr:!0}),braceBarL:new T("{|",{beforeExpr:F,startsExpr:!0}),braceR:new T("}"),braceBarR:new T("|}"),parenL:new T("(",{beforeExpr:F,startsExpr:!0}),parenR:new T(")"),comma:new T(",",{beforeExpr:F}),semi:new T(";",{beforeExpr:F}),colon:new T(":",{beforeExpr:F}),doubleColon:new T("::",{beforeExpr:F}),dot:new T("."),question:new T("?",{beforeExpr:F}),arrow:new T("=>",{beforeExpr:F}),template:new T("template"),ellipsis:new T("...",{beforeExpr:F}),backQuote:new T("`",{startsExpr:!0}),dollarBraceL:new T("${",{beforeExpr:F,startsExpr:!0}),at:new T("@"),eq:new T("=",{beforeExpr:F,isAssign:!0}),assign:new T("_=",{beforeExpr:F,isAssign:!0}),incDec:new T("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new T("prefix",{beforeExpr:F,prefix:!0,startsExpr:!0}),logicalOR:new B("||",1),logicalAND:new B("&&",2),bitwiseOR:new B("|",3),bitwiseXOR:new B("^",4),bitwiseAND:new B("&",5),equality:new B("==/!=",6),relational:new B("",7),bitShift:new B("<>",8),plusMin:new T("+/-",{beforeExpr:F,binop:9,prefix:!0,startsExpr:!0}),modulo:new B("%",10),star:new B("*",10),slash:new B("/",10),exponent:new T("**",{beforeExpr:F,binop:11,rightAssociative:!0})},I={break:new O("break"),case:new O("case",{beforeExpr:F}),catch:new O("catch"),continue:new O("continue"),debugger:new O("debugger"),default:new O("default",{beforeExpr:F}),do:new O("do",{isLoop:!0,beforeExpr:F}),else:new O("else",{beforeExpr:F}),finally:new O("finally"),for:new O("for",{isLoop:!0}),function:new O("function",{startsExpr:!0}),if:new O("if"),return:new O("return",{beforeExpr:F}),switch:new O("switch"),throw:new O("throw",{beforeExpr:F}),try:new O("try"),var:new O("var"),let:new O("let"),const:new O("const"),while:new O("while",{isLoop:!0}),with:new O("with"),new:new O("new",{beforeExpr:F,startsExpr:!0}),this:new O("this",{startsExpr:!0}),super:new O("super",{startsExpr:!0}),class:new O("class"),extends:new O("extends",{beforeExpr:F}),export:new O("export"),import:new O("import",{startsExpr:!0}),yield:new O("yield",{beforeExpr:F,startsExpr:!0}),null:new O("null",{startsExpr:!0}),true:new O("true",{startsExpr:!0}),false:new O("false",{startsExpr:!0}),in:new O("in",{beforeExpr:F,binop:7}),instanceof:new O("instanceof",{beforeExpr:F,binop:7}),typeof:new O("typeof",{beforeExpr:F,prefix:!0,startsExpr:!0}),void:new O("void",{beforeExpr:F,prefix:!0,startsExpr:!0}),delete:new O("delete",{beforeExpr:F,prefix:!0,startsExpr:!0})};Object.keys(I).forEach(function(e){R["_"+e]=I[e]});var M=/\r\n?|\n|\u2028|\u2029/,N=new RegExp(M.source,"g"),L=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,j=function e(t,r,n,i){w(this,e),this.token=t,this.isExpr=!!r,this.preserveSpace=!!n,this.override=i},U={braceStatement:new j("{",!1),braceExpression:new j("{",!0),templateQuasi:new j("${",!0),parenStatement:new j("(",!1),parenExpression:new j("(",!0),template:new j("`",!0,!0,function(e){return e.readTmplToken()}),functionExpression:new j("function",!0)};R.parenR.updateContext=R.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);var e=this.state.context.pop();e===U.braceStatement&&this.curContext()===U.functionExpression?(this.state.context.pop(),this.state.exprAllowed=!1):e===U.templateQuasi?this.state.exprAllowed=!0:this.state.exprAllowed=!e.isExpr},R.name.updateContext=function(e){this.state.exprAllowed=!1,e!==R._let&&e!==R._const&&e!==R._var||M.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},R.braceL.updateContext=function(e){this.state.context.push(this.braceIsBlock(e)?U.braceStatement:U.braceExpression),this.state.exprAllowed=!0},R.dollarBraceL.updateContext=function(){this.state.context.push(U.templateQuasi),this.state.exprAllowed=!0},R.parenL.updateContext=function(e){var t=e===R._if||e===R._for||e===R._with||e===R._while;this.state.context.push(t?U.parenStatement:U.parenExpression),this.state.exprAllowed=!0},R.incDec.updateContext=function(){},R._function.updateContext=function(){this.curContext()!==U.braceStatement&&this.state.context.push(U.functionExpression),this.state.exprAllowed=!1},R.backQuote.updateContext=function(){this.curContext()===U.template?this.state.context.pop():this.state.context.push(U.template),this.state.exprAllowed=!1};var V=function e(t,r){w(this,e),this.line=t,this.column=r},G=function e(t,r){w(this,e),this.start=t,this.end=r},W=function(){function e(){w(this,e)}return e.prototype.init=function(e,t){return this.strict=!1!==e.strictMode&&"module"===e.sourceType,this.input=t,this.potentialArrowAt=-1,this.inMethod=this.inFunction=this.inGenerator=this.inAsync=this.inPropertyName=this.inType=this.inClassProperty=this.noAnonFunctionType=!1,this.labels=[],this.decorators=[],this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.pos=this.lineStart=0,this.curLine=e.startLine,this.type=R.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[U.braceStatement],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this.invalidTemplateEscapePosition=null,this.exportedIdentifiers=[],this},e.prototype.curPosition=function(){return new V(this.curLine,this.pos-this.lineStart)},e.prototype.clone=function(t){var r=new e;for(var n in this){var i=this[n];t&&"context"!==n||!Array.isArray(i)||(i=i.slice()),r[n]=i}return r},e}(),Y=function e(t){w(this,e),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new G(t.startLoc,t.endLoc)},q=function(){function e(t,r){w(this,e),this.state=new W,this.state.init(t,r)}return e.prototype.next=function(){this.isLookahead||this.state.tokens.push(new Y(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},e.prototype.eat=function(e){return!!this.match(e)&&(this.next(),!0)},e.prototype.match=function(e){return this.state.type===e},e.prototype.isKeyword=function(e){return g(e)},e.prototype.lookahead=function(){var e=this.state;this.state=e.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var t=this.state.clone(!0);return this.state=e,t},e.prototype.setStrict=function(e){if(this.state.strict=e,this.match(R.num)||this.match(R.string)){for(this.state.pos=this.state.start;this.state.pos=this.input.length?this.finishToken(R.eof):e.override?e.override(this):this.readToken(this.fullCharCodeAtPos())},e.prototype.readToken=function(e){return i(e)||92===e?this.readWord():this.getTokenFromCode(e)},e.prototype.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.state.pos);return e<=55295||e>=57344?e:(e<<10)+this.input.charCodeAt(this.state.pos+1)-56613888},e.prototype.pushComment=function(e,t,r,n,i,s){var a={type:e?"CommentBlock":"CommentLine",value:t,start:r,end:n,loc:new G(i,s)};this.isLookahead||(this.state.tokens.push(a),this.state.comments.push(a),this.addComment(a))},e.prototype.skipBlockComment=function(){var e=this.state.curPosition(),t=this.state.pos,r=this.input.indexOf("*/",this.state.pos+=2);-1===r&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=r+2,N.lastIndex=t;for(var n=void 0;(n=N.exec(this.input))&&n.index8&&e<14||e>=5760&&L.test(String.fromCharCode(e))))break e;++this.state.pos}}},e.prototype.finishToken=function(e,t){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var r=this.state.type;this.state.type=e,this.state.value=t,this.updateContext(r)},e.prototype.readToken_dot=function(){var e=this.input.charCodeAt(this.state.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.state.pos+2);return 46===e&&46===t?(this.state.pos+=3,this.finishToken(R.ellipsis)):(++this.state.pos,this.finishToken(R.dot))},e.prototype.readToken_slash=function(){return this.state.exprAllowed?(++this.state.pos,this.readRegexp()):61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(R.assign,2):this.finishOp(R.slash,1)},e.prototype.readToken_mult_modulo=function(e){var t=42===e?R.star:R.modulo,r=1,n=this.input.charCodeAt(this.state.pos+1);return 42===n&&(r++,n=this.input.charCodeAt(this.state.pos+2),t=R.exponent),61===n&&(r++,t=R.assign),this.finishOp(t,r)},e.prototype.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?this.finishOp(124===e?R.logicalOR:R.logicalAND,2):61===t?this.finishOp(R.assign,2):124===e&&125===t&&this.hasPlugin("flow")?this.finishOp(R.braceBarR,2):this.finishOp(124===e?R.bitwiseOR:R.bitwiseAND,1)},e.prototype.readToken_caret=function(){return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(R.assign,2):this.finishOp(R.bitwiseXOR,1)},e.prototype.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?45===t&&62===this.input.charCodeAt(this.state.pos+2)&&M.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(R.incDec,2):61===t?this.finishOp(R.assign,2):this.finishOp(R.plusMin,1)},e.prototype.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.state.pos+1),r=1;return t===e?(r=62===e&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+r)?this.finishOp(R.assign,r+1):this.finishOp(R.bitShift,r)):33===t&&60===e&&45===this.input.charCodeAt(this.state.pos+2)&&45===this.input.charCodeAt(this.state.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===t&&(r=2),this.finishOp(R.relational,r))},e.prototype.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(R.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===e&&62===t?(this.state.pos+=2,this.finishToken(R.arrow)):this.finishOp(61===e?R.eq:R.prefix,1)},e.prototype.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(R.parenL);case 41:return++this.state.pos,this.finishToken(R.parenR);case 59:return++this.state.pos,this.finishToken(R.semi);case 44:return++this.state.pos,this.finishToken(R.comma);case 91:return++this.state.pos,this.finishToken(R.bracketL);case 93:return++this.state.pos,this.finishToken(R.bracketR);case 123:return this.hasPlugin("flow")&&124===this.input.charCodeAt(this.state.pos+1)?this.finishOp(R.braceBarL,2):(++this.state.pos,this.finishToken(R.braceL));case 125:return++this.state.pos,this.finishToken(R.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(R.doubleColon,2):(++this.state.pos,this.finishToken(R.colon));case 63:return++this.state.pos,this.finishToken(R.question);case 64:return++this.state.pos,this.finishToken(R.at);case 96:return++this.state.pos,this.finishToken(R.backQuote);case 48:var t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(R.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+l(e)+"'")},e.prototype.finishOp=function(e,t){var r=this.input.slice(this.state.pos,this.state.pos+t);return this.state.pos+=t,this.finishToken(e,r)},e.prototype.readRegexp=function(){for(var e=this.state.pos,t=void 0,r=void 0;;){this.state.pos>=this.input.length&&this.raise(e,"Unterminated regular expression");var n=this.input.charAt(this.state.pos);if(M.test(n)&&this.raise(e,"Unterminated regular expression"),t)t=!1;else{if("["===n)r=!0;else if("]"===n&&r)r=!1;else if("/"===n&&!r)break;t="\\"===n}++this.state.pos}var i=this.input.slice(e,this.state.pos);++this.state.pos;var s=this.readWord1();if(s){/^[gmsiyu]*$/.test(s)||this.raise(e,"Invalid regular expression flag")}return this.finishToken(R.regexp,{pattern:i,flags:s})},e.prototype.readInt=function(e,t){for(var r=this.state.pos,n=0,i=0,s=null==t?1/0:t;i=97?a-97+10:a>=65?a-65+10:a>=48&&a<=57?a-48:1/0)>=e)break;++this.state.pos,n=n*e+o}return this.state.pos===r||null!=t&&this.state.pos-r!==t?null:n},e.prototype.readRadixNumber=function(e){this.state.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.state.start+2,"Expected number in radix "+e),i(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),this.finishToken(R.num,t)},e.prototype.readNumber=function(e){var t=this.state.pos,r=48===this.input.charCodeAt(t),n=!1;e||null!==this.readInt(10)||this.raise(t,"Invalid number"),r&&this.state.pos==t+1&&(r=!1);var s=this.input.charCodeAt(this.state.pos);46!==s||r||(++this.state.pos,this.readInt(10),n=!0,s=this.input.charCodeAt(this.state.pos)),69!==s&&101!==s||r||(s=this.input.charCodeAt(++this.state.pos),43!==s&&45!==s||++this.state.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),n=!0),i(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var a=this.input.slice(t,this.state.pos),o=void 0;return n?o=parseFloat(a):r&&1!==a.length?this.state.strict?this.raise(t,"Invalid number"):o=/[89]/.test(a)?parseInt(a,10):parseInt(a,8):o=parseInt(a,10),this.finishToken(R.num,o)},e.prototype.readCodePoint=function(e){var t=this.input.charCodeAt(this.state.pos),r=void 0;if(123===t){var n=++this.state.pos;if(r=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,e),++this.state.pos,null===r)--this.state.invalidTemplateEscapePosition;else if(r>1114111){if(!e)return this.state.invalidTemplateEscapePosition=n-2,null;this.raise(n,"Code point out of bounds")}}else r=this.readHexChar(4,e);return r},e.prototype.readString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;92===n?(t+=this.input.slice(r,this.state.pos),t+=this.readEscapedChar(!1),r=this.state.pos):(o(n)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return t+=this.input.slice(r,this.state.pos++),this.finishToken(R.string,t)},e.prototype.readTmplToken=function(){for(var e="",t=this.state.pos,r=!1;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var n=this.input.charCodeAt(this.state.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(R.template)?36===n?(this.state.pos+=2,this.finishToken(R.dollarBraceL)):(++this.state.pos,this.finishToken(R.backQuote)):(e+=this.input.slice(t,this.state.pos),this.finishToken(R.template,r?null:e));if(92===n){e+=this.input.slice(t,this.state.pos);var i=this.readEscapedChar(!0);null===i?r=!0:e+=i,t=this.state.pos}else if(o(n)){switch(e+=this.input.slice(t,this.state.pos),++this.state.pos,n){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(n)}++this.state.curLine,this.state.lineStart=this.state.pos,t=this.state.pos}else++this.state.pos}},e.prototype.readEscapedChar=function(e){var t=!e,r=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,r){case 110:return"\n";case 114:return"\r";case 120:var n=this.readHexChar(2,t);return null===n?null:String.fromCharCode(n);case 117:var i=this.readCodePoint(t);return null===i?null:l(i);case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(r>=48&&r<=55){var s=this.state.pos-1,a=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],o=parseInt(a,8);if(o>255&&(a=a.slice(0,-1),o=parseInt(a,8)),o>0){if(e)return this.state.invalidTemplateEscapePosition=s,null;this.state.strict?this.raise(s,"Octal literal in strict mode"):this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=s)}return this.state.pos+=a.length-1,String.fromCharCode(o)}return String.fromCharCode(r)}},e.prototype.readHexChar=function(e,t){var r=this.state.pos,n=this.readInt(16,e);return null===n&&(t?this.raise(r,"Bad character escape sequence"):(this.state.pos=r-1,this.state.invalidTemplateEscapePosition=r-1)),n},e.prototype.readWord1=function(){this.state.containsEsc=!1;for(var e="",t=!0,r=this.state.pos;this.state.pos-1)||!!this.plugins[e]},t.prototype.extend=function(e,t){this[e]=t(this[e])},t.prototype.loadAllPlugins=function(){var e=this,t=Object.keys(K).filter(function(e){return"flow"!==e&&"estree"!==e});t.push("flow"),t.forEach(function(t){var r=K[t];r&&r(e)})},t.prototype.loadPlugins=function(e){if(e.indexOf("*")>=0)return this.loadAllPlugins(),{"*":!0};var t={};e.indexOf("flow")>=0&&(e=e.filter(function(e){return"flow"!==e}),e.push("flow")),e.indexOf("estree")>=0&&(e=e.filter(function(e){return"estree"!==e}),e.unshift("estree"));for(var r=e,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if(!t[a]){t[a]=!0;var o=K[a];o&&o(this)}}return t},t.prototype.parse=function(){var e=this.startNode(),t=this.startNode();return this.nextToken(),this.parseTopLevel(e,t)},t}(q),X=J.prototype;X.addExtra=function(e,t,r){if(e){(e.extra=e.extra||{})[t]=r}},X.isRelational=function(e){return this.match(R.relational)&&this.state.value===e},X.expectRelational=function(e){this.isRelational(e)?this.next():this.unexpected(null,R.relational)},X.isContextual=function(e){return this.match(R.name)&&this.state.value===e},X.eatContextual=function(e){return this.state.value===e&&this.eat(R.name)},X.expectContextual=function(e,t){this.eatContextual(e)||this.unexpected(null,t)},X.canInsertSemicolon=function(){return this.match(R.eof)||this.match(R.braceR)||M.test(this.input.slice(this.state.lastTokEnd,this.state.start))},X.isLineTerminator=function(){return this.eat(R.semi)||this.canInsertSemicolon()},X.semicolon=function(){this.isLineTerminator()||this.unexpected(null,R.semi)},X.expect=function(e,t){return this.eat(e)||this.unexpected(t,e)},X.unexpected=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unexpected token";t&&"object"===(void 0===t?"undefined":C(t))&&t.label&&(t="Unexpected token, expected "+t.label),this.raise(null!=e?e:this.state.start,t)};var z=J.prototype;z.parseTopLevel=function(e,t){return t.sourceType=this.options.sourceType,this.parseBlockBody(t,!0,!0,R.eof),e.program=this.finishNode(t,"Program"),e.comments=this.state.comments,e.tokens=this.state.tokens,this.finishNode(e,"File")};var $={kind:"loop"},Q={kind:"switch"};z.stmtToDirective=function(e){var t=e.expression,r=this.startNodeAt(t.start,t.loc.start),n=this.startNodeAt(e.start,e.loc.start),i=this.input.slice(t.start,t.end),s=r.value=i.slice(1,-1);return this.addExtra(r,"raw",i),this.addExtra(r,"rawValue",s),n.value=this.finishNodeAt(r,"DirectiveLiteral",t.end,t.loc.end),this.finishNodeAt(n,"Directive",e.end,e.loc.end)},z.parseStatement=function(e,t){this.match(R.at)&&this.parseDecorators(!0);var r=this.state.type,n=this.startNode();switch(r){case R._break:case R._continue:return this.parseBreakContinueStatement(n,r.keyword);case R._debugger:return this.parseDebuggerStatement(n);case R._do:return this.parseDoStatement(n);case R._for:return this.parseForStatement(n);case R._function:return e||this.unexpected(),this.parseFunctionStatement(n);case R._class:return e||this.unexpected(),this.parseClass(n,!0);case R._if:return this.parseIfStatement(n);case R._return:return this.parseReturnStatement(n);case R._switch:return this.parseSwitchStatement(n);case R._throw:return this.parseThrowStatement(n);case R._try:return this.parseTryStatement(n);case R._let:case R._const:e||this.unexpected();case R._var:return this.parseVarStatement(n,r);case R._while:return this.parseWhileStatement(n);case R._with:return this.parseWithStatement(n);case R.braceL:return this.parseBlock();case R.semi:return this.parseEmptyStatement(n);case R._export:case R._import:if(this.hasPlugin("dynamicImport")&&this.lookahead().type===R.parenL)break;return this.options.allowImportExportEverywhere||(t||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.state.start,"'import' and 'export' may appear only with 'sourceType: \"module\"'")),r===R._import?this.parseImport(n):this.parseExport(n);case R.name:if("async"===this.state.value){var i=this.state.clone();if(this.next(),this.match(R._function)&&!this.canInsertSemicolon())return this.expect(R._function),this.parseFunction(n,!0,!1,!0);this.state=i}}var s=this.state.value,a=this.parseExpression();return r===R.name&&"Identifier"===a.type&&this.eat(R.colon)?this.parseLabeledStatement(n,s,a):this.parseExpressionStatement(n,a)},z.takeDecorators=function(e){this.state.decorators.length&&(e.decorators=this.state.decorators,this.state.decorators=[])},z.parseDecorators=function(e){for(;this.match(R.at);){var t=this.parseDecorator();this.state.decorators.push(t)}e&&this.match(R._export)||this.match(R._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},z.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var e=this.startNode();return this.next(),e.expression=this.parseMaybeAssign(),this.finishNode(e,"Decorator")},z.parseBreakContinueStatement=function(e,t){var r="break"===t;this.next(),this.isLineTerminator()?e.label=null:this.match(R.name)?(e.label=this.parseIdentifier(),this.semicolon()):this.unexpected();var n=void 0;for(n=0;n=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}a.name===t&&this.raise(r.start,"Label '"+t+"' is already declared")}for(var o=this.state.type.isLoop?"loop":this.match(R._switch)?"switch":null,u=this.state.labels.length-1;u>=0;u--){var l=this.state.labels[u];if(l.statementStart!==e.start)break;l.statementStart=this.state.start,l.kind=o}return this.state.labels.push({name:t,kind:o,statementStart:this.state.start}),e.body=this.parseStatement(!0),this.state.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},z.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},z.parseBlock=function(e){var t=this.startNode();return this.expect(R.braceL),this.parseBlockBody(t,e,!1,R.braceR),this.finishNode(t,"BlockStatement")},z.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},z.parseBlockBody=function(e,t,r,n){e.body=[],e.directives=[];for(var i=!1,s=void 0,a=void 0;!this.eat(n);){i||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,r);if(t&&!i&&this.isValidDirective(o)){var u=this.stmtToDirective(o);e.directives.push(u),void 0===s&&"use strict"===u.value.value&&(s=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}else i=!0,e.body.push(o)}!1===s&&this.setStrict(!1)},z.parseFor=function(e,t){return e.init=t,this.expect(R.semi),e.test=this.match(R.semi)?null:this.parseExpression(),this.expect(R.semi),e.update=this.match(R.parenR)?null:this.parseExpression(),this.expect(R.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,"ForStatement")},z.parseForIn=function(e,t,r){var n=void 0;return r?(this.eatContextual("of"),n="ForAwaitStatement"):(n=this.match(R._in)?"ForInStatement":"ForOfStatement",this.next()),e.left=t,e.right=this.parseExpression(),this.expect(R.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,n)},z.parseVar=function(e,t,r){for(e.declarations=[],e.kind=r.keyword;;){var n=this.startNode();if(this.parseVarHead(n),this.eat(R.eq)?n.init=this.parseMaybeAssign(t):r!==R._const||this.match(R._in)||this.isContextual("of")?"Identifier"===n.id.type||t&&(this.match(R._in)||this.isContextual("of"))?n.init=null:this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(R.comma))break}return e},z.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0,void 0,"variable declaration")},z.parseFunction=function(e,t,r,n,i){var s=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(e,n),this.match(R.star)&&(e.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(e.generator=!0,this.next())),!t||i||this.match(R.name)||this.match(R._yield)||this.unexpected(),(this.match(R.name)||this.match(R._yield))&&(e.id=this.parseBindingIdentifier()),this.parseFunctionParams(e),this.parseFunctionBody(e,r),this.state.inMethod=s,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},z.parseFunctionParams=function(e){this.expect(R.parenL),e.params=this.parseBindingList(R.parenR)},z.parseClass=function(e,t,r){return this.next(),this.takeDecorators(e),this.parseClassId(e,t,r),this.parseClassSuper(e),this.parseClassBody(e),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},z.isClassProperty=function(){return this.match(R.eq)||this.match(R.semi)||this.match(R.braceR)},z.isClassMethod=function(){return this.match(R.parenL)},z.isNonstaticConstructor=function(e){return!(e.computed||e.static||"constructor"!==e.key.name&&"constructor"!==e.key.value)},z.parseClassBody=function(e){var t=this.state.strict;this.state.strict=!0;var r=!1,n=!1,i=[],s=this.startNode();for(s.body=[],this.expect(R.braceL);!this.eat(R.braceR);)if(this.eat(R.semi))i.length>0&&this.raise(this.state.lastTokEnd,"Decorators must not be followed by a semicolon");else if(this.match(R.at))i.push(this.parseDecorator());else{var a=this.startNode();if(i.length&&(a.decorators=i,i=[]),a.static=!1,this.match(R.name)&&"static"===this.state.value){var o=this.parseIdentifier(!0);if(this.isClassMethod()){a.kind="method",a.computed=!1,a.key=o,this.parseClassMethod(s,a,!1,!1);continue}if(this.isClassProperty()){a.computed=!1,a.key=o,s.body.push(this.parseClassProperty(a));continue}a.static=!0}if(this.eat(R.star))a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be a generator"),a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.parseClassMethod(s,a,!0,!1);else{var u=this.match(R.name),l=this.parsePropertyName(a);if(a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.isClassMethod())this.isNonstaticConstructor(a)?(n?this.raise(l.start,"Duplicate constructor in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),n=!0,a.kind="constructor"):a.kind="method",this.parseClassMethod(s,a,!1,!1);else if(this.isClassProperty())this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a));else if(u&&"async"===l.name&&!this.isLineTerminator()){var c=this.hasPlugin("asyncGenerators")&&this.eat(R.star);a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be an async function"),this.parseClassMethod(s,a,c,!0)}else!u||"get"!==l.name&&"set"!==l.name||this.isLineTerminator()&&this.match(R.star)?this.hasPlugin("classConstructorCall")&&u&&"call"===l.name&&this.match(R.name)&&"constructor"===this.state.value?(r?this.raise(a.start,"Duplicate constructor call in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),r=!0,a.kind="constructorCall",this.parsePropertyName(a),this.parseClassMethod(s,a,!1,!1)):this.isLineTerminator()?(this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a))):this.unexpected():(a.kind=l.name,this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't have get/set modifier"),this.parseClassMethod(s,a,!1,!1),this.checkGetterSetterParamCount(a))}}i.length&&this.raise(this.state.start,"You have trailing decorators with no method"),e.body=this.finishNode(s,"ClassBody"),this.state.strict=t},z.parseClassProperty=function(e){return this.state.inClassProperty=!0,this.match(R.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.state.inClassProperty=!1,this.finishNode(e,"ClassProperty")},z.parseClassMethod=function(e,t,r,n){this.parseMethod(t,r,n),e.body.push(this.finishNode(t,"ClassMethod"))},z.parseClassId=function(e,t,r){this.match(R.name)?e.id=this.parseIdentifier():r||!t?e.id=null:this.unexpected()},z.parseClassSuper=function(e){e.superClass=this.eat(R._extends)?this.parseExprSubscripts():null},z.parseExport=function(e){if(this.next(),this.match(R.star)){var t=this.startNode();if(this.next(),!this.hasPlugin("exportExtensions")||!this.eatContextual("as"))return this.parseExportFrom(e,!0),this.finishNode(e,"ExportAllDeclaration");t.exported=this.parseIdentifier(),e.specifiers=[this.finishNode(t,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(e),this.parseExportFrom(e,!0)}else if(this.hasPlugin("exportExtensions")&&this.isExportDefaultSpecifier()){var r=this.startNode();if(r.exported=this.parseIdentifier(!0),e.specifiers=[this.finishNode(r,"ExportDefaultSpecifier")],this.match(R.comma)&&this.lookahead().type===R.star){this.expect(R.comma);var n=this.startNode();this.expect(R.star),this.expectContextual("as"),n.exported=this.parseIdentifier(),e.specifiers.push(this.finishNode(n,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(e);this.parseExportFrom(e,!0)}else{if(this.eat(R._default)){var i=this.startNode(),s=!1;return this.eat(R._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(R._class)?i=this.parseClass(i,!0,!0):(s=!0,i=this.parseMaybeAssign()),e.declaration=i,s&&this.semicolon(),this.checkExport(e,!0,!0),this.finishNode(e,"ExportDefaultDeclaration")}this.shouldParseExportDeclaration()?(e.specifiers=[],e.source=null,e.declaration=this.parseExportDeclaration(e)):(e.declaration=null,e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e))}return this.checkExport(e,!0),this.finishNode(e,"ExportNamedDeclaration")},z.parseExportDeclaration=function(){return this.parseStatement(!0)},z.isExportDefaultSpecifier=function(){if(this.match(R.name))return"async"!==this.state.value;if(!this.match(R._default))return!1;var e=this.lookahead();return e.type===R.comma||e.type===R.name&&"from"===e.value},z.parseExportSpecifiersMaybe=function(e){this.eat(R.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},z.parseExportFrom=function(e,t){this.eatContextual("from")?(e.source=this.match(R.string)?this.parseExprAtom():this.unexpected(),this.checkExport(e)):t?this.unexpected():e.source=null,this.semicolon()},z.shouldParseExportDeclaration=function(){return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"let"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isContextual("async")},z.checkExport=function(e,t,r){if(t)if(r)this.checkDuplicateExports(e,"default");else if(e.specifiers&&e.specifiers.length)for(var n=e.specifiers,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;this.checkDuplicateExports(o,o.exported.name)}else if(e.declaration)if("FunctionDeclaration"===e.declaration.type||"ClassDeclaration"===e.declaration.type)this.checkDuplicateExports(e,e.declaration.id.name);else if("VariableDeclaration"===e.declaration.type)for(var u=e.declaration.declarations,l=Array.isArray(u),c=0,u=l?u:u[Symbol.iterator]();;){var f;if(l){if(c>=u.length)break;f=u[c++]}else{if(c=u.next(),c.done)break;f=c.value}var p=f;this.checkDeclaration(p.id)}if(this.state.decorators.length){var d=e.declaration&&("ClassDeclaration"===e.declaration.type||"ClassExpression"===e.declaration.type);e.declaration&&d||this.raise(e.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(e.declaration)}},z.checkDeclaration=function(e){if("ObjectPattern"===e.type)for(var t=e.properties,r=Array.isArray(t),n=0,t=r?t:t[Symbol.iterator]();;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;this.checkDeclaration(s)}else if("ArrayPattern"===e.type)for(var a=e.elements,o=Array.isArray(a),u=0,a=o?a:a[Symbol.iterator]();;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;c&&this.checkDeclaration(c)}else"ObjectProperty"===e.type?this.checkDeclaration(e.value):"RestElement"===e.type||"RestProperty"===e.type?this.checkDeclaration(e.argument):"Identifier"===e.type&&this.checkDuplicateExports(e,e.name)},z.checkDuplicateExports=function(e,t){this.state.exportedIdentifiers.indexOf(t)>-1&&this.raiseDuplicateExportError(e,t),this.state.exportedIdentifiers.push(t)},z.raiseDuplicateExportError=function(e,t){this.raise(e.start,"default"===t?"Only one default export allowed per module.":"`"+t+"` has already been exported. Exported identifiers must be unique.")},z.parseExportSpecifiers=function(){var e=[],t=!0,r=void 0;for(this.expect(R.braceL);!this.eat(R.braceR);){if(t)t=!1;else if(this.expect(R.comma),this.eat(R.braceR))break;var n=this.match(R._default);n&&!r&&(r=!0);var i=this.startNode();i.local=this.parseIdentifier(n),i.exported=this.eatContextual("as")?this.parseIdentifier(!0):i.local.__clone(),e.push(this.finishNode(i,"ExportSpecifier"))}return r&&!this.isContextual("from")&&this.unexpected(),e},z.parseImport=function(e){return this.eat(R._import),this.match(R.string)?(e.specifiers=[],e.source=this.parseExprAtom()):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.match(R.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},z.parseImportSpecifiers=function(e){var t=!0;if(this.match(R.name)){var r=this.state.start,n=this.state.startLoc;if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),r,n)),!this.eat(R.comma))return}if(this.match(R.star)){var i=this.startNode();return this.next(),this.expectContextual("as"),i.local=this.parseIdentifier(),this.checkLVal(i.local,!0,void 0,"import namespace specifier"),void e.specifiers.push(this.finishNode(i,"ImportNamespaceSpecifier"))}for(this.expect(R.braceL);!this.eat(R.braceR);){if(t)t=!1;else if(this.eat(R.colon)&&this.unexpected(null,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),this.expect(R.comma),this.eat(R.braceR))break;this.parseImportSpecifier(e)}},z.parseImportSpecifier=function(e){var t=this.startNode();t.imported=this.parseIdentifier(!0),this.eatContextual("as")?t.local=this.parseIdentifier():(this.checkReservedWord(t.imported.name,t.start,!0,!0),t.local=t.imported.__clone()),this.checkLVal(t.local,!0,void 0,"import specifier"),e.specifiers.push(this.finishNode(t,"ImportSpecifier"))},z.parseImportSpecifierDefault=function(e,t,r){var n=this.startNodeAt(t,r);return n.local=e,this.checkLVal(n.local,!0,void 0,"default import specifier"),this.finishNode(n,"ImportDefaultSpecifier")};var ee=J.prototype;ee.toAssignable=function(e,t,r){if(e)switch(e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=e.properties,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;"ObjectMethod"===o.type?"get"===o.kind||"set"===o.kind?this.raise(o.key.start,"Object pattern can't contain getter or setter"):this.raise(o.key.start,"Object pattern can't contain methods"):this.toAssignable(o,t,"object destructuring pattern")}break;case"ObjectProperty":this.toAssignable(e.value,t,r);break;case"SpreadProperty":e.type="RestProperty";var u=e.argument;this.toAssignable(u,t,r);break;case"ArrayExpression":e.type="ArrayPattern",this.toAssignableList(e.elements,t,r);break;case"AssignmentExpression":"="===e.operator?(e.type="AssignmentPattern",delete e.operator):this.raise(e.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!t)break;default:var l="Invalid left-hand side"+(r?" in "+r:"expression");this.raise(e.start,l)}return e},ee.toAssignableList=function(e,t,r){var n=e.length;if(n){var i=e[n-1];if(i&&"RestElement"===i.type)--n;else if(i&&"SpreadElement"===i.type){i.type="RestElement";var s=i.argument;this.toAssignable(s,t,r),"Identifier"!==s.type&&"MemberExpression"!==s.type&&"ArrayPattern"!==s.type&&this.unexpected(s.start),--n}}for(var a=0;a=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;"ObjectProperty"===l.type&&(l=l.value),this.checkLVal(l,t,r,"object destructuring pattern")}break;case"ArrayPattern":for(var c=e.elements,f=Array.isArray(c),p=0,c=f?c:c[Symbol.iterator]();;){var d;if(f){if(p>=c.length)break;d=c[p++]}else{if(p=c.next(),p.done)break;d=p.value}var h=d;h&&this.checkLVal(h,t,r,"array destructuring pattern")}break;case"AssignmentPattern":this.checkLVal(e.left,t,r,"assignment pattern");break;case"RestProperty":this.checkLVal(e.argument,t,r,"rest property");break;case"RestElement":this.checkLVal(e.argument,t,r,"rest element");break;default:var m=(t?"Binding invalid":"Invalid")+" left-hand side"+(n?" in "+n:"expression");this.raise(e.start,m)}};var te=J.prototype;te.checkPropClash=function(e,t){if(!e.computed&&!e.kind){var r=e.key;"__proto__"===("Identifier"===r.type?r.name:String(r.value))&&(t.proto&&this.raise(r.start,"Redefinition of __proto__ property"),t.proto=!0)}},te.getExpression=function(){this.nextToken();var e=this.parseExpression();return this.match(R.eof)||this.unexpected(),e},te.parseExpression=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeAssign(e,t);if(this.match(R.comma)){var s=this.startNodeAt(r,n);for(s.expressions=[i];this.eat(R.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return i},te.parseMaybeAssign=function(e,t,r,n){var i=this.state.start,s=this.state.startLoc;if(this.match(R._yield)&&this.state.inGenerator){var a=this.parseYield();return r&&(a=r.call(this,a,i,s)),a}var o=void 0;t?o=!1:(t={start:0},o=!0),(this.match(R.parenL)||this.match(R.name))&&(this.state.potentialArrowAt=this.state.start);var u=this.parseMaybeConditional(e,t,n);if(r&&(u=r.call(this,u,i,s)),this.state.type.isAssign){var l=this.startNodeAt(i,s);if(l.operator=this.state.value,l.left=this.match(R.eq)?this.toAssignable(u,void 0,"assignment expression"):u,t.start=0,this.checkLVal(u,void 0,void 0,"assignment expression"),u.extra&&u.extra.parenthesized){var c=void 0;"ObjectPattern"===u.type?c="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===u.type&&(c="`([a]) = 0` use `([a] = 0)`"),c&&this.raise(u.start,"You're trying to assign to a parenthesized expression, eg. instead of "+c)}return this.next(),l.right=this.parseMaybeAssign(e),this.finishNode(l,"AssignmentExpression")}return o&&t.start&&this.unexpected(t.start),u},te.parseMaybeConditional=function(e,t,r){var n=this.state.start,i=this.state.startLoc,s=this.parseExprOps(e,t);return t&&t.start?s:this.parseConditional(s,e,n,i,r)},te.parseConditional=function(e,t,r,n){if(this.eat(R.question)){var i=this.startNodeAt(r,n);return i.test=e,i.consequent=this.parseMaybeAssign(),this.expect(R.colon),i.alternate=this.parseMaybeAssign(t),this.finishNode(i,"ConditionalExpression")}return e},te.parseExprOps=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeUnary(t);return t&&t.start?i:this.parseExprOp(i,r,n,-1,e)},te.parseExprOp=function(e,t,r,n,i){var s=this.state.type.binop;if(!(null==s||i&&this.match(R._in))&&s>n){var a=this.startNodeAt(t,r);a.left=e,a.operator=this.state.value,"**"!==a.operator||"UnaryExpression"!==e.type||!e.extra||e.extra.parenthesizedArgument||e.extra.parenthesized||this.raise(e.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var o=this.state.type;this.next();var u=this.state.start,l=this.state.startLoc;return a.right=this.parseExprOp(this.parseMaybeUnary(),u,l,o.rightAssociative?s-1:s,i),this.finishNode(a,o===R.logicalOR||o===R.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(a,t,r,n,i)}return e},te.parseMaybeUnary=function(e){if(this.state.type.prefix){var t=this.startNode(),r=this.match(R.incDec);t.operator=this.state.value,t.prefix=!0,this.next();var n=this.state.type;return t.argument=this.parseMaybeUnary(),this.addExtra(t,"parenthesizedArgument",!(n!==R.parenL||t.argument.extra&&t.argument.extra.parenthesized)),e&&e.start&&this.unexpected(e.start),r?this.checkLVal(t.argument,void 0,void 0,"prefix operation"):this.state.strict&&"delete"===t.operator&&"Identifier"===t.argument.type&&this.raise(t.start,"Deleting local variable in strict mode"),this.finishNode(t,r?"UpdateExpression":"UnaryExpression")}var i=this.state.start,s=this.state.startLoc,a=this.parseExprSubscripts(e);if(e&&e.start)return a;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var o=this.startNodeAt(i,s);o.operator=this.state.value,o.prefix=!1,o.argument=a,this.checkLVal(a,void 0,void 0,"postfix operation"),this.next(),a=this.finishNode(o,"UpdateExpression")}return a},te.parseExprSubscripts=function(e){var t=this.state.start,r=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprAtom(e);return"ArrowFunctionExpression"===i.type&&i.start===n?i:e&&e.start?i:this.parseSubscripts(i,t,r)},te.parseSubscripts=function(e,t,r,n){for(;;){if(!n&&this.eat(R.doubleColon)){var i=this.startNodeAt(t,r);return i.object=e,i.callee=this.parseNoCallExpr(),this.parseSubscripts(this.finishNode(i,"BindExpression"),t,r,n)}if(this.eat(R.dot)){var s=this.startNodeAt(t,r);s.object=e,s.property=this.parseIdentifier(!0),s.computed=!1,e=this.finishNode(s,"MemberExpression")}else if(this.eat(R.bracketL)){var a=this.startNodeAt(t,r);a.object=e,a.property=this.parseExpression(),a.computed=!0,this.expect(R.bracketR),e=this.finishNode(a,"MemberExpression")}else if(!n&&this.match(R.parenL)){var o=this.state.potentialArrowAt===e.start&&"Identifier"===e.type&&"async"===e.name&&!this.canInsertSemicolon();this.next();var u=this.startNodeAt(t,r);if(u.callee=e,u.arguments=this.parseCallExpressionArguments(R.parenR,o),"Import"===u.callee.type&&1!==u.arguments.length&&this.raise(u.start,"import() requires exactly one argument"),e=this.finishNode(u,"CallExpression"),o&&this.shouldParseAsyncArrow())return this.parseAsyncArrowFromCallExpression(this.startNodeAt(t,r),u);this.toReferencedList(u.arguments)}else{if(!this.match(R.backQuote))return e;var l=this.startNodeAt(t,r);l.tag=e,l.quasi=this.parseTemplate(!0),e=this.finishNode(l,"TaggedTemplateExpression")}}},te.parseCallExpressionArguments=function(e,t){for(var r=[],n=void 0,i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(R.comma),this.eat(e))break;this.match(R.parenL)&&!n&&(n=this.state.start),r.push(this.parseExprListItem(!1,t?{start:0}:void 0,t?{start:0}:void 0))}return t&&n&&this.shouldParseAsyncArrow()&&this.unexpected(),r},te.shouldParseAsyncArrow=function(){return this.match(R.arrow)},te.parseAsyncArrowFromCallExpression=function(e,t){return this.expect(R.arrow),this.parseArrowExpression(e,t.arguments,!0)},te.parseNoCallExpr=function(){var e=this.state.start,t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),e,t,!0)},te.parseExprAtom=function(e){var t=this.state.potentialArrowAt===this.state.start,r=void 0;switch(this.state.type){case R._super:return this.state.inMethod||this.state.inClassProperty||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),r=this.startNode(),this.next(),this.match(R.parenL)||this.match(R.bracketL)||this.match(R.dot)||this.unexpected(),this.match(R.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(r.start,"super() outside of class constructor"),this.finishNode(r,"Super");case R._import:return this.hasPlugin("dynamicImport")||this.unexpected(),r=this.startNode(),this.next(),this.match(R.parenL)||this.unexpected(null,R.parenL),this.finishNode(r,"Import");case R._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case R._yield:this.state.inGenerator&&this.unexpected();case R.name:r=this.startNode();var n="await"===this.state.value&&this.state.inAsync,i=this.shouldAllowYieldIdentifier(),s=this.parseIdentifier(n||i);if("await"===s.name){if(this.state.inAsync||this.inModule)return this.parseAwait(r)}else{if("async"===s.name&&this.match(R._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(r,!1,!1,!0);if(t&&"async"===s.name&&this.match(R.name)){var a=[this.parseIdentifier()];return this.expect(R.arrow),this.parseArrowExpression(r,a,!0)}}return t&&!this.canInsertSemicolon()&&this.eat(R.arrow)?this.parseArrowExpression(r,[s]):s;case R._do:if(this.hasPlugin("doExpressions")){var o=this.startNode();this.next();var u=this.state.inFunction,l=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,o.body=this.parseBlock(!1,!0),this.state.inFunction=u,this.state.labels=l,this.finishNode(o,"DoExpression")}case R.regexp:var c=this.state.value;return r=this.parseLiteral(c.value,"RegExpLiteral"),r.pattern=c.pattern,r.flags=c.flags,r;case R.num:return this.parseLiteral(this.state.value,"NumericLiteral");case R.string:return this.parseLiteral(this.state.value,"StringLiteral");case R._null:return r=this.startNode(),this.next(),this.finishNode(r,"NullLiteral");case R._true:case R._false:return r=this.startNode(),r.value=this.match(R._true),this.next(),this.finishNode(r,"BooleanLiteral");case R.parenL:return this.parseParenAndDistinguishExpression(null,null,t);case R.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(R.bracketR,!0,e),this.toReferencedList(r.elements),this.finishNode(r,"ArrayExpression");case R.braceL:return this.parseObj(!1,e);case R._function:return this.parseFunctionExpression();case R.at:this.parseDecorators();case R._class:return r=this.startNode(),this.takeDecorators(r),this.parseClass(r,!1);case R._new:return this.parseNew();case R.backQuote:return this.parseTemplate(!1);case R.doubleColon:r=this.startNode(),this.next(),r.object=null;var f=r.callee=this.parseNoCallExpr();if("MemberExpression"===f.type)return this.finishNode(r,"BindExpression");this.raise(f.start,"Binding should be performed on object property.");default:this.unexpected()}},te.parseFunctionExpression=function(){var e=this.startNode(),t=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(R.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(e,t,"sent"):this.parseFunction(e,!1)},te.parseMetaProperty=function(e,t,r){return e.meta=t,e.property=this.parseIdentifier(!0),e.property.name!==r&&this.raise(e.property.start,"The only valid meta property for new is "+t.name+"."+r),this.finishNode(e,"MetaProperty")},te.parseLiteral=function(e,t,r,n){r=r||this.state.start,n=n||this.state.startLoc;var i=this.startNodeAt(r,n);return this.addExtra(i,"rawValue",e),this.addExtra(i,"raw",this.input.slice(r,this.state.end)),i.value=e,this.next(),this.finishNode(i,t)},te.parseParenExpression=function(){this.expect(R.parenL);var e=this.parseExpression();return this.expect(R.parenR),e},te.parseParenAndDistinguishExpression=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;var n=void 0;this.expect(R.parenL);for(var i=this.state.start,s=this.state.startLoc,a=[],o={start:0},u={start:0},l=!0,c=void 0,f=void 0;!this.match(R.parenR);){if(l)l=!1;else if(this.expect(R.comma,u.start||null),this.match(R.parenR)){f=this.state.start;break} -if(this.match(R.ellipsis)){var p=this.state.start,d=this.state.startLoc;c=this.state.start,a.push(this.parseParenItem(this.parseRest(),p,d));break}a.push(this.parseMaybeAssign(!1,o,this.parseParenItem,u))}var h=this.state.start,m=this.state.startLoc;this.expect(R.parenR);var y=this.startNodeAt(e,t);if(r&&this.shouldParseArrow()&&(y=this.parseArrow(y))){for(var v=a,g=Array.isArray(v),b=0,v=g?v:v[Symbol.iterator]();;){var E;if(g){if(b>=v.length)break;E=v[b++]}else{if(b=v.next(),b.done)break;E=b.value}var x=E;x.extra&&x.extra.parenthesized&&this.unexpected(x.extra.parenStart)}return this.parseArrowExpression(y,a)}return a.length||this.unexpected(this.state.lastTokStart),f&&this.unexpected(f),c&&this.unexpected(c),o.start&&this.unexpected(o.start),u.start&&this.unexpected(u.start),a.length>1?(n=this.startNodeAt(i,s),n.expressions=a,this.toReferencedList(n.expressions),this.finishNodeAt(n,"SequenceExpression",h,m)):n=a[0],this.addExtra(n,"parenthesized",!0),this.addExtra(n,"parenStart",e),n},te.shouldParseArrow=function(){return!this.canInsertSemicolon()},te.parseArrow=function(e){if(this.eat(R.arrow))return e},te.parseParenItem=function(e){return e},te.parseNew=function(){var e=this.startNode(),t=this.parseIdentifier(!0);if(this.eat(R.dot)){var r=this.parseMetaProperty(e,t,"target");return this.state.inFunction||this.raise(r.property.start,"new.target can only be used in functions"),r}return e.callee=this.parseNoCallExpr(),this.eat(R.parenL)?(e.arguments=this.parseExprList(R.parenR),this.toReferencedList(e.arguments)):e.arguments=[],this.finishNode(e,"NewExpression")},te.parseTemplateElement=function(e){var t=this.startNode();return null===this.state.value&&(e&&this.hasPlugin("templateInvalidEscapes")?this.state.invalidTemplateEscapePosition=null:this.raise(this.state.invalidTemplateEscapePosition,"Invalid escape sequence in template")),t.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),t.tail=this.match(R.backQuote),this.finishNode(t,"TemplateElement")},te.parseTemplate=function(e){var t=this.startNode();this.next(),t.expressions=[];var r=this.parseTemplateElement(e);for(t.quasis=[r];!r.tail;)this.expect(R.dollarBraceL),t.expressions.push(this.parseExpression()),this.expect(R.braceR),t.quasis.push(r=this.parseTemplateElement(e));return this.next(),this.finishNode(t,"TemplateLiteral")},te.parseObj=function(e,t){var r=[],n=Object.create(null),i=!0,s=this.startNode();s.properties=[],this.next();for(var a=null;!this.eat(R.braceR);){if(i)i=!1;else if(this.expect(R.comma),this.eat(R.braceR))break;for(;this.match(R.at);)r.push(this.parseDecorator());var o=this.startNode(),u=!1,l=!1,c=void 0,f=void 0;if(r.length&&(o.decorators=r,r=[]),this.hasPlugin("objectRestSpread")&&this.match(R.ellipsis)){if(o=this.parseSpread(e?{start:0}:void 0),o.type=e?"RestProperty":"SpreadProperty",e&&this.toAssignable(o.argument,!0,"object pattern"),s.properties.push(o),!e)continue;var p=this.state.start;if(null===a){if(this.eat(R.braceR))break;if(this.match(R.comma)&&this.lookahead().type===R.braceR)continue;a=p;continue}this.unexpected(a,"Cannot have multiple rest elements when destructuring")}if(o.method=!1,o.shorthand=!1,(e||t)&&(c=this.state.start,f=this.state.startLoc),e||(u=this.eat(R.star)),!e&&this.isContextual("async")){u&&this.unexpected();var d=this.parseIdentifier();this.match(R.colon)||this.match(R.parenL)||this.match(R.braceR)||this.match(R.eq)||this.match(R.comma)?(o.key=d,o.computed=!1):(l=!0,this.hasPlugin("asyncGenerators")&&(u=this.eat(R.star)),this.parsePropertyName(o))}else this.parsePropertyName(o);this.parseObjPropValue(o,c,f,u,l,e,t),this.checkPropClash(o,n),o.shorthand&&this.addExtra(o,"shorthand",!0),s.properties.push(o)}return null!==a&&this.unexpected(a,"The rest element has to be the last element when destructuring"),r.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},te.isGetterOrSetterMethod=function(e,t){return!t&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&(this.match(R.string)||this.match(R.num)||this.match(R.bracketL)||this.match(R.name)||this.state.type.keyword)},te.checkGetterSetterParamCount=function(e){var t="get"===e.kind?0:1;if(e.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}},te.parseObjectMethod=function(e,t,r,n){return r||t||this.match(R.parenL)?(n&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,t,r),this.finishNode(e,"ObjectMethod")):this.isGetterOrSetterMethod(e,n)?((t||r)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),this.parseMethod(e),this.checkGetterSetterParamCount(e),this.finishNode(e,"ObjectMethod")):void 0},te.parseObjectProperty=function(e,t,r,n,i){return this.eat(R.colon)?(e.value=n?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,i),this.finishNode(e,"ObjectProperty")):e.computed||"Identifier"!==e.key.type?void 0:(this.checkReservedWord(e.key.name,e.key.start,!0,!0),n?e.value=this.parseMaybeDefault(t,r,e.key.__clone()):this.match(R.eq)&&i?(i.start||(i.start=this.state.start),e.value=this.parseMaybeDefault(t,r,e.key.__clone())):e.value=e.key.__clone(),e.shorthand=!0,this.finishNode(e,"ObjectProperty"))},te.parseObjPropValue=function(e,t,r,n,i,s,a){var o=this.parseObjectMethod(e,n,i,s)||this.parseObjectProperty(e,t,r,s,a);return o||this.unexpected(),o},te.parsePropertyName=function(e){if(this.eat(R.bracketL))e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(R.bracketR);else{e.computed=!1;var t=this.state.inPropertyName;this.state.inPropertyName=!0,e.key=this.match(R.num)||this.match(R.string)?this.parseExprAtom():this.parseIdentifier(!0),this.state.inPropertyName=t}return e.key},te.initFunction=function(e,t){e.id=null,e.generator=!1,e.expression=!1,e.async=!!t},te.parseMethod=function(e,t,r){var n=this.state.inMethod;return this.state.inMethod=e.kind||!0,this.initFunction(e,r),this.expect(R.parenL),e.params=this.parseBindingList(R.parenR),e.generator=!!t,this.parseFunctionBody(e),this.state.inMethod=n,e},te.parseArrowExpression=function(e,t,r){return this.initFunction(e,r),e.params=this.toAssignableList(t,!0,"arrow function parameters"),this.parseFunctionBody(e,!0),this.finishNode(e,"ArrowFunctionExpression")},te.isStrictBody=function(e,t){if(!t&&e.body.directives.length)for(var r=e.body.directives,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if("use strict"===a.value.value)return!0}return!1},te.parseFunctionBody=function(e,t){var r=t&&!this.match(R.braceL),n=this.state.inAsync;if(this.state.inAsync=e.async,r)e.body=this.parseMaybeAssign(),e.expression=!0;else{var i=this.state.inFunction,s=this.state.inGenerator,a=this.state.labels;this.state.inFunction=!0,this.state.inGenerator=e.generator,this.state.labels=[],e.body=this.parseBlock(!0),e.expression=!1,this.state.inFunction=i,this.state.inGenerator=s,this.state.labels=a}this.state.inAsync=n;var o=this.isStrictBody(e,r),u=this.state.strict||t||o;if(o&&e.id&&"Identifier"===e.id.type&&"yield"===e.id.name&&this.raise(e.id.start,"Binding yield in strict mode"),u){var l=Object.create(null),c=this.state.strict;o&&(this.state.strict=!0),e.id&&this.checkLVal(e.id,!0,void 0,"function name");for(var f=e.params,p=Array.isArray(f),d=0,f=p?f:f[Symbol.iterator]();;){var h;if(p){if(d>=f.length)break;h=f[d++]}else{if(d=f.next(),d.done)break;h=d.value}var m=h;o&&"Identifier"!==m.type&&this.raise(m.start,"Non-simple parameter in strict mode"),this.checkLVal(m,!0,l,"function parameter list")}this.state.strict=c}},te.parseExprList=function(e,t,r){for(var n=[],i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(R.comma),this.eat(e))break;n.push(this.parseExprListItem(t,r))}return n},te.parseExprListItem=function(e,t,r){return e&&this.match(R.comma)?null:this.match(R.ellipsis)?this.parseSpread(t):this.parseMaybeAssign(!1,t,this.parseParenItem,r)},te.parseIdentifier=function(e){var t=this.startNode();return e||this.checkReservedWord(this.state.value,this.state.start,!!this.state.type.keyword,!1),this.match(R.name)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),!e&&"await"===t.name&&this.state.inAsync&&this.raise(t.start,"invalid use of await inside of an async function"),t.loc.identifierName=t.name,this.next(),this.finishNode(t,"Identifier")},te.checkReservedWord=function(e,t,r,n){(this.isReservedWord(e)||r&&this.isKeyword(e))&&this.raise(t,e+" is a reserved word"),this.state.strict&&(v.strict(e)||n&&v.strictBind(e))&&this.raise(t,e+" is a reserved word in strict mode")},te.parseAwait=function(e){return this.state.inAsync||this.unexpected(),this.match(R.star)&&this.raise(e.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),e.argument=this.parseMaybeUnary(),this.finishNode(e,"AwaitExpression")},te.parseYield=function(){var e=this.startNode();return this.next(),this.match(R.semi)||this.canInsertSemicolon()||!this.match(R.star)&&!this.state.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(R.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")};var re=J.prototype,ne=["leadingComments","trailingComments","innerComments"],ie=function(){function e(t,r,n){w(this,e),this.type="",this.start=t,this.end=0,this.loc=new G(r),n&&(this.loc.filename=n)}return e.prototype.__clone=function(){var t=new e;for(var r in this)ne.indexOf(r)<0&&(t[r]=this[r]);return t},e}();re.startNode=function(){return new ie(this.state.start,this.state.startLoc,this.filename)},re.startNodeAt=function(e,t){return new ie(e,t,this.filename)},re.finishNode=function(e,t){return c.call(this,e,t,this.state.lastTokEnd,this.state.lastTokEndLoc)},re.finishNodeAt=function(e,t,r,n){return c.call(this,e,t,r,n)},J.prototype.raise=function(e,t){var r=u(this.input,e);t+=" ("+r.line+":"+r.column+")";var n=new SyntaxError(t);throw n.pos=e,n.loc=r,n};var se=J.prototype;se.addComment=function(e){this.filename&&(e.loc.filename=this.filename),this.state.trailingComments.push(e),this.state.leadingComments.push(e)},se.processComment=function(e){if(!("Program"===e.type&&e.body.length>0)){var t=this.state.commentStack,r=void 0,n=void 0,i=void 0,s=void 0,a=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=e.end?(i=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var o=f(t);t.length>0&&o.trailingComments&&o.trailingComments[0].start>=e.end&&(i=o.trailingComments,o.trailingComments=null)}for(t.length>0&&f(t).start>=e.start&&(r=t.pop());t.length>0&&f(t).start>=e.start;)n=t.pop();if(!n&&r&&(n=r),r&&this.state.leadingComments.length>0){var u=f(this.state.leadingComments);if("ObjectProperty"===r.type){if(u.start>=e.start&&this.state.commentPreviousNode){for(a=0;a0&&(r.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}else if("CallExpression"===e.type&&e.arguments&&e.arguments.length){var l=f(e.arguments);l&&u.start>=l.start&&u.end<=e.end&&this.state.commentPreviousNode&&this.state.leadingComments.length>0&&(l.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}if(n){if(n.leadingComments)if(n!==e&&f(n.leadingComments).end<=e.start)e.leadingComments=n.leadingComments,n.leadingComments=null;else for(s=n.leadingComments.length-2;s>=0;--s)if(n.leadingComments[s].end<=e.start){e.leadingComments=n.leadingComments.splice(0,s+1);break}}else if(this.state.leadingComments.length>0)if(f(this.state.leadingComments).end<=e.start){if(this.state.commentPreviousNode)for(a=0;a0&&(e.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(s=0;se.start);s++);e.leadingComments=this.state.leadingComments.slice(0,s),0===e.leadingComments.length&&(e.leadingComments=null),i=this.state.leadingComments.slice(s),0===i.length&&(i=null)}this.state.commentPreviousNode=e,i&&(i.length&&i[0].start>=e.start&&f(i).end<=e.end?e.innerComments=i:e.trailingComments=i),t.push(e)}};var ae=J.prototype;ae.estreeParseRegExpLiteral=function(e){var t=e.pattern,r=e.flags,n=null;try{n=new RegExp(t,r)}catch(e){}var i=this.estreeParseLiteral(n);return i.regex={pattern:t,flags:r},i},ae.estreeParseLiteral=function(e){return this.parseLiteral(e,"Literal")},ae.directiveToStmt=function(e){var t=e.value,r=this.startNodeAt(e.start,e.loc.start),n=this.startNodeAt(t.start,t.loc.start);return n.value=t.value,n.raw=t.extra.raw,r.expression=this.finishNodeAt(n,"Literal",t.end,t.loc.end),r.directive=t.extra.raw.slice(1,-1),this.finishNodeAt(r,"ExpressionStatement",e.end,e.loc.end)};var oe=function(e){e.extend("checkDeclaration",function(e){return function(t){p(t)?this.checkDeclaration(t.value):e.call(this,t)}}),e.extend("checkGetterSetterParamCount",function(){return function(e){var t="get"===e.kind?0:1;if(e.value.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}}}),e.extend("checkLVal",function(e){return function(t,r,n){var i=this;switch(t.type){case"ObjectPattern":t.properties.forEach(function(e){i.checkLVal("Property"===e.type?e.value:e,r,n,"object destructuring pattern")});break;default:for(var s=arguments.length,a=Array(s>3?s-3:0),o=3;o0)for(var r=e.body.body,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if("ExpressionStatement"!==a.type||"Literal"!==a.expression.type)break;if("use strict"===a.expression.value)return!0}return!1}}),e.extend("isValidDirective",function(){return function(e){return!("ExpressionStatement"!==e.type||"Literal"!==e.expression.type||"string"!=typeof e.expression.value||e.expression.extra&&e.expression.extra.parenthesized)}}),e.extend("stmtToDirective",function(e){return function(t){var r=e.call(this,t),n=t.expression.value;return r.value.value=n,r}}),e.extend("parseBlockBody",function(e){return function(t){for(var r=this,n=arguments.length,i=Array(n>1?n-1:0),s=1;s1?n-1:0),s=1;s2?n-2:0),s=2;s=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;"get"===c.kind||"set"===c.kind?this.raise(c.key.start,"Object pattern can't contain getter or setter"):c.method?this.raise(c.key.start,"Object pattern can't contain methods"):this.toAssignable(c,r,"object destructuring pattern")}return t}return e.call.apply(e,[this,t,r].concat(i))}})},ue=["any","mixed","empty","bool","boolean","number","string","void","null"],le=J.prototype;le.flowParseTypeInitialiser=function(e){var t=this.state.inType;this.state.inType=!0,this.expect(e||R.colon);var r=this.flowParseType();return this.state.inType=t,r},le.flowParsePredicate=function(){var e=this.startNode(),t=this.state.startLoc,r=this.state.start;this.expect(R.modulo);var n=this.state.startLoc;return this.expectContextual("checks"),t.line===n.line&&t.column===n.column-1||this.raise(r,"Spaces between ´%´ and ´checks´ are not allowed here."),this.eat(R.parenL)?(e.expression=this.parseExpression(),this.expect(R.parenR),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")},le.flowParseTypeAndPredicateInitialiser=function(){var e=this.state.inType;this.state.inType=!0,this.expect(R.colon);var t=null,r=null;return this.match(R.modulo)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(R.modulo)&&(r=this.flowParsePredicate())),[t,r]},le.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},le.flowParseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdentifier(),r=this.startNode(),n=this.startNode();this.isRelational("<")?r.typeParameters=this.flowParseTypeParameterDeclaration():r.typeParameters=null,this.expect(R.parenL);var i=this.flowParseFunctionTypeParams();r.params=i.params,r.rest=i.rest,this.expect(R.parenR);var s=null,a=this.flowParseTypeAndPredicateInitialiser();return r.returnType=a[0],s=a[1],n.typeAnnotation=this.finishNode(r,"FunctionTypeAnnotation"),n.predicate=s,t.typeAnnotation=this.finishNode(n,"TypeAnnotation"),this.finishNode(t,t.type),this.semicolon(),this.finishNode(e,"DeclareFunction")},le.flowParseDeclare=function(e){return this.match(R._class)?this.flowParseDeclareClass(e):this.match(R._function)?this.flowParseDeclareFunction(e):this.match(R._var)?this.flowParseDeclareVariable(e):this.isContextual("module")?this.lookahead().type===R.dot?this.flowParseDeclareModuleExports(e):this.flowParseDeclareModule(e):this.isContextual("type")?this.flowParseDeclareTypeAlias(e):this.isContextual("opaque")?this.flowParseDeclareOpaqueType(e):this.isContextual("interface")?this.flowParseDeclareInterface(e):this.match(R._export)?this.flowParseDeclareExportDeclaration(e):void this.unexpected()},le.flowParseDeclareExportDeclaration=function(e){if(this.expect(R._export),this.isContextual("opaque"))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");throw this.unexpected()},le.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},le.flowParseDeclareModule=function(e){this.next(),this.match(R.string)?e.id=this.parseExprAtom():e.id=this.parseIdentifier();var t=e.body=this.startNode(),r=t.body=[];for(this.expect(R.braceL);!this.match(R.braceR);){var n=this.startNode();if(this.match(R._import)){var i=this.lookahead();"type"!==i.value&&"typeof"!==i.value&&this.unexpected(null,"Imports within a `declare module` body must always be `import type` or `import typeof`"),this.parseImport(n)}else this.expectContextual("declare","Only declares and type imports are allowed inside declare module"),n=this.flowParseDeclare(n,!0);r.push(n)}return this.expect(R.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},le.flowParseDeclareModuleExports=function(e){return this.expectContextual("module"),this.expect(R.dot),this.expectContextual("exports"),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},le.flowParseDeclareTypeAlias=function(e){return this.next(),this.flowParseTypeAlias(e),this.finishNode(e,"DeclareTypeAlias")},le.flowParseDeclareOpaqueType=function(e){return this.next(),this.flowParseOpaqueType(e,!0),this.finishNode(e,"DeclareOpaqueType")},le.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e),this.finishNode(e,"DeclareInterface")},le.flowParseInterfaceish=function(e){if(e.id=this.parseIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],e.mixins=[],this.eat(R._extends))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(R.comma));if(this.isContextual("mixins")){this.next();do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(R.comma))}e.body=this.flowParseObjectType(!0,!1,!1)},le.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},le.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},le.flowParseRestrictedIdentifier=function(e){return ue.indexOf(this.state.value)>-1&&this.raise(this.state.start,"Cannot overwrite primitive type "+this.state.value),this.parseIdentifier(e)},le.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(R.eq),this.semicolon(),this.finishNode(e,"TypeAlias")},le.flowParseOpaqueType=function(e,t){return this.expectContextual("type"),e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(R.colon)&&(e.supertype=this.flowParseTypeInitialiser(R.colon)),e.impltype=null,t||(e.impltype=this.flowParseTypeInitialiser(R.eq)),this.semicolon(),this.finishNode(e,"OpaqueType")},le.flowParseTypeParameter=function(){var e=this.startNode(),t=this.flowParseVariance(),r=this.flowParseTypeAnnotatableIdentifier();return e.name=r.name,e.variance=t,e.bound=r.typeAnnotation,this.match(R.eq)&&(this.eat(R.eq),e.default=this.flowParseType()),this.finishNode(e,"TypeParameter")},le.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.isRelational("<")||this.match(R.jsxTagStart)?this.next():this.unexpected();do{t.params.push(this.flowParseTypeParameter()),this.isRelational(">")||this.expect(R.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")},le.flowParseTypeParameterInstantiation=function(){var e=this.startNode(),t=this.state.inType;for(e.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flowParseType()),this.isRelational(">")||this.expect(R.comma);return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")},le.flowParseObjectPropertyKey=function(){return this.match(R.num)||this.match(R.string)?this.parseExprAtom():this.parseIdentifier(!0)},le.flowParseObjectTypeIndexer=function(e,t,r){return e.static=t,this.expect(R.bracketL),this.lookahead().type===R.colon?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(R.bracketR),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},le.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(R.parenL);!this.match(R.parenR)&&!this.match(R.ellipsis);)e.params.push(this.flowParseFunctionTypeParam()),this.match(R.parenR)||this.expect(R.comma);return this.eat(R.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),this.expect(R.parenR),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},le.flowParseObjectTypeMethod=function(e,t,r,n){var i=this.startNodeAt(e,t);return i.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e,t)),i.static=r,i.key=n,i.optional=!1,this.flowObjectTypeSemicolon(),this.finishNode(i,"ObjectTypeProperty")},le.flowParseObjectTypeCallProperty=function(e,t){var r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeCallProperty")},le.flowParseObjectType=function(e,t,r){var n=this.state.inType;this.state.inType=!0;var i=this.startNode(),s=void 0,a=void 0,o=!1;i.callProperties=[],i.properties=[],i.indexers=[];var u=void 0,l=void 0;for(t&&this.match(R.braceBarL)?(this.expect(R.braceBarL),u=R.braceBarR,l=!0):(this.expect(R.braceL),u=R.braceR,l=!1),i.exact=l;!this.match(u);){var c=!1,f=this.state.start,p=this.state.startLoc;s=this.startNode(),e&&this.isContextual("static")&&this.lookahead().type!==R.colon&&(this.next(),o=!0);var d=this.state.start,h=this.flowParseVariance();this.match(R.bracketL)?i.indexers.push(this.flowParseObjectTypeIndexer(s,o,h)):this.match(R.parenL)||this.isRelational("<")?(h&&this.unexpected(d),i.callProperties.push(this.flowParseObjectTypeCallProperty(s,o))):this.match(R.ellipsis)?(r||this.unexpected(null,"Spread operator cannot appear in class or interface definitions"),h&&this.unexpected(h.start,"Spread properties cannot have variance"),this.expect(R.ellipsis),s.argument=this.flowParseType(),this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeSpreadProperty"))):(a=this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(R.parenL)?(h&&this.unexpected(h.start),i.properties.push(this.flowParseObjectTypeMethod(f,p,o,a))):(this.eat(R.question)&&(c=!0),s.key=a,s.value=this.flowParseTypeInitialiser(),s.optional=c,s.static=o,s.variance=h,this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeProperty")))),o=!1}this.expect(u);var m=this.finishNode(i,"ObjectTypeAnnotation");return this.state.inType=n,m},le.flowObjectTypeSemicolon=function(){this.eat(R.semi)||this.eat(R.comma)||this.match(R.braceR)||this.match(R.braceBarR)||this.unexpected()},le.flowParseQualifiedTypeIdentifier=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;for(var n=r||this.parseIdentifier();this.eat(R.dot);){var i=this.startNodeAt(e,t);i.qualification=n,i.id=this.parseIdentifier(),n=this.finishNode(i,"QualifiedTypeIdentifier")}return n},le.flowParseGenericType=function(e,t,r){var n=this.startNodeAt(e,t);return n.typeParameters=null,n.id=this.flowParseQualifiedTypeIdentifier(e,t,r),this.isRelational("<")&&(n.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},le.flowParseTypeofType=function(){var e=this.startNode();return this.expect(R._typeof),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},le.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(R.bracketL);this.state.pos0&&void 0!==arguments[0]?arguments[0]:[],t={params:e,rest:null};!this.match(R.parenR)&&!this.match(R.ellipsis);)t.params.push(this.flowParseFunctionTypeParam()),this.match(R.parenR)||this.expect(R.comma);return this.eat(R.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),t},le.flowIdentToTypeAnnotation=function(e,t,r,n){switch(n.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"void":return this.finishNode(r,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");default:return this.flowParseGenericType(e,t,n)}},le.flowParsePrimaryType=function(){var e=this.state.start,t=this.state.startLoc,r=this.startNode(),n=void 0,i=void 0,s=!1,a=this.state.noAnonFunctionType;switch(this.state.type){case R.name:return this.flowIdentToTypeAnnotation(e,t,r,this.parseIdentifier());case R.braceL:return this.flowParseObjectType(!1,!1,!0);case R.braceBarL:return this.flowParseObjectType(!1,!0,!0);case R.bracketL:return this.flowParseTupleType();case R.relational:if("<"===this.state.value)return r.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(R.parenL),n=this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(R.parenR),this.expect(R.arrow),r.returnType=this.flowParseType(),this.finishNode(r,"FunctionTypeAnnotation");break;case R.parenL:if(this.next(),!this.match(R.parenR)&&!this.match(R.ellipsis))if(this.match(R.name)){var o=this.lookahead().type;s=o!==R.question&&o!==R.colon}else s=!0;if(s){if(this.state.noAnonFunctionType=!1,i=this.flowParseType(),this.state.noAnonFunctionType=a,this.state.noAnonFunctionType||!(this.match(R.comma)||this.match(R.parenR)&&this.lookahead().type===R.arrow))return this.expect(R.parenR),i;this.eat(R.comma)}return n=i?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(R.parenR),this.expect(R.arrow),r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation");case R.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case R._true:case R._false:return r.value=this.match(R._true),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case R.plusMin:if("-"===this.state.value)return this.next(), -this.match(R.num)||this.unexpected(null,"Unexpected token, expected number"),this.parseLiteral(-this.state.value,"NumericLiteralTypeAnnotation",r.start,r.loc.start);this.unexpected();case R.num:return this.parseLiteral(this.state.value,"NumericLiteralTypeAnnotation");case R._null:return r.value=this.match(R._null),this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case R._this:return r.value=this.match(R._this),this.next(),this.finishNode(r,"ThisTypeAnnotation");case R.star:return this.next(),this.finishNode(r,"ExistentialTypeParam");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},le.flowParsePostfixType=function(){for(var e=this.state.start,t=this.state.startLoc,r=this.flowParsePrimaryType();!this.canInsertSemicolon()&&this.match(R.bracketL);){var n=this.startNodeAt(e,t);n.elementType=r,this.expect(R.bracketL),this.expect(R.bracketR),r=this.finishNode(n,"ArrayTypeAnnotation")}return r},le.flowParsePrefixType=function(){var e=this.startNode();return this.eat(R.question)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()},le.flowParseAnonFunctionWithoutParens=function(){var e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(R.arrow)){var t=this.startNodeAt(e.start,e.loc.start);return t.params=[this.reinterpretTypeAsFunctionTypeParam(e)],t.rest=null,t.returnType=this.flowParseType(),t.typeParameters=null,this.finishNode(t,"FunctionTypeAnnotation")}return e},le.flowParseIntersectionType=function(){var e=this.startNode();this.eat(R.bitwiseAND);var t=this.flowParseAnonFunctionWithoutParens();for(e.types=[t];this.eat(R.bitwiseAND);)e.types.push(this.flowParseAnonFunctionWithoutParens());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},le.flowParseUnionType=function(){var e=this.startNode();this.eat(R.bitwiseOR);var t=this.flowParseIntersectionType();for(e.types=[t];this.eat(R.bitwiseOR);)e.types.push(this.flowParseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},le.flowParseType=function(){var e=this.state.inType;this.state.inType=!0;var t=this.flowParseUnionType();return this.state.inType=e,t},le.flowParseTypeAnnotation=function(){var e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")},le.flowParseTypeAndPredicateAnnotation=function(){var e=this.startNode(),t=this.flowParseTypeAndPredicateInitialiser();return e.typeAnnotation=t[0],e.predicate=t[1],this.finishNode(e,"TypeAnnotation")},le.flowParseTypeAnnotatableIdentifier=function(){var e=this.flowParseRestrictedIdentifier();return this.match(R.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,e.type)),e},le.typeCastToParameter=function(e){return e.expression.typeAnnotation=e.typeAnnotation,this.finishNodeAt(e.expression,e.expression.type,e.typeAnnotation.end,e.typeAnnotation.loc.end)},le.flowParseVariance=function(){var e=null;return this.match(R.plusMin)&&("+"===this.state.value?e="plus":"-"===this.state.value&&(e="minus"),this.next()),e};var ce=function(e){e.extend("parseFunctionBody",function(e){return function(t,r){return this.match(R.colon)&&!r&&(t.returnType=this.flowParseTypeAndPredicateAnnotation()),e.call(this,t,r)}}),e.extend("parseStatement",function(e){return function(t,r){if(this.state.strict&&this.match(R.name)&&"interface"===this.state.value){var n=this.startNode();return this.next(),this.flowParseInterface(n)}return e.call(this,t,r)}}),e.extend("parseExpressionStatement",function(e){return function(t,r){if("Identifier"===r.type)if("declare"===r.name){if(this.match(R._class)||this.match(R.name)||this.match(R._function)||this.match(R._var)||this.match(R._export))return this.flowParseDeclare(t)}else if(this.match(R.name)){if("interface"===r.name)return this.flowParseInterface(t);if("type"===r.name)return this.flowParseTypeAlias(t);if("opaque"===r.name)return this.flowParseOpaqueType(t,!1)}return e.call(this,t,r)}}),e.extend("shouldParseExportDeclaration",function(e){return function(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||e.call(this)}}),e.extend("isExportDefaultSpecifier",function(e){return function(){return(!this.match(R.name)||"type"!==this.state.value&&"interface"!==this.state.value&&"opaque"!==this.state.value)&&e.call(this)}}),e.extend("parseConditional",function(e){return function(t,r,n,i,s){if(s&&this.match(R.question)){var a=this.state.clone();try{return e.call(this,t,r,n,i)}catch(e){if(e instanceof SyntaxError)return this.state=a,s.start=e.pos||this.state.start,t;throw e}}return e.call(this,t,r,n,i)}}),e.extend("parseParenItem",function(e){return function(t,r,n){if(t=e.call(this,t,r,n),this.eat(R.question)&&(t.optional=!0),this.match(R.colon)){var i=this.startNodeAt(r,n);return i.expression=t,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return t}}),e.extend("parseExport",function(e){return function(t){return t=e.call(this,t),"ExportNamedDeclaration"===t.type&&(t.exportKind=t.exportKind||"value"),t}}),e.extend("parseExportDeclaration",function(e){return function(t){if(this.isContextual("type")){t.exportKind="type";var r=this.startNode();return this.next(),this.match(R.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(r)}if(this.isContextual("opaque")){t.exportKind="type";var n=this.startNode();return this.next(),this.flowParseOpaqueType(n,!1)}if(this.isContextual("interface")){t.exportKind="type";var i=this.startNode();return this.next(),this.flowParseInterface(i)}return e.call(this,t)}}),e.extend("parseClassId",function(e){return function(t){e.apply(this,arguments),this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration())}}),e.extend("isKeyword",function(e){return function(t){return(!this.state.inType||"void"!==t)&&e.call(this,t)}}),e.extend("readToken",function(e){return function(t){return!this.state.inType||62!==t&&60!==t?e.call(this,t):this.finishOp(R.relational,1)}}),e.extend("jsx_readToken",function(e){return function(){if(!this.state.inType)return e.call(this)}}),e.extend("toAssignable",function(e){return function(t,r,n){return"TypeCastExpression"===t.type?e.call(this,this.typeCastToParameter(t),r,n):e.call(this,t,r,n)}}),e.extend("toAssignableList",function(e){return function(t,r,n){for(var i=0;i2?n-2:0),s=2;s1114111||de(a)!=a)throw RangeError("Invalid code point: "+a);a<=65535?e.push(a):(a-=65536,t=55296+(a>>10),r=a%1024+56320,e.push(t,r)),(n+1==i||e.length>16384)&&(s+=pe.apply(null,e),e.length=0)}return s}}var he=fe,me={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},ye=/^[\da-fA-F]+$/,ve=/^\d+$/;U.j_oTag=new j("...",!0,!0),R.jsxName=new T("jsxName"),R.jsxText=new T("jsxText",{beforeExpr:!0}),R.jsxTagStart=new T("jsxTagStart",{startsExpr:!0}),R.jsxTagEnd=new T("jsxTagEnd"),R.jsxTagStart.updateContext=function(){this.state.context.push(U.j_expr),this.state.context.push(U.j_oTag),this.state.exprAllowed=!1},R.jsxTagEnd.updateContext=function(e){var t=this.state.context.pop();t===U.j_oTag&&e===R.slash||t===U.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===U.j_expr):this.state.exprAllowed=!0};var ge=J.prototype;ge.jsxReadToken=function(){for(var e="",t=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var r=this.input.charCodeAt(this.state.pos);switch(r){case 60:case 123:return this.state.pos===this.state.start?60===r&&this.state.exprAllowed?(++this.state.pos,this.finishToken(R.jsxTagStart)):this.getTokenFromCode(r):(e+=this.input.slice(t,this.state.pos),this.finishToken(R.jsxText,e));case 38:e+=this.input.slice(t,this.state.pos),e+=this.jsxReadEntity(),t=this.state.pos;break;default:o(r)?(e+=this.input.slice(t,this.state.pos),e+=this.jsxReadNewLine(!0),t=this.state.pos):++this.state.pos}}},ge.jsxReadNewLine=function(e){var t=this.input.charCodeAt(this.state.pos),r=void 0;return++this.state.pos,13===t&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,r=e?"\n":"\r\n"):r=String.fromCharCode(t),++this.state.curLine,this.state.lineStart=this.state.pos,r},ge.jsxReadString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;38===n?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos):o(n)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!1),r=this.state.pos):++this.state.pos}return t+=this.input.slice(r,this.state.pos++),this.finishToken(R.string,t)},ge.jsxReadEntity=function(){for(var e="",t=0,r=void 0,n=this.input[this.state.pos],i=++this.state.pos;this.state.pos")}return r.openingElement=i,r.closingElement=s,r.children=n,this.match(R.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(r,"JSXElement")},ge.jsxParseElement=function(){var e=this.state.start,t=this.state.startLoc;return this.next(),this.jsxParseElementAt(e,t)};var be=function(e){e.extend("parseExprAtom",function(e){return function(t){if(this.match(R.jsxText)){var r=this.parseLiteral(this.state.value,"JSXText");return r.extra=null,r}return this.match(R.jsxTagStart)?this.jsxParseElement():e.call(this,t)}}),e.extend("readToken",function(e){return function(t){if(this.state.inPropertyName)return e.call(this,t);var r=this.curContext();if(r===U.j_expr)return this.jsxReadToken();if(r===U.j_oTag||r===U.j_cTag){if(i(t))return this.jsxReadWord();if(62===t)return++this.state.pos,this.finishToken(R.jsxTagEnd);if((34===t||39===t)&&r===U.j_oTag)return this.jsxReadString(t)}return 60===t&&this.state.exprAllowed?(++this.state.pos,this.finishToken(R.jsxTagStart)):e.call(this,t)}}),e.extend("updateContext",function(e){return function(t){if(this.match(R.braceL)){var r=this.curContext();r===U.j_oTag?this.state.context.push(U.braceExpression):r===U.j_expr?this.state.context.push(U.templateQuasi):e.call(this,t),this.state.exprAllowed=!0}else{if(!this.match(R.slash)||t!==R.jsxTagStart)return e.call(this,t);this.state.context.length-=2,this.state.context.push(U.j_cTag),this.state.exprAllowed=!1}}})};K.estree=oe,K.flow=ce,K.jsx=be,t.parse=h,t.parseExpression=m,t.tokTypes=R},function(e,t,r){"use strict";var n=r(21),i=r(431),s=r(141),a=r(150)("IE_PROTO"),o=function(){},u=function(){var e,t=r(230)("iframe"),n=s.length;for(t.style.display="none",r(426).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("