Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/scw-wasm/async.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func asyncFunc(innerFunc fn) js.Func {

res, err := innerFunc(this, args)
if err != nil {
reject.Invoke(jshelpers.NewErrorWithCause(res, err.Error()))
reject.Invoke(jshelpers.NewError(err.Error()))
} else {
resolve.Invoke(res)
}
Expand Down
75 changes: 2 additions & 73 deletions cmd/scw-wasm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,89 +3,18 @@
package main

import (
"bytes"
"fmt"
"io"
"syscall/js"

"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/jshelpers"
"github.com/scaleway/scaleway-cli/v2/internal/namespaces"
"github.com/scaleway/scaleway-cli/v2/internal/platform/web"
"github.com/scaleway/scaleway-cli/v2/internal/wasm"
)

var commands *core.Commands

func getCommands() *core.Commands {
if commands == nil {
commands = namespaces.GetCommands()
}
return commands
}

type RunConfig struct {
JWT string `js:"jwt"`
}

func runCommand(cfg *RunConfig, args []string, stdout io.Writer, stderr io.Writer) chan int {
ret := make(chan int, 1)
go func() {
exitCode, _, _ := core.Bootstrap(&core.BootstrapConfig{
Args: args,
Commands: getCommands(),
BuildInfo: &core.BuildInfo{},
Stdout: stdout,
Stderr: stderr,
Stdin: nil,
Platform: &web.Platform{
JWT: cfg.JWT,
},
})
ret <- exitCode
}()

return ret
}

func wasmRun(this js.Value, args []js.Value) (any, error) {
cliArgs := []string{"scw"}
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)

if len(args) < 2 {
return nil, fmt.Errorf("not enough arguments")
}

runCfg, err := jshelpers.AsObject[RunConfig](args[0])
if err != nil {
return nil, fmt.Errorf("invalid config given: %w", err)
}

givenArgs, err := jshelpers.AsSlice[string](args[1])
if err != nil {
return nil, fmt.Errorf("invalid args given: %w", err)
}

cliArgs = append(cliArgs, givenArgs...)

exitCodeChan := runCommand(runCfg, cliArgs, stdout, stderr)
exitCode := <-exitCodeChan
if exitCode != 0 {
errBody := stderr.String()
return js.ValueOf(errBody), fmt.Errorf("exit code: %d", exitCode)
}

outBody := stdout.String()

return js.ValueOf(outBody), nil
}

