diff --git a/.github/workflows/sdk-publish.yml b/.github/workflows/sdk-publish.yml index f4706318..927ce3b8 100644 --- a/.github/workflows/sdk-publish.yml +++ b/.github/workflows/sdk-publish.yml @@ -1,81 +1,253 @@ -name: Automated SDK Build & Publish +name: SDK Publish + +# Builds, verifies and publishes the JavaScript, Python and Go SDKs together. +# The OpenAPI 3.1 check and publish manifest come from scripts/publish-sdks.js. +# +# - Pull requests, pushes to main and manual runs are dry runs: every SDK is +# tested and packaged, nothing is published. +# - Pushing a tag `sdk-vX.Y.Z` that matches sdks/VERSION publishes all three, +# and only after all three verified. A re-run skips registries that already +# have the version. +# +# Runbook: sdks/docs/releasing.md on: push: - branches: - - main + branches: [main] + tags: ['sdk-v*'] paths: + - 'sdks/**' - 'developer-portal/docs/openapi.json' + - 'scripts/publish-sdks.js' + - 'scripts/generate-sdks.js' + - '.github/workflows/sdk-publish.yml' + pull_request: + paths: - 'sdks/**' + - 'developer-portal/docs/openapi.json' - 'scripts/publish-sdks.js' - tags: - - 'sdk-v*' + - 'scripts/generate-sdks.js' + - '.github/workflows/sdk-publish.yml' workflow_dispatch: +permissions: + contents: read + +concurrency: + group: sdk-publish-${{ github.ref }} + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }} + jobs: - validate-and-build: - name: Build & Validate SDKs + prepare: + name: Plan release runs-on: ubuntu-latest + outputs: + version: ${{ steps.plan.outputs.version }} + python_version: ${{ steps.plan.outputs.python_version }} + npm_tag: ${{ steps.plan.outputs.npm_tag }} + go_module: ${{ steps.plan.outputs.go_module }} + go_tag: ${{ steps.plan.outputs.go_tag }} + publish: ${{ steps.plan.outputs.publish }} + npm_published: ${{ steps.registry.outputs.npm_published }} + pypi_published: ${{ steps.registry.outputs.pypi_published }} + go_published: ${{ steps.registry.outputs.go_published }} steps: - - name: Checkout Code - uses: actions/checkout@v7 - - - name: Validate OpenAPI 3.1 Spec + - uses: actions/checkout@v7 + - uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Test release tooling + run: node --test sdks/scripts/__tests__/release.test.mjs + - name: Check versions and changelog + run: node sdks/scripts/release.mjs check + - name: Plan + id: plan + run: node sdks/scripts/release.mjs plan + # OpenAPI 3.1 validation and publish manifest (scripts/publish-sdks.js, #2217). + # Always a dry run here: the publish-* jobs below do the registry uploads. + - name: Validate OpenAPI spec and write publish manifest + env: + VERSION: ${{ steps.plan.outputs.version }} run: | - npx @redocly/cli lint developer-portal/docs/openapi.json + node scripts/generate-sdks.js + node scripts/publish-sdks.js --version "sdk-v$VERSION" + - uses: actions/upload-artifact@v4 + with: + name: sdk-publish-manifest + path: sdks/generated/publish-manifest.json + if-no-files-found: error + - name: Check registries + id: registry + if: steps.plan.outputs.publish == 'true' + run: node sdks/scripts/release.mjs registry-status - - name: Setup Node.js - uses: pnpm/action-setup@v6 + verify-javascript: + name: Verify JavaScript SDK + needs: prepare + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdks/javascript + steps: + - uses: actions/checkout@v7 - uses: actions/setup-node@v4 with: node-version: '24' + cache: npm + cache-dependency-path: sdks/javascript/package-lock.json + - run: npm ci + - name: Typecheck + run: npm test + - name: Build + run: npm run build + - name: Pack + run: npm pack + - uses: actions/upload-artifact@v4 + with: + name: sdk-javascript + path: sdks/javascript/*.tgz + if-no-files-found: error - - name: Build JS SDK - run: | - cd sdks/javascript - pnpm install --frozen-lockfile - npm run build || true - - - name: Setup Python - uses: actions/setup-python@v7 + verify-python: + name: Verify Python SDK + needs: prepare + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdks/python + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: '3.11' - - - name: Validate Python SDK - run: | - cd sdks/python - python -m pip install --upgrade pip - pip install requests - - - name: Setup Go - uses: actions/setup-go@v7 + - name: Install + run: python -m pip install --upgrade pip build twine && python -m pip install -e . + - name: Test + run: python -m unittest discover tests + - name: Build sdist and wheel + run: python -m build + - name: Check distributions + run: python -m twine check --strict dist/* + - uses: actions/upload-artifact@v4 with: - go-version: '1.21' + name: sdk-python + path: sdks/python/dist/* + if-no-files-found: error - - name: Validate Go SDK - run: | - cd sdks/go - go test ./... || true - - publish: - name: Publish SDKs - if: startsWith(github.ref, 'refs/tags/sdk-v') - needs: validate-and-build + verify-go: + name: Verify Go SDK + needs: prepare runs-on: ubuntu-latest + defaults: + run: + working-directory: sdks/go steps: - - name: Checkout Code - uses: actions/checkout@v7 + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: sdks/go/go.mod + - run: go vet ./... + - run: go test -race ./... - - uses: pnpm/action-setup@v6 + publish-npm: + name: Publish to npm + needs: [prepare, verify-javascript, verify-python, verify-go] + if: needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.npm_published != 'true' + runs-on: ubuntu-latest + environment: npm + permissions: + contents: read + id-token: write # npm provenance + steps: - uses: actions/setup-node@v4 with: node-version: '24' registry-url: 'https://registry.npmjs.org' + - uses: actions/download-artifact@v4 + with: + name: sdk-javascript + - name: Publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + NPM_TAG: ${{ needs.prepare.outputs.npm_tag }} + run: npm publish ./*.tgz --tag "$NPM_TAG" --access public --provenance - - name: Generate SDK metadata - run: npm run sdk:generate + publish-pypi: + name: Publish to PyPI + needs: [prepare, verify-javascript, verify-python, verify-go] + if: needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.pypi_published != 'true' + runs-on: ubuntu-latest + environment: pypi + permissions: + contents: read + id-token: write # PyPI trusted publishing + steps: + - uses: actions/download-artifact@v4 + with: + name: sdk-python + path: dist + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist - - name: Publish SDKs - run: node scripts/publish-sdks.js --version "${GITHUB_REF_NAME}" --publish + publish-go: + name: Publish Go module + needs: [prepare, verify-javascript, verify-python, verify-go] + if: needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.go_published != 'true' + runs-on: ubuntu-latest + permissions: + contents: write # push the sdks/go/vX.Y.Z tag + env: + GO_TAG: ${{ needs.prepare.outputs.go_tag }} + GO_MODULE: ${{ needs.prepare.outputs.go_module }} + VERSION: ${{ needs.prepare.outputs.version }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: sdks/go/go.mod + - name: Tag module + run: | + if git ls-remote --exit-code --tags origin "refs/tags/$GO_TAG" >/dev/null; then + echo "[sdk-release] $GO_TAG already exists; not re-tagging" + else + git tag "$GO_TAG" "$GITHUB_SHA" + git push origin "refs/tags/$GO_TAG" + echo "[sdk-release] pushed $GO_TAG at $GITHUB_SHA" + fi + - name: Register with the Go module proxy + run: | + cd "$(mktemp -d)" + for attempt in 1 2 3 4 5; do + if GOPROXY=https://proxy.golang.org GOFLAGS=-mod=mod go mod download -json "$GO_MODULE@v$VERSION"; then + echo "[sdk-release] $GO_MODULE@v$VERSION is available on proxy.golang.org" + exit 0 + fi + echo "[sdk-release] proxy not ready (attempt $attempt); retrying" + sleep $((attempt * 15)) + done + echo "::error::$GO_MODULE@v$VERSION did not become available on proxy.golang.org" + exit 1 + + summary: + name: Release summary + needs: + [prepare, verify-javascript, verify-python, verify-go, publish-npm, publish-pypi, publish-go] + if: always() + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Summarise env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + # When publishing, report the publish job unless the registry already + # had the version; otherwise report the verify job. + JAVASCRIPT_RESULT: ${{ (needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.npm_published != 'true') && needs.publish-npm.result || needs.verify-javascript.result }} + PYTHON_RESULT: ${{ (needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.pypi_published != 'true') && needs.publish-pypi.result || needs.verify-python.result }} + GO_RESULT: ${{ (needs.prepare.outputs.publish == 'true' && needs.prepare.outputs.go_published != 'true') && needs.publish-go.result || needs.verify-go.result }} + JAVASCRIPT_ALREADY_PUBLISHED: ${{ needs.prepare.outputs.npm_published }} + PYTHON_ALREADY_PUBLISHED: ${{ needs.prepare.outputs.pypi_published }} + GO_ALREADY_PUBLISHED: ${{ needs.prepare.outputs.go_published }} + run: node sdks/scripts/release.mjs summary diff --git a/scripts/__tests__/openapiSdkPublisher.test.ts b/scripts/__tests__/openapiSdkPublisher.test.ts index 505525fb..b4a6ad44 100644 --- a/scripts/__tests__/openapiSdkPublisher.test.ts +++ b/scripts/__tests__/openapiSdkPublisher.test.ts @@ -53,6 +53,18 @@ describe('SDK publish plan', () => { ]); }); + it('accepts pre-release tags in the format sdks/scripts/release.mjs uses', () => { + expect(publisher.buildPublishPlan(spec, 'sdk-v2.1.0-rc.1').version).toBe('2.1.0-rc.1'); + expect(() => publisher.buildPublishPlan(spec, 'sdk-v2.1.0-dev.1')).toThrow( + 'Invalid version tag' + ); + }); + + it('targets the /v2 Go module path', () => { + const plan = publisher.buildPublishPlan(spec, 'sdk-v2.0.0', ['go']); + expect(plan.targets[0].package).toBe('github.com/Smartdevs17/SubTrackr/sdks/go/v2'); + }); + it('rejects invalid tags and unknown targets', () => { expect(() => publisher.buildPublishPlan(spec, 'v1.2.3')).toThrow('Invalid version tag'); expect(() => publisher.buildPublishPlan(spec, 'sdk-v1.2.3', [])).toThrow('No SDK targets'); diff --git a/scripts/publish-sdks.js b/scripts/publish-sdks.js index 5bed5c3c..22dea32f 100644 --- a/scripts/publish-sdks.js +++ b/scripts/publish-sdks.js @@ -14,12 +14,15 @@ const TARGETS = { javascript: { package: '@subtrackr/sdk', registry: 'npm' }, python: { package: 'subtrackr-sdk', registry: 'pypi' }, go: { - package: 'github.com/Smartdevs17/SubTrackr/sdks/go', + // Go semantic import versioning: the module path carries /vN from v2 on + // (see sdks/go/go.mod and sdks/scripts/lib/release.mjs). + package: 'github.com/Smartdevs17/SubTrackr/sdks/go/v2', registry: 'proxy.golang.org', }, }; -const TAG_PATTERN = /^sdk-v(\d+\.\d+\.\d+)$/; +// Matches the versions sdks/scripts/release.mjs accepts, pre-releases included. +const TAG_PATTERN = /^sdk-v(\d+\.\d+\.\d+(?:-(?:alpha|beta|rc)\.\d+)?)$/; function assertOpenApi31(spec) { if (!spec || typeof spec !== 'object') { @@ -37,7 +40,9 @@ function buildPublishPlan(spec, tag, languages = Object.keys(TARGETS)) { assertOpenApi31(spec); const match = TAG_PATTERN.exec(tag || ''); if (!match) { - throw new Error(`[sdk:publish] Invalid version tag "${tag}". Expected sdk-vX.Y.Z`); + throw new Error( + `[sdk:publish] Invalid version tag "${tag}". Expected sdk-vX.Y.Z or sdk-vX.Y.Z-(alpha|beta|rc).N` + ); } if (!languages.length) { throw new Error('[sdk:publish] No SDK targets selected'); diff --git a/sdks/CHANGELOG.md b/sdks/CHANGELOG.md new file mode 100644 index 00000000..721cfa5b --- /dev/null +++ b/sdks/CHANGELOG.md @@ -0,0 +1,22 @@ +# SubTrackr SDK changelog + +All three SDKs (JavaScript, Python, Go) share one version, set in +[`VERSION`](VERSION). Every release needs a section here before it can be +tagged; `node sdks/scripts/release.mjs check` enforces it. See +[docs/releasing.md](docs/releasing.md). + +## [2.0.0] + +First release published to the package registries. + +- JavaScript: `@subtrackr/sdk` on npm. +- Python: `subtrackr-sdk` on PyPI. +- Go: `github.com/Smartdevs17/SubTrackr/sdks/go/v2`. The module path takes the + `/v2` suffix that Go requires for major version 2. +- Python: restored `create_plan()` (same payload as the JavaScript SDK's + `createPlan`), which had been lost in a client refactor. Every call now goes + through one pooled `requests.Session`. +- JavaScript: includes the circuit breaker and resilience layer; fixed a + missing `CircuitState` import that stopped the package from compiling. +- Requests carry `X-SDK-Version` / `X-API-Version`. Deprecation policy: + [docs/deprecation-policy.md](docs/deprecation-policy.md). diff --git a/sdks/VERSION b/sdks/VERSION new file mode 100644 index 00000000..227cea21 --- /dev/null +++ b/sdks/VERSION @@ -0,0 +1 @@ +2.0.0 diff --git a/sdks/docs/index.md b/sdks/docs/index.md index 6403c135..dad33627 100644 --- a/sdks/docs/index.md +++ b/sdks/docs/index.md @@ -13,9 +13,11 @@ Welcome to the SubTrackr SDK documentation. SubTrackr provides official SDKs in ## JavaScript / TypeScript ### Installation + You can build the JS SDK into your project or install it as a package `npm install @subtrackr/sdk`. ### Basic Usage + ```typescript import { SubTrackrClient } from '@subtrackr/sdk'; @@ -36,16 +38,18 @@ run(); ## Python ### Installation + ```bash pip install subtrackr-sdk ``` ### Basic Usage + ```python from subtrackr import SubTrackrClient client = SubTrackrClient( - api_key="sk_test_12345", + api_key="sk_test_12345", environment="sandbox" ) @@ -59,17 +63,19 @@ for sub in subs: ## Go ### Installation + ```bash -go get github.com/Smartdevs17/SubTrackr/sdks/go +go get github.com/Smartdevs17/SubTrackr/sdks/go/v2 ``` ### Basic Usage + ```go package main import ( "fmt" - "github.com/Smartdevs17/SubTrackr/sdks/go" + subtrackr "github.com/Smartdevs17/SubTrackr/sdks/go/v2" ) func main() { @@ -86,6 +92,7 @@ func main() { fmt.Println(subs) } ``` + # SubTrackr SDKs Official SDKs are available for JavaScript/TypeScript, Python, and Go. The SDK contract method surface is generated from `docs/openapi.yaml`; run: @@ -107,10 +114,22 @@ npm run sdk:test:go ## Publication -The `Automated SDK Build & Publish` workflow validates all SDKs on pushes to `main` that touch OpenAPI or SDK files. Tags matching `sdk-vX.Y.Z` run the auto-publisher, which validates the OpenAPI 3.1 document, regenerates endpoint metadata, writes `sdks/generated/publish-manifest.json`, and publishes the JavaScript SDK to npm using `NPM_TOKEN`. +All three SDKs share one version (`sdks/VERSION`) and are released together +by the `SDK Publish` workflow (`.github/workflows/sdk-publish.yml`): + +- Pull requests that touch `sdks/**` run a dry run. The workflow validates the + OpenAPI 3.1 document, regenerates endpoint metadata and writes + `sdks/generated/publish-manifest.json` (`scripts/publish-sdks.js`), then + tests and packages every SDK. Nothing is published. +- Pushing a tag `sdk-vX.Y.Z` that matches `sdks/VERSION` publishes to npm, + PyPI and the Go module proxy, and only if all three SDKs pass. -To inspect the plan without publishing: +To check the spec and see the publish manifest locally without publishing: ```bash -npm run sdk:publish -- --version sdk-v1.2.3 +npm run sdk:generate +npm run sdk:publish -- --version sdk-v2.0.0 ``` + +See [releasing.md](releasing.md) for the runbook and the one-time registry +setup. diff --git a/sdks/docs/releasing.md b/sdks/docs/releasing.md new file mode 100644 index 00000000..53ea3fa9 --- /dev/null +++ b/sdks/docs/releasing.md @@ -0,0 +1,111 @@ +# Releasing the SDKs + +The JavaScript, Python and Go SDKs are released together under one version. +The pipeline is `.github/workflows/sdk-publish.yml`, driven by +`sdks/scripts/release.mjs`. + +| SDK | Registry | Package | +| ---------- | --------------- | -------------------------------------------------------------------- | +| JavaScript | npm | `@subtrackr/sdk` | +| Python | PyPI | `subtrackr-sdk` | +| Go | Go module proxy | `github.com/Smartdevs17/SubTrackr/sdks/go/v2` (tag `sdks/go/vX.Y.Z`) | + +## Versions + +[`sdks/VERSION`](../VERSION) is the single source of truth. These files must +agree with it, and CI fails if they don't: + +| File | Field | +| ----------------------------- | -------------------------------------------- | +| `javascript/package.json` | `version` | +| `javascript/src/version.ts` | `SDK_VERSION`, `SDK_VERSION_INFO` | +| `python/setup.py` | `version` (PEP 440) | +| `python/subtrackr/version.py` | `SDK_VERSION` (PEP 440), `SDK_VERSION_TUPLE` | +| `go/version.go` | `SDKVersion` | +| `go/go.mod` | module path: `/vN` suffix from v2 onwards | + +Allowed versions are `X.Y.Z` and the pre-releases `X.Y.Z-alpha.N`, +`X.Y.Z-beta.N` and `X.Y.Z-rc.N`. A pre-release becomes `X.Y.ZaN` / `bN` / +`rcN` on PyPI and is published to npm under the `next` dist-tag, so +`npm install @subtrackr/sdk` keeps getting the latest stable release. + +## Cutting a release + +```bash +node sdks/scripts/release.mjs set 2.1.0 # rewrites every file above +# add a "## [2.1.0]" section to sdks/CHANGELOG.md +node sdks/scripts/release.mjs check # must pass +git commit -am "chore(sdks): release 2.1.0" +# open a PR; after it merges: +git tag sdk-v2.1.0 +git push origin sdk-v2.1.0 +``` + +A major version bump changes the Go module path (for example `/v2` → `/v3`). +Go users then have to update their imports, so call that out in the +changelog. + +## What the pipeline does + +| Trigger | Result | +| ------------------------------------------------------------------ | ------------------------------------------------------------- | +| Pull request or push to `main` touching `sdks/**`, or a manual run | **Dry run:** test and package all three SDKs, publish nothing | +| Push of tag `sdk-vX.Y.Z` matching `sdks/VERSION` | **Release** | +| Push of a tag that doesn't match `sdks/VERSION` | Fails in _Plan release_ | + +The jobs run in this order: + +1. **Plan release.** Runs the release-tool tests and `check`, decides dry run + or release, and on a release asks each registry whether the version is + already there. +2. **Verify** (one job per SDK, in parallel): + - JavaScript: `npm ci`, typecheck, build, `npm pack`. + - Python: unit tests, `python -m build`, `twine check --strict`. + - Go: `go vet`, `go test -race`. + + The JavaScript tarball and the Python wheel and sdist are kept as + artifacts. The publish jobs upload exactly those files. + +3. **Publish** runs only when all three verify jobs pass, so one broken SDK + blocks the whole release instead of shipping a partial one. + - npm: `npm publish --tag --provenance`. + - PyPI: trusted publishing via `pypa/gh-action-pypi-publish`. + - Go: pushes `sdks/go/vX.Y.Z` at the release commit, then waits until + `proxy.golang.org` serves it. +4. **Release summary** writes a table to the run page, showing each SDK's + result and whether it was published, skipped or a dry run. + +## Failure handling + +| Situation | Behaviour | +| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| Version files or changelog out of sync | _Plan release_ fails and names every mismatched file. Run `set`, then add the changelog entry. | +| Tests or build fail for any SDK | Nothing is published. Fix, merge, move the tag (`git tag -f sdk-vX.Y.Z && git push -f origin sdk-vX.Y.Z`), or release the next patch. | +| One registry fails mid-release | Re-run the workflow. Registries that already have the version are skipped, and only the missing ones publish. | +| The Go tag exists but the proxy doesn't have it yet | The re-run leaves the tag alone and retries the proxy. | +| A registry is unreachable during the pre-check | Retried 3 times, then the run fails. It never publishes without knowing the registry's state. | +| The Go proxy is slow to pick up the tag | Retried 5 times with back-off, then the run fails. A re-run continues from there. | + +## One-time setup (repository admins) + +- **npm:** create the `@subtrackr` org on npm. Add an automation token as the + `NPM_TOKEN` secret on a GitHub environment named `npm`. +- **PyPI:** register `subtrackr-sdk`, and add a trusted publisher for + repository `Smartdevs17/SubTrackr`, workflow `sdk-publish.yml`, + environment `pypi`. No token is needed. +- **Go:** nothing to set up. The workflow's `GITHUB_TOKEN` pushes the + `sdks/go/v*` tag. +- **License:** the repository has no license file yet. Add one before the + first publish, since registries display it and consumers need it. +- Optionally, protect the `npm` and `pypi` environments with required + reviewers, so each release waits for an approval. + +## Local commands + +```bash +node --test sdks/scripts/__tests__/release.test.mjs # release tooling tests +node sdks/scripts/release.mjs check # versions + changelog +npm --prefix sdks/javascript ci && npm --prefix sdks/javascript test +PYTHONPATH=sdks/python python3 -m unittest discover sdks/python/tests +(cd sdks/go && go test ./...) +``` diff --git a/sdks/go/README.md b/sdks/go/README.md index 49489d67..ddc4838a 100644 --- a/sdks/go/README.md +++ b/sdks/go/README.md @@ -5,7 +5,7 @@ The official Go SDK for the SubTrackr API. ## Installation ```bash -go get github.com/subtrackr/subtrackr-go +go get github.com/Smartdevs17/SubTrackr/sdks/go/v2 ``` ## Quick Start @@ -21,7 +21,7 @@ import ( "log" "os" - "github.com/subtrackr/subtrackr-go" + subtrackr "github.com/Smartdevs17/SubTrackr/sdks/go/v2" ) func main() { diff --git a/sdks/go/go.mod b/sdks/go/go.mod index 312f140b..41154ecf 100644 --- a/sdks/go/go.mod +++ b/sdks/go/go.mod @@ -1,3 +1,3 @@ -module github.com/Smartdevs17/SubTrackr/sdks/go +module github.com/Smartdevs17/SubTrackr/sdks/go/v2 go 1.20 diff --git a/sdks/go/version.go b/sdks/go/version.go new file mode 100644 index 00000000..6bb55ce9 --- /dev/null +++ b/sdks/go/version.go @@ -0,0 +1,5 @@ +package subtrackr + +// SDKVersion is the released version of this module. It is kept in sync with +// sdks/VERSION by `node sdks/scripts/release.mjs set `. +const SDKVersion = "2.0.0" diff --git a/sdks/javascript/package-lock.json b/sdks/javascript/package-lock.json new file mode 100644 index 00000000..3c22c9e6 --- /dev/null +++ b/sdks/javascript/package-lock.json @@ -0,0 +1,554 @@ +{ + "name": "@subtrackr/sdk", + "version": "2.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@subtrackr/sdk", + "version": "2.0.0", + "devDependencies": { + "@types/jest": "^29.5.0", + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.12", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", + "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", + "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", + "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.5.14", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", + "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", + "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/jest-diff": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/sdks/javascript/package.json b/sdks/javascript/package.json index fd3ae8d3..3f235e92 100644 --- a/sdks/javascript/package.json +++ b/sdks/javascript/package.json @@ -1,15 +1,39 @@ { "name": "@subtrackr/sdk", - "version": "1.0.0", + "version": "2.0.0", "description": "Official SubTrackr JavaScript SDK", + "repository": { + "type": "git", + "url": "git+https://github.com/Smartdevs17/SubTrackr.git", + "directory": "sdks/javascript" + }, + "homepage": "https://github.com/Smartdevs17/SubTrackr/tree/main/sdks/javascript#readme", "main": "dist/sdks/javascript/src/index.js", "types": "dist/sdks/javascript/src/index.d.ts", + "files": [ + "dist/sdks/javascript/src/**/*.js", + "dist/sdks/javascript/src/**/*.d.ts", + "!dist/**/__tests__/**", + "dist/shared/**/*.js", + "dist/shared/**/*.d.ts", + "README.md" + ], + "publishConfig": { + "access": "public", + "provenance": true + }, + "engines": { + "node": ">=18" + }, "scripts": { "build": "tsc", - "test": "tsc --noEmit" + "test": "tsc --noEmit", + "prepublishOnly": "npm test && npm run build" }, "dependencies": {}, "devDependencies": { + "@types/jest": "^29.5.0", + "@types/node": "^20.0.0", "typescript": "^5.0.0" } } diff --git a/sdks/javascript/src/resilience.ts b/sdks/javascript/src/resilience.ts index 04355452..f54ea510 100644 --- a/sdks/javascript/src/resilience.ts +++ b/sdks/javascript/src/resilience.ts @@ -18,7 +18,12 @@ * a dead server. */ -import { CircuitBreaker, type CircuitBreakerOptions, CircuitOpenError } from './circuitBreaker'; +import { + CircuitBreaker, + type CircuitBreakerOptions, + CircuitOpenError, + type CircuitState, +} from './circuitBreaker'; import { withRetry, type RetryOptions, RetryableError } from './retry'; export interface ResilienceOptions { @@ -44,7 +49,7 @@ export interface ResilienceResult { */ export async function withResilience( action: (attempt: number) => Promise, - options: ResilienceOptions = {}, + options: ResilienceOptions = {} ): Promise> { const breaker = new CircuitBreaker(options.circuitBreaker ?? { name: 'sdk' }); return withResilienceAndBreaker(action, breaker, options); @@ -57,7 +62,7 @@ export async function withResilience( export async function withResilienceAndBreaker( action: (attempt: number) => Promise, breaker: CircuitBreaker, - options: ResilienceOptions = {}, + options: ResilienceOptions = {} ): Promise> { const retryOpts: RetryOptions = { maxAttempts: 3, diff --git a/sdks/javascript/tsconfig.json b/sdks/javascript/tsconfig.json index b728ac9a..b9bbe084 100644 --- a/sdks/javascript/tsconfig.json +++ b/sdks/javascript/tsconfig.json @@ -11,5 +11,6 @@ "forceConsistentCasingInFileNames": true, "types": ["jest", "node"] }, - "include": ["src/**/*", "../../shared/types/contract.ts"] + "include": ["src/**/*", "../../shared/types/contract.ts"], + "exclude": ["src/**/__tests__/**"] } diff --git a/sdks/python/setup.py b/sdks/python/setup.py index 765c948b..ec6c224e 100644 --- a/sdks/python/setup.py +++ b/sdks/python/setup.py @@ -1,11 +1,20 @@ -from setuptools import setup, find_packages +from pathlib import Path + +from setuptools import find_packages, setup setup( name="subtrackr-sdk", - version="1.0.0", + version="2.0.0", description="Official SubTrackr Python SDK", + long_description=(Path(__file__).parent / "README.md").read_text(encoding="utf-8"), + long_description_content_type="text/markdown", author="SubTrackr", - packages=find_packages(), + url="https://github.com/Smartdevs17/SubTrackr/tree/main/sdks/python", + project_urls={ + "Source": "https://github.com/Smartdevs17/SubTrackr", + "Changelog": "https://github.com/Smartdevs17/SubTrackr/blob/main/sdks/CHANGELOG.md", + }, + packages=find_packages(exclude=["tests", "tests.*"]), install_requires=[ "requests>=2.25.1", ], diff --git a/sdks/python/subtrackr/client.py b/sdks/python/subtrackr/client.py index 9c0c3a70..df75193a 100644 --- a/sdks/python/subtrackr/client.py +++ b/sdks/python/subtrackr/client.py @@ -85,6 +85,8 @@ def __init__( self.token = token self.api_version = api_version self.warn_on_deprecation = warn_on_deprecation + # One pooled HTTP session for every call; replaceable in tests. + self.session = requests.Session() # ── Headers ────────────────────────────────────────────────────────────── @@ -112,21 +114,40 @@ def get_api_version(self) -> int: # ── Current REST methods ────────────────────────────────────────────────── - def list_subscriptions(self) -> List[Dict[str, Any]]: - """List all subscriptions (current, preferred method).""" - response = requests.get( - f"{self.base_url}/subscriptions", headers=self._headers() + def _request( + self, method: str, path: str, json: Optional[Dict[str, Any]] = None + ) -> Any: + response = self.session.request( + method, f"{self.base_url}{path}", headers=self._headers(), json=json ) raise_for_response(response) - return response.json() # type: ignore[no-any-return] + return response.json() + + def list_subscriptions(self) -> List[Dict[str, Any]]: + """List all subscriptions (current, preferred method).""" + return self._request("GET", "/subscriptions") # type: ignore[no-any-return] def create_subscription(self, payload: Dict[str, Any]) -> Dict[str, Any]: """Create a new subscription.""" - response = requests.post( - f"{self.base_url}/subscriptions", json=payload, headers=self._headers() + return self._request("POST", "/subscriptions", json=payload) # type: ignore[no-any-return] + + # ── Contract methods ────────────────────────────────────────────────────── + + def create_plan( + self, merchant: str, name: str, price: int, token: str, interval: str + ) -> int: + """Create a billing plan and return its id (same payload as the JS SDK's createPlan).""" + return self._request( # type: ignore[no-any-return] + "POST", + "/create_plan", + json={ + "merchant": merchant, + "name": name, + "price": price, + "token": token, + "interval": interval, + }, ) - raise_for_response(response) - return response.json() # type: ignore[no-any-return] # ── Deprecated aliases ──────────────────────────────────────────────────── diff --git a/sdks/python/tests/test_client.py b/sdks/python/tests/test_client.py index 17dda617..1d4175e9 100644 --- a/sdks/python/tests/test_client.py +++ b/sdks/python/tests/test_client.py @@ -1,6 +1,6 @@ import unittest -from subtrackr import SubTrackrClient +from subtrackr import ApiError, SubTrackrClient class FakeResponse: @@ -25,7 +25,7 @@ def request(self, method, url, headers=None, json=None): class SubTrackrClientTest(unittest.TestCase): def test_create_plan_posts_contract_payload(self): - client = SubTrackrClient("test-key", base_url="https://example.test") + client = SubTrackrClient(base_url="https://example.test", api_key="test-key") session = FakeSession() client.session = session @@ -35,6 +35,33 @@ def test_create_plan_posts_contract_payload(self): self.assertEqual(session.calls[0][1], "https://example.test/create_plan") self.assertEqual(session.calls[0][3]["interval"], "Monthly") + def test_requests_carry_auth_and_version_headers(self): + client = SubTrackrClient(base_url="https://example.test/", api_key="test-key") + session = FakeSession() + client.session = session + + client.list_subscriptions() + + method, url, headers, body = session.calls[0] + self.assertEqual((method, url, body), ("GET", "https://example.test/subscriptions", None)) + self.assertEqual(headers["X-API-Key"], "test-key") + self.assertIn("X-SDK-Version", headers) + + def test_error_responses_raise_api_error(self): + class ErrorSession(FakeSession): + def request(self, method, url, headers=None, json=None): + response = FakeResponse({"error": {"code": "plan_exists", "message": "Plan exists"}}) + response.ok = False + response.status_code = 409 + return response + + client = SubTrackrClient(base_url="https://example.test", api_key="test-key") + client.session = ErrorSession() + + with self.assertRaises(ApiError) as ctx: + client.create_plan("GMERCHANT", "Pro", 100, "TOKEN", "Monthly") + self.assertEqual(ctx.exception.status_code, 409) + if __name__ == "__main__": unittest.main() diff --git a/sdks/scripts/__tests__/release.test.mjs b/sdks/scripts/__tests__/release.test.mjs new file mode 100644 index 00000000..b125b40d --- /dev/null +++ b/sdks/scripts/__tests__/release.test.mjs @@ -0,0 +1,286 @@ +/** + * Tests for the SDK release library. Run with: + * node --test sdks/scripts/__tests__/release.test.mjs + */ + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + changelogHasEntry, + checkVersions, + escapeGoModulePath, + goModulePath, + goTag, + npmDistTag, + parseVersion, + planRelease, + registryStatus, + registryUrls, + renderSummary, + setVersions, + toPep440, +} from '../lib/release.mjs'; + +const SDK_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..'); +const readRepo = (rel) => readFileSync(join(SDK_ROOT, rel), 'utf8'); + +/** In-memory copy of the real version-bearing files. */ +function fixtureFs() { + const files = new Map( + [ + 'javascript/package.json', + 'javascript/src/version.ts', + 'python/setup.py', + 'python/subtrackr/version.py', + 'go/version.go', + 'go/go.mod', + ].map((f) => [f, readRepo(f)]) + ); + return { + files, + read: (f) => { + if (!files.has(f)) throw new Error(`ENOENT ${f}`); + return files.get(f); + }, + write: (f, c) => files.set(f, c), + }; +} + +const response = (status) => ({ status }); + +describe('versions', () => { + test('parses stable and pre-release versions', () => { + assert.deepEqual(parseVersion('2.1.3'), { + raw: '2.1.3', + major: 2, + minor: 1, + patch: 3, + pre: null, + }); + assert.deepEqual(parseVersion(' 3.0.0-rc.2\n').pre, { label: 'rc', number: 2 }); + }); + + test('rejects malformed versions and unsupported pre-release labels', () => { + for (const bad of ['2.1', 'v2.1.0', '02.1.0', '2.1.0-dev.1', '2.1.0-rc', '2.1.0-rc.01', '']) { + assert.throws(() => parseVersion(bad), /Invalid SDK version/, bad); + } + }); + + test('maps to PEP 440 and npm dist-tags', () => { + assert.equal(toPep440(parseVersion('2.1.0')), '2.1.0'); + assert.equal(toPep440(parseVersion('2.1.0-alpha.1')), '2.1.0a1'); + assert.equal(toPep440(parseVersion('2.1.0-beta.3')), '2.1.0b3'); + assert.equal(toPep440(parseVersion('2.1.0-rc.2')), '2.1.0rc2'); + assert.equal(npmDistTag(parseVersion('2.1.0')), 'latest'); + assert.equal(npmDistTag(parseVersion('2.1.0-rc.1')), 'next'); + }); + + test('applies Go semantic import versioning', () => { + assert.equal(goModulePath(parseVersion('1.4.0')), 'github.com/Smartdevs17/SubTrackr/sdks/go'); + assert.equal( + goModulePath(parseVersion('2.0.0')), + 'github.com/Smartdevs17/SubTrackr/sdks/go/v2' + ); + assert.equal( + goModulePath(parseVersion('3.0.0-rc.1')), + 'github.com/Smartdevs17/SubTrackr/sdks/go/v3' + ); + assert.equal(goTag(parseVersion('2.0.1')), 'sdks/go/v2.0.1'); + assert.equal( + escapeGoModulePath('github.com/Smartdevs17/SubTrackr/sdks/go/v2'), + 'github.com/!smartdevs17/!sub!trackr/sdks/go/v2' + ); + }); +}); + +describe('manifest sync', () => { + test('the committed SDK files match sdks/VERSION', () => { + const version = readRepo('VERSION').trim(); + assert.deepEqual(checkVersions(version, readRepo), []); + assert.ok(changelogHasEntry(readRepo('CHANGELOG.md'), version)); + }); + + test('reports every file that disagrees', () => { + const fs = fixtureFs(); + const problems = checkVersions('2.4.0', fs.read); + assert.equal(problems.length, 7); // all but go.mod, whose /v2 path still holds + assert.ok(problems.some((p) => p.startsWith('python/setup.py: setup() version is "2.0.0"'))); + }); + + test('reports missing files and missing markers', () => { + const fs = fixtureFs(); + fs.files.delete('go/version.go'); + fs.write('python/setup.py', 'setup(name="x")'); + const problems = checkVersions('2.0.0', fs.read); + assert.ok(problems.includes('go/version.go: file not found')); + assert.ok(problems.includes('python/setup.py: could not find setup() version')); + }); + + test('set rewrites every file so check passes', () => { + const fs = fixtureFs(); + const changed = setVersions('3.1.0-rc.1', fs.read, fs.write); + assert.deepEqual(changed.sort(), [...fs.files.keys()].sort()); + assert.deepEqual(checkVersions('3.1.0-rc.1', fs.read), []); + assert.match(fs.read('python/setup.py'), /version="3\.1\.0rc1"/); + assert.match( + fs.read('python/subtrackr/version.py'), + /SDK_VERSION_TUPLE: tuple\[int, int, int\] = \(3, 1, 0\)/ + ); + assert.match(fs.read('javascript/src/version.ts'), /major: 3,\n {2}minor: 1,\n {2}patch: 0,/); + assert.match( + fs.read('go/go.mod'), + /^module github\.com\/Smartdevs17\/SubTrackr\/sdks\/go\/v3$/m + ); + }); + + test('set is idempotent', () => { + const fs = fixtureFs(); + setVersions('2.0.0', fs.read, fs.write); + assert.deepEqual(setVersions('2.0.0', fs.read, fs.write), []); + }); + + test('set leaves everything untouched when a marker is missing', () => { + const fs = fixtureFs(); + const before = new Map(fs.files); + fs.write('go/version.go', 'package subtrackr\n'); + assert.throws(() => setVersions('2.1.0', fs.read, fs.write), /go\/version\.go/); + assert.equal(fs.read('javascript/package.json'), before.get('javascript/package.json')); + }); + + test('changelog entries must match the exact version', () => { + const log = '# Changelog\n\n## [2.1.0]\n\n- x\n\n## [2.0.0]\n'; + assert.ok(changelogHasEntry(log, '2.1.0')); + assert.ok(!changelogHasEntry(log, '2.1')); + assert.ok(!changelogHasEntry(log, '2.1.0-rc.1')); + assert.ok(!changelogHasEntry('see [2.1.0] notes', '2.1.0')); + }); +}); + +describe('release plan', () => { + test('publishes only for a matching sdk tag push', () => { + const plan = planRelease({ version: '2.1.0', eventName: 'push', ref: 'refs/tags/sdk-v2.1.0' }); + assert.deepEqual(plan, { + version: '2.1.0', + pythonVersion: '2.1.0', + npmTag: 'latest', + goModule: 'github.com/Smartdevs17/SubTrackr/sdks/go/v2', + goTag: 'sdks/go/v2.1.0', + prerelease: false, + publish: true, + }); + }); + + test('every other trigger is a dry run', () => { + for (const [eventName, ref] of [ + ['pull_request', 'refs/pull/12/merge'], + ['push', 'refs/heads/main'], + ['workflow_dispatch', 'refs/heads/main'], + ['workflow_dispatch', 'refs/tags/sdk-v2.1.0'], + ['local', ''], + ]) { + assert.equal( + planRelease({ version: '2.1.0', eventName, ref }).publish, + false, + `${eventName} ${ref}` + ); + } + }); + + test('rejects tags that do not match sdks/VERSION', () => { + assert.throws( + () => planRelease({ version: '2.1.0', eventName: 'push', ref: 'refs/tags/sdk-v2.0.9' }), + /does not match sdks\/VERSION \(2\.1\.0\)/ + ); + assert.throws( + () => planRelease({ version: '2.1.0', eventName: 'push', ref: 'refs/tags/v2.1.0' }), + /not an SDK release tag/ + ); + }); + + test('routes pre-releases to the next dist-tag', () => { + const plan = planRelease({ + version: '2.2.0-beta.1', + eventName: 'push', + ref: 'refs/tags/sdk-v2.2.0-beta.1', + }); + assert.equal(plan.npmTag, 'next'); + assert.equal(plan.pythonVersion, '2.2.0b1'); + assert.equal(plan.prerelease, true); + }); +}); + +describe('registry status', () => { + const plan = planRelease({ version: '2.1.0', eventName: 'local', ref: '' }); + + test('builds the per-registry version URLs', () => { + assert.deepEqual(registryUrls(plan), { + npm: 'https://registry.npmjs.org/@subtrackr%2Fsdk/2.1.0', + pypi: 'https://pypi.org/pypi/subtrackr-sdk/2.1.0/json', + go: 'https://proxy.golang.org/github.com/!smartdevs17/!sub!trackr/sdks/go/v2/@v/v2.1.0.info', + }); + }); + + test('treats 200 as published and 404/410 as not published', async () => { + const codes = { 'registry.npmjs.org': 200, 'pypi.org': 404, 'proxy.golang.org': 410 }; + const fetchImpl = async (url) => response(codes[new URL(url).host]); + assert.deepEqual(await registryStatus(plan, { fetchImpl }), { + npm: true, + pypi: false, + go: false, + }); + }); + + test('retries transient failures', async () => { + let calls = 0; + const fetchImpl = async () => { + calls++; + if (calls === 1) throw new Error('ECONNRESET'); + if (calls === 2) return response(503); + return response(404); + }; + const status = await registryStatus(plan, { fetchImpl, delayMs: 0 }); + assert.equal(status.npm, false); + assert.equal(calls, 5); // 3 for npm, then 1 each for PyPI and Go + }); + + test('fails closed when a registry keeps erroring', async () => { + const fetchImpl = async () => response(500); + await assert.rejects( + registryStatus(plan, { fetchImpl, retries: 2, delayMs: 0 }), + /Registry check failed after 2 attempts: .* returned HTTP 500/ + ); + }); +}); + +describe('summary', () => { + const ok = { result: 'success', alreadyPublished: false }; + + test('reports published, skipped and failed SDKs', () => { + const plan = planRelease({ version: '2.1.0', eventName: 'push', ref: 'refs/tags/sdk-v2.1.0' }); + const md = renderSummary(plan, { + javascript: ok, + python: { result: 'success', alreadyPublished: true }, + go: { result: 'failure', alreadyPublished: false }, + }); + assert.match(md, /^## SDK release 2\.1\.0\n/); + assert.match( + md, + /\| JavaScript \| npm `@subtrackr\/sdk@2\.1\.0` \(latest\) \| ✅ success \| published \|/ + ); + assert.match( + md, + /\| Python \| PyPI `subtrackr-sdk==2\.1\.0` \| ✅ success \| already published, skipped \|/ + ); + assert.match(md, /\| Go \| .* \| ❌ failure \| — \|/); + }); + + test('labels dry runs', () => { + const plan = planRelease({ version: '2.1.0', eventName: 'pull_request', ref: '' }); + const md = renderSummary(plan, { javascript: ok, python: ok, go: ok }); + assert.match(md, /\(dry run\)/); + assert.equal(md.match(/dry run \(not published\)/g).length, 3); + }); +}); diff --git a/sdks/scripts/lib/release.mjs b/sdks/scripts/lib/release.mjs new file mode 100644 index 00000000..a8a30c7c --- /dev/null +++ b/sdks/scripts/lib/release.mjs @@ -0,0 +1,303 @@ +/** + * SDK release library: one version for the JavaScript, Python and Go SDKs. + * + * `sdks/VERSION` is the single source of truth. Everything here is pure or + * takes its I/O (file reads/writes, fetch) as arguments so it can be unit + * tested without touching the repo or the network. The CLI lives in + * ../release.mjs. + */ + +// ── Versions ────────────────────────────────────────────────────────────────── + +const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(alpha|beta|rc)\.(0|[1-9]\d*))?$/; + +/** + * Parses `MAJOR.MINOR.PATCH` or `MAJOR.MINOR.PATCH-(alpha|beta|rc).N`. + * Other pre-release labels are rejected because they have no PEP 440 form. + */ +export function parseVersion(input) { + const version = String(input).trim(); + const m = SEMVER_RE.exec(version); + if (!m) { + throw new Error( + `Invalid SDK version "${version}". Expected MAJOR.MINOR.PATCH or MAJOR.MINOR.PATCH-(alpha|beta|rc).N` + ); + } + return { + raw: version, + major: Number(m[1]), + minor: Number(m[2]), + patch: Number(m[3]), + pre: m[4] ? { label: m[4], number: Number(m[5]) } : null, + }; +} + +/** PEP 440 spelling used by PyPI: `2.1.0-rc.1` → `2.1.0rc1`. */ +export function toPep440(v) { + if (!v.pre) return `${v.major}.${v.minor}.${v.patch}`; + const label = { alpha: 'a', beta: 'b', rc: 'rc' }[v.pre.label]; + return `${v.major}.${v.minor}.${v.patch}${label}${v.pre.number}`; +} + +/** npm dist-tag: pre-releases go to `next` so `npm install` keeps getting stable. */ +export function npmDistTag(v) { + return v.pre ? 'next' : 'latest'; +} + +// ── Go module path (semantic import versioning) ─────────────────────────────── + +export const GO_MODULE_BASE = 'github.com/Smartdevs17/SubTrackr/sdks/go'; + +/** Go requires a `/vN` suffix on the module path from v2 onwards. */ +export function goModulePath(v) { + return v.major >= 2 ? `${GO_MODULE_BASE}/v${v.major}` : GO_MODULE_BASE; +} + +/** Tag Go resolves for a module in the `sdks/go` subdirectory. */ +export function goTag(v) { + return `sdks/go/v${v.raw}`; +} + +/** proxy.golang.org path escaping: each upper-case letter becomes `!` + lower-case. */ +export function escapeGoModulePath(path) { + return path.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`); +} + +// ── Version-bearing files ───────────────────────────────────────────────────── + +/** + * Every file that carries the SDK version, with how to read and rewrite it. + * Paths are relative to `sdks/`. `expected(v)` is the value that file must + * hold for version `v`. + */ +export const VERSION_TARGETS = [ + { + file: 'javascript/package.json', + label: 'npm package version', + pattern: /("version"\s*:\s*")([^"]+)(")/, + expected: (v) => v.raw, + }, + { + file: 'javascript/src/version.ts', + label: 'SDK_VERSION', + pattern: /(export const SDK_VERSION = ')([^']+)(')/, + expected: (v) => v.raw, + }, + { + file: 'javascript/src/version.ts', + label: 'SDK_VERSION_INFO', + pattern: /(export const SDK_VERSION_INFO = \{\s*major: )(\d+,\s*minor: \d+,\s*patch: \d+)(,)/, + expected: (v) => `${v.major},\n minor: ${v.minor},\n patch: ${v.patch}`, + normalize: (s) => s.replace(/\s+/g, ' '), + }, + { + file: 'python/setup.py', + label: 'setup() version', + pattern: /(version=")([^"]+)(")/, + expected: toPep440, + }, + { + file: 'python/subtrackr/version.py', + label: 'SDK_VERSION', + pattern: /(SDK_VERSION: str = ")([^"]+)(")/, + expected: toPep440, + }, + { + file: 'python/subtrackr/version.py', + label: 'SDK_VERSION_TUPLE', + pattern: /(SDK_VERSION_TUPLE: tuple\[int, int, int\] = \()([^)]+)(\))/, + expected: (v) => `${v.major}, ${v.minor}, ${v.patch}`, + }, + { + file: 'go/version.go', + label: 'SDKVersion', + pattern: /(const SDKVersion = ")([^"]+)(")/, + expected: (v) => v.raw, + }, + { + file: 'go/go.mod', + label: 'module path', + pattern: /^(module )(\S+)()$/m, + expected: goModulePath, + }, +]; + +/** + * Compares every target against `version`. + * @param readFile (relPath) => string + * @returns list of human-readable mismatches (empty when in sync) + */ +export function checkVersions(version, readFile) { + const v = parseVersion(version); + const problems = []; + for (const target of VERSION_TARGETS) { + let content; + try { + content = readFile(target.file); + } catch { + problems.push(`${target.file}: file not found`); + continue; + } + const m = target.pattern.exec(content); + if (!m) { + problems.push(`${target.file}: could not find ${target.label}`); + continue; + } + const norm = target.normalize ?? ((s) => s); + const want = target.expected(v); + if (norm(m[2]) !== norm(want)) { + problems.push(`${target.file}: ${target.label} is "${norm(m[2])}", expected "${norm(want)}"`); + } + } + return problems; +} + +/** + * Rewrites every target to `version`. + * @returns list of files that changed + */ +export function setVersions(version, readFile, writeFile) { + const v = parseVersion(version); + const contents = new Map(); + for (const target of VERSION_TARGETS) { + const content = contents.get(target.file) ?? readFile(target.file); + if (!target.pattern.test(content)) { + throw new Error(`${target.file}: could not find ${target.label}`); + } + contents.set( + target.file, + content.replace(target.pattern, (_, pre, _old, post) => `${pre}${target.expected(v)}${post}`) + ); + } + const changed = []; + for (const [file, content] of contents) { + if (content !== readFile(file)) { + writeFile(file, content); + changed.push(file); + } + } + return changed; +} + +/** Whether CHANGELOG.md has a `## [x.y.z]` section for this version. */ +export function changelogHasEntry(changelog, version) { + const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return new RegExp(`^## \\[${escaped}\\]`, 'm').test(changelog); +} + +// ── Release planning ────────────────────────────────────────────────────────── + +export const TAG_PREFIX = 'sdk-v'; + +/** + * Decides what a workflow run should do. + * + * Only a pushed `sdk-vX.Y.Z` tag publishes, and only when it matches + * `sdks/VERSION`. Every other trigger (pull request, branch push, manual run) + * is a dry run that builds and verifies all three SDKs. + */ +export function planRelease({ version, eventName, ref }) { + const v = parseVersion(version); + const isTag = eventName === 'push' && typeof ref === 'string' && ref.startsWith('refs/tags/'); + let publish = false; + if (isTag) { + const tag = ref.slice('refs/tags/'.length); + if (!tag.startsWith(TAG_PREFIX)) { + throw new Error(`Tag "${tag}" is not an SDK release tag (expected ${TAG_PREFIX}${v.raw})`); + } + if (tag !== `${TAG_PREFIX}${v.raw}`) { + throw new Error(`Tag "${tag}" does not match sdks/VERSION (${v.raw})`); + } + publish = true; + } + return { + version: v.raw, + pythonVersion: toPep440(v), + npmTag: npmDistTag(v), + goModule: goModulePath(v), + goTag: goTag(v), + prerelease: Boolean(v.pre), + publish, + }; +} + +// ── Registry state ──────────────────────────────────────────────────────────── + +export const NPM_PACKAGE = '@subtrackr/sdk'; +export const PYPI_PACKAGE = 'subtrackr-sdk'; + +export function registryUrls(plan) { + return { + npm: `https://registry.npmjs.org/${NPM_PACKAGE.replace('/', '%2F')}/${plan.version}`, + pypi: `https://pypi.org/pypi/${PYPI_PACKAGE}/${plan.pythonVersion}/json`, + go: `https://proxy.golang.org/${escapeGoModulePath(plan.goModule)}/@v/v${plan.version}.info`, + }; +} + +/** + * Whether this version is already on each registry, so a re-run of a + * partially failed release only publishes what is missing. + * + * 200 means published, 404/410 means not published. Anything else is + * retried and then thrown: publishing blind could double-publish or skip. + */ +export async function registryStatus( + plan, + { fetchImpl = fetch, retries = 3, delayMs = 1000 } = {} +) { + const urls = registryUrls(plan); + const result = {}; + for (const [registry, url] of Object.entries(urls)) { + result[registry] = await probe(url, fetchImpl, retries, delayMs); + } + return result; +} + +async function probe(url, fetchImpl, retries, delayMs) { + let lastError; + for (let attempt = 1; attempt <= retries; attempt++) { + try { + const res = await fetchImpl(url, { method: 'GET', headers: { accept: 'application/json' } }); + if (res.status === 200) return true; + if (res.status === 404 || res.status === 410) return false; + lastError = new Error(`${url} returned HTTP ${res.status}`); + } catch (err) { + lastError = err; + } + if (attempt < retries) await new Promise((r) => setTimeout(r, delayMs * attempt)); + } + throw new Error( + `Registry check failed after ${retries} attempts: ${lastError?.message ?? lastError}` + ); +} + +// ── Run summary ─────────────────────────────────────────────────────────────── + +/** + * Markdown for $GITHUB_STEP_SUMMARY: one row per SDK with its job result and + * what happened on its registry. + */ +export function renderSummary(plan, jobs) { + const action = (job) => { + if (job.result !== 'success') return '—'; + if (!plan.publish) return 'dry run (not published)'; + return job.alreadyPublished ? 'already published, skipped' : 'published'; + }; + const rows = [ + ['JavaScript', `npm \`${NPM_PACKAGE}@${plan.version}\` (${plan.npmTag})`, jobs.javascript], + ['Python', `PyPI \`${PYPI_PACKAGE}==${plan.pythonVersion}\``, jobs.python], + ['Go', `\`${plan.goModule}@v${plan.version}\``, jobs.go], + ]; + const icon = (r) => ({ success: '✅', skipped: '⏭️', cancelled: '⚪' })[r] ?? '❌'; + return [ + `## SDK release ${plan.version}${plan.publish ? '' : ' (dry run)'}`, + '', + '| SDK | Package | Result | Registry |', + '|---|---|---|---|', + ...rows.map( + ([name, pkg, job]) => + `| ${name} | ${pkg} | ${icon(job.result)} ${job.result} | ${action(job)} |` + ), + '', + ].join('\n'); +} diff --git a/sdks/scripts/release.mjs b/sdks/scripts/release.mjs new file mode 100644 index 00000000..66bef599 --- /dev/null +++ b/sdks/scripts/release.mjs @@ -0,0 +1,141 @@ +#!/usr/bin/env node +/** + * SDK release CLI. See sdks/docs/releasing.md. + * + * node sdks/scripts/release.mjs check # manifests + changelog match sdks/VERSION + * node sdks/scripts/release.mjs set 2.1.0 # write a new version everywhere + * node sdks/scripts/release.mjs plan # decide dry run vs publish (CI) + * node sdks/scripts/release.mjs registry-status # which registries already have it (CI) + * node sdks/scripts/release.mjs summary # job summary table (CI) + * + * In GitHub Actions, `plan` and `registry-status` write to $GITHUB_OUTPUT and + * `summary` writes to $GITHUB_STEP_SUMMARY. Logs are `[sdk-release]` lines + * with `::error::` annotations on failure. + */ + +import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + changelogHasEntry, + checkVersions, + parseVersion, + planRelease, + registryStatus, + renderSummary, + setVersions, +} from './lib/release.mjs'; + +const SDK_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); +const read = (rel) => readFileSync(join(SDK_ROOT, rel), 'utf8'); +const write = (rel, content) => writeFileSync(join(SDK_ROOT, rel), content); + +const log = (msg) => console.log(`[sdk-release] ${msg}`); +const fail = (msg) => { + console.error(process.env.GITHUB_ACTIONS ? `::error::${msg}` : `[sdk-release] ERROR: ${msg}`); + process.exitCode = 1; +}; + +function setOutputs(outputs) { + for (const [k, v] of Object.entries(outputs)) log(`${k}=${v}`); + if (process.env.GITHUB_OUTPUT) { + appendFileSync( + process.env.GITHUB_OUTPUT, + Object.entries(outputs) + .map(([k, v]) => `${k}=${v}\n`) + .join('') + ); + } +} + +const currentVersion = () => read('VERSION').trim(); + +function currentPlan() { + return planRelease({ + version: currentVersion(), + eventName: process.env.GITHUB_EVENT_NAME ?? 'local', + ref: process.env.GITHUB_REF ?? '', + }); +} + +const commands = { + check() { + const version = currentVersion(); + parseVersion(version); + const problems = checkVersions(version, read); + if (!changelogHasEntry(read('CHANGELOG.md'), version)) { + problems.push(`CHANGELOG.md: no "## [${version}]" section`); + } + if (problems.length > 0) { + problems.forEach(fail); + fail( + `SDK versions are out of sync with sdks/VERSION (${version}). Run: node sdks/scripts/release.mjs set ${version}` + ); + return; + } + log(`all SDK manifests match ${version}`); + }, + + set(version) { + if (!version) throw new Error('Usage: release.mjs set '); + parseVersion(version); + write('VERSION', `${version}\n`); + const changed = setVersions(version, read, write); + log(`set SDK version to ${version}; updated ${['VERSION', ...changed].join(', ')}`); + if (!changelogHasEntry(read('CHANGELOG.md'), version)) { + log(`next: add a "## [${version}]" section to sdks/CHANGELOG.md`); + } + }, + + plan() { + const plan = currentPlan(); + setOutputs({ + version: plan.version, + python_version: plan.pythonVersion, + npm_tag: plan.npmTag, + go_module: plan.goModule, + go_tag: plan.goTag, + prerelease: plan.prerelease, + publish: plan.publish, + }); + }, + + async 'registry-status'() { + const status = await registryStatus(currentPlan()); + setOutputs({ + npm_published: status.npm, + pypi_published: status.pypi, + go_published: status.go, + }); + }, + + summary() { + const env = process.env; + const job = (name) => ({ + result: env[`${name.toUpperCase()}_RESULT`] ?? 'skipped', + alreadyPublished: env[`${name.toUpperCase()}_ALREADY_PUBLISHED`] === 'true', + }); + const markdown = renderSummary(currentPlan(), { + javascript: job('javascript'), + python: job('python'), + go: job('go'), + }); + if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, markdown); + console.log(markdown); + if (['javascript', 'python', 'go'].some((n) => job(n).result !== 'success')) { + fail('one or more SDK jobs did not succeed'); + } + }, +}; + +const [command, ...args] = process.argv.slice(2); +const run = commands[command]; +if (!run) { + console.error(`Usage: release.mjs <${Object.keys(commands).join('|')}>`); + process.exit(2); +} +try { + await run(...args); +} catch (err) { + fail(err instanceof Error ? err.message : String(err)); +}