|
| 1 | +//go:build wasm && js |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "syscall/js" |
| 10 | + |
| 11 | + "github.com/scaleway/scaleway-cli/v2/internal/core" |
| 12 | + "github.com/scaleway/scaleway-cli/v2/internal/namespaces" |
| 13 | +) |
| 14 | + |
| 15 | +var commands *core.Commands |
| 16 | + |
| 17 | +func getCommands() *core.Commands { |
| 18 | + if commands == nil { |
| 19 | + commands = namespaces.GetCommands() |
| 20 | + } |
| 21 | + return commands |
| 22 | +} |
| 23 | + |
| 24 | +func runCommand(args []string, stdout io.Writer, stderr io.Writer) chan int { |
| 25 | + ret := make(chan int, 1) |
| 26 | + go func() { |
| 27 | + exitCode, _, _ := core.Bootstrap(&core.BootstrapConfig{ |
| 28 | + Args: args, |
| 29 | + Commands: getCommands(), |
| 30 | + BuildInfo: &core.BuildInfo{}, |
| 31 | + Stdout: stdout, |
| 32 | + Stderr: stderr, |
| 33 | + Stdin: nil, |
| 34 | + }) |
| 35 | + ret <- exitCode |
| 36 | + }() |
| 37 | + |
| 38 | + return ret |
| 39 | +} |
| 40 | + |
| 41 | +func wasmRun(this js.Value, args []js.Value) (any, error) { |
| 42 | + cliArgs := []string{"scw"} |
| 43 | + stdout := bytes.NewBuffer(nil) |
| 44 | + stderr := bytes.NewBuffer(nil) |
| 45 | + |
| 46 | + for argIndex, arg := range args { |
| 47 | + if arg.Type() != js.TypeString { |
| 48 | + return nil, fmt.Errorf("invalid argument at index %d", argIndex) |
| 49 | + } |
| 50 | + cliArgs = append(cliArgs, arg.String()) |
| 51 | + } |
| 52 | + |
| 53 | + exitCodeChan := runCommand(cliArgs, stdout, stderr) |
| 54 | + exitCode := <-exitCodeChan |
| 55 | + if exitCode != 0 { |
| 56 | + errBody := stderr.String() |
| 57 | + return js.ValueOf(errBody), fmt.Errorf("exit code: %d", exitCode) |
| 58 | + } |
| 59 | + |
| 60 | + outBody := stdout.String() |
| 61 | + |
| 62 | + return js.ValueOf(outBody), nil |
| 63 | +} |
| 64 | + |
| 65 | +func main() { |
| 66 | + args := getArgs() |
| 67 | + |
| 68 | + if args.targetObject != "" { |
| 69 | + cliPackage := js.ValueOf(map[string]any{}) |
| 70 | + cliPackage.Set("run", asyncFunc(wasmRun)) |
| 71 | + js.Global().Set(args.targetObject, cliPackage) |
| 72 | + } |
| 73 | + |
| 74 | + if args.callback != "" { |
| 75 | + givenCallback := js.Global().Get(args.callback) |
| 76 | + if !givenCallback.IsUndefined() { |
| 77 | + givenCallback.Invoke() |
| 78 | + } |
| 79 | + } |
| 80 | + <-make(chan struct{}, 0) |
| 81 | +} |
0 commit comments