specified a default goja script name when executing plain JS strings

This commit is contained in:
Gani Georgiev
2025-02-18 11:29:55 +02:00
parent 5aa380927a
commit 4d40463d8d
3 changed files with 30 additions and 7 deletions

View File

@@ -35,6 +35,24 @@ import (
const typesFileName = "types.d.ts"
var defaultScriptPath = "pb.js"
func init() {
// For backward compatibility and consistency with the Go exposed
// methods that accepts relative paths (e.g. `$os.writeFile`),
// we define the "current JS module" as if it is a file in the current working directory
// (the filename itself doesn't really matter and in our case the hook handlers are executed as separate "programs").
//
// This is necessary for `require(module)` to properly traverse parents node_modules (goja_nodejs#95).
cwd, err := os.Getwd()
if err != nil {
// truly rare case, log just for debug purposes
color.Yellow("Failed to retrieve the current working directory: %v", err)
} else {
defaultScriptPath = filepath.Join(cwd, defaultScriptPath)
}
}
// Config defines the config options of the jsvm plugin.
type Config struct {
// OnInit is an optional function that will be called
@@ -191,7 +209,7 @@ func (p *plugin) registerMigrations() error {
p.config.OnInit(vm)
}
_, err := vm.RunString(string(content))
_, err := vm.RunScript(defaultScriptPath, string(content))
if err != nil {
return fmt.Errorf("failed to run migration %s: %w", file, err)
}
@@ -306,7 +324,7 @@ func (p *plugin) registerHooks() error {
}
}()
_, err := loader.RunString(string(content))
_, err := loader.RunScript(defaultScriptPath, string(content))
if err != nil {
panic(err)
}