|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +//go:build js && wasm |
| 16 | + |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + // Work around https://github.com/prep/wasmexec/issues/3 until it is resolved upstream. |
| 21 | + // This should be the first one among all imports. |
| 22 | + _ "github.com/GoogleContainerTools/kpt-functions-catalog/functions/go/set-namespace/setosargs" |
| 23 | + |
| 24 | + "fmt" |
| 25 | + "syscall/js" |
| 26 | + |
| 27 | + "github.com/GoogleContainerTools/kpt-functions-catalog/functions/go/set-namespace/transformer" |
| 28 | + "github.com/GoogleContainerTools/kpt-functions-sdk/go/fn" |
| 29 | +) |
| 30 | + |
| 31 | +func run() error { |
| 32 | + js.Global().Set("processResourceList", resourceListProcessorWrapper()) |
| 33 | + <-make(chan bool) |
| 34 | + return nil |
| 35 | +} |
| 36 | + |
| 37 | +func transformNamespace(input []byte) ([]byte, error) { |
| 38 | + return fn.Run(fn.ResourceListProcessorFunc(transformer.Run), []byte(input)) |
| 39 | +} |
| 40 | + |
| 41 | +func resourceListProcessorWrapper() js.Func { |
| 42 | + // TODO: figure out a better way to surface a golang error to JS environment. |
| 43 | + // Currently error is surfaced as a string. |
| 44 | + jsonFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} { |
| 45 | + if len(args) != 1 { |
| 46 | + return "Invalid number of arguments passed" |
| 47 | + } |
| 48 | + input := args[0].String() |
| 49 | + transformed, err := transformNamespace([]byte(input)) |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("unable to process resource list:", err.Error()) |
| 52 | + } |
| 53 | + return string(transformed) |
| 54 | + }) |
| 55 | + return jsonFunc |
| 56 | +} |
0 commit comments