func main() {
args := getArgs()

if args.targetObject != "" {
cliPackage := js.ValueOf(map[string]any{})
cliPackage.Set("run", asyncFunc(wasmRun))
cliPackage.Set("run", asyncFunc(jshelpers.AsFunction(wasm.Run)))
js.Global().Set(args.targetObject, cliPackage)
}

Expand Down
31 changes: 31 additions & 0 deletions cmd/scw-wasm/run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//go:build wasm && js

package main

import (
"fmt"
"syscall/js"

"github.com/scaleway/scaleway-cli/v2/internal/jshelpers"
"github.com/scaleway/scaleway-cli/v2/internal/wasm"
)

func wasmRun(this js.Value, args []js.Value) (any, error) {
if len(args) < 2 {
return nil, fmt.Errorf("not enough arguments")
}

runCfg, err := jshelpers.AsObject[wasm.RunConfig](args[0])
if err != nil {
return nil, fmt.Errorf("invalid config given: %w", err)
}

givenArgs, err := jshelpers.AsSlice[string](args[1])
if err != nil {
return nil, fmt.Errorf("invalid args given: %w", err)
}

resp, err := wasm.Run(runCfg, givenArgs)

return jshelpers.FromObject(resp), nil
}
72 changes: 72 additions & 0 deletions internal/jshelpers/function.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//go:build js

package jshelpers

import (
"fmt"
"reflect"
"syscall/js"
)

var (
goErrorInterface = reflect.TypeOf((*error)(nil)).Elem()
)

func jsValue(val any) js.Value {
valType := reflect.TypeOf(val)
if valType.Kind() == reflect.Pointer {
valType = valType.Elem()
}

switch valType.Kind() {
case reflect.Struct:
return FromObject(val)
}
return js.ValueOf(val)
}

func errValue(val any) error {
if val == nil {
return nil
}
return val.(error)
}

// AsFunction convert a classic Go function to a function taking js arguments.
// arguments and return types must be types handled by this package
// function must return 2 variables, second one must be an error
func AsFunction(goFunc any) func(this js.Value, args []js.Value) (any, error) {
goFuncValue := reflect.ValueOf(goFunc)
goFuncType := goFuncValue.Type()

goFuncArgs := make([]reflect.Type, goFuncType.NumIn())
for i := 0; i < goFuncType.NumIn(); i++ {
goFuncArgs[i] = goFuncType.In(i)
}

if goFuncType.NumOut() != 2 {
panic("function must return 2 variables")
}
if !goFuncType.Out(1).Implements(goErrorInterface) {
panic("function must return an error")
}

return func(this js.Value, args []js.Value) (any, error) {
if len(args) != len(goFuncArgs) {
return nil, fmt.Errorf("invalid number of arguments, expected %d, got %d", len(goFuncArgs), len(args))
}

argValues := make([]reflect.Value, len(goFuncArgs))
for i, argType := range goFuncArgs {
arg, err := goValue(argType, args[i])
if err != nil {
return nil, fmt.Errorf("invalid argument at index %d with type %s: %w", i, argType.String(), err)
}
argValues[i] = reflect.ValueOf(arg)
}

returnValues := goFuncValue.Call(argValues)

return jsValue(returnValues[0].Interface()), errValue(returnValues[1].Interface())
}
}
25 changes: 25 additions & 0 deletions internal/jshelpers/objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@ func asString(value js.Value) (string, error) {

func goValue(typ reflect.Type, value js.Value) (any, error) {
switch typ.Kind() {
case reflect.Pointer:
return goValue(typ.Elem(), value)
case reflect.String:
return asString(value)
case reflect.Struct:
return asObject(typ, value)
case reflect.Slice:
return asSlice(typ.Elem(), value)
}
return nil, fmt.Errorf("value type is unknown")
}
Expand Down Expand Up @@ -60,3 +66,22 @@ func AsObject[T any](value js.Value) (*T, error) {

return obj.(*T), nil
}

// FromObject converts a Go struct to a JS Object
// Given Go struct must have "js" tags to specify fields mapping
func FromObject(from any) js.Value {
fromValue := reflect.Indirect(reflect.ValueOf(from))
fromType := fromValue.Type()

obj := jsObject.New()

for i := 0; i < fromValue.NumField(); i++ {
field := fromType.Field(i)
jsFieldName := field.Tag.Get("js")
if jsFieldName != "" {
obj.Set(jsFieldName, js.ValueOf(fromValue.Field(i).Interface()))
}
}

return obj
}
61 changes: 61 additions & 0 deletions internal/wasm/run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package wasm

import (
"bytes"
"io"

"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/namespaces"
"github.com/scaleway/scaleway-cli/v2/internal/platform/web"
)

var commands *core.Commands

func getCommands() *core.Commands {
if commands == nil {
commands = namespaces.GetCommands()
}
return commands
}

type RunConfig struct {
JWT string `js:"jwt"`
}

type RunResponse struct {
Stdout string `js:"stdout"`
Stderr string `js:"stderr"`
ExitCode int `js:"exitCode"`
}

func runCommand(cfg *RunConfig, args []string, stdout io.Writer, stderr io.Writer) int {
exitCode, _, _ := core.Bootstrap(&core.BootstrapConfig{
Args: args,
Commands: getCommands(),
BuildInfo: &core.BuildInfo{},
Stdout: stdout,
Stderr: stderr,
Stdin: nil,
Platform: &web.Platform{
JWT: cfg.JWT,
},
})

return exitCode
}

func Run(cfg *RunConfig, args []string) (*RunResponse, error) {
cliArgs := []string{"scw"}
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)

cliArgs = append(cliArgs, args...)

exitCode := runCommand(cfg, cliArgs, stdout, stderr)

return &RunResponse{
Stdout: stdout.String(),
Stderr: stderr.String(),
ExitCode: exitCode,
}, nil
}
8 changes: 7 additions & 1 deletion wasm/cli.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ export type RunConfig = {
jwt: string
}

export type RunResponse = {
stdout: string
stderr: string
exitCode: string
}

export type CLI = {
run(cfg: RunConfig, args: string[]): Promise<string>
run(cfg: RunConfig, args: string[]): Promise<RunResponse>
}
9 changes: 9 additions & 0 deletions wasm/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {CLI, RunConfig, RunResponse} from "./cli";

export type _ = {
wasmURL: URL,
RunConfig,
RunResponse,
CLI,
Go,
}
1 change: 1 addition & 0 deletions wasm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"scripts": {
"test": "vitest"
},
"types": "index.d.ts",
"keywords": [],
"author": "",
"devDependencies": {
Expand Down
37 changes: 25 additions & 12 deletions wasm/src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ import * as fs from 'fs'
const CLI_PACKAGE = 'scw'
const CLI_CALLBACK = 'cliLoaded'

const runWithError = async (cli: CLI, runCfg: RunConfig, expected: string | RegExp, command: string[]) => {
await expect((async () => await cli.run(runCfg, command))).rejects.toThrowError(expected)
}

describe('With wasm CLI', async () => {
// @ts-ignore
const go = new globalThis.Go()
Expand All @@ -38,16 +34,33 @@ describe('With wasm CLI', async () => {
await waitForCLI
// @ts-ignore
const cli = globalThis[CLI_PACKAGE] as CLI
const runCfg: RunConfig = {
jwt: "",

const run = async (expected: string | RegExp, command: string[], runCfg: RunConfig | null = null) => {
if (runCfg === null) {
runCfg = {
jwt: "",
}
}

const resp = await cli.run(runCfg, command)
expect(resp.exitCode).toBe(0)
expect(resp.stdout).toMatch(expected)
}

it('can run cli commands', async () => {
const res = await cli.run(runCfg, ['info'])
expect(res).toMatch(/profile.*default/)
})
const runWithError = async (expected: string | RegExp, command: string[], runCfg: RunConfig | null = null) => {
if (runCfg === null) {
runCfg = {
jwt: "",
}
}
const resp = await cli.run(runCfg, command)
expect(resp.exitCode).toBeGreaterThan(0)
expect(resp.stderr).toMatch(expected)
}

it('can run cli commands', async () => run(/profile.*default/, ['info']))

it('can run help', async () => runWithError(cli, runCfg, /USAGE:\n.*scw <command>.*/, []))
it('can run help', async () => runWithError(/USAGE:\n.*scw <command>.*/, []))

it('can use jwt', async () => runWithError(cli, runCfg, /.*denied authentication.*invalid JWT.*/, ['instance', 'server', 'list']))
it('can use jwt', async () => runWithError(/.*denied authentication.*invalid JWT.*/, ['instance', 'server', 'list']))
})