diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8de45bf..eda52f4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,32 +1,5 @@ -# MIT License -# -# Copyright (c) 2023 Iván Szkiba -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - name: Build -on: - pull_request: - workflow_dispatch: - push: - branches: - - feature/* +on: [pull_request] jobs: build: @@ -35,17 +8,12 @@ jobs: steps: - name: Check out code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 -# - name: Lint Go Code -# uses: golangci/golangci-lint-action@v3 -# with: -# version: v1.50.1 - - name: Build id: build uses: szkiba/xk6bundler@v0 with: - with: github.com/szkiba/xk6-enhanced=/github/workspace + with: github.com/szkiba/xk6-ts=/github/workspace diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..698a2ab --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,32 @@ +name: Lint + +on: + pull_request: + workflow_dispatch: + push: + paths-ignore: + - "docs/**" + - README.md + - "releases/**" + +permissions: + contents: read + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup go + uses: actions/setup-go@v4 + with: + go-version: "1.21" + cache: false + - name: Go linter + uses: golangci/golangci-lint-action@v3 + with: + version: v1.55 + args: --timeout=30m + install-mode: binary diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 595cc05..c511a1a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,25 +1,3 @@ -# MIT License -# -# Copyright (c) 2023 Iván Szkiba -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - name: Release on: push: @@ -38,21 +16,16 @@ jobs: IMAGE_NAME: ${{ github.repository }} steps: - - name: Check out code - uses: actions/checkout@v3 + - name: Checkout code + uses: actions/checkout@v4 with: fetch-depth: 0 -# - name: Lint Go Code -# uses: golangci/golangci-lint-action@v3 -# with: -# version: v1.50.1 - - name: Build id: build uses: szkiba/xk6bundler@v0 with: - with: github.com/szkiba/xk6-enhanced=/github/workspace + with: github.com/szkiba/xk6-ts=/github/workspace - name: Create Release uses: softprops/action-gh-release@v1 @@ -60,7 +33,7 @@ jobs: files: dist/*.tar.gz - name: Log in to the Container registry - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -68,7 +41,7 @@ jobs: - name: Extract metadata (tags, labels) for Docker id: meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | @@ -77,7 +50,7 @@ jobs: type=semver,pattern={{major}} - name: Build and push Docker image - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: push: true context: ./${{ steps.build.outputs.dockerdir }} diff --git a/.gitignore b/.gitignore index 15159ca..449bd97 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,7 @@ -# custom binary -k6 +/k6 +/k6.exe +/build -# taskfile.io -.task - -# Editor directories and files .vscode/* !.vscode/extensions.json !.vscode/settings.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? diff --git a/.golangci.yml b/.golangci.yml index 879a826..cdd1054 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,54 +1,135 @@ -# MIT License -# -# Copyright (c) 2023 Iván Szkiba -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. +# v1.55.2 +# Please don't remove the first line. It uses in CI to determine the golangci version +run: + deadline: 5m + +issues: + # Maximum issues count per one linter. Set to 0 to disable. Default is 50. + max-issues-per-linter: 0 + # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + max-same-issues: 0 + + # We want to try and improve the comments in the k6 codebase, so individual + # non-golint items from the default exclusion list will gradually be added + # to the exclude-rules below + exclude-use-default: false + + exclude-rules: + # Exclude duplicate code and function length and complexity checking in test + # files (due to common repeats and long functions in test code) + - path: _(test|gen)\.go + linters: + - cyclop + - dupl + - gocognit + - funlen + - lll + - path: js\/modules\/k6\/http\/.*_test\.go + linters: + # k6/http module's tests are quite complex because they often have several nested levels. + # The module is in maintainance mode, so we don't intend to port the tests to a parallel version. + - paralleltest + - tparallel + - linters: + - staticcheck # Tracked in https://github.com/grafana/xk6-grpc/issues/14 + text: "The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated." + - linters: + - forbidigo + text: 'use of `os\.(SyscallError|Signal|Interrupt)` forbidden' + +linters-settings: + nolintlint: + # Disable to ensure that nolint directives don't have a leading space. Default is true. + allow-leading-space: false + exhaustive: + default-signifies-exhaustive: true + govet: + check-shadowing: true + cyclop: + max-complexity: 25 + maligned: + suggest-new: true + dupl: + threshold: 150 + goconst: + min-len: 10 + min-occurrences: 4 + funlen: + lines: 80 + statements: 60 + forbidigo: + forbid: + - '^(fmt\\.Print(|f|ln)|print|println)$' + # Forbid everything in os, except os.Signal and os.SyscalError + - '^os\.(.*)$(# Using anything except Signal and SyscallError from the os package is forbidden )?' + # Forbid everything in syscall except the uppercase constants + - '^syscall\.[^A-Z_]+$(# Using anything except constants from the syscall package is forbidden )?' + - '^logrus\.Logger$' linters: - presets: - - bugs - - style - - unused - - complexity - - format - - performance + disable-all: true enable: + - asasalint + - asciicheck + - bidichk + - bodyclose + - contextcheck + - cyclop + - dogsled + - dupl + - durationcheck + - errcheck + - errchkjson + - errname + - errorlint + - exhaustive - exportloopref - disable: - - nolintlint + - forbidigo + - forcetypeassert + - funlen + - gocheckcompilerdirectives - gochecknoglobals - - gochecknoinits + - gocognit + - goconst + - gocritic + - gofmt + - gofumpt + - goimports + - gomoddirectives + - goprintffuncname + - gosec + - gosimple + - govet + - importas + - ineffassign + - interfacebloat - lll - - maligned - - interfacer - - scopelint - - wrapcheck - - depguard -# deprecated - - deadcode - - nosnakecase - - exhaustivestruct - - ifshort - - structcheck - - varcheck - - golint -# generics + - makezero + - misspell + - nakedret + - nestif + - nilerr + - nilnil + - noctx + - nolintlint + - nosprintfhostport + - paralleltest + - prealloc + - predeclared + - promlinter + - revive + - reassign - rowserrcheck - sqlclosecheck + - staticcheck + - stylecheck + - tenv + - tparallel + - typecheck + - unconvert + - unparam + - unused + - usestdlibvars - wastedassign + - whitespace + fast: false diff --git a/README.md b/README.md index fb42892..21e8098 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ # xk6-enhanced +**TypeScript support for k6** + + A [k6 extension](https://k6.io/docs/extensions/) adds enhanced JavaScript compatibility (TypeSyript, import JSON files, etc) to [k6](https://k6.io) scripts. Use `--compatibility-mode=enhanced` to activate enhanced JavaScript compatibility mode. @@ -32,37 +35,25 @@ In enhanced compatibility mode the test script will be loaded using (embedded) [ - import TypeScript module from JavaScript script/module - import JavaScript module from TypeScript script/module -## Limitations - -Remote modules loaded by k6, so no enhanced features (TypeScript, etc) not available (yet) for remote modules. Remote module loading support is a planned feature. - ## Download -You can download pre-built k6 binaries from [Releases](https://github.com/szkiba/xk6-enhanced/releases/) page. Check [Packages](https://github.com/szkiba/xk6-enhanced/pkgs/container/xk6-enhanced) page for pre-built k6 Docker images. +You can download pre-built k6 binaries from [Releases](https://github.com/szkiba/xk6-ts/releases/) page. Check [Packages](https://github.com/szkiba/xk6-ts/pkgs/container/xk6-ts) page for pre-built k6 Docker images. -## Build +**Build** -To build a `k6` binary with this extension, first ensure you have the prerequisites: +The [xk6](https://github.com/grafana/xk6) build tool can be used to build a k6 that will include xk6-faker extension: -- [Go toolchain](https://go101.org/article/go-toolchain.html) -- Git - -Then: +```bash +$ xk6 build --with github.com/szkiba/xk6-ts@latest +``` -1. Download `xk6`: - ```bash - $ go install go.k6.io/xk6/cmd/xk6@latest - ``` +For more build options and how to use xk6, check out the [xk6 documentation](https://github.com/grafana/xk6). -2. Build the binary: - ```bash - $ xk6 build --with github.com/szkiba/xk6-enhanced@latest - ``` ## Usage ```bash -$ ./k6 run --compatibility-mode=enhanced script.js +$ ./k6 run script.ts ``` ## Docker diff --git a/Taskfile.yml b/Taskfile.yml deleted file mode 100644 index 1d820ad..0000000 --- a/Taskfile.yml +++ /dev/null @@ -1,65 +0,0 @@ -# MIT License -# -# Copyright (c) 2023 Iván Szkiba -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -version: "3" - -env: - K6_VERSION: v0.43.1 - -silent: true - -tasks: - default: - cmds: - - task: test - - clean: - desc: Clean up working directory - cmds: - - rm -f k6 - - license: - cmds: - - addlicense -ignore '**/node_modules/**' -ignore '.task/**' -ignore '**/dist/**' -ignore '*.js' -ignore '*.ts' -f LICENSE . internal - - lint: - desc: Run linter - sources: - - "**/*.go" - - "*.go" - cmds: - - golangci-lint run - - build: - deps: [lint] - sources: - - "**/*.go" - - "*.go" - generates: - - k6 - cmds: - - xk6 build --with github.com/szkiba/xk6-enhanced=$(pwd) - - test: - deps: [build] - cmds: - - ./k6 run --compatibility-mode=enhanced --no-usage-report script.ts diff --git a/examples/script.js b/examples/script.js new file mode 100644 index 0000000..919049c --- /dev/null +++ b/examples/script.js @@ -0,0 +1,6 @@ +import { newUser } from "./user"; + +export default () => { + const user = newUser("John"); + console.log(user); +}; diff --git a/examples/script.ts b/examples/script.ts new file mode 100644 index 0000000..875b528 --- /dev/null +++ b/examples/script.ts @@ -0,0 +1,6 @@ +import { User, newUser } from "./user"; + +export default () => { + const user: User = newUser("John"); + console.log(user); +}; diff --git a/examples/simple.ts b/examples/simple.ts new file mode 100644 index 0000000..ad91ad0 --- /dev/null +++ b/examples/simple.ts @@ -0,0 +1,23 @@ +interface User { + name: string; + id: number; +} + +class UserAccount implements User { + name: string; + id: number; + + constructor(name: string) { + this.name = name; + this.id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + } +} + +function newUser(name: string): User { + return new UserAccount(name); +} + +export default () => { + const user: User = newUser("John"); + console.log(user); +}; diff --git a/examples/user.ts b/examples/user.ts new file mode 100644 index 0000000..a149cd5 --- /dev/null +++ b/examples/user.ts @@ -0,0 +1,20 @@ +interface User { + name: string; + id: number; +} + +class UserAccount implements User { + name: string; + id: number; + + constructor(name: string) { + this.name = name; + this.id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + } +} + +function newUser(name: string): User { + return new UserAccount(name); +} + +export { User, newUser }; diff --git a/extension.go b/extension.go deleted file mode 100644 index 2239b59..0000000 --- a/extension.go +++ /dev/null @@ -1,34 +0,0 @@ -// MIT License -// -// Copyright (c) 2023 Iván Szkiba -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package enhanced - -import ( - "github.com/szkiba/xk6-enhanced/internal" - "go.k6.io/k6/output" -) - -// Register the extensions on module initialization. -func init() { - internal.Build() - output.RegisterExtension("enhanced", internal.New) -} diff --git a/go.mod b/go.mod index 8bdf1d4..65e7236 100644 --- a/go.mod +++ b/go.mod @@ -1,23 +1,13 @@ module github.com/szkiba/xk6-enhanced -go 1.19 +go 1.21 require ( - github.com/evanw/esbuild v0.17.15 github.com/sirupsen/logrus v1.9.0 - go.k6.io/k6 v0.45.1 + github.com/szkiba/k6pack v0.1.0 ) require ( - github.com/fatih/color v1.15.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/mailru/easyjson v0.7.7 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.18 // indirect - github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd // indirect - github.com/spf13/afero v1.1.2 // indirect - golang.org/x/sys v0.8.0 // indirect - golang.org/x/text v0.9.0 // indirect - golang.org/x/time v0.3.0 // indirect - gopkg.in/guregu/null.v3 v3.3.0 // indirect + github.com/evanw/esbuild v0.20.2 // indirect + golang.org/x/sys v0.18.0 // indirect ) diff --git a/go.sum b/go.sum index 205a8f1..772b08b 100644 --- a/go.sum +++ b/go.sum @@ -1,54 +1,22 @@ -github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/evanw/esbuild v0.17.15 h1:SyCbMVh61kWVC9klvH/iugLzvG/JDwA5hEpnBRx+Lro= -github.com/evanw/esbuild v0.17.15/go.mod h1:iINY06rn799hi48UqEnaQvVfZWe6W9bET78LbvN8VWk= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= -github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa h1:lx8ZnNPwjkXSzOROz0cg69RlErRXs+L3eDkggASWKLo= -github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd h1:AC3N94irbx2kWGA8f/2Ks7EQl2LxKIRQYuT9IJDwgiI= -github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd/go.mod h1:9vRHVuLCjoFfE3GT06X0spdOAO+Zzo4AMjdIwUHBvAk= -github.com/mstoykov/envconfig v1.4.1-0.20220114105314-765c6d8c76f1 h1:94EkGmhXrVUEal+uLwFUf4fMXPhZpM5tYxuIsxrCCbI= +github.com/evanw/esbuild v0.20.2 h1:E4Y0iJsothpUCq7y0D+ERfqpJmPWrZpNybJA3x3I4p8= +github.com/evanw/esbuild v0.20.2/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= -go.k6.io/k6 v0.45.1 h1:z+iVxE7Qze2Ka8tKvnjerOsoTuQb8e27Vqd1wcG2IFI= -go.k6.io/k6 v0.45.1/go.mod h1:SBO/sqx6h/a0lJqEioMEpneb6zULogIyDmz+ufFqtIE= -golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= -golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/szkiba/k6pack v0.1.0 h1:n1XrDFehZ0EsvYJ8oX5ExsryZMCBwA6GNsTi95eLsas= +github.com/szkiba/k6pack v0.1.0/go.mod h1:2yxZBwXidrURozrVZWwohqqEOjdCVyHCZPSKu77i7Bc= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 h1:DdoeryqhaXp1LtT/emMP1BRJPHHKFi5akj/nbx/zNTA= -google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/guregu/null.v3 v3.3.0 h1:8j3ggqq+NgKt/O7mbFVUFKUMWN+l1AmT5jQmJ6nPh2c= -gopkg.in/guregu/null.v3 v3.3.0/go.mod h1:E4tX2Qe3h7QdL+uZ3a0vqvYwKQsRSQKM5V4YltdgH9Y= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/build.go b/internal/build.go deleted file mode 100644 index af6636b..0000000 --- a/internal/build.go +++ /dev/null @@ -1,123 +0,0 @@ -// MIT License -// -// Copyright (c) 2023 Iván Szkiba -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package internal - -import ( - "errors" - "os" - - "github.com/evanw/esbuild/pkg/api" - "github.com/sirupsen/logrus" -) - -var ( - ErrBuild = errors.New("build error") - ErrStdin = errors.New("stdin not supported in enhanced mode") -) - -func checkArgs(args []string) bool { - argn := len(args) - - var runIndex, modeIndex int - - for idx := 0; idx < argn; idx++ { - arg := args[idx] - if arg == "run" && runIndex == 0 { - runIndex = idx - - continue - } - - if runIndex != 0 && arg == "--compatibility-mode=enhanced" { - modeIndex = idx - args[idx] = "--compatibility-mode=extended" - - continue - } - } - - if os.Getenv("K6_COMPATIBILITY_MODE") == "enhanced" { - os.Setenv("K6_COMPATIBILITY_MODE", "extended") - - modeIndex++ - } - - return modeIndex != 0 -} - -func Build() { - if !checkArgs(os.Args) { - return - } - - scriptIndex := len(os.Args) - 1 - - script := os.Args[scriptIndex] - if script == "-" { - logrus.WithError(ErrStdin).Fatal() - } - - os.Args[scriptIndex] = "-" - - content, err := load(script) - if err != nil { - logrus.WithError(err).Fatal() - } - - reader, writer, err := os.Pipe() - if err != nil { - logrus.WithError(err).Fatal() - } - - origStdin := os.Stdin - - os.Stdin = reader - - _, err = writer.Write(content) - if err != nil { - writer.Close() - - os.Stdin = origStdin - - logrus.WithError(err).Fatal() - } -} - -func load(filename string) ([]byte, error) { - result := api.Build(api.BuildOptions{ //nolint:exhaustruct - EntryPoints: []string{filename}, - Bundle: true, - Write: false, - LogLevel: api.LogLevelWarning, - Target: api.ES5, - Platform: api.PlatformBrowser, - Format: api.FormatESModule, - External: []string{"k6"}, - }) - - if len(result.Errors) > 0 { - return nil, ErrBuild - } - - return result.OutputFiles[0].Contents, nil -} diff --git a/internal/output.go b/internal/output.go deleted file mode 100644 index f9f1997..0000000 --- a/internal/output.go +++ /dev/null @@ -1,55 +0,0 @@ -// MIT License -// -// Copyright (c) 2023 Iván Szkiba -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package internal - -import ( - "errors" - - "go.k6.io/k6/metrics" - "go.k6.io/k6/output" -) - -type Output struct{} - -var _ output.Output = (*Output)(nil) - -func New(params output.Params) (output.Output, error) { //nolint:ireturn,revive - return new(Output), nil -} - -func (out *Output) Description() string { - return "enhanced" -} - -func (out *Output) Start() error { - return ErrUsage -} - -func (out *Output) Stop() error { - return nil -} - -func (out *Output) AddMetricSamples(samples []metrics.SampleContainer) { //nolint:revive -} - -var ErrUsage = errors.New("use --compatibility-mode=enhanced to enable enhanced JavaScript compatibility (TypeScript, etc)") diff --git a/joe.json b/joe.json deleted file mode 100644 index 1cd269c..0000000 --- a/joe.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "joe", - "age": 56 -} \ No newline at end of file diff --git a/loader.go b/loader.go new file mode 100644 index 0000000..35cb3bd --- /dev/null +++ b/loader.go @@ -0,0 +1,107 @@ +// Package ts contains xk6-ts extension. +package ts + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/sirupsen/logrus" + "github.com/szkiba/k6pack" +) + +func init() { + redirectStdin() +} + +func isRunCommand(args []string) (bool, int) { + argn := len(args) + + scriptIndex := argn - 1 + if scriptIndex < 0 { + return false, scriptIndex + } + + var runIndex int + + for idx := 0; idx < argn; idx++ { + arg := args[idx] + if arg == "run" && runIndex == 0 { + runIndex = idx + + break + } + } + + if runIndex == 0 { + return false, -1 + } + + return true, scriptIndex +} + +func isEnabled(filename string) bool { + if strings.HasSuffix(filename, ".ts") { + return true + } + + if !strings.HasSuffix(filename, ".js") { + return true + } + + return os.Getenv("XK6_TS") == "always" //nolint:forbidigo +} + +//nolint:forbidigo +func redirectStdin() { + isRun, scriptIndex := isRunCommand(os.Args) + if !isRun { + return + } + + filename := os.Args[scriptIndex] + + if !isEnabled(filename) { + return + } + + fmt.Println("Heeee") + + opts := &k6pack.Options{ + Filename: filename, + SourceMap: os.Getenv("XK6_TS_SOURCEMAP") == "true", + } + + source, err := os.ReadFile(filepath.Clean(filename)) + if err != nil { + logrus.WithError(err).Fatal() + } + + jsScript, err := k6pack.Pack(string(source), opts) + if err != nil { + logrus.WithError(err).Fatal() + } + + os.Args[scriptIndex] = "-" + + reader, writer, err := os.Pipe() + if err != nil { + logrus.WithError(err).Fatal() + } + + defer writer.Close() //nolint:errcheck + + origStdin := os.Stdin + + os.Stdin = reader + + _, err = writer.Write(jsScript) + if err != nil { + writer.Close() //nolint:errcheck,gosec + + os.Stdin = origStdin + + logrus.WithError(err).Fatal() + } +} diff --git a/script.js b/script.js deleted file mode 100644 index e763a3d..0000000 --- a/script.js +++ /dev/null @@ -1,7 +0,0 @@ -import joe from "./joe.json" -import {NewUser} from "./user.ts" - -export default function () { - console.log(joe) - console.log(NewUser("jim", 33)) -} diff --git a/script.ts b/script.ts deleted file mode 100644 index 1631ab5..0000000 --- a/script.ts +++ /dev/null @@ -1,7 +0,0 @@ -import joe from "./joe.json" -import {NewUser} from "./user" - -export default function () { - console.log(joe) - console.log(NewUser("jim", 33)) -} diff --git a/user.ts b/user.ts deleted file mode 100644 index eadd52d..0000000 --- a/user.ts +++ /dev/null @@ -1,13 +0,0 @@ -interface User { - name: string - age: number -} - -function NewUser(name: string, age: number) : User { - return { - name: name, - age: age - } -} - -export {NewUser}