Skip to content

Commit 34d0110

Browse files
authored
chore: make globalSourceMapContext local on the VM such that multiple VMs can run in parallel (#12)
1 parent aa9a43a commit 34d0110

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

internal/vm/vm.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,10 @@ var (
2828

2929
var lineNumberRegex = regexp.MustCompile(` \(*([^ ]+):([0-9]+):([0-9]+)\([0-9]+\)`)
3030

31-
var globalSourceMapCache = map[string]*sourcemap.Consumer{}
32-
3331
// VM is a wrapper around the goja runtime.
3432
type VM struct {
3533
*goja.Runtime
34+
globalSourceMapCache map[string]*sourcemap.Consumer
3635
}
3736

3837
// Options represents options for running a script.
@@ -66,7 +65,7 @@ func New() (*VM, error) {
6665
new(require.Registry).Enable(g)
6766
console.Enable(g)
6867

69-
return &VM{Runtime: g}, nil
68+
return &VM{Runtime: g, globalSourceMapCache: make(map[string]*sourcemap.Consumer)}, nil
7069
}
7170

7271
// Run runs a script in the VM.
@@ -86,7 +85,7 @@ func (v *VM) Run(name string, src string, opts ...Option) (goja.Value, error) {
8685
return nil, fmt.Errorf("failed to compile source map for script: %w", err)
8786
}
8887

89-
globalSourceMapCache[name] = m
88+
v.globalSourceMapCache[name] = m
9089

9190
res, err := v.Runtime.RunProgram(p.prog)
9291
if err == nil {
@@ -99,7 +98,7 @@ func (v *VM) Run(name string, src string, opts ...Option) (goja.Value, error) {
9998

10099
errString := jsErr.String()
101100

102-
fixedStackTrace, _ := utils.ReplaceAllStringSubmatchFunc(lineNumberRegex, errString, remapLineNumbers(name, options.startingLineNumber))
101+
fixedStackTrace, _ := utils.ReplaceAllStringSubmatchFunc(lineNumberRegex, errString, v.remapLineNumbers(name, options.startingLineNumber))
103102

104103
return nil, fmt.Errorf("failed to run script %s: %w", fixedStackTrace, ErrRuntime)
105104
}
@@ -141,7 +140,7 @@ func (v *VM) compile(name string, src string, strict bool) (*program, error) {
141140
}, nil
142141
}
143142

144-
func remapLineNumbers(name string, startingLineNumber int) func(match []string) (string, error) {
143+
func (v *VM) remapLineNumbers(name string, startingLineNumber int) func(match []string) (string, error) {
145144
return func(match []string) (string, error) {
146145
const expectedMatches = 4
147146

@@ -151,7 +150,7 @@ func remapLineNumbers(name string, startingLineNumber int) func(match []string)
151150

152151
file := match[1]
153152

154-
sm, ok := globalSourceMapCache[file]
153+
sm, ok := v.globalSourceMapCache[file]
155154
if !ok {
156155
return match[0], nil
157156
}

0 commit comments

Comments
 (0)