diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh new file mode 100755 index 0000000..dee0e53 --- /dev/null +++ b/.claude/hooks/session-start.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# SessionStart hook for Claude Code on the web: bootstrap Aikido Safe Chain and +# install dependencies through its shims, as .devcontainer and .cursor do. +# +# Hook stdout is injected into the session, so the install log goes to stderr. +# Shim PATH is written by setup-cloud-environment.sh before that script can fail +# (CLAUDE_ENV_FILE). Do not append it here after the bootstrap: a failed hook +# would then leave the package managers unshimmed. +set -euo pipefail + +if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then + exit 0 +fi + +cd "$CLAUDE_PROJECT_DIR" + +bash ./scripts/setup-cloud-environment.sh >&2 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..1833e5e --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "bash \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/session-start.sh", + "timeout": 600 + } + ] + } + ] + } +} diff --git a/.cursor/environment.json b/.cursor/environment.json new file mode 100644 index 0000000..dea3aa2 --- /dev/null +++ b/.cursor/environment.json @@ -0,0 +1,3 @@ +{ + "install": "bash ./scripts/setup-cloud-environment.sh" +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..ac42279 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,11 @@ +{ + "name": "Node.js", + "image": "mcr.microsoft.com/devcontainers/javascript-node:5.2.5-24-trixie@sha256:2015e2c863cb1e608bc0876860dd063cdb9e3d9a02dca63d1c2fce8fad02d088", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/docker-in-docker:4": { + "moby": false + } + }, + "postCreateCommand": "bash ./scripts/setup-cloud-environment.sh" +} diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..589d0f8 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,9 @@ +# High-risk paths. Last matching pattern wins. +# Root-anchored so nested copies (e.g. skills/**/scripts/) are not owned here. +/.github/ @jaredwray @hyphen/engineers +/.vscode/ @jaredwray @hyphen/engineers +/.cursor/ @jaredwray @hyphen/engineers +/.devcontainer/ @jaredwray @hyphen/engineers +/.claude/ @jaredwray @hyphen/engineers +/.codex/ @jaredwray @hyphen/engineers +/scripts/ @jaredwray @hyphen/engineers diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..0e4c9d8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,14 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**How To Reproduce (best to provide workable code or tests!)** +Please provide code or unit test example that will reproduce the error. If you can't provide code, please provide a detailed description of how to reproduce the error. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..c444027 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,14 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..ccdc2ef --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +**Please check if the PR fulfills these requirements** +- [ ] Followed the [Contributing](../blob/main/CONTRIBUTING.md) guidelines and [Code of Conduct](../blob/main/CODE_OF_CONDUCT.md) +- [ ] Tests for the changes have been added (for bug fixes/features) with 100% code coverage. + +**What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...) diff --git a/.github/workflows/check-workflows.yaml b/.github/workflows/check-workflows.yaml new file mode 100644 index 0000000..6a97664 --- /dev/null +++ b/.github/workflows/check-workflows.yaml @@ -0,0 +1,34 @@ +name: check-workflows + +on: + push: + branches: [main] + pull_request: + +permissions: {} + +jobs: + zizmor: + runs-on: ubuntu-latest + permissions: + contents: read + actions: read + # The SARIF upload needs this permission. + # GitHub ignores the write grant on a fork pull request. + security-events: write + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + - name: Run zizmor + uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0 + with: + # A fork pull request cannot upload SARIF. It uses annotations. + advanced-security: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + annotations: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} diff --git a/.github/workflows/code-coverage.yaml b/.github/workflows/code-coverage.yaml new file mode 100644 index 0000000..2b55876 --- /dev/null +++ b/.github/workflows/code-coverage.yaml @@ -0,0 +1,60 @@ +name: code-coverage + +on: + workflow_dispatch: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +permissions: + contents: read + +env: + HYPHEN_PUBLIC_API_KEY: ${{ secrets.HYPHEN_PUBLIC_API_KEY }} + HYPHEN_API_KEY: ${{ secrets.HYPHEN_API_KEY }} + HYPHEN_APPLICATION_ID: ${{ secrets.HYPHEN_APPLICATION_ID }} + HYPHEN_ORGANIZATION_ID: ${{ secrets.HYPHEN_ORGANIZATION_ID }} + HYPHEN_LINK_DOMAIN: test.h4n.link + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - name: Use Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: 'pnpm' + + - name: Install Dependencies + run: sfw pnpm install --frozen-lockfile + + - name: Build + run: pnpm build + + - name: Testing + run: pnpm test:ci + + - name: Code Coverage + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + token: ${{ secrets.CODECOV_TOKEN }} + slug: Hyphen/javascript-sdks + # Each package writes one lcov file. The paths in each file start at the repository root. + files: ./packages/nodejs-sdk/coverage/lcov.info,./packages/browser-sdk/coverage/lcov.info,./packages/react-sdk/coverage/lcov.info diff --git a/.github/workflows/codeql.yaml b/.github/workflows/codeql.yaml new file mode 100644 index 0000000..bb364e3 --- /dev/null +++ b/.github/workflows/codeql.yaml @@ -0,0 +1,83 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: codeql + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + +permissions: + contents: read + +jobs: + analyze: + name: analyze-${{ matrix.language }} + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'javascript' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + + # โ„น๏ธ Command-line programs to run using the OS shell. + # ๐Ÿ“š See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..595e6f3 --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,123 @@ +name: release + +on: + workflow_dispatch: + release: + types: [released] + +permissions: + contents: read + +jobs: + aikido-gate: + runs-on: ubuntu-latest + # A stalled scan stops after 15 minutes. + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Install Aikido CI client + # zizmor: ignore[adhoc-packages] pinned Aikido CI client for the release gate + run: sfw npm install --global @aikidosec/ci-api-client@1.0.17 + + - name: Run Aikido release scan + # The scan fails when Aikido reports a new finding at severity LOW or above. + # The API key comes from the Aikido CI settings. + # The key cannot publish a package. + env: + REPO_NAME: ${{ github.event.repository.name }} + AIKIDO_CLIENT_API_KEY: ${{ secrets.AIKIDO_CLIENT_API_KEY }} + run: > + aikido-api-client scan-release + "$REPO_NAME" "$GITHUB_SHA" + --apikey "$AIKIDO_CLIENT_API_KEY" + --fail-on-sast-scan --fail-on-iac-scan --fail-on-secrets-scan + --minimum-severity-level LOW + + build: + needs: [aikido-gate] + + runs-on: ubuntu-latest + permissions: + contents: read + # OIDC lets this job stage the packages. + id-token: write + + env: + HYPHEN_PUBLIC_API_KEY: ${{ secrets.HYPHEN_PUBLIC_API_KEY }} + HYPHEN_API_KEY: ${{ secrets.HYPHEN_API_KEY }} + HYPHEN_APPLICATION_ID: ${{ secrets.HYPHEN_APPLICATION_ID }} + HYPHEN_ORGANIZATION_ID: ${{ secrets.HYPHEN_ORGANIZATION_ID }} + HYPHEN_LINK_DOMAIN: test.h4n.link + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - name: Use Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Install Dependencies + run: sfw pnpm install --frozen-lockfile + + - name: Build + run: pnpm build + + - name: Testing + run: pnpm test:ci + + - name: Pack + # This step packs each package that has a version that is not on npm. + # It does not pack a package when npm has the version. + run: | + mkdir -p packed + for dir in packages/*/; do + name=$(node -p "require('./${dir}package.json').name") + version=$(node -p "require('./${dir}package.json').version") + if [ -n "$(npm view "${name}@${version}" version 2>/dev/null)" ]; then + echo "Skip ${name}@${version}. npm has this version." + else + echo "Pack ${name}@${version}." + pnpm --dir "$dir" pack --pack-destination "$PWD/packed" + fi + done + ls -la packed + + - name: Stage publish + # OIDC stages each tarball. This job does not use an npm token. + # --no-git-checks is required. The release checkout is a detached tag. + run: | + shopt -s nullglob + tarballs=(./packed/*.tgz) + if [ "${#tarballs[@]}" -eq 0 ]; then + echo "No package has a new version." + exit 0 + fi + for tarball in "${tarballs[@]}"; do + pnpm stage publish "$tarball" --access public --provenance --no-git-checks + done diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000..7c6d8a9 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,57 @@ +name: tests + +on: + workflow_dispatch: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +permissions: + contents: read + +env: + HYPHEN_PUBLIC_API_KEY: ${{ secrets.HYPHEN_PUBLIC_API_KEY }} + HYPHEN_API_KEY: ${{ secrets.HYPHEN_API_KEY }} + HYPHEN_APPLICATION_ID: ${{ secrets.HYPHEN_APPLICATION_ID }} + HYPHEN_ORGANIZATION_ID: ${{ secrets.HYPHEN_ORGANIZATION_ID }} + HYPHEN_LINK_DOMAIN: test.h4n.link + +jobs: + build-test: + name: build-test-${{ matrix.node-version }} + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: ['22', '24', '26'] + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Socket Firewall + uses: SocketDev/action@ba6de6cc0565af1f42295590380973573297e31f # v1.3.2 + with: + mode: firewall-free + firewall-version: "1.15.6" + + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ matrix.node-version }} + cache: 'pnpm' + + - name: Install Dependencies + run: sfw pnpm install --frozen-lockfile + + - name: Build + run: pnpm build + + - name: Testing + run: pnpm test:ci diff --git a/.gitignore b/.gitignore index 1301e01..7ae6274 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* +.pnpm-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json @@ -56,11 +57,18 @@ web_modules/ # Optional stylelint cache .stylelintcache +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz +packed/ # Yarn Integrity file .yarn-integrity @@ -81,7 +89,6 @@ out # Nuxt.js build / generate output .nuxt dist -.output # Gatsby files .cache/ @@ -92,11 +99,9 @@ dist # vuepress build output .vuepress/dist -# vuepress v2.x temp directory +# vuepress v2.x temp and cache directory .temp - -# Sveltekit cache directory -.svelte-kit/ +.cache # vitepress build output **/.vitepress/dist @@ -116,34 +121,23 @@ dist # DynamoDB Local files .dynamodb/ -# Firebase cache directory -.firebase/ - # TernJS port file .tern-port -# Stores Visual Studio Code versions used for testing Visual Studio Code extensions +# Stores VSCode versions used for testing VSCode extensions .vscode-test -# pnpm -.pnpm-store - -# yarn v3 +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz .pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/sdks -!.yarn/versions - -# Vite files -vite.config.js.timestamp-* -vite.config.ts.timestamp-* -.vite/ - -# Astro generated types -.astro/ - -# Turbo Repo -.turbo +.DS_Store + +!**/test/fixtures/** + +# AI (keep the shared Claude Code settings and hooks; ignore local state) +.claude/* +!.claude/settings.json +!.claude/hooks/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..cabf43b --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..dd78805 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,108 @@ +# Agent Guidelines + +- Use `pnpm` instead of `npm` for all package management commands +- When making changes, always run `pnpm test` to verify tests pass +- When making changes, always maintain 100% code coverage + +## Repository structure + +This repository is a `pnpm` workspace. Each SDK is a package in the `packages` directory. + +- `packages/nodejs-sdk` contains `@hyphen/sdk`, the SDK for Node.js. +- `packages/browser-sdk` contains `@hyphen/browser-sdk`, the SDK for the browser. Its tests use + `@hyphen/sdk`. +- `packages/react-sdk` contains `@hyphen/react-sdk`, the SDK for React. It uses + `@hyphen/browser-sdk`. + +Obey these rules for the workspace: + +- Run `pnpm install`, `pnpm build`, `pnpm lint`, and `pnpm test` from the root of the repository. + Each command runs in all packages. +- To run a command in one package, use a filter. An example is + `pnpm --filter @hyphen/browser-sdk test`. +- Keep `pnpm-lock.yaml` and `pnpm-workspace.yaml` only in the root of the repository. +- Use the `workspace:^` protocol when one package uses a different package of this repository. +- Some packages have an `AGENTS.md` file. Obey that file also when you change that package. + +## Simplified Technical English + +Write in ASD-STE100 Simplified Technical English (STE). Get the current issue of the specification +free of charge from . STE applies to all text that you write for this +repository, its pull requests, and its issues. This text includes documentation, code comments, +commit messages, review replies, and changelog entries. + +- Use approved STE words with their approved meanings. You can also use technical names and + technical verbs. If you cannot confirm that a word is approved, use a short, common word with one + meaning. +- Use one word for one meaning. +- Write an instruction in the imperative. Write one instruction in each sentence. +- Do not write more than 20 words in an instruction or 25 words in a descriptive sentence. +- Use the active voice. +- Use only the simple present, simple past, or simple future tense. Do not use the present perfect. +- Do not use the "-ing" form of a verb, except in a technical name. +- Do not write a noun cluster of more than three words. +- Do not omit articles, verbs, or subjects to make a sentence shorter. +- Write one topic in each paragraph. Do not write more than six sentences in a paragraph. +- Use a vertical list for steps, conditions, and other complex text. +- Do not change code, commands, identifiers, file paths, or quoted text to make them STE. +- Use STE for the text that you add or change. Do not rewrite other text only to make it STE. + +## Safe Chain + +Aikido Safe Chain shims examine each package that a package manager installs in this environment. +Never bypass the shims. + +- Keep `~/.safe-chain/shims` first on `PATH`. +- Run `npm`, `npx`, `pnpm`, and `pnpx` only through the shims. Do not run a different copy by its + full path. +- Do not install a package with `curl | sh` or with a package manager that has no shim. +- If Safe Chain blocks a package, stop. Do not use a different command, path, or package to get the + same code. Tell the user the package name and the Safe Chain message. + +## Test audit + +Apply this gate to each test that a pull request adds, changes, or deletes. Apply it before you open +or update the pull request. This gate is the authoring gate of the `test-audit` skill in +`jaredwray/agentic`. If that skill is installed, use it. + +Keep a new or changed test only if you can answer all four questions: + +1. Which observable behavior, invariant, or contract does the test protect? +2. Which credible regression makes the test fail? +3. Why does the current coverage not find that regression? If a test or its table owns the + contract, extend it. Do not add a near-duplicate test. +4. Does the test need an export, flag, or hook that no production caller uses? If yes, test at the + real boundary. + +- A regression test for a bug fix must fail on the code before the fix, for the intended reason. +- Do not keep a test that asserts nothing, restates the implementation, repeats the type checker, + or only proves a mock. +- A coverage target does not lower this bar. Reach an uncovered line through its public entry + point. If no caller can reach a branch, remove the branch. Do not add a test for it. +- Delete a test only when a different test proves its contract, or when the contract is gone. Do + not delete a test because it fails. +- Record the gate in the verification list of the pull request body. List each test that you did + not keep, rewrote, or deleted, and give the reason. For a deleted test, name the test that proves + its contract, or show that the contract is gone. +- Do not audit tests that this pull request does not touch. Audit them in a separate pull request. + +## Pull requests + +The task does not stop when you open a pull request. Do these steps before you start a different +task: + +1. Wait approximately 20 minutes for automated and human code reviews. +2. Read each new comment. Find each comment that has a finding, a question, or a change request. +3. Examine the code for each finding or change request. Decide if it is correct. Do not decide from + who the reviewer is. +4. If it is correct, change the code. Run the same checks that CI runs. Push the change. On the + thread, reply with what changed and the commit SHA. +5. If it is not correct, reply on the thread with the reason. Give the file and line. Do not + resolve the thread. The reviewer closes it. +6. If a comment asks a question, answer it on the thread. +7. If CI fails, find the root cause and fix it. Do not skip or disable a test to make CI pass. +8. If you pushed a change or CI did not finish, do steps 1 to 7 again. Stop when CI passes and each + finding, question, and change request has a reply. + +Do not reply to a comment that needs no answer: your own replies, approvals, thanks, and bot status +notices. A reply to one of these comments starts the loop again. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..eef4bd2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..5e5de92 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at in the repo issues +or maintainers public email address. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..67e91d9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# Contributing +When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. + +Please note we have a [Code of Conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. + +We release new versions of this project (maintenance/features) on a monthly cadence so please be aware that some items will not get released right away. + +# Pull Request Process +You can contribute changes to this repo by opening a pull request: + +1) After forking this repository to your Git account, make the proposed changes on your forked branch. +2) Run tests and linting locally `pnpm i && pnpm test` to ensure that your changes do not break any existing functionality. +3) Commit your changes and push them to your forked repository. +4) Navigate to the main `javascript-sdks` repository and select the *Pull Requests* tab. +5) Click the *New pull request* button, then select the option "Compare across forks" +6) Leave the base branch set to main. Set the compare branch to your forked branch, and open the pull request. +7) Once your pull request is created, ensure that all checks have passed and that your branch has no conflicts with the base branch. If there are any issues, resolve these changes in your local repository, and then commit and push them to git. +8) Similarly, respond to any reviewer comments or requests for changes by making edits to your local repository and pushing them to Git. +9) Once the pull request has been reviewed, those with write access to the branch will be able to merge your changes into the `javascript-sdks` repository. + +If you need more information on the steps to create a pull request, you can find a detailed walkthrough in the [Github documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) + +# Code of Conduct +Please refer to our [Code of Conduct](CODE_OF_CONDUCT.md) readme for how to contribute to this open source project and work within the community. diff --git a/DEFENSE_IN_DEPTH.md b/DEFENSE_IN_DEPTH.md new file mode 100644 index 0000000..6cae5ff --- /dev/null +++ b/DEFENSE_IN_DEPTH.md @@ -0,0 +1,58 @@ +# Defense in Depth + +Tracking against https://github.com/jaredwray/agentic/blob/main/skills/security/defense-in-depth-nodejs/SKILL.md. + +Profile: npm libraries (pnpm workspace) ยท public + +This repository contains the packages that were in `Hyphen/nodejs-sdk`, `Hyphen/browser-sdk`, and `Hyphen/react-sdk`. +The settings of those repositories do not apply to this repository. A repository admin must do each item that has the `(manual)` label again. + +## 1. Security docs +- [x] `SECURITY.md` present โ€” contact info + "How this repository is secured" summary โ€” verified 2026-11-12 +- [x] `DEFENSE_IN_DEPTH.md` present (this file) โ€” verified 2026-11-12 + +## 2. CODEOWNERS and cloud bootstrap +- [x] `.github/CODEOWNERS` covers `/.github/`, `/.vscode/`, `/.cursor/`, `/.devcontainer/`, `/.claude/`, `/.codex/`, `/scripts/` with owners the maintainer names โ€” verified 2026-11-12 +- [x] Codespaces, Cursor Cloud Agents, and Claude Code on the web bootstrap Aikido Safe Chain via scripts/setup-cloud-environment.sh (--ci shims, frozen lockfile); Claude Code runs it from `.claude/hooks/session-start.sh` (web sessions only, install log on stderr, 600s timeout) and `.gitignore` keeps `.claude/settings.json` and `.claude/hooks/` tracked โ€” verified 2026-11-12 +- [ ] Codex cloud environments use Manual setup with `bash ./scripts/setup-cloud-environment.sh` as the setup and maintenance script (manual) +- [ ] Claude Code on the web environments allow `malware-list.aikido.dev` (Custom network access plus the default package-manager list) (manual) +- [x] Dev Container `image` pinned by digest (`name:@sha256:`; not a floating tag) โ€” verified 2026-11-12 + +## 3. Dependencies (pnpm) +- [x] `packageManager: pnpm@11.3+` pinned in the root `package.json` (`pnpm@12.17.0`) โ€” verified 2026-11-12 +- [x] 7-day cooldown: `minimumReleaseAge: 10080`, `minimumReleaseAgeStrict: true`, `minimumReleaseAgeIgnoreMissingTime: false`; no first-party `minimumReleaseAgeExclude` โ€” verified 2026-11-12 +- [x] `trustPolicy: no-downgrade`; no first-party `trustPolicyExclude` โ€” verified 2026-11-12 +- [x] Lifecycle scripts blocked: `strictDepBuilds: true`, `dangerouslyAllowAllBuilds: false`, `allowBuilds` has only `esbuild: false` โ€” verified 2026-11-12 +- [x] `blockExoticSubdeps: true` โ€” verified 2026-11-12 +- [x] One lockfile committed in the root; CI installs with `pnpm install --frozen-lockfile` โ€” verified 2026-11-12 +- [x] No `.github/dependabot.yml`; other dependency-update tools (if any) open PRs only โ€” never auto-merge โ€” verified 2026-11-12 + +## 4. GitHub Actions +- [x] `permissions: contents: read` (or `{}` + per-job grants) on every workflow โ€” verified 2026-11-12 +- [x] No `contents: write` except jobs whose purpose is mutating the repo (GitHub Release, Changesets version PR); generated output is a workflow artifact, never committed back from CI โ€” verified 2026-11-12 +- [x] Every action pinned to a full commit SHA (`npx actions-up`) โ€” verified 2026-11-12 +- [x] Every job installs Socket Firewall (`SocketDev/action` SHA-pinned, `firewall-version` pinned); `pnpm install` / `npm install` run as `sfw pnpm install` / `sfw npm install` โ€” verified 2026-11-12 +- [x] `.github/workflows/check-workflows.yaml` lints workflows with zizmor on every PR โ€” verified 2026-11-12 +- [x] Workflow `name:` and job `name:` contain no spaces (kebab-case) so they can be set as required status checks โ€” verified 2026-11-12 +- [x] `persist-credentials: false` on checkouts that don't push โ€” verified 2026-11-12 +- [x] No `pull_request_target` on workflows that run untrusted PR code โ€” verified 2026-11-12 +- [x] Artifact-publishing workflows disable `actions/setup-node` default caching (`package-manager-cache: false`) to prevent cache poisoning โ€” verified 2026-11-12 +- [ ] No npm tokens (or other registry credentials) in Actions secrets โ€” the workflows use no npm token; a repository admin must examine the Actions secrets (manual) + +## 5. npm publishing โ€” npm libraries only +- [ ] OIDC trusted publishing configured **stage-only** on npmjs.com for `@hyphen/sdk`, `@hyphen/browser-sdk`, and `@hyphen/react-sdk` โ€” each package must name `Hyphen/javascript-sdks` and `release.yaml` (manual) +- [x] `.github/workflows/release.yaml` packs each package that has a version that is not on npm, then stages each tarball with `pnpm stage publish --no-git-checks` โ€” verified 2026-11-12 +- [ ] Maintainer promotes staged versions with 2FA (manual) +- [ ] Drydock connected โ€” staged releases reviewed before promotion (manual) +- [ ] No direct publish rights: each package requires 2FA and disallows tokens (manual) +- [x] `repository.url` and `repository.directory` in each `package.json` are accurate so provenance maps to this repo โ€” verified 2026-11-12 + +## 6. Security tooling +- [ ] Aikido runs on every build โ€” the repository must be connected in Aikido (manual) +- [x] Aikido release gate: the release workflow's stage-publish job `needs:` a passing `aikido-gate` job that runs `scan-release` โ€” verified 2026-11-12 +- [ ] Socket reviews every PR that changes dependencies + +## 7. Repository lockdown +- [ ] Phishing-resistant 2FA (passkeys / hardware keys) on the GitHub and npm accounts (manual) +- [ ] Recovery codes stored offline in a password manager (manual) +- [ ] `lockdown-repo.sh` applied by a repo admin (never committed to this repo); `--check` with `--required-checks` and `--allowed-actions` passes (PRs required on the default branch, merges blocked unless required status checks pass, tag ruleset, immutable releases, fork-PR approval (public repos), read-only workflow tokens, Actions allowlist, secret scanning, Dependabot disabled, private vulnerability reporting (public repos)) diff --git a/README.md b/README.md index ad4b8e9..0f9ec6d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,67 @@ -# javascript-sdks -Javascript Based SDKs +![Hyphen AI](https://github.com/Hyphen/javascript-sdks/raw/main/logo.png) + +[![tests](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml/badge.svg)](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/gh/Hyphen/javascript-sdks/graph/badge.svg)](https://codecov.io/gh/Hyphen/javascript-sdks) +[![license](https://img.shields.io/github/license/Hyphen/javascript-sdks)](https://github.com/Hyphen/javascript-sdks/blob/main/LICENSE) + +# Hyphen JavaScript SDKs + +This repository contains the [Hyphen](https://hyphen.ai) SDKs for JavaScript. It is a `pnpm` workspace. Each SDK is a package in the `packages` directory. + +# Packages + +| Package | Directory | Description | +|----------------|----------------|----------------| +| [@hyphen/sdk](https://www.npmjs.com/package/@hyphen/sdk) | [packages/nodejs-sdk](./packages/nodejs-sdk) | The Hyphen SDK for Node.js | +| [@hyphen/browser-sdk](https://www.npmjs.com/package/@hyphen/browser-sdk) | [packages/browser-sdk](./packages/browser-sdk) | The Hyphen SDK for the browser | +| [@hyphen/react-sdk](https://www.npmjs.com/package/@hyphen/react-sdk) | [packages/react-sdk](./packages/react-sdk) | The Hyphen SDK for React | + +Each package has a `README.md` file that shows how to install and use the package. + +The packages use each other in the workspace: + +- `@hyphen/react-sdk` uses `@hyphen/browser-sdk`. +- The tests of `@hyphen/browser-sdk` use `@hyphen/sdk`. + +# Development + +Use `pnpm` for all commands. Do not use `npm`. + +Run these commands from the root of the repository. Each command runs in all packages. + +| Command | Description | +|----------------|----------------| +| `pnpm install` | Installs the dependencies of all packages | +| `pnpm build` | Builds all packages | +| `pnpm lint` | Runs the Biome linter and applies the fixes | +| `pnpm test` | Builds all packages, then runs the linter and the tests with coverage | +| `pnpm test:ci` | Builds all packages, then runs the linter with no fixes and the tests with coverage | +| `pnpm clean` | Removes the `dist`, `node_modules`, and `coverage` directories | + +To run a command in one package, use a filter: + +```bash +pnpm --filter @hyphen/browser-sdk test +``` + +Some tests call the Hyphen API. The [Node.js SDK README](./packages/nodejs-sdk/README.md#testing-your-changes) gives the environment variables that these tests need. Put the `.env` file in the directory of the package that you test. + +# Releases + +Each package has its own version. To release a package, do these steps: + +1. Set the new version in the `package.json` file of the package. +2. Merge the change into the `main` branch. +3. Publish a GitHub release. + +The `release` workflow then stages each package that has a version that is not on npm. A maintainer promotes each staged version on npm. + +# Contributing + +We welcome contributions. Follow the [Contributing](./CONTRIBUTING.md) guidelines and our [Code of Conduct](./CODE_OF_CONDUCT.md). + +To report a security problem, follow the [Security Policy](./SECURITY.md). + +# License and Copyright + +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..888dda1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policy + +We take security seriously and work to keep this project up to date. If you discover a security vulnerability, please report it **privately** so we can investigate and ship a fix before the issue becomes public. + +## Reporting a vulnerability + +Please use one of the following private channels โ€” **do not open a public issue, pull request, or discussion** for security concerns: + +1. **Preferred:** open a private report via GitHub's [Privately reporting a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability) flow on this repository's **Security** tab. +2. **Email:** send the details to hello@hyphen.ai. If the issue is urgent, include `[SECURITY]` in the subject line and we will respond as soon as possible. + +When reporting, please include as much of the following as you can: + +- A description of the vulnerability and its impact. +- Steps to reproduce, or a proof-of-concept. +- The affected version(s) and platform. +- Any suggested remediation, if you have one. + +We will acknowledge receipt, work with you on a coordinated disclosure timeline, and credit you in the advisory once a fix is published unless you ask to remain anonymous. + +## How this repository is secured + +This repository follows the [defense-in-depth](https://github.com/jaredwray/agentic/blob/main/skills/security/defense-in-depth-nodejs/SKILL.md) +hardening checklist; progress is tracked in [DEFENSE_IN_DEPTH.md](./DEFENSE_IN_DEPTH.md). diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..09bb0ed Binary files /dev/null and b/logo.png differ diff --git a/package.json b/package.json new file mode 100644 index 0000000..a2c7eb8 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "@hyphen/javascript-sdks", + "version": "0.0.0", + "private": true, + "description": "Hyphen SDKs for JavaScript", + "repository": { + "type": "git", + "url": "git+https://github.com/Hyphen/javascript-sdks.git" + }, + "homepage": "https://github.com/Hyphen/javascript-sdks#readme", + "bugs": { + "url": "https://github.com/Hyphen/javascript-sdks/issues" + }, + "type": "module", + "packageManager": "pnpm@12.17.0+sha512.b8d223ebec04b580a89ed206daa71d1bccb6a1ee1d52efa95cc3b0db75271561df8f0d8e2c43add39c5ec08018af7a8a95108e7090f95a29f88727b7a40fd53d", + "scripts": { + "build": "pnpm -r build", + "lint": "pnpm -r lint", + "test": "pnpm build && pnpm -r test", + "test:ci": "pnpm build && pnpm -r test:ci", + "clean": "pnpm -r clean && node -e \"fs.rmSync('node_modules', { recursive: true, force: true })\"" + }, + "author": "Team Hyphen ", + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.0.0" + } +} diff --git a/packages/browser-sdk/AGENTS.md b/packages/browser-sdk/AGENTS.md new file mode 100644 index 0000000..6552c16 --- /dev/null +++ b/packages/browser-sdk/AGENTS.md @@ -0,0 +1,31 @@ +# AGENTS.md + +Guidelines for AI coding agents (Claude, Gemini, Codex). + +## Project + +Hyphen Browser SDK is a TypeScript library for feature flag (toggle) evaluation in browser environments. It serves as the base library for JavaScript frameworks like React, Vue, and Svelte. The SDK provides type-safe methods for retrieving boolean, string, number, and object toggles from the Hyphen platform with support for user targeting and context-based evaluation. + +## Commands + +- `pnpm install` - Install dependencies +- `pnpm build` - Build for production (ESM + CJS + browser bundle + type definitions) +- `pnpm lint` - Run Biome linter with auto-fix +- `pnpm test` - Run linter and Vitest with coverage +- `pnpm test:ci` - CI-specific testing (strict linting + coverage) +- `pnpm clean` - Remove dist, node_modules, pnpm-lock.yaml, and coverage directories + +**Use pnpm, not npm.** + +## Development Rules + +1. **Always run `pnpm build` before committing** - Build must succeed +2. **Always run `pnpm test` before committing** - All tests must pass +3. **Follow existing code style** - Biome enforces formatting and linting +4. **Mirror source structure in tests** - Test files go in `test/` matching `src/` structure + +## Structure + +- `src/index.ts` - Main Toggle client class with evaluation methods (getBoolean, getString, getNumber, getObject, get) +- `src/types.ts` - TypeScript type definitions for toggle contexts, options, and responses +- `test/` - Test files (Vitest) diff --git a/packages/browser-sdk/CLAUDE.md b/packages/browser-sdk/CLAUDE.md new file mode 100644 index 0000000..eef4bd2 --- /dev/null +++ b/packages/browser-sdk/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md \ No newline at end of file diff --git a/packages/browser-sdk/LICENSE b/packages/browser-sdk/LICENSE new file mode 100644 index 0000000..5533221 --- /dev/null +++ b/packages/browser-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Hyphen + +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. diff --git a/packages/browser-sdk/README.md b/packages/browser-sdk/README.md new file mode 100644 index 0000000..e37c65f --- /dev/null +++ b/packages/browser-sdk/README.md @@ -0,0 +1,273 @@ +![Hyphen AI](https://github.com/Hyphen/javascript-sdks/raw/main/logo.png) + +[![tests](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml/badge.svg)](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml) +[![](https://data.jsdelivr.com/v1/package/npm/@hyphen/browser-sdk/badge)](https://www.jsdelivr.com/package/npm/@hyphen/browser-sdk) +[![npm](https://img.shields.io/npm/v/@hyphen/browser-sdk)](https://www.npmjs.com/package/@hyphen/browser-sdk) +[![npm](https://img.shields.io/npm/dm/@hyphen/browser-sdk)](https://www.npmjs.com/package/@hyphen/browser-sdk) +[![license](https://img.shields.io/github/license/Hyphen/javascript-sdks)](https://github.com/Hyphen/javascript-sdks/blob/main/LICENSE) + +# Hyphen Browser SDK + +The Hyphen Browser SDK is used as a base library to get evaluations and works for browsers and the base for javascript libraries such as react, vuejs, svelte, etc . For the full featured nodejs sdk use [@hyphen/sdk](https://npmjs.com/package/@hyphen/sdk) + +# Table of Contents +- [Installation](#installation) +- [Usage](#usage) + - [Basic Setup](#basic-setup) + - [Using Helper Methods](#using-helper-methods) + - [Boolean Toggles](#boolean-toggles) + - [String Toggles](#string-toggles) + - [Number Toggles](#number-toggles) + - [Object Toggles](#object-toggles) + - [Using the Generic `get()` Method](#using-the-generic-get-method) + - [Context Override](#context-override) + - [Error Handling and Events](#error-handling-and-events) + - [Browser Integration Example](#browser-integration-example) + - [Using ES Modules](#using-es-modules) + - [Using jsDelivr CDN](#using-jsdelivr-cdn) +- [API Reference](#api-reference) + - [Constructor Options](#constructor-options) + - [Helper Methods](#helper-methods) +- [Contributing](#contributing) +- [License and Copyright](#license-and-copyright) + +# Installation + +Install the package using npm, yarn, or pnpm: + +```bash +npm install @hyphen/browser-sdk +``` + +For browser usage via CDN: + +```html + +``` + +# Usage + +## Basic Setup + +```javascript +import { Toggle } from '@hyphen/browser-sdk'; + +// Initialize the Toggle client +const toggle = new Toggle({ + publicApiKey: 'public_your-api-key-here', + applicationId: 'your-app-id', + environment: 'production', // or 'development' + defaultContext: { + targetingKey: 'user-123', + user: { + id: 'user-123', + email: 'user@example.com', + name: 'John Doe' + } + } +}); +``` + +## Using Helper Methods + +The SDK provides type-safe helper methods for common data types: + +### Boolean Toggles + +```javascript +const isFeatureEnabled = await toggle.getBoolean('feature-flag', false); +if (isFeatureEnabled) { + console.log('Feature is enabled!'); +} +``` + +### String Toggles + +```javascript +const welcomeMessage = await toggle.getString('welcome-message', 'Hello World'); +document.getElementById('welcome').textContent = welcomeMessage; +``` + +### Number Toggles + +```javascript +const maxRetries = await toggle.getNumber('max-retries', 3); +const timeout = await toggle.getNumber('api-timeout', 5000); +``` + +### Object Toggles + +```javascript +const config = await toggle.getObject('app-config', { theme: 'light' }); +console.log('App configuration:', config); +``` + +## Using the Generic `get()` Method + +```javascript +// Generic method with type parameter +const feature = await toggle.get('feature-toggle', false); +const settings = await toggle.get('user-settings', {}); +``` + +## Context Override + +You can override the default context for specific evaluations: + +```javascript +const customContext = { + targetingKey: 'special-user', + user: { id: 'special-user', plan: 'premium' }, + customAttributes: { region: 'us-west' } +}; + +const result = await toggle.getBoolean('premium-feature', false, { + context: customContext +}); +``` + +## Error Handling and Events + +The `Toggle` client extends [`Hookified`](https://hookified.org), so it exposes +a standard event-emitter surface. Toggle evaluation errors are swallowed by +design (the SDK falls back to your `defaultValue`) and re-emitted on the +`ToggleEvents.Error` event so you can observe them without breaking the caller. + +```javascript +import { Toggle, ToggleEvents } from '@hyphen/browser-sdk'; + +const toggle = new Toggle({ + publicApiKey: 'public_your-api-key-here', + applicationId: 'your-app-id', +}); + +toggle.on(ToggleEvents.Error, (error) => { + console.error('Toggle evaluation failed:', error); +}); + +// Still returns `false` on failure โ€” the listener above also fires. +const isFeatureEnabled = await toggle.getBoolean('feature-flag', false); +``` + +You can use `once`, `off`, and `removeAllListeners` as you would with any +Node-style event emitter. + +## Browser Integration Example + +### Using ES Modules + +```html + + + + Hyphen Toggle Example + + + + + + + +``` + +### Using jsDelivr CDN + +```html + + + + Hyphen Toggle Example + + + + + + + + +``` + +# API Reference + +## Constructor Options + +- `publicApiKey` (string): Your Hyphen public API key +- `applicationId` (string): Your application identifier +- `environment` (string, optional): Environment name (default: 'development') +- `defaultContext` (ToggleContext, optional): Default evaluation context +- `horizonUrls` (string[], optional): Custom Horizon endpoint URLs +- `defaultTargetKey` (string, optional): Default targeting key + +## Helper Methods + +- `getBoolean(toggleKey, defaultValue, options?)` - Get boolean toggle +- `getString(toggleKey, defaultValue, options?)` - Get string toggle +- `getNumber(toggleKey, defaultValue, options?)` - Get number toggle +- `getObject(toggleKey, defaultValue, options?)` - Get object toggle +- `get(toggleKey, defaultValue, options?)` - Generic toggle getter + +# Contributing + +We welcome contributions to the Hyphen Node.js SDK! If you have an idea for a new feature, bug fix, or improvement, please follow the [Contribution](../../CONTRIBUTING.md) guidelines and our [Code of Conduct](../../CODE_OF_CONDUCT.md). + +# License and Copyright +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. +The copyright for this project is held by Hyphen, Inc. All rights reserved. \ No newline at end of file diff --git a/packages/browser-sdk/biome.json b/packages/browser-sdk/biome.json new file mode 100644 index 0000000..7cce606 --- /dev/null +++ b/packages/browser-sdk/biome.json @@ -0,0 +1,35 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "vcs": { + "enabled": false, + "clientKind": "git", + "useIgnoreFile": false + }, + "files": { + "ignoreUnknown": false, + "includes": ["src/**/*.ts", "test/**/*.ts"] + }, + "formatter": { + "enabled": true, + "indentStyle": "tab" + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + }, + "assist": { + "enabled": true, + "actions": { + "source": { + "organizeImports": "on" + } + } + } +} diff --git a/packages/browser-sdk/package.json b/packages/browser-sdk/package.json new file mode 100644 index 0000000..7e7dd11 --- /dev/null +++ b/packages/browser-sdk/package.json @@ -0,0 +1,65 @@ +{ + "name": "@hyphen/browser-sdk", + "version": "1.1.6", + "description": "Hyphen SDK for Browser / Javascript", + "type": "module", + "main": "dist/index.js", + "module": "dist/index.js", + "browser": "dist/index.browser.js", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs" + } + }, + "types": "dist/index.d.ts", + "scripts": { + "lint": "biome check --write --error-on-warnings", + "test": "pnpm lint && vitest run --coverage", + "test:ci": "biome check --error-on-warnings && vitest run --coverage", + "build": "rimraf ./dist && tsdown", + "clean": "rimraf ./dist node_modules coverage", + "prepare": "rimraf ./dist && tsdown" + }, + "keywords": [ + "hyphen", + "sdk", + "browser", + "react", + "vue", + "vuejs", + "svelt", + "javascript", + "typescript" + ], + "author": "Team Hyphen ", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Hyphen/javascript-sdks.git", + "directory": "packages/browser-sdk" + }, + "bugs": { + "url": "https://github.com/Hyphen/javascript-sdks/issues" + }, + "homepage": "https://github.com/Hyphen/javascript-sdks/tree/main/packages/browser-sdk#readme", + "devDependencies": { + "@biomejs/biome": "^2.5.13", + "@faker-js/faker": "^10.6.0", + "@hyphen/sdk": "workspace:^", + "@types/node": "^24.13.3", + "@vitest/coverage-v8": "^5.0.0", + "rimraf": "^6.1.3", + "tsdown": "^0.23.0", + "typescript": "^7.0.2", + "vitest": "^5.0.0" + }, + "files": [ + "dist", + "LICENSE" + ], + "dependencies": { + "hookified": "^3.0.3" + } +} diff --git a/packages/browser-sdk/src/index.ts b/packages/browser-sdk/src/index.ts new file mode 100644 index 0000000..20aeb5b --- /dev/null +++ b/packages/browser-sdk/src/index.ts @@ -0,0 +1,622 @@ +import { Hookified } from "hookified"; +import { + type EvaluationResponse, + type GetOptions, + type ToggleContext, + type ToggleEvaluation, + ToggleEvents, +} from "./types.js"; + +export type { ToggleContext } from "./types.js"; +export { ToggleEvents } from "./types.js"; + +export type ToggleOptions = { + /** + * public api key + */ + publicApiKey?: string; + + /** + * The default context to use when once is not passed + */ + defaultContext?: ToggleContext; + + /** + * Horizon Endpoint Urls to use for Toggle. This will place these urls to be + * load balanced. If endpoints fail it will attempt to use the default horizon + * endpoint service. + * @see {@link https://hyphen.ai/horizon} for more information + */ + horizonUrls?: string[]; + + applicationId?: string; + + environment?: string; + + defaultTargetKey?: string; +}; + +export class Toggle extends Hookified { + private _publicApiKey?: string; + private _organizationId: string | undefined; + private _applicationId: string | undefined; + private _environment: string | undefined; + private _horizonUrls: string[] = []; + + private _defaultContext: ToggleContext | undefined; + private _defaultTargetingKey: string = + `${Math.random().toString(36).substring(7)}`; + + constructor(options?: ToggleOptions) { + // hookified v2 defaults `throwOnEmptyListeners` to `true`, which would + // cause `emit(ToggleEvents.Error, ...)` to re-throw when no listener is + // attached. The SDK swallows evaluation errors and returns the caller's + // default value, so we opt back into the v1 behavior. + super({ throwOnEmptyListeners: false }); + + if (options?.applicationId) { + this._applicationId = options.applicationId; + } + + if (options?.environment) { + this._environment = options.environment; + } else { + this._environment = "development"; + } + + if (options?.defaultContext) { + this._defaultContext = options.defaultContext; + } + + if (options?.publicApiKey) { + this._publicApiKey = options.publicApiKey; + this._organizationId = this.getOrgIdFromPublicKey(this._publicApiKey); + } + + if (options?.horizonUrls) { + this._horizonUrls = options.horizonUrls; + } else { + this._horizonUrls = this.getDefaultHorizonUrls(this._publicApiKey); + } + + if (options?.defaultTargetKey) { + this._defaultTargetingKey = options?.defaultTargetKey; + } else { + if (this._defaultContext) { + this._defaultTargetingKey = this.getTargetingKey(this._defaultContext); + } else { + this._defaultTargetingKey = this.generateTargetKey(); + } + } + } + + /** + * Gets the public API key used for authentication. + * + * @returns The current public API key or undefined if not set + */ + public get publicApiKey(): string | undefined { + return this._publicApiKey; + } + + /** + * Sets the public API key used for authentication. + * + * @param value - The public API key string or undefined to clear + * @throws {Error} If the key doesn't start with "public_" + */ + public set publicApiKey(value: string | undefined) { + this.setPublicKey(value); + } + + /** + * Gets the default context used for toggle evaluations. + * + * @returns The current default ToggleContext + */ + public get defaultContext(): ToggleContext | undefined { + return this._defaultContext; + } + + /** + * Sets the default context used for toggle evaluations. + * + * @param value - The ToggleContext to use as default + */ + public set defaultContext(value: ToggleContext) { + this._defaultContext = value; + } + + /** + * Gets the organization ID extracted from the public API key. + * + * @returns The organization ID string or undefined if not available + */ + public get organizationId(): string | undefined { + return this._organizationId; + } + + /** + * Gets the Horizon endpoint URLs used for load balancing. + * + * These URLs are used to distribute requests across multiple Horizon endpoints. + * If endpoints fail, the system will attempt to use the default horizon endpoint service. + * + * @returns Array of Horizon endpoint URLs + * @see {@link https://hyphen.ai/horizon} for more information + */ + public get horizonUrls(): string[] { + return this._horizonUrls; + } + + /** + * Sets the Horizon endpoint URLs for load balancing. + * + * Configures multiple Horizon endpoints that will be used for load balancing. + * When endpoints fail, the system will fall back to the default horizon endpoint service. + * + * @param value - Array of Horizon endpoint URLs or empty array to clear + * @see {@link https://hyphen.ai/horizon} for more information + * + * @example + * ```typescript + * const toggle = new Toggle(); + * toggle.horizonUrls = [ + * 'https://org1.toggle.hyphen.cloud', + * 'https://org2.toggle.hyphen.cloud' + * ]; + * ``` + */ + public set horizonUrls(value: string[]) { + this._horizonUrls = value; + } + + /** + * Gets the application ID used for toggle context. + * + * @returns The current application ID or undefined if not set + */ + public get applicationId(): string | undefined { + return this._applicationId; + } + + /** + * Sets the application ID used for toggle context. + * + * @param value - The application ID string or undefined to clear + */ + public set applicationId(value: string | undefined) { + this._applicationId = value; + } + + /** + * Gets the environment used for toggle context. + * + * @returns The current environment (defaults to 'development') + */ + public get environment(): string | undefined { + return this._environment; + } + + /** + * Sets the environment used for toggle context. + * + * @param value - The environment string or undefined to clear + */ + public set environment(value: string | undefined) { + this._environment = value; + } + + /** + * Gets the default targeting key used for toggle evaluations. + * + * @returns The current default targeting key or undefined if not set + */ + public get defaultTargetingKey(): string { + return this._defaultTargetingKey; + } + + /** + * Sets the default targeting key used for toggle evaluations. + * + * @param value - The targeting key string or undefined to clear + */ + public set defaultTargetingKey(value: string) { + this._defaultTargetingKey = value; + } + + public async get( + toggleKey: string, + defaultValue: T, + options?: GetOptions, + ): Promise { + try { + const context: ToggleEvaluation = { + application: this._applicationId ?? "", + environment: this._environment ?? "development", + }; + + if (options?.context) { + context.targetingKey = options?.context.targetingKey; + context.ipAddress = options?.context.ipAddress; + context.user = options?.context.user; + context.customAttributes = options?.context.customAttributes; + } else { + context.targetingKey = this._defaultContext?.targetingKey; + context.ipAddress = this._defaultContext?.ipAddress; + context.user = this._defaultContext?.user; + context.customAttributes = this._defaultContext?.customAttributes; + } + + const fetchOptions = { headers: {} as Record }; + + if (!context.targetingKey) { + context.targetingKey = this.getTargetingKey(context); + } + + // api key + if (this._publicApiKey) { + fetchOptions.headers["x-api-key"] = this._publicApiKey; + } else { + throw new Error("You must set the publicApiKey"); + } + + // application + if (context.application === "") { + throw new Error("You must set the applicationId"); + } + + const result = await this.fetch( + "/toggle/evaluate", + context, + fetchOptions, + ); + + if (result?.toggles) { + return result.toggles[toggleKey].value as T; + } + } catch (error) { + this.emit(ToggleEvents.Error, error); + } + + return defaultValue; + } + + /** + * Retrieves a boolean toggle value. + * + * This is a convenience method that wraps the generic get() method with boolean type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The boolean value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the boolean toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const isFeatureEnabled = await toggle.getBoolean('feature-flag', false); + * console.log(isFeatureEnabled); // true or false + * ``` + */ + public async getBoolean( + toggleKey: string, + defaultValue: boolean, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves a string toggle value. + * + * This is a convenience method that wraps the generic get() method with string type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The string value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the string toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const message = await toggle.getString('welcome-message', 'Hello World'); + * console.log(message); // 'Welcome to our app!' or 'Hello World' + * ``` + */ + public async getString( + toggleKey: string, + defaultValue: string, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves an object toggle value. + * + * This is a convenience method that wraps the generic get() method with object type safety. + * Note that the toggle service may return JSON as a string, which should be parsed if needed. + * + * @template T - The expected object type + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The object value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the object toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const config = await toggle.getObject('app-config', { theme: 'light' }); + * console.log(config); // { theme: 'dark', features: ['a', 'b'] } or { theme: 'light' } + * ``` + */ + public async getObject( + toggleKey: string, + defaultValue: T, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves a number toggle value. + * + * This is a convenience method that wraps the generic get() method with number type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The number value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the number toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const maxRetries = await toggle.getNumber('max-retries', 3); + * console.log(maxRetries); // 5 or 3 + * ``` + */ + public async getNumber( + toggleKey: string, + defaultValue: number, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Makes an HTTP POST request to the specified URL with automatic authentication. + * + * This method uses browser-compatible fetch and automatically includes the + * public API key in the x-api-key header if available. It supports load + * balancing across multiple horizon URLs with fallback behavior. + * + * @template T - The expected response type + * @param path - The API path to request (e.g., '/api/toggles') + * @param payload - The JSON payload to send in the request body + * @param options - Optional fetch configuration + * @returns Promise resolving to the parsed JSON response + * @throws {Error} If no horizon URLs are configured or all requests fail + * + * @example + * ```typescript + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key-here', + * horizonUrls: ['https://api.hyphen.cloud'] + * }); + * + * interface ToggleResponse { + * enabled: boolean; + * value: string; + * } + * + * const result = await toggle.fetch('/api/toggle/feature-flag', { + * context: { targetingKey: 'user-123' } + * }); + * console.log(result.enabled); // true/false + * ``` + */ + public async fetch( + path: string, + payload?: unknown, + options?: RequestInit, + ): Promise { + if (this._horizonUrls.length === 0) { + throw new Error( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + } + + const headers: Record = { + "Content-Type": "application/json", + }; + + if (options?.headers) { + if (options.headers instanceof Headers) { + options.headers.forEach((value, key) => { + headers[key] = value; + }); + } else if (Array.isArray(options.headers)) { + options.headers.forEach(([key, value]) => { + headers[key] = value; + }); + } else { + Object.assign(headers, options.headers); + } + } + + if (this._publicApiKey) { + headers["x-api-key"] = this._publicApiKey; + } + + const fetchOptions: RequestInit = { + method: "POST", + ...options, + headers, + body: payload ? JSON.stringify(payload) : options?.body, + }; + + const errors: Error[] = []; + + for (const baseUrl of this._horizonUrls) { + try { + const url = `${baseUrl.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`; + const response = await fetch(url, fetchOptions); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const data = (await response.json()) as T; + return data; + } catch (error) { + const fetchError = + error instanceof Error ? error : new Error("Unknown fetch error"); + errors.push(fetchError); + } + } + + throw new Error( + `All horizon URLs failed. Last errors: ${errors.map((e) => e.message).join(", ")}`, + ); + } + + /** + * Validates and sets the public API key. This is used internally + * + * @param key - The public API key string or undefined to clear + * @throws {Error} If the key doesn't start with "public_" + */ + public setPublicKey(key: string | undefined): void { + if (key !== undefined && !key.startsWith("public_")) { + throw new Error("Public API key must start with 'public_'"); + } + this._publicApiKey = key; + } + + /** + * Extracts the organization ID from a public API key. + * + * The public key format is: `public_` + * The base64 data contains: `orgId:secretData` + * Only alphanumeric characters, underscores, and hyphens are considered valid in org IDs. + * + * @param publicKey - The public API key to extract the organization ID from + * @returns The organization ID if valid and extractable, undefined otherwise + * + * @example + * ```typescript + * const toggle = new Toggle(); + * const orgId = toggle.getOrgIdFromPublicKey('public_dGVzdC1vcmc6c2VjcmV0'); + * console.log(orgId); // 'test-org' + * ``` + */ + public getOrgIdFromPublicKey(publicKey: string): string | undefined { + try { + const keyWithoutPrefix = publicKey.replace(/^public_/, ""); + // Browsers / modern runtimes expose `atob`; fall back to Node's + // `Buffer` without depending on @types/node globally. + const nodeBuffer = ( + globalThis as typeof globalThis & { + Buffer?: { + from(input: string, encoding: string): { toString(): string }; + }; + } + ).Buffer; + const decoded = globalThis.atob + ? globalThis.atob(keyWithoutPrefix) + : (nodeBuffer?.from(keyWithoutPrefix, "base64").toString() ?? ""); + const [orgId] = decoded.split(":"); + const isValidOrgId = /^[a-zA-Z0-9_-]+$/.test(orgId); + return isValidOrgId ? orgId : undefined; + } catch { + return undefined; + } + } + + /** + * Builds the default Horizon API URL for the given public key. + * + * If a valid organization ID can be extracted from the public key, returns an + * organization-specific URL. Otherwise, returns the default fallback URL. + * + * @param publicKey - The public API key to build the URL for + * @returns Organization-specific URL or default fallback URL + * + * @example + * ```typescript + * const toggle = new Toggle(); + * + * // With valid org ID + * const orgUrl = toggle.buildDefaultHorizonUrl('public_dGVzdC1vcmc6c2VjcmV0'); + * console.log(orgUrl); // 'https://test-org.toggle.hyphen.cloud' + * + * // With invalid key + * const defaultUrl = toggle.buildDefaultHorizonUrl('invalid-key'); + * console.log(defaultUrl); // 'https://toggle.hyphen.cloud' + * ``` + */ + public getDefaultHorizonUrl(publicKey?: string): string { + if (publicKey) { + const orgId = this.getOrgIdFromPublicKey(publicKey); + return orgId + ? `https://${orgId}.toggle.hyphen.cloud` + : "https://toggle.hyphen.cloud"; + } + + return "https://toggle.hyphen.cloud"; + } + + /** + * Will get the urls. If you pass in the public key it will provide two urls. + * @param publicKey + * @returns + */ + public getDefaultHorizonUrls(publicKey?: string): string[] { + let result = [this.getDefaultHorizonUrl()]; + if (publicKey) { + const defaultUrl = result[0]; + const orgUrl = this.getDefaultHorizonUrl(publicKey); + result = []; + if (orgUrl !== defaultUrl) { + result.push(orgUrl); + } + // make the default url the secondary + result.push(defaultUrl); + } + return result; + } + + /** + * Generates a unique targeting key based on available context. + * + * @returns A targeting key in the format: `[app]-[env]-[random]` or simplified versions + */ + public generateTargetKey(): string { + const randomSuffix = Math.random().toString(36).substring(7); + const app = this._applicationId || ""; + const env = this._environment || ""; + + // Build key components in order of preference + const components = [app, env, randomSuffix].filter(Boolean); + + return components.join("-"); + } + + /** + * Extracts targeting key from a toggle context with fallback logic. + * + * @param context - The toggle context to extract targeting key from + * @returns The targeting key string + */ + private getTargetingKey(context: ToggleContext): string { + if (context.targetingKey) { + return context.targetingKey; + } + if (context.user) { + return context.user.id; + } + // TODO: what is a better way to do this? Should we also have a service property so we don't add the random value? + return this._defaultTargetingKey; + } +} diff --git a/packages/browser-sdk/src/types.ts b/packages/browser-sdk/src/types.ts new file mode 100644 index 0000000..eb13a82 --- /dev/null +++ b/packages/browser-sdk/src/types.ts @@ -0,0 +1,100 @@ +/** + * Custom attributes that can contain any key-value pairs. + */ +export type CustomAttributes = Record; + +/** + * User information for evaluation context. + */ +export type ToggleUser = { + /** + * Unique identifier for the user. + */ + id: string; + + /** + * User's email address. + */ + email?: string; + + /** + * User's display name. + */ + name?: string; + + /** + * Custom attributes specific to the user. + */ + customAttributes?: CustomAttributes; +}; + +/** + * Evaluation context for Hyphen feature toggle evaluation. + * + * @example + * ```typescript + * const context: ToggleContext = { + * targetingKey: "user-123", + * ipAddress: "203.0.113.42", + * customAttributes: { + * subscriptionLevel: "premium", + * region: "us-east", + * }, + * user: { + * id: "user-123", + * email: "john.doe@example.com", + * name: "John Doe", + * customAttributes: { + * role: "admin", + * }, + * }, + * }; + * ``` + */ +export type ToggleContext = { + /** + * Primary key used for targeting and bucketing. + */ + targetingKey?: string; + + /** + * IP address of the user making the request. + */ + ipAddress?: string; + + /** + * Custom attributes for evaluation context. + */ + customAttributes?: CustomAttributes; + + /** + * User information for evaluation. + */ + user?: ToggleUser; +}; + +export type ToggleEvaluation = { + application: string; + environment: string; +} & ToggleContext; + +export interface Evaluation { + key: string; + value: boolean | string | number | Record; + type: "boolean" | "string" | "number" | "object"; + reason?: unknown; + errorMessage?: string; +} + +export interface EvaluationResponse { + toggles: Record; +} + +export type GetOptions = { + context?: ToggleContext; + cache?: boolean; +}; + +export enum ToggleEvents { + Error = "error", +} diff --git a/packages/browser-sdk/test/index-evals.test.ts b/packages/browser-sdk/test/index-evals.test.ts new file mode 100644 index 0000000..eb849c5 --- /dev/null +++ b/packages/browser-sdk/test/index-evals.test.ts @@ -0,0 +1,286 @@ +import process from "node:process"; +import { env } from "@hyphen/sdk"; +import { describe, expect, test } from "vitest"; +import { Toggle, type ToggleContext } from "../src/index.js"; + +/* +hyphen-sdk-boolean +hyphen-sdk-json +hyphen-sdk-number +hyphen-sdk-string +*/ + +env(); + +const hyphenPublicApiKey = process.env.HYPHEN_PUBLIC_API_KEY; +const hyphenApplicationId = process.env.HYPHEN_APPLICATION_ID; + +const defaultTimeout = 10_000; + +// check that we have values + +if (!hyphenPublicApiKey || !hyphenApplicationId) { + console.warn("You need HYPHEN_PUBLIC_API_KEY and HYPHEN_APPLICATION_ID"); +} + +const context: ToggleContext = { + targetingKey: "user-123", + ipAddress: "203.0.113.42", + customAttributes: { + subscriptionLevel: "premium", + region: "us-east", + }, + user: { + id: "user-123", + email: "john.doe@example.com", + name: "John Doe", + customAttributes: { + role: "admin", + }, + }, +}; + +describe("Toggle Evaluations", () => { + test( + "Getting a string", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.get( + "hyphen-sdk-string", + "fake-default-value-123", + ); + + expect(result).toBe("Hyphen!"); + }, + defaultTimeout, + ); + + test( + "getBoolean helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getBoolean("hyphen-sdk-boolean", false); + + expect(typeof result).toBe("boolean"); + expect(result).toBe(true); + }, + defaultTimeout, + ); + + test( + "getString helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getString( + "hyphen-sdk-string", + "default-string", + ); + + expect(typeof result).toBe("string"); + expect(result).toBe("Hyphen!"); + }, + defaultTimeout, + ); + + test( + "getNumber helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getNumber("hyphen-sdk-number", 0); + + expect(typeof result).toBe("number"); + expect(result).toBe(42); + }, + defaultTimeout, + ); + + test( + "getObject helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getObject("hyphen-sdk-json", {}); + + // The toggle returns a JSON string, so we expect a string type + expect(typeof result).toBe("string"); + expect(result).toBe('{ "id": "Hello World!"}'); + + // Verify it's valid JSON + const parsed = JSON.parse(result as string); + expect(parsed).toEqual({ id: "Hello World!" }); + }, + defaultTimeout, + ); + + describe("get method error handling", () => { + test( + "should return defaultValue when no publicApiKey is set", + async () => { + const toggle = new Toggle({ + applicationId: "test-app", + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("test-toggle", "default-value"); + expect(result).toBe("default-value"); + }, + defaultTimeout, + ); + + test( + "should return defaultValue when no defaultContext and no context option", + async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "test-app", + }); + + const result = await toggle.get("test-toggle", "fallback"); + expect(result).toBe("fallback"); + }, + defaultTimeout, + ); + + test( + "should return defaultValue when application is empty", + async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "", + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("test-toggle", "default"); + expect(result).toBe("default"); + }, + defaultTimeout, + ); + + test("should set targetingKey when context has no targetingKey", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultTargetKey: "fallback-key", + }); + + const result = await toggle.get("hyphen-sdk-string", "default", { + context: { user: { id: "user-123" } }, + }); + + expect(typeof result).toBe("string"); + }); + + test("should handle fetch failures gracefully", async () => { + const toggle = new Toggle({ + publicApiKey: "public_invalid-key", + applicationId: "test-app", + defaultContext: { targetingKey: "test" }, + horizonUrls: ["https://invalid-domain.test"], + }); + + const result = await toggle.get("test-toggle", "fallback-value"); + expect(result).toBe("fallback-value"); + }); + + test("should handle missing toggle in response", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("non-existent-toggle", "not-found"); + expect(result).toBe("not-found"); + }); + + test("should use provided context with all properties", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + }); + + // This should trigger lines 244-247 (options?.context branch) + const customContext: ToggleContext = { + targetingKey: "custom-targeting", + ipAddress: "192.168.1.1", + user: { id: "custom-user", email: "test@example.com" }, + customAttributes: { role: "tester" }, + }; + + const result = await toggle.get("hyphen-sdk-string", "default", { + context: customContext, + }); + + expect(typeof result).toBe("string"); + }); + + test("should handle application validation error", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: undefined, // This will cause validation to fail + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + + test("should copy context properties correctly when no options.context", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultContext: { + targetingKey: "default-targeting", + ipAddress: "127.0.0.1", + user: { id: "default-user" }, + customAttributes: { plan: "basic" }, + }, + }); + + // This should trigger lines 249-252 (else branch, using defaultContext) + const result = await toggle.get("hyphen-sdk-string", "default"); + expect(typeof result).toBe("string"); + }); + + test("should handle application validation error when applicationId is empty", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "", // This will cause validation to fail + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + + test("should handle application validation error when applicationId is undefined", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + // No applicationId provided, will be undefined -> "" + defaultContext: { targetingKey: "test" }, + }); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + }); +}); diff --git a/packages/browser-sdk/test/index-methods.test.ts b/packages/browser-sdk/test/index-methods.test.ts new file mode 100644 index 0000000..695275d --- /dev/null +++ b/packages/browser-sdk/test/index-methods.test.ts @@ -0,0 +1,821 @@ +import process from "node:process"; +import { describe, expect, test } from "vitest"; +import { Toggle } from "../src/index.js"; + +const baseMockUrl = process.env.BASE_MOCK_URL ?? "https://mockhttp.org"; + +describe("getOrgIdFromPublicKey", () => { + test("should extract org ID from valid public key", () => { + const toggle = new Toggle(); + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + }); + + test("should handle public key without prefix", () => { + const toggle = new Toggle(); + const orgId = "org-without-prefix"; + const keyWithoutPrefix = Buffer.from(`${orgId}:secret-data`).toString( + "base64", + ); + expect(toggle.getOrgIdFromPublicKey(keyWithoutPrefix)).toBe(orgId); + }); + + test("should return undefined for malformed base64", () => { + const toggle = new Toggle(); + expect( + toggle.getOrgIdFromPublicKey("public_invalid-base64!"), + ).toBeUndefined(); + }); + + test("should return undefined for empty decoded content", () => { + const toggle = new Toggle(); + const emptyKey = `public_${Buffer.from("").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(emptyKey)).toBeUndefined(); + }); + + test("should return undefined for decoded content without colon", () => { + const toggle = new Toggle(); + const keyWithoutColon = `public_${Buffer.from("orgidwithoutcolon").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithoutColon)).toBe( + "orgidwithoutcolon", + ); + }); + + test("should handle org ID with valid characters", () => { + const toggle = new Toggle(); + const orgId = "valid_org-123"; + const validKey = `public_${Buffer.from(`${orgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + }); + + test("should return undefined for org ID with invalid characters", () => { + const toggle = new Toggle(); + const invalidOrgId = "org@invalid#chars"; + const invalidKey = `public_${Buffer.from(`${invalidOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(invalidKey)).toBeUndefined(); + }); + + test("should handle org ID with spaces (invalid)", () => { + const toggle = new Toggle(); + const orgIdWithSpaces = "org with spaces"; + const keyWithSpaces = `public_${Buffer.from(`${orgIdWithSpaces}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithSpaces)).toBeUndefined(); + }); + + test("should handle multiple colons in decoded content", () => { + const toggle = new Toggle(); + const orgId = "multi-colon-org"; + const keyWithMultipleColons = `public_${Buffer.from(`${orgId}:secret:extra:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithMultipleColons)).toBe(orgId); + }); + + test("should handle empty org ID", () => { + const toggle = new Toggle(); + const emptyOrgKey = `public_${Buffer.from(":secret-data").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(emptyOrgKey)).toBeUndefined(); + }); + + test("should handle numeric org ID", () => { + const toggle = new Toggle(); + const numericOrgId = "123456"; + const numericKey = `public_${Buffer.from(`${numericOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(numericKey)).toBe(numericOrgId); + }); + + test("should handle very long org ID", () => { + const toggle = new Toggle(); + const longOrgId = "a".repeat(100); + const longKey = `public_${Buffer.from(`${longOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(longKey)).toBe(longOrgId); + }); + + test("should handle single character org ID", () => { + const toggle = new Toggle(); + const singleCharOrgId = "a"; + const singleCharKey = `public_${Buffer.from(`${singleCharOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(singleCharKey)).toBe(singleCharOrgId); + }); + + test("should return undefined for null input", () => { + const toggle = new Toggle(); + expect(() => + toggle.getOrgIdFromPublicKey(null as unknown as string), + ).not.toThrow(); + }); + + test("should return undefined for undefined input", () => { + const toggle = new Toggle(); + expect(() => + toggle.getOrgIdFromPublicKey(undefined as unknown as string), + ).not.toThrow(); + }); + + test("should handle edge case with only public_ prefix", () => { + const toggle = new Toggle(); + expect(toggle.getOrgIdFromPublicKey("public_")).toBeUndefined(); + }); + + test("should use Buffer fallback when atob is not available", () => { + const toggle = new Toggle(); + const orgId = "fallback-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + + // Temporarily remove atob to force Buffer fallback + const originalAtob = globalThis.atob; + // @ts-expect-error - Intentionally setting to undefined for testing + globalThis.atob = undefined; + + try { + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + } finally { + // Restore original atob + globalThis.atob = originalAtob; + } + }); +}); + +describe("fetch method", () => { + test("should throw error when horizon URLs array is explicitly empty", async () => { + const toggle = new Toggle({ horizonUrls: [] }); + await expect(toggle.fetch("/api/test")).rejects.toThrow( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + }); + + test("should throw error when horizon URLs array is empty", async () => { + const toggle = new Toggle({ horizonUrls: [] }); + await expect(toggle.fetch("/api/test")).rejects.toThrow( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + }); + + test("should successfully make POST request to mockhttp.org", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + body: Record; + } + + const result = await toggle.fetch("/post", { + test: "data", + }); + expect(result.method).toBe("POST"); + expect(result.headers).toBeDefined(); + expect(result.body).toBeDefined(); + }); + + test("should handle 404 error response from mockhttp.org", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + await expect( + toggle.fetch("/status/404", { test: "error" }), + ).rejects.toThrow("HTTP 404"); + }); + + test("should handle 500 error response from mockhttp.org", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + await expect( + toggle.fetch("/status/500", { test: "error" }), + ).rejects.toThrow("HTTP 500"); + }); + + test("should return typed JSON response with request body", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpPostResponse { + method: string; + body: { + test: string; + number: number; + }; + } + + const result = await toggle.fetch("/post", { + test: "hello", + number: 42, + }); + expect(result.method).toBe("POST"); + expect(result.body.test).toBe("hello"); + expect(result.body.number).toBe(42); + }); + + test("should include x-api-key header when publicApiKey is set", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + horizonUrls: [baseMockUrl], + }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch("/post", { + test: "auth", + }); + expect(result.method).toBe("POST"); + expect(result.headers["x-api-key"]).toBe("public_test-key"); + }); + + test("should include custom headers in request", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "custom" }, + { + headers: { "X-Custom-Header": "test-value" }, + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-custom-header"]).toBe("test-value"); + }); + + test("should work with path without leading slash", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const result = await toggle.fetch("post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should work with path with leading slash", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should try multiple horizon URLs on failure", async () => { + const toggle = new Toggle({ + horizonUrls: [ + "https://invalid-url-that-should-fail.example", + baseMockUrl, + ], + }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should fail when all horizon URLs are invalid", async () => { + const toggle = new Toggle({ + horizonUrls: [ + "https://invalid-url-1.example", + "https://invalid-url-2.example", + ], + }); + + await expect(toggle.fetch("/test", { test: "data" })).rejects.toThrow( + "All horizon URLs failed", + ); + }); + + test("should handle URLs with trailing slashes correctly", async () => { + const toggle = new Toggle({ horizonUrls: [`${baseMockUrl}/`] }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should handle Headers object in request options", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const headers = new Headers(); + headers.set("X-Test-Header", "headers-object-value"); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "headers" }, + { + headers: headers, + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-test-header"]).toBe("headers-object-value"); + }); + + test("should handle array headers in request options", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "array" }, + { + headers: [ + ["X-Array-Header", "array-value"], + ["X-Another-Header", "another-value"], + ], + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-array-header"]).toBe("array-value"); + expect(result.headers["x-another-header"]).toBe("another-value"); + }); + + test("should handle non-Error exceptions in fetch method", async () => { + const toggle = new Toggle({ + horizonUrls: ["https://invalid-domain-that-does-not-exist.test"], + }); + + // Mock fetch to throw a non-Error value + const originalFetch = global.fetch; + global.fetch = (() => { + throw "string error"; // Non-Error exception + }) as typeof fetch; + + try { + await expect(toggle.fetch("/test", { test: "data" })).rejects.toThrow( + "All horizon URLs failed", + ); + } finally { + // Restore original fetch + global.fetch = originalFetch; + } + }); + + test("should send payload as JSON in request body", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + name: string; + age: number; + active: boolean; + }; + } + + const payload = { name: "test-user", age: 25, active: true }; + const result = await toggle.fetch("/post", payload); + + expect(result.method).toBe("POST"); + expect(result.body.name).toBe("test-user"); + expect(result.body.age).toBe(25); + expect(result.body.active).toBe(true); + }); + + test("should handle undefined payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: unknown; + } + + const result = await toggle.fetch("/post", undefined, { + body: JSON.stringify({ default: "body" }), + }); + expect(result.method).toBe("POST"); + }); + + test("should handle null payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: unknown; + } + + const result = await toggle.fetch("/post", null, { + body: JSON.stringify({ default: "body" }), + }); + expect(result.method).toBe("POST"); + }); + + test("should handle complex nested payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + user: { + profile: { + name: string; + preferences: string[]; + }; + }; + metadata: Record; + }; + } + + const complexPayload = { + user: { + profile: { + name: "complex-user", + preferences: ["dark-mode", "notifications"], + }, + }, + metadata: { + version: "1.0", + feature_flags: { newUI: true }, + }, + }; + + const result = await toggle.fetch( + "/post", + complexPayload, + ); + + expect(result.method).toBe("POST"); + expect(result.body.user.profile.name).toBe("complex-user"); + expect(result.body.user.profile.preferences).toEqual([ + "dark-mode", + "notifications", + ]); + expect(result.body.metadata.version).toBe("1.0"); + }); + + test("should prioritize payload over options.body when both provided", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + source: string; + }; + } + + const result = await toggle.fetch( + "/post", + { source: "payload" }, + { + body: JSON.stringify({ source: "options" }), + }, + ); + + expect(result.method).toBe("POST"); + expect(result.body.source).toBe("payload"); + }); + + test("should fall back to options.body when payload is undefined", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + source: string; + }; + } + + const result = await toggle.fetch("/post", undefined, { + body: JSON.stringify({ source: "options" }), + }); + + expect(result.method).toBe("POST"); + expect(result.body.source).toBe("options"); + }); +}); + +describe("buildDefaultHorizonUrl", () => { + test("should build URL with org ID from valid public key", () => { + const toggle = new Toggle(); + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(validKey)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL when org ID cannot be extracted", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("invalid-key")).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for malformed base64", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("public_invalid-base64!")).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should build URL with complex org ID", () => { + const toggle = new Toggle(); + const orgId = "my-org-123_test"; + const validKey = `public_${Buffer.from(`${orgId}:secret-data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(validKey)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL for org ID with invalid characters", () => { + const toggle = new Toggle(); + const invalidOrgId = "org@invalid#chars"; + const invalidKey = `public_${Buffer.from(`${invalidOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(invalidKey)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for empty org ID", () => { + const toggle = new Toggle(); + const emptyOrgKey = `public_${Buffer.from(":secret-data").toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(emptyOrgKey)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should build URL with numeric org ID", () => { + const toggle = new Toggle(); + const numericOrgId = "123456"; + const numericKey = `public_${Buffer.from(`${numericOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(numericKey)).toBe( + `https://${numericOrgId}.toggle.hyphen.cloud`, + ); + }); + + test("should build URL with single character org ID", () => { + const toggle = new Toggle(); + const singleCharOrgId = "a"; + const singleCharKey = `public_${Buffer.from(`${singleCharOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(singleCharKey)).toBe( + `https://${singleCharOrgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL for null input", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl(null as unknown as string)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for undefined input", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl(undefined as unknown as string)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for empty string", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("")).toBe("https://toggle.hyphen.cloud"); + }); + + test("should handle key without prefix", () => { + const toggle = new Toggle(); + const orgId = "no-prefix-org"; + const keyWithoutPrefix = Buffer.from(`${orgId}:secret-data`).toString( + "base64", + ); + expect(toggle.getDefaultHorizonUrl(keyWithoutPrefix)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); +}); + +describe("generateTargetKey", () => { + test("should generate key with app, env, and random suffix when both are provided", () => { + const toggle = new Toggle({ + applicationId: "myapp", + environment: "production", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + expect(parts.length).toBe(3); + expect(parts[0]).toBe("myapp"); + expect(parts[1]).toBe("production"); + expect(parts[2]).toBeTruthy(); // Random suffix should exist + expect(parts[2].length).toBeGreaterThan(0); + }); + + test("should generate key with env and random suffix when app is not provided", () => { + const toggle = new Toggle(); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + // Environment defaults to "development" when not provided + expect(key).toBeTruthy(); + expect(parts.length).toBe(2); + expect(parts[0]).toBe("development"); + expect(parts[1]).toBeTruthy(); // Random suffix + }); + + test("should generate key with app, env, and random suffix when only app is provided", () => { + const toggle = new Toggle({ + applicationId: "myapp", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + // Environment defaults to "development" when not explicitly provided + expect(parts.length).toBe(3); + expect(parts[0]).toBe("myapp"); + expect(parts[1]).toBe("development"); + expect(parts[2]).toBeTruthy(); // Random suffix + }); + + test("should generate key with env and random suffix when only env is provided", () => { + const toggle = new Toggle({ + environment: "staging", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + expect(parts.length).toBe(2); + expect(parts[0]).toBe("staging"); + expect(parts[1]).toBeTruthy(); // Random suffix + }); + + test("should generate different keys on consecutive calls", () => { + const toggle = new Toggle({ + applicationId: "myapp", + environment: "production", + }); + const key1 = toggle.generateTargetKey(); + const key2 = toggle.generateTargetKey(); + + expect(key1).not.toBe(key2); + // But they should have the same prefix + expect(key1.startsWith("myapp-production-")).toBe(true); + expect(key2.startsWith("myapp-production-")).toBe(true); + }); + + test("should generate random suffix with correct format", () => { + const toggle = new Toggle(); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + // Random suffix from Math.random().toString(36).substring(7) + // Should be alphanumeric with possible dots (base36) + expect(parts[parts.length - 1]).toBeTruthy(); + expect(/^[a-z0-9.]+$/.test(parts[parts.length - 1])).toBe(true); + }); + + test("should handle empty string applicationId", () => { + const toggle = new Toggle({ + applicationId: "", + environment: "production", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + // Empty string is filtered out + expect(parts.length).toBe(2); + expect(parts[0]).toBe("production"); + expect(parts[1]).toBeTruthy(); + }); + + test("should handle empty string environment", () => { + const toggle = new Toggle({ + applicationId: "myapp", + environment: "", + }); + const key = toggle.generateTargetKey(); + + // Empty string is filtered out, but environment defaults to "development" in constructor + // So we need to check the actual behavior + expect(key).toBeTruthy(); + expect(key.startsWith("myapp-")).toBe(true); + }); + + test("should handle both empty strings", () => { + const toggle = new Toggle({ + applicationId: "", + environment: "", + }); + const key = toggle.generateTargetKey(); + + // Empty strings are filtered out, but environment defaults to "development" in constructor + expect(key).toBeTruthy(); + expect(key.length).toBeGreaterThan(0); + }); + + test("should handle special characters in applicationId", () => { + const toggle = new Toggle({ + applicationId: "my-app_v2", + environment: "prod", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + expect(parts.length).toBeGreaterThan(2); // Will split on hyphens in app name too + expect(key.startsWith("my-app_v2-prod-")).toBe(true); + }); + + test("should handle special characters in environment", () => { + const toggle = new Toggle({ + applicationId: "myapp", + environment: "prod-us-east-1", + }); + const key = toggle.generateTargetKey(); + + expect(key.startsWith("myapp-prod-us-east-1-")).toBe(true); + }); + + test("should generate unique keys across multiple instances", () => { + const toggle1 = new Toggle({ + applicationId: "myapp", + environment: "production", + }); + const toggle2 = new Toggle({ + applicationId: "myapp", + environment: "production", + }); + + const key1 = toggle1.generateTargetKey(); + const key2 = toggle2.generateTargetKey(); + + expect(key1).not.toBe(key2); + }); + + test("should handle very long applicationId", () => { + const longAppId = "a".repeat(100); + const toggle = new Toggle({ + applicationId: longAppId, + environment: "prod", + }); + const key = toggle.generateTargetKey(); + + expect(key.startsWith(longAppId)).toBe(true); + expect(key).toContain("prod"); + }); + + test("should handle very long environment", () => { + const longEnv = "e".repeat(100); + const toggle = new Toggle({ + applicationId: "app", + environment: longEnv, + }); + const key = toggle.generateTargetKey(); + + expect(key.startsWith("app")).toBe(true); + expect(key).toContain(longEnv); + }); + + test("should generate key with only environment when explicitly set without app", () => { + const toggle = new Toggle({ + environment: "production", + }); + const key = toggle.generateTargetKey(); + const parts = key.split("-"); + + expect(parts.length).toBe(2); + expect(parts[0]).toBe("production"); + expect(parts[1]).toBeTruthy(); + }); + + test("should handle numeric values in applicationId", () => { + const toggle = new Toggle({ + applicationId: "app123", + environment: "prod", + }); + const key = toggle.generateTargetKey(); + + expect(key).toContain("app123"); + expect(key).toContain("prod"); + }); + + test("should handle numeric values in environment", () => { + const toggle = new Toggle({ + applicationId: "myapp", + environment: "env2", + }); + const key = toggle.generateTargetKey(); + + expect(key).toContain("myapp"); + expect(key).toContain("env2"); + }); + + test("should maintain consistent format across multiple calls", () => { + const toggle = new Toggle({ + applicationId: "testapp", + environment: "staging", + }); + + const keys = Array.from({ length: 5 }, () => toggle.generateTargetKey()); + + // All keys should start with the same prefix + keys.forEach((key) => { + expect(key.startsWith("testapp-staging-")).toBe(true); + }); + + // All keys should be unique + const uniqueKeys = new Set(keys); + expect(uniqueKeys.size).toBe(5); + }); +}); diff --git a/packages/browser-sdk/test/index.test.ts b/packages/browser-sdk/test/index.test.ts new file mode 100644 index 0000000..6961603 --- /dev/null +++ b/packages/browser-sdk/test/index.test.ts @@ -0,0 +1,634 @@ +import { describe, expect, test } from "vitest"; +import { Toggle, type ToggleOptions } from "../src/index.js"; +import { getRandomToggleContext, mockToggleContexts } from "./mock-contexts.js"; + +describe("Hyphen sdk", () => { + test("should create an instance of Toggle", () => { + const toggle = new Toggle(); + expect(toggle).toBeInstanceOf(Toggle); + }); + + describe("constructor", () => { + test("should create Toggle with no options", () => { + const toggle = new Toggle(); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with undefined options", () => { + const toggle = new Toggle(undefined); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with empty options object", () => { + const options: ToggleOptions = {}; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with defaultContext option", () => { + const customContext = getRandomToggleContext(); + const options: ToggleOptions = { + defaultContext: customContext, + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.ipAddress).toBe(customContext.ipAddress); + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should create Toggle with publicApiKey option", () => { + const options: ToggleOptions = { + publicApiKey: "public_test-api-key", + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBe("public_test-api-key"); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with both defaultContext and publicApiKey options", () => { + const customContext = getRandomToggleContext(); + const options: ToggleOptions = { + defaultContext: customContext, + publicApiKey: "public_comprehensive-key", + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBe("public_comprehensive-key"); + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.user?.email).toBe( + customContext.user?.email, + ); + }); + + test("should not validate publicApiKey in constructor", () => { + const options: ToggleOptions = { + publicApiKey: "invalid-key-without-prefix", + }; + expect(() => { + new Toggle(options); + }).not.toThrow(); + const toggle = new Toggle(options); + expect(toggle.publicApiKey).toBe("invalid-key-without-prefix"); + }); + }); + + describe("publicApiKey property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should allow getting the publicApiKey property", () => { + const toggle = new Toggle(); + const apiKey = toggle.publicApiKey; + expect(apiKey).toBeUndefined(); + }); + + test("should allow setting the publicApiKey property", () => { + const toggle = new Toggle(); + const testApiKey = "public_test-api-key-123"; + toggle.publicApiKey = testApiKey; + expect(toggle.publicApiKey).toBe(testApiKey); + }); + + test("should allow setting publicApiKey to undefined", () => { + const toggle = new Toggle(); + toggle.publicApiKey = "public_test-key"; + toggle.publicApiKey = undefined; + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should maintain the same publicApiKey value when accessed multiple times", () => { + const toggle = new Toggle(); + const testApiKey = "public_consistent-api-key"; + toggle.publicApiKey = testApiKey; + const key1 = toggle.publicApiKey; + const key2 = toggle.publicApiKey; + expect(key1).toBe(key2); + expect(key1).toBe(testApiKey); + }); + + test("should update publicApiKey property when set to a new value", () => { + const toggle = new Toggle(); + const originalKey = "public_original-key"; + const newKey = "public_new-key"; + toggle.publicApiKey = originalKey; + expect(toggle.publicApiKey).toBe(originalKey); + toggle.publicApiKey = newKey; + expect(toggle.publicApiKey).toBe(newKey); + expect(toggle.publicApiKey).not.toBe(originalKey); + }); + + test("should throw error when publicApiKey does not start with 'public_'", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = "invalid-key"; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should throw error when publicApiKey starts with different prefix", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = "private_some-key"; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should throw error when publicApiKey is empty string", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = ""; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should accept publicApiKey that starts with 'public_'", () => { + const toggle = new Toggle(); + const validKey = "public_valid-key-123"; + expect(() => { + toggle.publicApiKey = validKey; + }).not.toThrow(); + expect(toggle.publicApiKey).toBe(validKey); + }); + + test("should accept undefined publicApiKey without throwing", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = undefined; + }).not.toThrow(); + expect(toggle.publicApiKey).toBeUndefined(); + }); + }); + + describe("defaultContext property", () => { + test("should return undefined when no defaultContext is set", () => { + const toggle = new Toggle(); + const context = toggle.defaultContext; + expect(context).toBeUndefined(); + }); + + test("should allow getting the defaultContext property", () => { + const toggle = new Toggle(); + const context = toggle.defaultContext; + expect(context).toBeUndefined(); + }); + + test("should allow setting the defaultContext property", () => { + const toggle = new Toggle(); + const customContext = getRandomToggleContext(); + toggle.defaultContext = customContext; + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.ipAddress).toBe(customContext.ipAddress); + }); + + test("should maintain the same defaultContext when accessed multiple times", () => { + const toggle = new Toggle(); + const customContext = getRandomToggleContext(); + toggle.defaultContext = customContext; + const context1 = toggle.defaultContext; + const context2 = toggle.defaultContext; + expect(context1).toBe(context2); + }); + + test("should update defaultContext property when set to a new value", () => { + const toggle = new Toggle(); + const originalContext = toggle.defaultContext; // undefined + const newContext = getRandomToggleContext(); + toggle.defaultContext = newContext; + expect(toggle.defaultContext).not.toBe(originalContext); + expect(toggle.defaultContext).toBe(newContext); + expect(toggle.defaultContext?.targetingKey).toBe(newContext.targetingKey); + }); + + test("should handle complex defaultContext with all properties", () => { + const toggle = new Toggle(); + // Using specific index for edge case user to test complex nested data structures + const complexContext = mockToggleContexts[9]; + toggle.defaultContext = complexContext; + expect(toggle.defaultContext).toBe(complexContext); + expect(toggle.defaultContext?.user?.customAttributes?.tags).toEqual([ + "vip", + "beta-tester", + "early-adopter", + ]); + expect(toggle.defaultContext?.customAttributes?.complexData).toEqual({ + nested: { + value: "deep-nested-value", + array: [1, 2, 3], + }, + }); + }); + }); + + describe("horizonUrls property", () => { + test("should return default url", () => { + const toggle = new Toggle(); + expect(toggle.horizonUrls).toEqual(["https://toggle.hyphen.cloud"]); + }); + + test("should be set when constructor receives horizonUrls option", () => { + const testUrls = [ + "https://org1.toggle.hyphen.cloud", + "https://org2.toggle.hyphen.cloud", + ]; + const toggle = new Toggle({ horizonUrls: testUrls }); + expect(toggle.horizonUrls).toEqual(testUrls); + }); + + test("should remain empty when constructor receives no horizonUrls", () => { + const toggle = new Toggle({ publicApiKey: "public_test-key" }); + expect(toggle.horizonUrls).toEqual(["https://toggle.hyphen.cloud"]); + }); + + test("should allow getting the horizonUrls property", () => { + const toggle = new Toggle(); + const urls = toggle.horizonUrls; + expect(urls).toEqual(["https://toggle.hyphen.cloud"]); + expect(Array.isArray(urls)).toBe(true); + }); + + test("should allow setting the horizonUrls property", () => { + const toggle = new Toggle(); + const testUrls = ["https://test.toggle.hyphen.cloud"]; + toggle.horizonUrls = testUrls; + expect(toggle.horizonUrls).toEqual(testUrls); + }); + + test("should allow setting horizonUrls to empty array", () => { + const toggle = new Toggle(); + const testUrls = ["https://test.toggle.hyphen.cloud"]; + toggle.horizonUrls = testUrls; + toggle.horizonUrls = []; + expect(toggle.horizonUrls).toEqual([]); + }); + + test("should maintain the same horizonUrls array when accessed multiple times", () => { + const toggle = new Toggle(); + const testUrls = [ + "https://endpoint1.hyphen.cloud", + "https://endpoint2.hyphen.cloud", + ]; + toggle.horizonUrls = testUrls; + const urls1 = toggle.horizonUrls; + const urls2 = toggle.horizonUrls; + expect(urls1).toBe(urls2); + expect(urls1).toEqual(testUrls); + }); + + test("should update horizonUrls property when set to a new array", () => { + const toggle = new Toggle(); + const originalUrls = ["https://original.hyphen.cloud"]; + const newUrls = [ + "https://new1.hyphen.cloud", + "https://new2.hyphen.cloud", + ]; + toggle.horizonUrls = originalUrls; + expect(toggle.horizonUrls).toEqual(originalUrls); + toggle.horizonUrls = newUrls; + expect(toggle.horizonUrls).toEqual(newUrls); + expect(toggle.horizonUrls).not.toEqual(originalUrls); + }); + + test("should handle single URL in array", () => { + const toggle = new Toggle(); + const singleUrl = ["https://single.toggle.hyphen.cloud"]; + toggle.horizonUrls = singleUrl; + expect(toggle.horizonUrls).toEqual(singleUrl); + expect(toggle.horizonUrls.length).toBe(1); + }); + + test("should handle multiple URLs with different formats", () => { + const toggle = new Toggle(); + const mixedUrls = [ + "https://prod.toggle.hyphen.cloud", + "http://staging.toggle.hyphen.cloud", + "https://org-123.toggle.hyphen.cloud", + "https://api.custom-domain.com/toggle", + ]; + toggle.horizonUrls = mixedUrls; + expect(toggle.horizonUrls).toEqual(mixedUrls); + expect(toggle.horizonUrls.length).toBe(4); + }); + + test("should handle very large URL array", () => { + const toggle = new Toggle(); + const largeUrlArray = Array.from( + { length: 100 }, + (_, i) => `https://endpoint-${i}.toggle.hyphen.cloud`, + ); + toggle.horizonUrls = largeUrlArray; + expect(toggle.horizonUrls).toEqual(largeUrlArray); + expect(toggle.horizonUrls.length).toBe(100); + }); + + test("should not interfere with other properties", () => { + const testOrgId = "test-org"; + const validKey = `public_${Buffer.from(`${testOrgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + const testUrls = ["https://test.hyphen.cloud"]; + const testContext = getRandomToggleContext(); + + toggle.horizonUrls = testUrls; + toggle.defaultContext = testContext; + + expect(toggle.horizonUrls).toEqual(testUrls); + expect(toggle.defaultContext).toBe(testContext); + expect(toggle.organizationId).toBe(testOrgId); + }); + + test("should work with constructor containing all options", () => { + const testUrls = [ + "https://primary.toggle.hyphen.cloud", + "https://secondary.toggle.hyphen.cloud", + ]; + const testContext = getRandomToggleContext(); + const toggle = new Toggle({ + publicApiKey: "public_test-comprehensive-key", + defaultContext: testContext, + horizonUrls: testUrls, + }); + + expect(toggle.horizonUrls).toEqual(testUrls); + expect(toggle.defaultContext).toBe(testContext); + expect(toggle.publicApiKey).toBe("public_test-comprehensive-key"); + }); + + test("should handle URLs with query parameters and paths", () => { + const toggle = new Toggle(); + const complexUrls = [ + "https://api.hyphen.cloud/v1/toggle?version=latest", + "https://cdn.hyphen.cloud/toggle/endpoint", + "https://backup.hyphen.cloud:8443/api/toggle", + ]; + toggle.horizonUrls = complexUrls; + expect(toggle.horizonUrls).toEqual(complexUrls); + }); + }); + + describe("applicationId property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.applicationId).toBeUndefined(); + }); + + test("should be set when constructor receives applicationId option", () => { + const toggle = new Toggle({ applicationId: "test-app" }); + expect(toggle.applicationId).toBe("test-app"); + }); + + test("should allow getting the applicationId property", () => { + const toggle = new Toggle(); + const appId = toggle.applicationId; + expect(appId).toBeUndefined(); + }); + + test("should allow setting the applicationId property", () => { + const toggle = new Toggle(); + const testAppId = "my-application"; + toggle.applicationId = testAppId; + expect(toggle.applicationId).toBe(testAppId); + }); + + test("should allow setting applicationId to undefined", () => { + const toggle = new Toggle(); + toggle.applicationId = "test-app"; + toggle.applicationId = undefined; + expect(toggle.applicationId).toBeUndefined(); + }); + }); + + describe("defaultTargetingKey property", () => { + test("should generate random key by default", () => { + const toggle = new Toggle(); + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + expect(toggle.defaultTargetingKey.length).toBeGreaterThan(0); + }); + + test("should be set when constructor receives defaultTargetKey option", () => { + const toggle = new Toggle({ + defaultTargetKey: "explicit-key", + }); + expect(toggle.defaultTargetingKey).toBe("explicit-key"); + }); + + test("should be set from defaultContext with targetingKey", () => { + const toggle = new Toggle({ + defaultContext: { targetingKey: "context-key" }, + }); + expect(toggle.defaultTargetingKey).toBe("context-key"); + }); + + test("should be set from defaultContext with user.id", () => { + const toggle = new Toggle({ + defaultContext: { + user: { id: "user-123" }, + }, + }); + expect(toggle.defaultTargetingKey).toBe("user-123"); + }); + + test("should generate key with applicationId and environment when no context", () => { + const toggle = new Toggle({ + applicationId: "test-app", + environment: "production", + }); + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-production-[a-z0-9]+$/, + ); + }); + + test("should prefer defaultTargetKey option over defaultContext", () => { + const toggle = new Toggle({ + defaultTargetKey: "explicit-key", + defaultContext: { + targetingKey: "context-key", + }, + }); + expect(toggle.defaultTargetingKey).toBe("explicit-key"); + }); + + test("should prefer targetingKey over user.id in context", () => { + const toggle = new Toggle({ + defaultContext: { + targetingKey: "targeting-key", + user: { id: "user-123" }, + }, + }); + expect(toggle.defaultTargetingKey).toBe("targeting-key"); + }); + + test("should allow setting defaultTargetingKey property", () => { + const toggle = new Toggle(); + const originalKey = toggle.defaultTargetingKey; + toggle.defaultTargetingKey = "custom-key"; + expect(toggle.defaultTargetingKey).toBe("custom-key"); + expect(toggle.defaultTargetingKey).not.toBe(originalKey); + }); + + test("should generate different keys for different instances", () => { + const toggle1 = new Toggle(); + const toggle2 = new Toggle(); + expect(toggle1.defaultTargetingKey).not.toBe(toggle2.defaultTargetingKey); + }); + + test("should generate key with applicationId and default environment", () => { + const toggle = new Toggle({ + applicationId: "test-app", + }); + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-development-[a-z0-9]+$/, + ); + }); + + test("should generate key with environment only", () => { + const toggle = new Toggle({ + environment: "staging", + }); + expect(toggle.defaultTargetingKey).toMatch(/^staging-[a-z0-9]+$/); + }); + + test("should fall back to getTargetingKey when defaultContext returns to default", () => { + const toggle = new Toggle({ + defaultContext: {}, + }); + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + }); + + test("should generate key with environment when no applicationId", () => { + const toggle = new Toggle(); + // This triggers generateTargetKey() since no defaultContext is provided + expect(toggle.defaultTargetingKey).toMatch(/^development-[a-z0-9]+$/); + }); + + test("should handle empty string values in key generation", () => { + const toggle = new Toggle({ + applicationId: "", + environment: "", + }); + // Empty environment defaults to "development", empty app is filtered out + expect(toggle.defaultTargetingKey).toMatch(/^development-[a-z0-9]+$/); + }); + + test("should generate key when environment is explicitly set to empty", () => { + const toggle = new Toggle({ + applicationId: "test-app", + environment: "", + }); + // Empty environment defaults to "development" + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-development-[a-z0-9]+$/, + ); + }); + + test("should handle environment set to undefined after construction", () => { + const toggle = new Toggle({ + applicationId: "test-app", + }); + + // Set environment to undefined to trigger the fallback branch + toggle.environment = undefined; + + // Set a new defaultContext to trigger regeneration via getTargetingKey + toggle.defaultContext = {}; + + // This should eventually trigger generateTargetKey with undefined environment + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + }); + }); + + describe("environment property", () => { + test("should return 'development' by default", () => { + const toggle = new Toggle(); + expect(toggle.environment).toBe("development"); + }); + + test("should be set when constructor receives environment option", () => { + const toggle = new Toggle({ environment: "production" }); + expect(toggle.environment).toBe("production"); + }); + + test("should allow getting the environment property", () => { + const toggle = new Toggle(); + const env = toggle.environment; + expect(env).toBe("development"); + }); + + test("should allow setting the environment property", () => { + const toggle = new Toggle(); + const testEnv = "staging"; + toggle.environment = testEnv; + expect(toggle.environment).toBe(testEnv); + }); + + test("should allow setting environment to undefined", () => { + const toggle = new Toggle(); + toggle.environment = "production"; + toggle.environment = undefined; + expect(toggle.environment).toBeUndefined(); + }); + }); + + describe("organizationId property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.organizationId).toBeUndefined(); + }); + + test("should be set when constructor receives valid publicApiKey", () => { + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + expect(toggle.organizationId).toBe(orgId); + }); + + test("should remain undefined when constructor receives invalid publicApiKey", () => { + const toggle = new Toggle({ publicApiKey: "invalid-key" }); + expect(toggle.organizationId).toBeUndefined(); + }); + + test("should allow getting the organizationId property", () => { + const toggle = new Toggle(); + const orgId = toggle.organizationId; + expect(orgId).toBeUndefined(); + }); + + test("should maintain the same organizationId value when accessed multiple times", () => { + const testOrgId = "consistent-org-id"; + const validKey = `public_${Buffer.from(`${testOrgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + const orgId1 = toggle.organizationId; + const orgId2 = toggle.organizationId; + expect(orgId1).toBe(orgId2); + expect(orgId1).toBe(testOrgId); + }); + }); + + describe("get method", () => { + test("should return defaultValue when error occurs", async () => { + const toggle = new Toggle({ + horizonUrls: ["https://api.test.com"], + }); + + const result = await toggle.get("feature-flag", false); + expect(result).toBe(false); // Returns defaultValue when error occurs + }); + }); +}); diff --git a/packages/browser-sdk/test/mock-contexts.ts b/packages/browser-sdk/test/mock-contexts.ts new file mode 100644 index 0000000..995a1ba --- /dev/null +++ b/packages/browser-sdk/test/mock-contexts.ts @@ -0,0 +1,225 @@ +import type { ToggleContext } from "../src/types.js"; + +/** + * Mock ToggleContext examples for testing purposes. + * These provide a variety of realistic scenarios for comprehensive test coverage. + */ +export const mockToggleContexts: ToggleContext[] = [ + // Basic context with minimal data + { + targetingKey: "user-123", + }, + + // Standard user context with email and basic attributes + { + targetingKey: "user-456", + ipAddress: "203.0.113.42", + user: { + id: "user-456", + email: "john.doe@example.com", + name: "John Doe", + }, + customAttributes: { + region: "us-west", + plan: "basic", + }, + }, + + // Premium user with extensive custom attributes + { + targetingKey: "premium-user-789", + ipAddress: "198.51.100.15", + user: { + id: "premium-user-789", + email: "jane.smith@company.com", + name: "Jane Smith", + customAttributes: { + role: "admin", + department: "engineering", + seniority: "senior", + permissions: ["read", "write", "delete"], + }, + }, + customAttributes: { + subscriptionLevel: "premium", + region: "us-east", + tier: "gold", + betaFeatures: true, + accountType: "business", + }, + }, + + // Mobile user context with device information + { + targetingKey: "mobile-user-321", + ipAddress: "192.168.1.100", + user: { + id: "mobile-user-321", + email: "mobile@user.com", + name: "Mobile User", + customAttributes: { + deviceType: "mobile", + os: "iOS", + appVersion: "2.1.0", + }, + }, + customAttributes: { + platform: "mobile", + region: "eu-west", + language: "en", + }, + }, + + // Enterprise user with complex organizational data + { + targetingKey: "enterprise-user-654", + ipAddress: "10.0.0.5", + user: { + id: "enterprise-user-654", + email: "admin@enterprise.com", + name: "Enterprise Admin", + customAttributes: { + role: "super-admin", + organizationId: "org-12345", + tenantId: "tenant-abc", + permissions: ["all"], + lastLogin: "2023-12-01T10:00:00Z", + }, + }, + customAttributes: { + subscriptionLevel: "enterprise", + region: "us-central", + industryVertical: "finance", + companySize: "large", + contractType: "annual", + }, + }, + + // Anonymous user context + { + targetingKey: "anonymous-987", + ipAddress: "172.16.0.25", + customAttributes: { + region: "ap-southeast", + sessionId: "sess_anonymous_123", + userAgent: "Mozilla/5.0", + referrer: "https://google.com", + }, + }, + + // Developer/QA testing context + { + targetingKey: "dev-user-111", + ipAddress: "127.0.0.1", + user: { + id: "dev-user-111", + email: "developer@test.com", + name: "Test Developer", + customAttributes: { + role: "developer", + team: "platform", + environment: "staging", + }, + }, + customAttributes: { + region: "us-west", + testMode: true, + debugEnabled: true, + featureFlags: ["new-ui", "beta-api"], + }, + }, + + // International user with localization data + { + targetingKey: "intl-user-888", + ipAddress: "185.199.108.153", + user: { + id: "intl-user-888", + email: "usuario@ejemplo.es", + name: "Marรญa Garcรญa", + customAttributes: { + locale: "es-ES", + timezone: "Europe/Madrid", + currency: "EUR", + }, + }, + customAttributes: { + region: "eu-south", + language: "spanish", + country: "Spain", + gdprConsent: true, + }, + }, + + // API/Service account context + { + targetingKey: "service-account-555", + ipAddress: "10.1.1.50", + user: { + id: "service-account-555", + email: "api@service.com", + name: "API Service Account", + customAttributes: { + accountType: "service", + apiVersion: "v2", + clientId: "client_12345", + }, + }, + customAttributes: { + region: "us-east", + serviceType: "api", + rateLimitTier: "premium", + authentication: "oauth2", + }, + }, + + // Edge case: User with numeric and special character data + { + targetingKey: "edge-case-user_999", + ipAddress: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + user: { + id: "edge-case-user_999", + email: "test+special@domain-name.co.uk", + name: "Test User-Name O'Connor", + customAttributes: { + userId: 12345, + score: 98.5, + isActive: true, + tags: ["vip", "beta-tester", "early-adopter"], + metadata: { + source: "referral", + campaign: "spring-2023", + }, + }, + }, + customAttributes: { + region: "ap-north", + numericId: 999, + percentage: 85.75, + enabled: false, + complexData: { + nested: { + value: "deep-nested-value", + array: [1, 2, 3], + }, + }, + }, + }, +]; + +/** + * Gets a random ToggleContext from the mock contexts array. + * Useful for testing with varied context data without hardcoding specific indices. + * + * @returns A randomly selected ToggleContext from the mockToggleContexts array + * + * @example + * ```typescript + * const randomContext = getRandomToggleContext(); + * const toggle = new Toggle({ defaultContext: randomContext }); + * ``` + */ +export function getRandomToggleContext(): ToggleContext { + const randomIndex = Math.floor(Math.random() * mockToggleContexts.length); + return mockToggleContexts[randomIndex]; +} diff --git a/packages/browser-sdk/tsconfig.json b/packages/browser-sdk/tsconfig.json new file mode 100644 index 0000000..db23a66 --- /dev/null +++ b/packages/browser-sdk/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "outDir": "./dist", + "rootDir": "./src", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] + } \ No newline at end of file diff --git a/packages/browser-sdk/tsdown.config.ts b/packages/browser-sdk/tsdown.config.ts new file mode 100644 index 0000000..4d9685e --- /dev/null +++ b/packages/browser-sdk/tsdown.config.ts @@ -0,0 +1,42 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig([ + // ESM and CJS builds for Node.js / bundlers + { + entry: ["src/index.ts"], + format: ["esm", "cjs"], + dts: true, + clean: true, + sourcemap: true, + minify: false, + outDir: "dist", + platform: "neutral", + target: "es2018", + deps: { + neverBundle: ["hookified"], + }, + }, + // Browser IIFE build with bundled dependencies + { + entry: ["src/index.ts"], + format: ["iife"], + dts: false, + clean: false, + sourcemap: true, + minify: false, + outDir: "dist", + globalName: "HyphenBrowserSDK", + platform: "browser", + target: "es2018", + deps: { + alwaysBundle: ["hookified"], + onlyBundle: false, + }, + outputOptions: { + entryFileNames: "index.browser.js", + }, + define: { + global: "globalThis", + }, + }, +]); diff --git a/packages/browser-sdk/vitest.config.ts b/packages/browser-sdk/vitest.config.ts new file mode 100644 index 0000000..0d84da8 --- /dev/null +++ b/packages/browser-sdk/vitest.config.ts @@ -0,0 +1,16 @@ +import {defineConfig} from 'vitest/config'; + +export default defineConfig({ + test: { + coverage: { + // The lcov paths start at the repository root, so that Codecov finds each file. + reporter: ['text', 'json', ['lcov', { projectRoot: '../..' }]], + exclude: [ + 'dist/**', + 'vitest.config.ts', + 'tsup.config.ts', + 'src/types.ts', + ], + }, + }, +}); diff --git a/packages/nodejs-sdk/LICENSE b/packages/nodejs-sdk/LICENSE new file mode 100644 index 0000000..5533221 --- /dev/null +++ b/packages/nodejs-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Hyphen + +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. diff --git a/packages/nodejs-sdk/README.md b/packages/nodejs-sdk/README.md new file mode 100644 index 0000000..2ddf541 --- /dev/null +++ b/packages/nodejs-sdk/README.md @@ -0,0 +1,1132 @@ +![Hyphen AI](https://github.com/Hyphen/javascript-sdks/raw/main/logo.png) + +[![tests](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml/badge.svg)](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/gh/Hyphen/javascript-sdks/graph/badge.svg)](https://codecov.io/gh/Hyphen/javascript-sdks) +[![npm](https://img.shields.io/npm/v/@hyphen/sdk)](https://www.npmjs.com/package/@hyphen/sdk) +[![npm](https://img.shields.io/npm/dm/@hyphen/sdk)](https://www.npmjs.com/package/@hyphen/sdk) +[![license](https://img.shields.io/github/license/Hyphen/javascript-sdks)](https://github.com/Hyphen/javascript-sdks/blob/main/LICENSE) + +# Hyphen Node.js SDK + +The Hyphen Node.js SDK is a JavaScript library that allows developers to easily integrate Hyphen's feature flag service [Toggle](https://hyphen.ai/toggle), secret management service [ENV](https://hyphen.ai/env), and geo information service [Net Info](https://hyphen.ai/net-info) into their Node.js applications. + +# Table of Contents +- [Installation](#installation) +- [Basic Usage with Hyphen](#basic-usage-with-hyphen) +- [Toggle - Feature Flag Service](#toggle---feature-flag-service) + - [Toggle Options](#toggle-options) + - [Toggle API](#toggle-api) + - [Toggle Hooks](#toggle-hooks) + - [Toggle Error Handling](#toggle-error-handling) + - [Toggle Caching](#toggle-caching) + - [Toggle Environment Variables](#toggle-environment-variables) + - [Toggle Self-Hosted](#toggle-self-hosted) +- [ENV - Secret Management Service](#env---secret-management-service) + - [Loading Environment Variables from Hyphen](#loading-environment-variables-from-hyphen) + - [Loading Local Environment Files](#loading-local-environment-files) +- [Net Info - Geo Information Service](#net-info---geo-information-service) +- [Execution Context - API Key Validation](#execution-context---api-key-validation) +- [Link - Short Code Service](#link---short-code-service) + - [Creating a Short Code](#creating-a-short-code) + - [Updating a Short Code](#updating-a-short-code) + - [Getting a Short Code](#getting-a-short-code) + - [Getting Short Codes](#getting-short-codes) + - [Getting all Organization Tags](#getting-all-organization-tags) + - [Getting Short Code Stats](#getting-short-code-stats) + - [Deleting a Short Code](#deleting-a-short-code) + - [Creating a QR Code from a Short Code](#creating-a-qr-code-from-a-short-code) + - [Get QR Codes for a Short Code](#get-qr-codes-for-a-short-code) + - [Deleting a QR Code](#deleting-a-qr-code) +- [Migrating to v3](#migrating-to-v3) +- [Contributing](#contributing) +- [Testing Your Changes](#testing-your-changes) +- [License and Copyright](#license-and-copyright) + +# Installation + +To install the Hyphen Node.js SDK, you can use npm or yarn. Run the following command in your terminal: + +```bash +npm install @hyphen/sdk +``` + +# Basic Usage with Hyphen + +There are many ways to use the Hyphen Node.js SDK. Because of this we have created examples for each of the different ways in each secton of the documentation. To get started, you can create an instance of the `Hyphen` class and use its methods to interact with the various services. + +```javascript +import { Hyphen } from '@hyphen/sdk'; + +const hyphen = new Hyphen({ + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', +}); +const result = await hyphen.toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +You can also use `netInfo` to access the network information service. + +```javascript +import { Hyphen, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const hyphen = new Hyphen({ + publicApiKey: 'your_public_api_key', + toggle: { + applicationId: 'your_application_id', + context: context, + }, +}); +const result = await hyphen.toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +You can also use `netInfo` to access the network information service. + +```javascript +import { Hyphen } from '@hyphen/sdk'; + +const hyphen = new Hyphen({ + apiKey: 'your_api_key', +}); +const result = await hyphen.netInfo.getIpInfo('8.8.8.8'); +console.log('Geo IP information:', result); +``` + +If you need to set the `apiKey` or `publicApiKey` after initializing `Hyphen` you can do so and it will cascade the setting to the individual services: + +```javascript +import { Hyphen } from '@hyphen/sdk'; + +const hyphen = new Hyphen(); +hyphen.apiKey = 'your_api_key'; +const result = await hyphen.netInfo.getIpInfo('8.8.8.8'); +console.log('Geo IP information:', result); +``` + +Finally, `error`, `warn`, and `info` emitters are enabled from each of the services and you can access them by doing the following example with `error`: + +```javascript +import { Hyphen } from '@hyphen/sdk'; + +const hyphen = new Hyphen({ apiKey: 'your_api_key'}); + +hyphen.on('error', (error) => { + console.log(error); +}); + +const result = await hyphen.netInfo.getIpInfo('8.8.8.8'); +console.log('Geo IP information:', result); +``` + +The rest of the examples for each service show you accessing the service instance directly. + +# Toggle - Feature Flag Service + +[Toggle](https://hyphen.ai/toggle) is our feature flag service that allows you to control the rollout of new features to your users. You can access your feature flags using the `Toggle` class. + +## Breaking Changes (v2.0) + +**โš ๏ธ The Toggle API has been simplified in v2.0. Please review the changes below:** + +### Removed Methods +- โŒ `setContext(context)` - Use property setter instead: `toggle.defaultContext = context` +- โŒ `setPublicApiKey(key)` - Use property setter instead: `toggle.publicApiKey = key` +- โŒ `getClient()` - No longer needed, use the Toggle instance directly + +### Removed Options +- โŒ `throwErrors` - Errors are now always emitted via events and default values are returned + +### Changed Behavior +- Hooks removed from convenience methods (`getBoolean`, `getString`, etc.) +- Hooks now only available via event system (`toggle.on('error', ...)`) +- All toggle methods now return default values on error instead of throwing + +### Migration Guide + +**Before (v1.x):** +```javascript +const toggle = new Toggle(options); +toggle.setContext(context); +const client = await toggle.getClient(); +``` + +**After (v2.0):** +```javascript +const toggle = new Toggle(options); +toggle.defaultContext = context; +// Use toggle directly - no getClient() needed +``` + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); + +console.log('Boolean toggle value:', result); // true +``` + +You can also set or update the context after initialization using the `defaultContext` property: + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', +}; + +const toggle = new Toggle(toggleOptions); + +// Set the default context +toggle.defaultContext = context; + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); + +console.log('Boolean toggle value:', result); // true +``` + +If you would like to override the context for a single request you can do it like this: + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, +}; + +const overrideContext: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false, { context: overrideContext }); + +console.log('Boolean toggle value:', result); // true +``` + +## Toggle Options + +| Option | Type | Description | +|----------------|----------------|----------------| +| *publicApiKey* | `string` | The public API key for your Hyphen project. You can find this in the Hyphen dashboard. Must start with "public_". | +| *applicationId* | `string` | The application ID for your Hyphen project. You can find this in the Hyphen dashboard. | +| *environment?* | `string` | The environment for your Hyphen project such as `production`. Defaults to `development` if not provided. | +| *defaultContext?* | `ToggleContext` | The default context to use when one is not passed to getter methods. Can be overridden per-request using the GetOptions parameter. | +| *horizonUrls?* | `string[]` | Array of Horizon endpoint URLs for load balancing and failover. If not provided, defaults to Hyphen's hosted service. | +| *defaultTargetKey?* | `string` | Default targeting key to use if one cannot be derived from context. If not provided, a random key will be generated. | +| *cache?* | `Cacheable` | Cacheable instance for caching fetch operations. See [@cacheable/cacheable](https://github.com/jaredwray/cacheable) for more information. | + +## Toggle API + +### Methods + +| Method | Parameters | Description | +|----------------|----------------|----------------| +| *get* | `key: string, defaultValue: T, options?: GetOptions` | Get the value of a toggle. This is a generic method that can be used to get any type from toggle. | +| *getBoolean* | `key: string, defaultValue: boolean, options?: GetOptions` | Get the value of a boolean toggle. | +| *getNumber* | `key: string, defaultValue: number, options?: GetOptions` | Get the value of a number toggle. | +| *getString* | `key: string, defaultValue: string, options?: GetOptions` | Get the value of a string toggle. | +| *getObject* | `key: string, defaultValue: T, options?: GetOptions` | Get the value of an object toggle. | +| *fetch* | `path: string, payload?: unknown, options?: FetchOptions` | Make a raw HTTP POST request to Horizon endpoints with automatic authentication and load balancing. | + +### Properties (Getters/Setters) + +| Property | Type | Description | +|----------------|----------------|----------------| +| *publicApiKey* | `string \| undefined` | Get or set the public API key. | +| *defaultContext* | `ToggleContext \| undefined` | Get or set the default context for toggle evaluations. | +| *applicationId* | `string \| undefined` | Get or set the application ID. | +| *environment* | `string \| undefined` | Get or set the environment. | +| *horizonUrls* | `string[]` | Get or set the Horizon endpoint URLs for load balancing. | +| *defaultTargetingKey* | `string` | Get or set the default targeting key. | +| *organizationId* | `string \| undefined` | Get the organization ID (read-only, extracted from public key). | +| *cache* | `Cacheable` | Get or set the Cacheable instance used for caching fetch operations. | + +### GetOptions + +The `GetOptions` type is used in toggle getter methods: + +```typescript +type GetOptions = { + context?: ToggleContext; // Override the default context for this request + cache?: boolean; // Whether to use caching (if configured) +}; +``` + +## Toggle Hooks + +Toggle extends the Hookified class, which provides a flexible hook system for intercepting and modifying behavior. You can register hooks using the `onHook()` method. + +**Note:** Hooks are currently only implemented on the base `get()` method and event emitters. + +### Available Hooks + +You can listen to errors using the `error` event: + +```javascript +import { Toggle } from '@hyphen/sdk'; + +const toggle = new Toggle({ + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', +}); + +toggle.on('error', (error) => { + console.error('Toggle error:', error); +}); + +const result = await toggle.getBoolean('my-feature', false); +``` + +### Custom Hooks (Advanced) + +Since Toggle extends Hookified, you can create custom hooks for advanced use cases: + +```javascript +import { Toggle } from '@hyphen/sdk'; + +const toggle = new Toggle({ + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', +}); + +// Register a custom hook +toggle.onHook('myCustomHook', (data) => { + console.log('Custom hook called:', data); +}); + +// Trigger the hook (in your own code) +await toggle.hook('myCustomHook', { someData: 'value' }); +``` + +## Toggle Error Handling + +The SDK provides a way to handle errors that occur during toggle requests. You can use the `.on` method to listen for errors globally. When an error occurs, the toggle methods will return the default value provided. + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, +}; + +const toggle = new Toggle(toggleOptions); +toggle.on('error', (error) => { + console.error('Error fetching toggle:', error); +}); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // Returns false (default) if error occurs +``` + +## Toggle Caching +The SDK supports caching of toggle values to improve performance and reduce the number of requests made to the server. You can enable caching by providing a `caching` option in the constructor. + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, + caching: { + ttl: 60000, // Cache for 60 seconds (in milliseconds) + }, +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +If you want to use a custom cache key generation function, you can provide a `generateCacheKeyFn` function in the `caching` option: + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, + caching: { + ttl: 60000, // Cache for 60 seconds (in milliseconds) + generateCacheKeyFn: (context) => { + return `toggle-${context?.targetingKey || 'default'}-hyphen-sdk-boolean`; + }, + }, +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +# Toggle Environment Variables + +You can also use environment variables to set the `publicApiKey` and `applicationId`. This is useful for keeping your API keys secure and not hardcoding them in your code. To do this just set your `.env` file with the following variables: + +```bash +HYPHEN_PUBLIC_API_KEY=your_public_api_key +HYPHEN_APPLICATION_ID=your_application_id +``` + +On initialization of the `Toggle` class, the SDK will automatically check for these environment variables and use them if they are set. If they are not set, you will need to provide them in the constructor. + +## Toggle Self-Hosted + +Toggle uses [Horizon](https://hyphen.ai/horizon) to fetch the feature flags. If you are using a self-hosted version of Hyphen you can use the `horizonUrls` (or `uris` for backward compatibility) option in the constructor to set the URL of your self-hosted version: + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, + horizonUrls: [ + 'https://your-self-hosted-horizon-url', + ], +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +If you want to use your self-hosted version of [Horizon](https://hyphen.ai/horizon) as a primary and fallback to our hosted version you can do it like this: + +```javascript +import { Toggle, ToggleContext } from '@hyphen/sdk'; + +const context: ToggleContext = { + targetingKey: 'user-123', + ipAddress: '203.0.113.42', + customAttributes: { + subscriptionLevel: 'premium', + region: 'us-east', + }, + user: { + id: 'user-123', + email: 'john.doe@example.com', + name: 'John Doe', + customAttributes: { + role: 'admin', + }, + }, +}; + +const toggleOptions = { + publicApiKey: 'your_public_api_key', + applicationId: 'your_application_id', + context: context, + horizonUrls: [ + 'https://your-self-hosted-horizon-url', + 'https://toggle.hyphen.cloud', + ], +}; + +const toggle = new Toggle(toggleOptions); + +const result = await toggle.getBoolean('hyphen-sdk-boolean', false); +console.log('Boolean toggle value:', result); // true +``` + +# ENV - Secret Management Service + +Hyphens secret management service known as [ENV](https://hyphen.ai/env) allows you to manage your environment variables in a secure way. The Hyphen Node.js SDK provides a simple way to access your environment variables. + +## Loading Environment Variables from Hyphen + +Use the authenticated `Env` service to fetch encrypted variables from Hyphen, +decrypt them in memory, and add them to `process.env`: + +```javascript +import { Hyphen } from '@hyphen/sdk'; + +const hyphen = new Hyphen({ + apiKey: 'your_api_key', + env: { + organizationId: 'your_organization_id', + projectId: 'your_project_id', + applicationId: 'your_application_id', + }, +}); + +const variables = await hyphen.env.load('production'); +``` + +Loading a named environment fetches both `default` and the named environment. +Named values take precedence, and remote values overwrite matching values in +`process.env`. The returned object contains the merged remote values. + +You can change those defaults per load: + +```javascript +await hyphen.env.load('production', { + includeDefault: false, + override: false, +}); +``` + +The service reads missing configuration from `HYPHEN_API_KEY`, +`HYPHEN_ORGANIZATION_ID`, `HYPHEN_PROJECT_ID`, and +`HYPHEN_APPLICATION_ID`, with `HYPHEN_APP_ID` supported as a compatibility +fallback. When running with Hyphen Deploy, `HYPHEN_PROJECT_NAME` and +`HYPHEN_APP_NAME` are used if their corresponding IDs are unavailable, and an +omitted load environment uses `HYPHEN_APP_ENVIRONMENT` before falling back to +`default`. Projects that do not use Hyphen's secure key store can provide their +key directly with `decryptionKey: { secretKeyId, secretKey }`. Decryption keys +and plaintext ENV data are never written to disk by this API. + +The `Env` class can also be used directly: + +```javascript +import { Env } from '@hyphen/sdk'; + +const remoteEnv = new Env({ + apiKey: 'your_api_key', + organizationId: 'your_organization_id', + projectId: 'your_project_id', + applicationId: 'your_application_id', +}); + +await remoteEnv.load('production'); +``` + +## Loading Local Environment Files + +To load your environment variables, you can use the `env()` function from the SDK. This function will automatically load your environment variables from the `.env` file and then override them with the environment based environment file if it exists (ex: `.env.development`). This is useful for managing different environments such as development, staging, and production. + +The following override path is: +``` +.env -> .env.local -> .env. -> .env..local +``` + +Here is an example of how to use the `env()` function: + +```javascript +import { env } from '@hyphen/sdk'; + +//load your default environment variables and envrionment variables +env(); +``` + +If your environment variables are not stored in the root of your project you can specify the path to your `.env` file: + +```javascript +import { env } from '@hyphen/sdk'; +//load your default environment variables and envrionment variables +env({ path: '/path/to/your/env/files/' }); +``` + +You can also specify the environment variables to load by passing an array of variable names: + +```javascript +import { env } from '@hyphen/sdk'; +//load your default environment variables and envrionment variables +env({ environment: 'development' }); +``` + +if you want to turn off the local environment variables you can do it like this: + +```javascript +import { env } from '@hyphen/sdk'; +//load your default environment variables and envrionment variables +env({ local: false }); +``` + +# Net Info - Geo Information Service + +The Hyphen Node.js SDK also provides a `NetInfo` class that allows you to fetch geo information about an IP address. This can be useful for debugging or logging purposes. You can read more about it: + +* [Website](https://hyphen.ai/net-info) +* [https://net.info](https://net.info) - webservice uri used by the SDK +* [Quick Start Guide](https://docs.hyphen.ai/docs/netinfo-quickstart) + +To use the `NetInfo` class, you can do the following: + +```javascript +import { NetInfo } from '@hyphen/sdk'; +const netInfo = new NetInfo({ + apiKey: 'your_api_key', +}); + +const ipInfo = await netInfo.getIpInfo('8.8.8.8'); +console.log('IP Info:', ipInfo); +``` + +If you want to fetch information for multiple IP addresses, you can do it like this: + +```javascript +import { NetInfo } from '@hyphen/sdk'; +const netInfo = new NetInfo({ + apiKey: 'your_api_key', +}); +const ips = ['8.8.8.8', '1.1.1.1']; +const ipInfos = await netInfo.getIpInfos(ips); +console.log('IP Infos:', ipInfos); +``` + +You can also set the API key using the `HYPHEN_API_KEY` environment variable. This is useful for keeping your API key secure and not hardcoding it in your code. + +# Execution Context - API Key Validation + +The `getExecutionContext` function validates an API key and returns information about the authenticated user, organization, and request context. This is useful for verifying API keys and getting user/organization details. + +## Basic Usage + +```javascript +import { getExecutionContext } from '@hyphen/sdk'; + +const context = await getExecutionContext('your-api-key'); + +console.log('User:', context.user?.name); +console.log('Organization:', context.member?.organization?.name); +console.log('IP Address:', context.ipAddress); +console.log('Location:', context.location?.city, context.location?.country); +``` + +## Options + +| Option | Type | Description | +|--------|------|-------------| +| `organizationId` | `string` | Optional organization ID to scope the context request | +| `baseUri` | `string` | Custom API base URI (defaults to `https://api.hyphen.ai`) | +| `cache` | `Cacheable` | Cacheable instance for caching requests | + +## With Organization ID + +If you need to get context for a specific organization: + +```javascript +import { getExecutionContext } from '@hyphen/sdk'; + +const context = await getExecutionContext('your-api-key', { + organizationId: 'org_123456789', +}); + +console.log('Organization:', context.organization?.name); +``` + +## With Caching + +To enable caching of execution context requests: + +```javascript +import { Cacheable } from 'cacheable'; +import { getExecutionContext } from '@hyphen/sdk'; + +const cache = new Cacheable({ ttl: 60000 }); // Cache for 60 seconds + +const context = await getExecutionContext('your-api-key', { + cache, +}); + +console.log('User:', context.user?.name); +``` + +## Return Type + +The function returns an `ExecutionContext` object with the following properties: + +| Property | Type | Description | +|----------|------|-------------| +| `request` | `object` | Request metadata (`id`, `causationId`, `correlationId`) | +| `user` | `object` | User info (`id`, `name`, `rules`, `type`) | +| `member` | `object` | Member info with nested `organization` | +| `organization` | `object` | Organization info (`id`, `name`) | +| `ipAddress` | `string` | The IP address of the request | +| `location` | `object` | Geo location (`country`, `region`, `city`, `lat`, `lng`, `postalCode`, `timezone`) | + +# Link - Short Code Service + +The Hyphen Node.js SDK also provides a `Link` class that allows you to create and manage short codes. This can be useful for generating short links for your application. + +* [Website](https://hyphen.ai/link) +* [Guides](https://docs.hyphen.ai/docs/create-short-link) +* [API Reference](https://docs.hyphen.ai/reference/post_api-organizations-organizationid-link-codes) + +## Creating a Short Code +To create a short code, you can use the `createShortCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const longUrl = 'https://hyphen.ai'; +const domain = 'test.h4n.link'; +const options = { + tags: ['sdk-test', 'unit-test'], +}; +const response = await link.createShortCode(longUrl, domain, options); +console.log('Short Code Response:', response); +``` + +## Updating a Short Code +To update a short code, you can use the `updateShortCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code you want to update +const longUrl = 'https://hyphen.ai/updated'; +const options = { + title: 'Updated Short Code', + tags: ['sdk-test', 'unit-test'], + long_url: longUrl, +}; + +const updateResponse = await link.updateShortCode(code, options); +console.log('Update Short Code Response:', updateResponse); +``` + +## Getting a Short Code +To get a short code, you can use the `getShortCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code you want to get +const response = await link.getShortCode(code); +console.log('Get Short Code Response:', response); +``` + +## Getting Short Codes +To get a list of short codes, you can use the `getShortCodes` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const title = 'My Short Codes'; // Optional title to filter short codes +const tags = ['sdk-test', 'unit-test']; // Optional tags to filter short codes +const response = await link.getShortCodes(title, tags); +console.log('Get Short Codes Response:', response); +``` + +## Getting all Organization Tags + +To get all tags for your organization, you can use the `getTags` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const response = await link.getTags(); +console.log('Get Tags Response:', response); +``` + +## Get Short Code Stats + +To get the stats for a short code, you can use the `getShortCodeStats` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code +const startDate = new Date('2023-01-01'); // Optional start date for the stats +const endDate = new Date('2023-12-31'); // Optional end date for the stats +const response = await link.getShortCodeStats(code, startDate, endDate); +console.log('Get Short Code Stats Response:', response); +``` + +## Deleting a Short Code +if you want to delete a short code you can do it like this: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code you want to delete +const response = await link.deleteShortCode(code); +console.log('Delete Short Code Response:', response); +``` + +## Creating a QR Code from a Short Code + +To create a QR code from a short code, you can use the `createQrCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code you want to create a QR code for +const response = await link.createQrCode(code); +console.log('Create QR Code Response:', response); +``` + +There are options that you can pass in to the `createQrCode` method to customize the QR code: + +```typescript +export type CreateQrCodeOptions = { + /** + * The title of the QR code. This is used for display purposes. + * @default undefined + */ + title?: string; + /** + * The background color of the QR code. This is a hex color code. + * @default '#ffffff' + */ + backgroundColor?: string; + /** + * The color of the QR code. This is a hex color code. + * @default '#000000' + */ + color?: string; + /** + * The size of the QR code. This can be 'small', 'medium', or 'large'. + * @default QrSize.MEDIUM + */ + size?: QrSize; + /** + * The logo to include in the QR code. This should be a base64 encoded string. + * @default undefined + */ + logo?: string; +}; +``` + +## Get a QR Code By Id + +To get a specific QR code by its ID, you can use the `getQrCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code +const qr = 'qr_1234567890'; // It is the ID of the QR code you want to retrieve +const response = await link.getQrCode(code, qr); +console.log('Get QR Code Response:', response); +``` + +## Get QR Codes for a Short Code + +To get all QR codes for a short code, you can use the `getQrCodes` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code +const response = await link.getQrCodes(code); +console.log('Get QR Codes Response:', response); +``` + +## Deleting a QR Code + +To delete a QR code, you can use the `deleteQrCode` method: + +```javascript +import { Link } from '@hyphen/sdk'; +const link = new Link({ + organizationId: 'your_organization_id', + apiKey: 'your_api_key', +}); +const code = 'code_1234567890'; // It is the code identifier for the short code +const qr = 'qr_1234567890'; // It is the ID of the QR code you want to delete +const response = await link.deleteQrCode(code, qr); +console.log('Delete QR Code Response:', response); +``` + +# Migrating to v3 + +v3 upgrades the underlying event system to [hookified v2](https://hookified.org). There are two breaking changes: + +## `throwOnEmptyListeners` now defaults to `true` + +In v2, emitting events (`error`) without any registered listeners was silently ignored. In v3, this will throw an error by default. If your code emits events, you must register listeners: + +```typescript +const hyphen = new Hyphen({ apiKey: 'your-key' }); + +// Register listeners before triggering operations that emit events +hyphen.on('error', (message) => { + console.error('Error:', message); +}); +``` + +If you want to restore the previous behavior where unhandled events are silently ignored, pass `throwOnEmptyListeners: false` in the options: + +```typescript +const hyphen = new Hyphen({ + apiKey: 'your-key', + throwOnEmptyListeners: false, +}); + +const toggle = new Toggle({ + publicApiKey: 'public_your-key', + throwOnEmptyListeners: false, +}); +``` + +## `throwErrors` option removed + +The `throwErrors` option has been removed from `BaseServiceOptions`, `HyphenOptions`, and all service classes. Error throwing is now handled natively by hookified v2. + +To get the previous `throwErrors: true` behavior, use `throwOnEmitError: true` instead: + +```typescript +// v2 (old) +const netInfo = new NetInfo({ throwErrors: true }); + +// v3 (new) +const netInfo = new NetInfo({ throwOnEmitError: true }); +``` + +The `throwErrors` getter/setter on service instances has also been removed as you can use `.throwOnEmitError` getter/setter now. + + +# Contributing + +We welcome contributions to the Hyphen Node.js SDK! If you have an idea for a new feature, bug fix, or improvement, please follow these steps: + +1. Fork the repository. +2. Create a new branch for your feature or bug fix. +3. Install `pnpm` by running `npm install -g pnpm` if you don't have it already. +3. Run the installation and tests to ensure everything is working correctly `pnpm i && pnpm test`. +4. Make your changes and commit them with a clear message. In the following format: + - `feat: ` + - `fix: ` + - `chore: updgrading xxx to version x.x.x` + +5. Push your changes to your forked repository. +6. Create a pull request to the main repository. +7. Describe your changes and why they are necessary. + +## Testing Your Changes + +To test your changes locally you will need to create an account on [Hyphen](https://hyphen.ai) and do the following: +1. Create a new project in the Hyphen dashboard. This will give you a project ID and an Public API key. +2. On the project please add the following toggles: + + +| Name | Type | Value | +|----------------|----------------|----------------| +| hyphen-sdk-boolean | boolean | true | +| hyphen-sdk-number | number | 42 | +| hyphen-sdk-string | string | "Hyphen!" | +| hyphen-sdk-json | json | `{ "id": "Hello World!"}` | + +Then, create a new application in the project. This will give you an application ID. + +Once you have created the project, added the toggles, and created your application you can run the tests then create an `.env` file in the `packages/nodejs-sdk` directory with the following content: + + +```bash +HYPHEN_PUBLIC_API_KEY=your_public_api_key +HYPHEN_API_KEY=your_api_key +HYPHEN_APPLICATION_ID=your_application_id +HYPHEN_LINK_DOMAIN=your_link_domain +HYPHEN_ORGANIZATION_ID=your_organization_id +``` + +A bit more information about the environment variables: + +| Variable | Example Value | Description | +|----------------|----------------|----------------| +| *HYPHEN_PUBLIC_API_KEY* | `public_api_key` | The public API key for your Hyphen project. You can find this in the Hyphen dashboard. | +| *HYPHEN_API_KEY* | `api_key` | The API key for your Hyphen project. You can find this in the Hyphen dashboard. | +| *HYPHEN_APPLICATION_ID* | `application_id` | The application ID for your Hyphen project. You can find this in the Hyphen dashboard. | +| *HYPHEN_LINK_DOMAIN* | `test.h4n.link` | The domain for the Link service. This is used for generating links. | +| *HYPHEN_ORGANIZATION_ID* | `org_668575c0e169cde974a5c76a` | | The organization ID for your Hyphen project. This is used for the Link service. | + +Then run the tests with the following command: + +```bash +pnpm i && pnpm test +``` + +# License and Copyright +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. +The copyright for this project is held by Hyphen, Inc. All rights reserved. diff --git a/packages/nodejs-sdk/biome.json b/packages/nodejs-sdk/biome.json new file mode 100644 index 0000000..e6415c4 --- /dev/null +++ b/packages/nodejs-sdk/biome.json @@ -0,0 +1,35 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "vcs": { + "enabled": false, + "clientKind": "git", + "useIgnoreFile": false + }, + "files": { + "ignoreUnknown": false, + "includes": ["src/**/*.ts", "test/**/*.ts"] + }, + "formatter": { + "enabled": true, + "indentStyle": "tab" + }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended" + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + }, + "assist": { + "enabled": true, + "actions": { + "source": { + "organizeImports": "on" + } + } + } +} diff --git a/packages/nodejs-sdk/package.json b/packages/nodejs-sdk/package.json new file mode 100644 index 0000000..37e38b2 --- /dev/null +++ b/packages/nodejs-sdk/package.json @@ -0,0 +1,71 @@ +{ + "name": "@hyphen/sdk", + "version": "4.0.1", + "description": "Hyphen SDK for Node.js", + "repository": { + "type": "git", + "url": "git+https://github.com/Hyphen/javascript-sdks.git", + "directory": "packages/nodejs-sdk" + }, + "homepage": "https://github.com/Hyphen/javascript-sdks/tree/main/packages/nodejs-sdk#readme", + "bugs": { + "url": "https://github.com/Hyphen/javascript-sdks/issues" + }, + "type": "module", + "main": "dist/index.cjs", + "module": "dist/index.mjs", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "types": "dist/index.d.mts", + "scripts": { + "lint": "biome check --write --error-on-warnings", + "test": "pnpm lint && vitest run --coverage", + "test:ci": "biome check --error-on-warnings && vitest run --coverage", + "build": "tsdown src/index.ts --format esm,cjs --dts", + "clean": "rimraf ./dist node_modules coverage", + "prepublishOnly": "pnpm build" + }, + "keywords": [ + "hyphen", + "sdk", + "nodejs", + "javascript", + "typescript" + ], + "author": "Team Hyphen ", + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.0.0" + }, + "devDependencies": { + "@biomejs/biome": "^2.5.15", + "@faker-js/faker": "^10.6.0", + "@types/node": "^24.19.0", + "@vitest/coverage-v8": "^5.0.3", + "rimraf": "^6.1.3", + "tsd": "^0.33.0", + "tsdown": "^0.23.0", + "typescript": "^7.0.2", + "vitest": "^5.0.3" + }, + "files": [ + "dist", + "LICENSE" + ], + "dependencies": { + "@cacheable/net": "^2.1.0", + "cacheable": "^2.5.0", + "hookified": "^3.0.4", + "pino": "^10.3.1" + } +} diff --git a/packages/nodejs-sdk/src/base-service.ts b/packages/nodejs-sdk/src/base-service.ts new file mode 100644 index 0000000..c6ecdb3 --- /dev/null +++ b/packages/nodejs-sdk/src/base-service.ts @@ -0,0 +1,210 @@ +// biome-ignore-all lint/suspicious/noExplicitAny: this is for http client and helpers +import { + CacheableNet, + type FetchRequestInit, + type NetFetchOptions, +} from "@cacheable/net"; +import { Cacheable } from "cacheable"; +import { Hookified, type HookifiedOptions } from "hookified"; +import pino from "pino"; + +// Define response type to match axios response structure +export interface HttpResponse { + data: T; + status: number; + statusText: string; + headers: any; + config: any; + request?: any; +} + +export type BaseServiceOptions = HookifiedOptions; + +export enum ErrorMessages { + API_KEY_REQUIRED = "API key is required. Please provide it via options or set the HYPHEN_API_KEY environment variable.", + PUBLIC_API_KEY_SHOULD_NOT_BE_USED = "The provided API key is a public API key. Please provide a valid non public API key for authentication.", +} + +export class BaseService extends Hookified { + private _log: pino.Logger = pino(); + private _cache = new Cacheable(); + private _net: CacheableNet; + + constructor(options?: BaseServiceOptions) { + super(options); + this._net = new CacheableNet({ + cache: this._cache, + }); + } + + public get log(): pino.Logger { + return this._log; + } + + public set log(value: pino.Logger) { + this._log = value; + } + + public get cache(): Cacheable { + return this._cache; + } + + public set cache(value: Cacheable) { + this._cache = value; + this._net.cache = value; + } + + public error(message: string, ...args: any[]): void { + this._log.error(message, ...args); + this.emit("error", message, ...args); + } + + public warn(message: string, ...args: any[]): void { + this._log.warn(message, ...args); + + this.emit("warn", message, ...args); + } + + public info(message: string, ...args: any[]): void { + this._log.info(message, ...args); + this.emit("info", message, ...args); + } + + public async get( + url: string, + config?: NetFetchOptions & { params?: any }, + ): Promise> { + // Handle query parameters if provided + let finalUrl = url; + if (config?.params) { + const params = new URLSearchParams(config.params); + finalUrl = `${url}?${params.toString()}`; + } + const { params: _, ...fetchConfig } = config || {}; + const response = await this._net.get(finalUrl, fetchConfig); + return { + data: response.data, + status: response.response.status, + statusText: response.response.statusText, + headers: response.response.headers, + config: config as any, + request: undefined, + }; + } + + public async post( + url: string, + data: any, + config?: FetchRequestInit, + ): Promise> { + const response = await this._net.post(url, data, config); + return { + data: response.data, + status: response.response.status, + statusText: response.response.statusText, + headers: response.response.headers, + config: config as any, + request: undefined, + }; + } + + public async put( + url: string, + data: any, + config?: FetchRequestInit, + ): Promise> { + const response = await this._net.put(url, data, config); + return { + data: response.data, + status: response.response.status, + statusText: response.response.statusText, + headers: response.response.headers, + config: config as any, + request: undefined, + }; + } + + public async delete( + url: string, + config?: FetchRequestInit & { data?: any }, + ): Promise> { + const headers = { ...(config?.headers as any) }; + /* v8 ignore next -- @preserve */ + if (headers) { + delete headers["content-type"]; + } + + // Handle data property from axios-style config + const { data: configData, ...restConfig } = config || {}; + let body: string | undefined; + if (configData) { + /* v8 ignore next -- @preserve */ + body = + typeof configData === "string" + ? configData + : JSON.stringify(configData); + // Add content-type back if we have data + /* v8 ignore next -- @preserve */ + if (!headers["content-type"] && !headers["Content-Type"]) { + headers["content-type"] = "application/json"; + } + } + + // Use fetch directly for DELETE to handle 204 status codes properly + const response = await this._net.fetch(url, { + ...restConfig, + headers, + body, + method: "DELETE", + }); + + let data: T | undefined; + if (response.status !== 204) { + const text = await response.text(); + /* v8 ignore next -- @preserve */ + try { + data = text ? JSON.parse(text) : undefined; + } catch { + data = text as any; + } + } + + return { + data: data as T, + status: response.status, + statusText: response.statusText, + headers: response.headers, + config: config as any, + request: undefined, + }; + } + + public async patch( + url: string, + data: any, + config?: FetchRequestInit, + ): Promise> { + const response = await this._net.patch(url, data, config); + return { + data: response.data, + status: response.response.status, + statusText: response.response.statusText, + headers: response.response.headers, + config: config as any, + request: undefined, + }; + } + + public createHeaders(apiKey?: string): Record { + const headers: Record = { + "content-type": "application/json", + accept: "application/json", + }; + /* v8 ignore next -- @preserve */ + if (apiKey) { + headers["x-api-key"] = apiKey; + } + + return headers; + } +} diff --git a/packages/nodejs-sdk/src/env-service.ts b/packages/nodejs-sdk/src/env-service.ts new file mode 100644 index 0000000..523545d --- /dev/null +++ b/packages/nodejs-sdk/src/env-service.ts @@ -0,0 +1,298 @@ +import { Buffer } from "node:buffer"; +import { createDecipheriv, createHash } from "node:crypto"; +import process from "node:process"; +import { parseEnv, TextDecoder } from "node:util"; +import { BaseService, type BaseServiceOptions } from "./base-service.js"; + +const defaultEnvHorizonUri = "https://toggle.hyphen.cloud"; +const defaultEnvKeyStoreUri = "https://vinz.hyphen.ai"; + +export type EnvKey = { + secretKeyId: number; + secretKey: string; +}; + +export type EnvLoadOptions = { + includeDefault?: boolean; + override?: boolean; +}; + +export type EnvServiceOptions = { + apiKey?: string; + organizationId?: string; + projectId?: string; + applicationId?: string; + decryptionKey?: EnvKey; + horizonUri?: string; + keyStoreUri?: string; +} & BaseServiceOptions; + +const environmentNamePattern = /^[a-z0-9_-]+$/; +const base64UrlPattern = /^[A-Za-z0-9_-]+={0,2}$/; +const utf8Decoder = new TextDecoder("utf-8", { fatal: true }); + +class SafeEnvError extends Error {} + +export class Env extends BaseService { + private _apiKey: string | undefined; + private readonly _organizationId: string | undefined; + private readonly _projectId: string | undefined; + private readonly _applicationId: string | undefined; + private readonly _decryptionKey: EnvKey | undefined; + private readonly _horizonUri: string; + private readonly _keyStoreUri: string; + + constructor(options?: EnvServiceOptions) { + super(options); + this._organizationId = + options?.organizationId ?? process.env.HYPHEN_ORGANIZATION_ID; + this._projectId = + options?.projectId ?? + process.env.HYPHEN_PROJECT_ID ?? + process.env.HYPHEN_PROJECT_NAME; + this._applicationId = + options?.applicationId ?? + process.env.HYPHEN_APPLICATION_ID ?? + process.env.HYPHEN_APP_ID ?? + process.env.HYPHEN_APP_NAME; + this._decryptionKey = options?.decryptionKey; + this._horizonUri = stripTrailingSlash( + options?.horizonUri ?? defaultEnvHorizonUri, + ); + this._keyStoreUri = stripTrailingSlash( + options?.keyStoreUri ?? defaultEnvKeyStoreUri, + ); + this.apiKey = options?.apiKey ?? process.env.HYPHEN_API_KEY; + } + + public get apiKey(): string | undefined { + return this._apiKey; + } + + public set apiKey(value: string | undefined) { + this._apiKey = value; + } + + public async load( + environment?: string, + options?: EnvLoadOptions, + ): Promise> { + const environmentName = normalizeEnvironmentName( + environment ?? process.env.HYPHEN_APP_ENVIRONMENT ?? "default", + ); + this.validateConfiguration(); + + const key = await this.getDecryptionKey(); + const includeDefault = options?.includeDefault ?? true; + const environmentNames = + environmentName !== "default" && includeDefault + ? ["default", environmentName] + : [environmentName]; + const layers = await Promise.all( + environmentNames.map((name) => this.loadEnvironment(name, key)), + ); + const variables = Object.assign({}, ...layers) as Record; + const entries = Object.entries(variables); + if ( + entries.some( + ([name, value]) => name.includes("\0") || value.includes("\0"), + ) + ) { + throw new Error( + "Hyphen ENV contains a variable that cannot be added to process.env.", + ); + } + + for (const [name, value] of entries) { + if ((options?.override ?? true) || process.env[name] === undefined) { + process.env[name] = value; + } + } + + return variables; + } + + private validateConfiguration(): void { + if (!this._apiKey) { + throw new Error("An API key is required to load Hyphen ENV data."); + } + if (this._apiKey.startsWith("public_")) { + throw new Error("A public API key cannot load Hyphen ENV data."); + } + if (!this._organizationId) { + throw new Error( + "An organization ID is required to load Hyphen ENV data.", + ); + } + if (!this._applicationId) { + throw new Error("An application ID is required to load Hyphen ENV data."); + } + if (!this._decryptionKey && !this._projectId) { + throw new Error( + "A project ID or decryption key is required to load Hyphen ENV data.", + ); + } + } + + private async getDecryptionKey(): Promise { + if (this._decryptionKey) { + return validateKey(this._decryptionKey); + } + + try { + const url = `${this._keyStoreUri}/${encodeURIComponent(this._organizationId as string)}/${encodeURIComponent(this._projectId as string)}/key`; + const response = await this.get(url, { + caching: false, + headers: this.createHeaders(this._apiKey), + }); + if (response.status !== 200) { + throw new SafeEnvError(`HTTP ${response.status}`); + } + return readKeyResponse(response.data); + } catch (error) { + throw contextualError("Failed to fetch the Hyphen ENV key", error); + } + } + + private async loadEnvironment( + environment: string, + key: EnvKey, + ): Promise> { + let encryptedData: string; + try { + const url = `${this._horizonUri}/api/organizations/${encodeURIComponent(this._organizationId as string)}/apps/${encodeURIComponent(this._applicationId as string)}/dot-env/`; + const params: Record = { + secretKeyId: key.secretKeyId, + }; + if (environment !== "default") { + params.environmentId = environment; + } + + const response = await this.get(url, { + caching: false, + headers: this.createHeaders(this._apiKey), + params, + }); + if (response.status !== 200) { + throw new SafeEnvError(`HTTP ${response.status}`); + } + encryptedData = readEnvironmentResponse(response.data); + } catch (error) { + throw contextualError( + `Failed to fetch Hyphen ENV "${environment}"`, + error, + ); + } + + try { + return parseEnv(decrypt(encryptedData, key.secretKey)); + } catch { + throw new Error( + `Failed to decrypt or parse Hyphen ENV "${environment}".`, + ); + } + } +} + +function normalizeEnvironmentName(environment: string): string { + const name = environment === "" ? "default" : environment.toLowerCase(); + if (!environmentNamePattern.test(name)) { + throw new Error( + "Environment must contain only lowercase letters, numbers, hyphens, and underscores.", + ); + } + return name; +} + +function validateKey(key: { + secretKeyId: unknown; + secretKey: unknown; +}): EnvKey { + if ( + typeof key.secretKeyId !== "number" || + !Number.isSafeInteger(key.secretKeyId) || + key.secretKeyId < 1 || + typeof key.secretKey !== "string" || + key.secretKey.length === 0 + ) { + throw new SafeEnvError("The Hyphen ENV key is invalid."); + } + return { + secretKeyId: key.secretKeyId, + secretKey: key.secretKey, + }; +} + +function readKeyResponse(value: unknown): EnvKey { + if (!isRecord(value) || !isRecord(value.key)) { + throw new SafeEnvError("The key-store response is invalid."); + } + return validateKey({ + secretKeyId: value.key.secret_key_id, + secretKey: value.key.secret_key, + }); +} + +function readEnvironmentResponse(value: unknown): string { + if (!isRecord(value) || typeof value.data !== "string") { + throw new SafeEnvError("The response did not contain encrypted ENV data."); + } + return value.data; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function decrypt(encryptedData: string, secretKey: string): string { + const ciphertext = decodeBase64Url(encryptedData); + if (ciphertext.length < 16) { + throw new Error( + "Encrypted ENV data is shorter than its initialization vector.", + ); + } + + const keyHash = createHash("sha256").update(secretKey).digest("hex"); + const key = Buffer.from(keyHash.slice(0, 32), "utf8"); + const decipher = createDecipheriv( + "aes-256-cfb", + key, + ciphertext.subarray(0, 16), + ); + const plaintext = Buffer.concat([ + decipher.update(ciphertext.subarray(16)), + decipher.final(), + ]); + return utf8Decoder.decode(plaintext); +} + +function decodeBase64Url(value: string): Buffer { + if (!base64UrlPattern.test(value) || value.length % 4 === 1) { + throw new Error("Encrypted ENV data is not valid base64url."); + } + + const unpadded = value.replace(/=+$/, ""); + const padding = value.length - unpadded.length; + const requiredPadding = (4 - (unpadded.length % 4)) % 4; + if ( + padding !== requiredPadding || + Buffer.from(unpadded, "base64url").toString("base64url") !== unpadded + ) { + throw new Error("Encrypted ENV data is not valid base64url."); + } + return Buffer.from(unpadded, "base64url"); +} + +function stripTrailingSlash(uri: string): string { + let end = uri.length; + while (end > 0 && uri[end - 1] === "/") { + end -= 1; + } + return uri.slice(0, end); +} + +function contextualError(message: string, error: unknown): Error { + const detail = + error instanceof SafeEnvError ? error.message : "Request failed."; + return new Error(`${message}: ${detail}`); +} diff --git a/packages/nodejs-sdk/src/env.ts b/packages/nodejs-sdk/src/env.ts new file mode 100644 index 0000000..42a4ecd --- /dev/null +++ b/packages/nodejs-sdk/src/env.ts @@ -0,0 +1,74 @@ +import fs from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { parseEnv } from "node:util"; + +export type EnvOptions = { + path?: string; + environment?: string; + local?: boolean; +}; + +function loadEnvFile(filePath: string, override: boolean): void { + try { + const content = fs.readFileSync(filePath, "utf8"); + const parsed = parseEnv(content); + for (const [key, value] of Object.entries(parsed)) { + if (override || process.env[key] === undefined) { + process.env[key] = value; + } + } + } catch { + // File doesn't exist or can't be read, skip silently + } +} + +/** + * @description Helper function to load your environment variables based on your default .env file + * and the current environment. + * @param {EnvOptions} [options] - Options to customize the loading of environment variables. + * @returns {void} + * @example + * import { env } from '@hyphen/sdk'; + * env(); + */ +export function env(options?: EnvOptions): void { + const local = options?.local ?? true; + + // Set the current working directory if provided + const currentWorkingDirectory = options?.path ?? process.cwd(); + + // Load the default .env file + const envPath = path.resolve(currentWorkingDirectory, ".env"); + loadEnvFile(envPath, false); + + // Load the .env.local file if it exists + if (local) { + const localEnvPath = path.resolve(currentWorkingDirectory, ".env.local"); + loadEnvFile(localEnvPath, true); + } + + // Load the environment specific .env file + const environment = options?.environment ?? process.env.NODE_ENV; + + /* v8 ignore next -- @preserve */ + if (environment) { + const envSpecificPath = path.resolve( + currentWorkingDirectory, + `.env.${environment}`, + ); + loadEnvFile(envSpecificPath, true); + + // Load the environment specific .env.local file if it exists + if (local) { + const envLocalPath = path.resolve( + currentWorkingDirectory, + `.env.${environment}.local`, + ); + loadEnvFile(envLocalPath, true); + } + } +} + +export const loadEnv: (options?: EnvOptions) => void = env; // Alias for backward compatibility +export type LoadEnvOptions = EnvOptions; // Alias for backward compatibility diff --git a/packages/nodejs-sdk/src/execution-context.ts b/packages/nodejs-sdk/src/execution-context.ts new file mode 100644 index 0000000..5faa61b --- /dev/null +++ b/packages/nodejs-sdk/src/execution-context.ts @@ -0,0 +1,124 @@ +import { CacheableNet } from "@cacheable/net"; +import type { Cacheable } from "cacheable"; + +export type ExecutionContextOptions = { + /** + * The organization ID for the Hyphen API. + */ + organizationId?: string; + /** + * The base URI for the Hyphen API. + * @default "https://api.hyphen.ai" + */ + baseUri?: string; + /** + * The Cacheable instance to use for caching requests. + */ + cache?: Cacheable; +}; + +export type ExecutionContextRequest = { + id?: string; + causationId?: string; + correlationId?: string; +}; + +export type ExecutionContextUser = { + id?: string; + name?: string; + rules?: Record[]; + type?: string; +}; + +export type ExecutionContextMember = { + id?: string; + name?: string; + organization?: { + id?: string; + name?: string; + }; + rules?: Record[]; +}; + +export type ExecutionContextOrganization = { + id?: string; + name?: string; +}; + +export type ExecutionContextLocation = { + country?: string; + region?: string; + city?: string; + lat?: number; + lng?: number; + postalCode?: string; + timezone?: string; +}; + +export type ExecutionContext = { + request?: ExecutionContextRequest; + user?: ExecutionContextUser; + member?: ExecutionContextMember; + organization?: ExecutionContextOrganization; + ipAddress?: string; + location?: ExecutionContextLocation; +}; + +/** + * Get the execution context for the provided API key. + * This validates the API key and returns information about the organization, user, and request context. + * + * @param apiKey - The API key for the Hyphen API. + * @param options - Additional options for the request. + * @returns The execution context. + * @throws Error if the API key is not provided or if the request fails. + * + * @example + * ```typescript + * import { getExecutionContext } from '@hyphen/sdk'; + * + * const context = await getExecutionContext('your-api-key', { + * organizationId: 'optional-org-id', + * }); + * + * console.log(context.organization?.name); + * ``` + */ +export async function getExecutionContext( + apiKey: string, + options?: ExecutionContextOptions, +): Promise { + if (!apiKey) { + throw new Error("API key is required"); + } + + const baseUri = options?.baseUri ?? "https://api.hyphen.ai"; + let url = `${baseUri}/api/execution-context`; + + if (options?.organizationId) { + url += `?organizationId=${encodeURIComponent(options.organizationId)}`; + } + + const net = options?.cache + ? new CacheableNet({ cache: options.cache }) + : new CacheableNet(); + + const caching = options?.cache !== undefined; + + const response = await net.get(url, { + headers: { + "x-api-key": apiKey, + "content-type": "application/json", + accept: "application/json", + }, + caching, + }); + + if (response.response.status !== 200) { + throw new Error( + `Failed to get execution context: ${response.response.statusText}`, + ); + } + + return response.data; +} diff --git a/packages/nodejs-sdk/src/hyphen.ts b/packages/nodejs-sdk/src/hyphen.ts new file mode 100644 index 0000000..39732c3 --- /dev/null +++ b/packages/nodejs-sdk/src/hyphen.ts @@ -0,0 +1,208 @@ +import { Hookified, type HookifiedOptions } from "hookified"; +import { Env, type EnvServiceOptions } from "./env-service.js"; +import { Link, type LinkOptions } from "./link.js"; +import { NetInfo, type NetInfoOptions } from "./net-info.js"; +import { Toggle, type ToggleOptions } from "./toggle.js"; + +export type HyphenOptions = { + /** + * The public API key to use for the Hyphen service. + * This is used for public endpoints that do not require authentication. + */ + publicApiKey?: string; + /** + * The API key to use for the Hyphen service. + * This is used for authenticated endpoints that require an API key. + */ + apiKey?: string; + /** + * Options for the Toggle service. + * Excludes `publicApiKey` as it's provided at the top level. + * @see ToggleOptions + * @default {Toggle} + */ + toggle?: Omit; + /** + * Options for the NetInfo service. + * Excludes `apiKey` as it's provided at the top level. + * @see NetInfoOptions + * @default {NetInfo} + */ + netInfo?: Omit; + /** + * Options for the Link service. + * Excludes `apiKey` as it's provided at the top level. + * @see LinkOptions + * @default {Link} + */ + link?: Omit; + /** + * Options for the ENV service. + * Excludes `apiKey` as it's provided at the top level. + * @see EnvServiceOptions + * @default {Env} + */ + env?: Omit; +} & HookifiedOptions; + +export class Hyphen extends Hookified { + private readonly _env: Env; + private readonly _netInfo: NetInfo; + private readonly _toggle: Toggle; + private readonly _link: Link; + + private _publicApiKey?: string; + private _apiKey?: string; + + constructor(options?: HyphenOptions) { + super(options); + + const toggleOptions: ToggleOptions = options?.toggle ?? {}; + const netInfoOptions: NetInfoOptions = options?.netInfo ?? {}; + const linkOptions: LinkOptions = options?.link ?? {}; + const envOptions: EnvServiceOptions = { ...options?.env }; + + if (options?.publicApiKey) { + this._publicApiKey = options.publicApiKey; + toggleOptions.publicApiKey = options.publicApiKey; + } + + if (options?.apiKey) { + this._apiKey = options.apiKey; + netInfoOptions.apiKey = options.apiKey; + linkOptions.apiKey = options.apiKey; + envOptions.apiKey = options.apiKey; + } + + this._env = new Env(envOptions); + + this._env.on("error", (message, ...args) => + this.emit("error", message, ...args), + ); + + this._env.on("info", (message, ...args) => + this.emit("info", message, ...args), + ); + + this._env.on("warn", (message, ...args) => + this.emit("warn", message, ...args), + ); + + this._netInfo = new NetInfo(netInfoOptions); + // Set error, info, warn emitters for netInfo + + this._netInfo.on("error", (message, ...args) => + this.emit("error", message, ...args), + ); + + this._netInfo.on("info", (message, ...args) => + this.emit("info", message, ...args), + ); + + this._netInfo.on("warn", (message, ...args) => + this.emit("warn", message, ...args), + ); + + this._toggle = new Toggle(toggleOptions); + // Set error, info, warn emitters for toggle + + this._toggle.on("error", (message, ...args) => + this.emit("error", message, ...args), + ); + + this._toggle.on("info", (message, ...args) => + this.emit("info", message, ...args), + ); + + this._toggle.on("warn", (message, ...args) => + this.emit("warn", message, ...args), + ); + + this._link = new Link(linkOptions); + // Set error, info, warn emitters for link + + this._link.on("error", (message, ...args) => + this.emit("error", message, ...args), + ); + + this._link.on("info", (message, ...args) => + this.emit("info", message, ...args), + ); + + this._link.on("warn", (message, ...args) => + this.emit("warn", message, ...args), + ); + } + + /** + * Get the ENV service instance. + * @returns {Env} The ENV service instance. + */ + public get env(): Env { + return this._env; + } + + /** + * Get the NetInfo service instance. + * @returns {NetInfo} The NetInfo service instance. + */ + public get netInfo(): NetInfo { + return this._netInfo; + } + + /** + * Get the Toggle service instance. + * @returns {Toggle} The Toggle service instance. + */ + public get toggle(): Toggle { + return this._toggle; + } + + /** + * Get the Link service instance. + * @returns {Link} The Link service instance. + */ + public get link(): Link { + return this._link; + } + + /** + * Get the public API key for the Hyphen service. + * This is used for public endpoints that do not require authentication. + * @returns {string | undefined} The public API key. + */ + public get publicApiKey(): string | undefined { + return this._publicApiKey; + } + + /** + * Set the public API key for the Hyphen service. If set, this will also update the underlying services. + * This is used for public endpoints that do not require authentication such as the Toggle service. + * @param {string | undefined} value - The public API key to set. + */ + public set publicApiKey(value: string | undefined) { + this._publicApiKey = value; + this._toggle.publicApiKey = value; + } + + /** + * Get the API key for the Hyphen service. + * This is used for authenticated endpoints that require an API key such as the ENV, NetInfo, and Link services. + * @returns {string | undefined} The API key. + */ + public get apiKey(): string | undefined { + return this._apiKey; + } + + /** + * Set the API key for the Hyphen service. If set, this will also update the underlying services. + * This is used for authenticated endpoints that require an API key such as the ENV, NetInfo, and Link services. + * @param {string | undefined} value - The API key to set. + */ + public set apiKey(value: string | undefined) { + this._apiKey = value; + this._env.apiKey = value; + this._netInfo.apiKey = value; + this._link.apiKey = value; + } +} diff --git a/packages/nodejs-sdk/src/index.ts b/packages/nodejs-sdk/src/index.ts new file mode 100644 index 0000000..e919847 --- /dev/null +++ b/packages/nodejs-sdk/src/index.ts @@ -0,0 +1,26 @@ +export { type EnvOptions, env, type LoadEnvOptions, loadEnv } from "./env.js"; +export { + Env, + type EnvKey, + type EnvLoadOptions, + type EnvServiceOptions, +} from "./env-service.js"; +export { + type ExecutionContext, + type ExecutionContextLocation, + type ExecutionContextMember, + type ExecutionContextOptions, + type ExecutionContextOrganization, + type ExecutionContextRequest, + type ExecutionContextUser, + getExecutionContext, +} from "./execution-context.js"; +export { Hyphen, type HyphenOptions } from "./hyphen.js"; +export { + Toggle, + type ToggleContext, + type ToggleEvaluation, + type ToggleEvents, + type ToggleOptions, + type ToggleUser, +} from "./toggle.js"; diff --git a/packages/nodejs-sdk/src/link-stats-type.ts b/packages/nodejs-sdk/src/link-stats-type.ts new file mode 100644 index 0000000..552630c --- /dev/null +++ b/packages/nodejs-sdk/src/link-stats-type.ts @@ -0,0 +1,40 @@ +export type ClickByDay = { + date: string; + total: number; + unique: number; +}; + +export type Clicks = { + total: number; + unique: number; + byDay: ClickByDay[]; +}; + +export type Referral = { + url: string; + total: number; +}; + +export type Browser = { + name: string; + total: number; +}; + +export type Device = { + name: string; + total: number; +}; + +export type Location = { + country: string; + total: number; + unique: number; +}; + +export type GetCodeStatsResponse = { + clicks: Clicks; + referrals: Referral[]; + browsers: Browser[]; + devices: Device[]; + locations: Location[]; +}; diff --git a/packages/nodejs-sdk/src/link.ts b/packages/nodejs-sdk/src/link.ts new file mode 100644 index 0000000..5fd97fd --- /dev/null +++ b/packages/nodejs-sdk/src/link.ts @@ -0,0 +1,651 @@ +import { Buffer } from "node:buffer"; +import process from "node:process"; +import { BaseService, type BaseServiceOptions } from "./base-service.js"; +import { env } from "./env.js"; +import type { GetCodeStatsResponse } from "./link-stats-type.js"; + +env(); + +export const defaultLinkUris: string[] = [ + "https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/", +]; + +export type CreateShortCodeOptions = { + /** + * The short code used for this link. If not provided, a random code will be generated. + * @default undefined + */ + code?: string; + /** + * The title of the link. This is used for display purposes. + * @default undefined + */ + title?: string; + /** + * The tags associated with the link. This is used for categorization purposes. + * @default undefined + */ + tags?: string[]; +}; + +export type CreateShortCodeResponse = { + id: string; + code: string; + long_url: string; + domain: string; + createdAt: string; + title?: string; + tags?: string[]; + organizationId: { + id: string; + name: string; + }; +}; + +export type UpdateShortCodeResponse = CreateShortCodeResponse; + +export type UpdateShortCodeOptions = { + /** + * The long URL that the short code will redirect to. + * @default undefined + */ + long_url?: string; + /** + * The title of the link. This is used for display purposes. + * @default undefined + */ + title?: string; + /** + * The tags associated with the link. This is used for categorization purposes. + * @default undefined + */ + tags?: string[]; +}; + +export type GetShortCodesResponse = { + total: number; + pageNum: number; + pageSize: number; + data: GetShortCodeResponse[]; +}; + +export type GetShortCodeResponse = CreateShortCodeResponse; + +export enum QrSize { + SMALL = "small", + MEDIUM = "medium", + LARGE = "large", +} + +export type CreateQrCodeOptions = { + /** + * The title of the QR code. This is used for display purposes. + * @default undefined + */ + title?: string; + /** + * The background color of the QR code. This is a hex color code. + * @default '#ffffff' + */ + backgroundColor?: string; + /** + * The color of the QR code. This is a hex color code. + * @default '#000000' + */ + color?: string; + /** + * The size of the QR code. This can be 'small', 'medium', or 'large'. + * @default QrSize.MEDIUM + */ + size?: QrSize; + /** + * The logo to include in the QR code. This should be a base64 encoded string. + * @default undefined + */ + logo?: string; +}; + +export type CreateQrCodeResponse = { + id: string; + title?: string; + qrCode: string; + qrCodeBytes: Uint8Array; + qrLink: string; +}; + +export type GetQrCodesResponse = { + total: number; + pageNum: number; + pageSize: number; + data: CreateQrCodeResponse[]; +}; + +export type LinkOptions = { + /** + * The URIs to access the link service. + * @default ["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"] + */ + uris?: string[]; + /** + * The organization ID to use for the link service. + * @requires organizationId + */ + organizationId?: string; + + /** + * The API key to use for the link service. This should be provided as the service requires authentication. + */ + apiKey?: string; +} & BaseServiceOptions; + +export class Link extends BaseService { + private _uris: string[] = defaultLinkUris; + private _organizationId?: string; + private _apiKey?: string; + + constructor(options?: LinkOptions) { + super(options); + this._uris = options?.uris ?? defaultLinkUris; + this._organizationId = options?.organizationId; + if (options?.apiKey) { + this.setApiKey(options.apiKey); + } + + if (!this._apiKey && process.env.HYPHEN_API_KEY) { + this.setApiKey(process.env.HYPHEN_API_KEY); + } + + if (!this._organizationId && process.env.HYPHEN_ORGANIZATION_ID) { + this._organizationId = process.env.HYPHEN_ORGANIZATION_ID; + } + } + + /** + * Get the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`. + * @returns {string[]} The URIs for the link service. + */ + public get uris(): string[] { + return this._uris; + } + + /** + * Set the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`. + * @param {string[]} uris - The URIs to set. + */ + public set uris(uris: string[]) { + this._uris = uris; + } + + /** + * Get the organization ID for the link service. This is required to access the link service. + * @returns {string | undefined} The organization ID. + */ + public get organizationId(): string | undefined { + return this._organizationId; + } + + /** + * Set the organization ID for the link service. This is required to access the link service. + * @param {string | undefined} organizationId - The organization ID to set. + */ + public set organizationId(organizationId: string | undefined) { + this._organizationId = organizationId; + } + + /** + * Get the API key for the link service. This is required to access the link service. + * @returns {string | undefined} The API key. + */ + public get apiKey(): string | undefined { + return this._apiKey; + } + + /** + * Set the API key for the link service. This is required to access the link service. + * @param {string | undefined} apiKey - The API key to set. + */ + public set apiKey(apiKey: string | undefined) { + this.setApiKey(apiKey); + } + + /** + * Set the API key for the link service. If the API key starts with 'public_', an error is thrown. + * This is to ensure that the API key is not a public key, which should not be used for authenticated requests. + * @param {string} apiKey + */ + public setApiKey(apiKey: string | undefined): void { + if (apiKey?.startsWith("public_")) { + throw new Error('API key cannot start with "public_"'); + } + + /* v8 ignore next -- @preserve */ + if (apiKey) { + this._apiKey = apiKey; + } + } + + /** + * Get the URI for a specific organization and code. This is used internally to construct the URI for the link service. + * @param {string} organizationId The ID of the organization. + * @param {string} code The code to include in the URI. + * @returns {string} The constructed URI. + */ + public getUri( + organizationId: string, + prefix1?: string, + prefix2?: string, + prefix3?: string, + ): string { + /* v8 ignore next -- @preserve */ + if (!organizationId) { + throw new Error("Organization ID is required to get the URI."); + } + + let url = this._uris[0].replace("{organizationId}", organizationId); + if (prefix1) { + url = url.endsWith("/") ? `${url}${prefix1}/` : `${url}/${prefix1}`; + } + + /* v8 ignore next -- @preserve */ + if (prefix2) { + url = url.endsWith("/") ? `${url}${prefix2}/` : `${url}/${prefix2}`; + } + + /* v8 ignore next -- @preserve */ + if (prefix3) { + url = url.endsWith("/") ? `${url}${prefix3}/` : `${url}/${prefix3}`; + } + + if (url.endsWith("/")) { + url = url.slice(0, -1); // Remove trailing slash if present + } + + return url; + } + + /** + * Create a short code for a long URL. + * @param {string} longUrl The long URL to shorten. + * @param {string} domain The domain to use for the short code. + * @param {CreateShortCodeOptions} options Optional parameters for creating the short code. + * @returns {Promise} A promise that resolves to the created short code details. + */ + public async createShortCode( + longUrl: string, + domain: string, + options?: CreateShortCodeOptions, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to create a short code."); + } + + const url = this.getUri(this._organizationId); + const body = { + long_url: longUrl, + domain, + code: options?.code, + title: options?.title, + tags: options?.tags, + }; + + const headers = this.createHeaders(this._apiKey); + + const response = await this.post(url, body, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 201) { + return response.data as CreateShortCodeResponse; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to create short code: ${response.statusText}`); + } + + /** + * Get a short code by its code. + * @param {string} code The short code to retrieve. Example: 'code_686bed403c3991bd676bba4d' + * @returns {Promise} A promise that resolves to the short code details. + */ + public async getShortCode(code: string): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get a short code."); + } + + const url = this.getUri(this._organizationId, code); + const headers = this.createHeaders(this._apiKey); + + const response = await this.get(url, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + return response.data as GetShortCodeResponse; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get short code: ${response.statusText}`); + } + + /** + * Get all short codes for the organization. + * @param {string} titleSearch Optional search term to filter short codes by title. + * @param {string[]} tags Optional tags to filter short codes. + * @param {number} pageNumber The page number to retrieve. Default is 1. + * @param {number} pageSize The number of short codes per page. Default is 100. + * @returns {Promise} A promise that resolves to the list of short codes. + */ + public async getShortCodes( + titleSearch: string, + tags?: string[], + pageNumber = 1, + pageSize = 100, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get short codes."); + } + + const url = this.getUri(this._organizationId); + const headers = this.createHeaders(this._apiKey); + + const parameters: Record = {}; + if (titleSearch) { + parameters.title = titleSearch; + } + + if (tags && tags.length > 0) { + parameters.tags = tags.join(","); + } + + parameters.pageNum = pageNumber.toString(); + parameters.pageSize = pageSize.toString(); + + const response = await this.get(url, { headers, params: parameters }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + return response.data as GetShortCodesResponse; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get short codes: ${response.statusText}`); + } + + /** + * Get all tags associated with the organization's short codes. + * @returns {Promise} A promise that resolves to an array of tags. + */ + public async getTags(): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get tags."); + } + + const url = this.getUri(this._organizationId, "tags"); + const headers = this.createHeaders(this._apiKey); + + const response = await this.get(url, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + return response.data as string[]; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get tags: ${response.statusText}`); + } + + /** + * Get statistics for a specific short code. + * @param code The short code to retrieve statistics for. + * @returns {Promise} A promise that resolves to the code statistics. + */ + public async getCodeStats( + code: string, + startDate: Date, + endDate: Date, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get code stats."); + } + + const url = this.getUri(this._organizationId, code, "stats"); + const headers = this.createHeaders(this._apiKey); + + const parameters: Record = { + startDate: startDate.toISOString(), + endDate: endDate.toISOString(), + }; + + const response = await this.get(url, { headers, params: parameters }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + return response.data as GetCodeStatsResponse; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get code stats: ${response.statusText}`); + } + + /** + * Update a short code. + * @param {string} code The short code to update. Example: 'code_686bed403c3991bd676bba4d' + * @param {UpdateShortCodeOptions} options The options to update the short code with. + * @returns {Promise} A promise that resolves to the updated short code details. + */ + public async updateShortCode( + code: string, + options: UpdateShortCodeOptions, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to update a short code."); + } + + const url = this.getUri(this._organizationId, code); + const headers = this.createHeaders(this._apiKey); + + const response = await this.patch(url, options, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + return response.data as UpdateShortCodeResponse; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to update short code: ${response.statusText}`); + } + + /** + * Delete a short code. + * @param {string} code The short code to delete. Example: 'code_686bed403c3991bd676bba4d' + * @returns {Promise} A promise that resolves to true if the short code was deleted successfully, or false if it was not. + */ + public async deleteShortCode(code: string): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to delete a short code."); + } + + const url = this.getUri(this._organizationId, code); + + const headers = this.createHeaders(this._apiKey); + + const response = await this.delete(url, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 204) { + return true; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to delete short code: ${response.statusText}`); + } + + /** + * Create a QR code for a specific short code. + * @param {string} code The short code to create a QR code for. + * @param {CreateQrCodeOptions} options The options for creating the QR code. + * @returns {Promise} A promise that resolves to the created QR code details. + */ + public async createQrCode( + code: string, + options?: CreateQrCodeOptions, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to create a QR code."); + } + + const url = this.getUri(this._organizationId, code, "qrs"); + const headers = this.createHeaders(this._apiKey); + + // The QR code endpoint consumes multipart/form-data, so each + // personalization option is sent as a form field (and the logo as a + // file upload) rather than as a JSON payload. + const form = new FormData(); + if (options?.title !== undefined) { + form.append("title", options.title); + } + if (options?.backgroundColor !== undefined) { + form.append("backgroundColor", options.backgroundColor); + } + if (options?.color !== undefined) { + form.append("color", options.color); + } + if (options?.size !== undefined) { + form.append("size", options.size); + } + if (options?.logo !== undefined) { + // The logo is supplied as a base64-encoded string but the API expects + // a file upload, so decode it and append it as a file. + const logo = new Blob([Buffer.from(options.logo, "base64")]); + form.append("logo", logo, "logo"); + } + + // The API rejects an empty multipart body ("body must be object"), so + // when no options are provided fall back to an empty JSON payload, which + // yields a QR code with default personalization. + // biome-ignore lint/suspicious/noExplicitAny: body is either form data or JSON + let body: any = {}; + if ([...form.keys()].length > 0) { + body = form; + // Remove the JSON content-type so the multipart boundary is set + // automatically by the underlying fetch call. + delete headers["content-type"]; + } + + const response = await this.post(url, body, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 201) { + const result = response.data as CreateQrCodeResponse; + + if (result.qrCode) { + const buffer = Buffer.from(result.qrCode, "base64"); + result.qrCodeBytes = new Uint8Array(buffer); + } + + return result; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to create QR code: ${response.statusText}`); + } + + /** + * Get a QR code by its ID. + * @param code The short code associated with the QR code. + * @param qr The ID of the QR code to retrieve. + * @returns The details of the requested QR code. + */ + public async getQrCode( + code: string, + qr: string, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get a QR code."); + } + + const url = this.getUri(this._organizationId, code, "qrs", qr); + const headers = this.createHeaders(this._apiKey); + + const response = await this.get(url, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + const result = response.data as CreateQrCodeResponse; + + if (result.qrCode) { + const buffer = Buffer.from(result.qrCode, "base64"); + result.qrCodeBytes = new Uint8Array(buffer); + } + + return result; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get QR code: ${response.statusText}`); + } + + public async getQrCodes( + code: string, + pageNumber?: number, + pageSize?: number, + ): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to get QR codes."); + } + + const url = this.getUri(this._organizationId, code, "qrs"); + const headers = this.createHeaders(this._apiKey); + + const parameters: Record = {}; + if (pageNumber) { + parameters.pageNum = pageNumber.toString(); + } + + if (pageSize) { + parameters.pageSize = pageSize.toString(); + } + + const response = await this.get(url, { headers, params: parameters }); + + /* v8 ignore next -- @preserve */ + if (response.status === 200) { + const result = response.data as GetQrCodesResponse; + for (const qrCode of result.data) { + if (qrCode.qrCode) { + const buffer = Buffer.from(qrCode.qrCode, "base64"); + qrCode.qrCodeBytes = new Uint8Array(buffer); + } + } + + return result; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to get QR codes: ${response.statusText}`); + } + + /** + * Delete a QR code by its ID. + * @param {string} code The short code associated with the QR code. + * @param {string} qr The ID of the QR code to delete. + * @returns {Promise} A promise that resolves to true if the QR code was deleted successfully, or false if it was not. + */ + public async deleteQrCode(code: string, qr: string): Promise { + if (!this._organizationId) { + throw new Error("Organization ID is required to delete a QR code."); + } + + const url = this.getUri(this._organizationId, code, "qrs", qr); + + const headers = this.createHeaders(this._apiKey); + + const response = await this.delete(url, { headers }); + + /* v8 ignore next -- @preserve */ + if (response.status === 204) { + return true; + } + + /* v8 ignore next -- @preserve */ + throw new Error(`Failed to delete QR code: ${response.statusText}`); + } +} diff --git a/packages/nodejs-sdk/src/net-info.ts b/packages/nodejs-sdk/src/net-info.ts new file mode 100644 index 0000000..ff02916 --- /dev/null +++ b/packages/nodejs-sdk/src/net-info.ts @@ -0,0 +1,208 @@ +import process from "node:process"; +import { + BaseService, + type BaseServiceOptions, + ErrorMessages, +} from "./base-service.js"; +import { env } from "./env.js"; + +env(); + +export enum NetInfoErrors { + INVALID_IPS_ARRAY = "The provided IPs array is invalid. It should be a non-empty array of strings.", +} + +export type NetInfoOptions = { + /** + * API key for authentication. If this is not provided it will try to use `HYPHEN_API_KEY` environment variable. + * @type {string} - The API key for authentication. This is not the public API key. + * @default undefined + */ + apiKey?: string; + + /** + * Base URI for the API. If not provided, it will use the default Hyphen API base URI. + * @type {string} - The base URI for the API. + * @default 'https://net.info' + */ + baseUri?: string; +} & BaseServiceOptions; + +export type ipInfo = { + ip: string; + type: string; + location: { + country: string; + region: string; + city: string; + lat: number; + lng: number; + postalCode: string; + timezone: string; + geonameId: number; + }; +}; + +export type ipInfoError = { + ip: string; + type: string; + errorMessage: string; +}; + +export class NetInfo extends BaseService { + private _apiKey: string | undefined; + private _baseUri = "https://net.info"; + constructor(options?: NetInfoOptions) { + super(options); + + if (options?.baseUri) { + this._baseUri = options.baseUri; + } + + this.setApiKey(options?.apiKey); + // If apiKey is not set in options, try to get it from environment variable + if (!this._apiKey && process.env.HYPHEN_API_KEY) { + this.setApiKey(process.env.HYPHEN_API_KEY); + } + + if (!this._apiKey) { + this.error(ErrorMessages.API_KEY_REQUIRED); + } + } + + /** + * Gets or sets the API key for authentication. + * If not set, it will try to use the `HYPHEN_API_KEY` environment variable. + * @type {string | undefined} + */ + public get apiKey(): string | undefined { + return this._apiKey; + } + + /** + * Sets the API key for authentication. + * @param {string | undefined} value - The API key to set. + */ + public set apiKey(value: string | undefined) { + this.setApiKey(value); + } + + /** + * Gets or sets the base URI for the API. + * @type {string} + */ + public get baseUri(): string { + return this._baseUri; + } + + /** + * Sets the base URI for the API. + * @param {string} value - The base URI to set. + */ + public set baseUri(value: string) { + this._baseUri = value; + } + + public setApiKey(value: string | undefined): void { + if (value?.startsWith("public_")) { + this.error(ErrorMessages.PUBLIC_API_KEY_SHOULD_NOT_BE_USED); + return; + } + + this._apiKey = value; + } + + /** + * Fetches GeoIP information for a given IP address. + * @param {string} ip - The IP address to fetch GeoIP information for. + * @returns {Promise} - A promise that resolves to the ip information or an error. + */ + public async getIpInfo(ip: string): Promise { + try { + /* v8 ignore next -- @preserve */ + if (!this._apiKey) { + throw new Error(ErrorMessages.API_KEY_REQUIRED); + } + + const url = `${this._baseUri}/ip/${ip}`; + const headers = this.createHeaders(this._apiKey); + const response = await this.get(url, { + headers, + }); + + /* v8 ignore next -- @preserve */ + if (response.status !== 200) { + const errorResult: ipInfoError = { + ip, + type: "error", + errorMessage: `Failed to fetch ip info: ${response.statusText}`, + }; + return errorResult; + } + + return response.data as ipInfo; + } catch (error) { + /* v8 ignore next -- @preserve */ + this.error( + `Failed to fetch ip info: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + const errorResult: ipInfoError = { + ip, + type: "error", + /* v8 ignore next -- @preserve */ + errorMessage: error instanceof Error ? error.message : "Unknown error", + }; + return errorResult; + } + } + + public async getIpInfos(ips: string[]): Promise> { + if (!Array.isArray(ips) || ips.length === 0) { + this.error(NetInfoErrors.INVALID_IPS_ARRAY); + return []; + } + + const errorResults: Array = []; + try { + /* v8 ignore next -- @preserve */ + if (!this._apiKey) { + throw new Error(ErrorMessages.API_KEY_REQUIRED); + } + + const url = `${this._baseUri}/ip`; + const headers = this.createHeaders(this._apiKey); + const response = await this.post(url, ips, { + headers, + }); + + /* v8 ignore next -- @preserve */ + if (response.status !== 200) { + errorResults.push({ + ip: "", + type: "error", + errorMessage: `Failed to fetch ip infos: ${response.statusText}`, + }); + return errorResults; + } + + const responseData = response?.data as { + data: Array; + }; + return responseData.data; + } catch (error) { + /* v8 ignore next -- @preserve */ + this.error( + `Failed to fetch ip infos: ${error instanceof Error ? error.message : "Unknown error"}`, + ); + /* v8 ignore next -- @preserve */ + errorResults.push({ + ip: "", + type: "error", + errorMessage: error instanceof Error ? error.message : "Unknown error", + }); + + /* v8 ignore next -- @preserve */ + return errorResults; + } + } +} diff --git a/packages/nodejs-sdk/src/toggle.ts b/packages/nodejs-sdk/src/toggle.ts new file mode 100644 index 0000000..763c5fe --- /dev/null +++ b/packages/nodejs-sdk/src/toggle.ts @@ -0,0 +1,941 @@ +import { CacheableNet, type FetchOptions } from "@cacheable/net"; +import type { Cacheable } from "cacheable"; +import { Hookified } from "hookified"; + +/** + * Custom attributes that can contain any key-value pairs. + */ +export type CustomAttributes = Record; + +/** + * User information for evaluation context. + */ +export type ToggleUser = { + /** + * Unique identifier for the user. + */ + id: string; + + /** + * User's email address. + */ + email?: string; + + /** + * User's display name. + */ + name?: string; + + /** + * Custom attributes specific to the user. + */ + customAttributes?: CustomAttributes; +}; + +/** + * Evaluation context for Hyphen feature toggle evaluation. + * + * @example + * ```typescript + * const context: ToggleContext = { + * targetingKey: "user-123", + * ipAddress: "203.0.113.42", + * customAttributes: { + * subscriptionLevel: "premium", + * region: "us-east", + * }, + * user: { + * id: "user-123", + * email: "john.doe@example.com", + * name: "John Doe", + * customAttributes: { + * role: "admin", + * }, + * }, + * }; + * ``` + */ +export type ToggleContext = { + /** + * Primary key used for targeting and bucketing. + */ + targetingKey?: string; + + /** + * IP address of the user making the request. + */ + ipAddress?: string; + + /** + * Custom attributes for evaluation context. + */ + customAttributes?: CustomAttributes; + + /** + * User information for evaluation. + */ + user?: ToggleUser; +}; + +/** + * Internal type combining application info with toggle context for evaluation. + */ +export type ToggleEvaluation = { + application: string; + environment: string; +} & ToggleContext; + +/** + * Represents a single toggle evaluation result. + */ +export interface Evaluation { + /** + * The toggle key. + */ + key: string; + + /** + * The evaluated value of the toggle. + */ + value: boolean | string | number | Record; + + /** + * The type of the toggle value. + */ + type: "boolean" | "string" | "number" | "object"; + + /** + * Optional reason for the evaluation result. + */ + reason?: unknown; + + /** + * Error message if evaluation failed. + */ + errorMessage?: string; +} + +/** + * Response from the toggle evaluation API. + */ +export interface EvaluationResponse { + /** + * Map of toggle keys to their evaluation results. + */ + toggles: Record; +} + +/** + * Options for toggle getter methods. + */ +export type GetOptions = { + /** + * Override the default context for this request. + */ + context?: ToggleContext; + + /** + * Whether to use caching for this request (if caching is configured). + */ + cache?: boolean; +}; + +/** + * Events emitted by the Toggle class. + */ +export enum ToggleEvents { + /** + * Emitted when an error occurs during toggle evaluation. + */ + Error = "error", +} + +/** + * Configuration options for the Toggle class. + */ +export type ToggleOptions = { + /** + * Public API key for authentication. + * Can be found in your Hyphen dashboard. + * Must start with "public_". + */ + publicApiKey?: string; + + /** + * The default context to use when one is not passed to getter methods. + * Can be overridden per-request using the GetOptions parameter. + */ + defaultContext?: ToggleContext; + + /** + * Horizon endpoint URLs for load balancing and failover. + * If provided, requests will be attempted in order. If all fail, + * defaults to Hyphen's hosted service. + * @see {@link https://hyphen.ai/horizon} for more information + */ + horizonUrls?: string[]; + + /** + * Application ID for your Hyphen project. + * Can be found in your Hyphen dashboard. + */ + applicationId?: string; + + /** + * Environment name (e.g., "production", "development", "staging"). + * Defaults to "development" if not provided. + */ + environment?: string; + + /** + * Default targeting key to use if one cannot be derived from context. + * If not provided, a random key will be generated. + */ + defaultTargetKey?: string; + + cache?: Cacheable; +}; + +/** + * Toggle class for feature flag management with Hyphen. + * + * This class provides methods to retrieve feature toggle values with support for + * multiple value types (boolean, string, number, object), context-based targeting, + * and load-balanced requests across multiple Horizon endpoints. + * + * @extends Hookified - Provides event and hook system capabilities + * + * @example + * Basic usage: + * ```typescript + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key-here', + * applicationId: 'app-123', + * environment: 'production' + * }); + * + * const isEnabled = await toggle.getBoolean('new-feature', false); + * ``` + * + * @example + * With context: + * ```typescript + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key-here', + * applicationId: 'app-123', + * defaultContext: { + * targetingKey: 'user-456', + * user: { id: 'user-456', email: 'user@example.com' } + * } + * }); + * + * const message = await toggle.getString('welcome-message', 'Hello!'); + * ``` + * + * @example + * With error handling: + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app' }); + * + * toggle.on('error', (error) => { + * console.error('Toggle error:', error); + * }); + * + * const value = await toggle.getNumber('max-items', 10); + * ``` + */ +export class Toggle extends Hookified { + private _publicApiKey?: string; + private _organizationId: string | undefined; + private _applicationId: string | undefined; + private _environment: string | undefined; + private _horizonUrls: string[] = []; + + private _net: CacheableNet = new CacheableNet(); + private _defaultContext: ToggleContext | undefined; + private _defaultTargetingKey: string = + `${Math.random().toString(36).substring(7)}`; + + /** + * Creates a new Toggle instance. + * + * @param options - Configuration options for the toggle client + * + * @example + * ```typescript + * // Minimal configuration + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key', + * applicationId: 'app-123' + * }); + * + * // With full options + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key', + * applicationId: 'app-123', + * environment: 'production', + * defaultContext: { targetingKey: 'user-456' }, + * horizonUrls: ['https://my-horizon.example.com'] + * }); + * ``` + */ + constructor(options?: ToggleOptions) { + super(); + + if (options?.applicationId) { + this._applicationId = options.applicationId; + } + + if (options?.environment) { + this._environment = options.environment; + } else { + this._environment = "development"; + } + + if (options?.defaultContext) { + this._defaultContext = options.defaultContext; + } + + if (options?.publicApiKey) { + this._publicApiKey = options.publicApiKey; + this._organizationId = this.getOrgIdFromPublicKey(this._publicApiKey); + } + + if (options?.horizonUrls) { + this._horizonUrls = options.horizonUrls; + } else { + this._horizonUrls = this.getDefaultHorizonUrls(this._publicApiKey); + } + + if (options?.defaultTargetKey) { + this._defaultTargetingKey = options?.defaultTargetKey; + } else { + if (this._defaultContext) { + this._defaultTargetingKey = this.getTargetingKey(this._defaultContext); + } else { + this._defaultTargetingKey = this.generateTargetKey(); + } + } + + if (options?.cache) { + this._net.cache = options.cache; + } + } + + /** + * Gets the public API key used for authentication. + * + * @returns The current public API key or undefined if not set + */ + public get publicApiKey(): string | undefined { + return this._publicApiKey; + } + + /** + * Sets the public API key used for authentication. + * + * @param value - The public API key string or undefined to clear + * @throws {Error} If the key doesn't start with "public_" + */ + public set publicApiKey(value: string | undefined) { + this.setPublicKey(value); + } + + /** + * Gets the default context used for toggle evaluations. + * + * @returns The current default ToggleContext + */ + public get defaultContext(): ToggleContext | undefined { + return this._defaultContext; + } + + /** + * Sets the default context used for toggle evaluations. + * + * @param value - The ToggleContext to use as default + */ + public set defaultContext(value: ToggleContext) { + this._defaultContext = value; + } + + /** + * Gets the organization ID extracted from the public API key. + * + * @returns The organization ID string or undefined if not available + */ + public get organizationId(): string | undefined { + return this._organizationId; + } + + /** + * Gets the Horizon endpoint URLs used for load balancing. + * + * These URLs are used to distribute requests across multiple Horizon endpoints. + * If endpoints fail, the system will attempt to use the default horizon endpoint service. + * + * @returns Array of Horizon endpoint URLs + * @see {@link https://hyphen.ai/horizon} for more information + */ + public get horizonUrls(): string[] { + return this._horizonUrls; + } + + /** + * Sets the Horizon endpoint URLs for load balancing. + * + * Configures multiple Horizon endpoints that will be used for load balancing. + * When endpoints fail, the system will fall back to the default horizon endpoint service. + * + * @param value - Array of Horizon endpoint URLs or empty array to clear + * @see {@link https://hyphen.ai/horizon} for more information + * + * @example + * ```typescript + * const toggle = new Toggle(); + * toggle.horizonUrls = [ + * 'https://org1.toggle.hyphen.cloud', + * 'https://org2.toggle.hyphen.cloud' + * ]; + * ``` + */ + public set horizonUrls(value: string[]) { + this._horizonUrls = value; + } + + /** + * Gets the application ID used for toggle context. + * + * @returns The current application ID or undefined if not set + */ + public get applicationId(): string | undefined { + return this._applicationId; + } + + /** + * Sets the application ID used for toggle context. + * + * @param value - The application ID string or undefined to clear + */ + public set applicationId(value: string | undefined) { + this._applicationId = value; + } + + /** + * Gets the environment used for toggle context. + * + * @returns The current environment (defaults to 'development') + */ + public get environment(): string | undefined { + return this._environment; + } + + /** + * Sets the environment used for toggle context. + * + * @param value - The environment string or undefined to clear + */ + public set environment(value: string | undefined) { + this._environment = value; + } + + /** + * Gets the default targeting key used for toggle evaluations. + * + * @returns The current default targeting key or undefined if not set + */ + public get defaultTargetingKey(): string { + return this._defaultTargetingKey; + } + + /** + * Sets the default targeting key used for toggle evaluations. + * + * @param value - The targeting key string or undefined to clear + */ + public set defaultTargetingKey(value: string) { + this._defaultTargetingKey = value; + } + + /** + * Gets the Cacheable instance used for caching fetch operations. + * + * @returns The current Cacheable instance + */ + public get cache(): Cacheable { + return this._net.cache; + } + + /** + * Sets the Cacheable instance for caching fetch operations. + * + * @param cache - The Cacheable instance to use for caching + */ + public set cache(cache: Cacheable) { + this._net.cache = cache; + } + + /** + * Retrieves a toggle value with generic type support. + * + * This is the core method for fetching toggle values. All convenience methods + * (getBoolean, getString, getNumber, getObject) delegate to this method. + * + * @template T - The expected type of the toggle value + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context override + * @returns Promise resolving to the toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * + * // Get a boolean + * const enabled = await toggle.get('feature-flag', false); + * + * // Get an object with type safety + * interface Config { theme: string; } + * const config = await toggle.get('app-config', { theme: 'light' }); + * + * // Override context for a single request + * const value = await toggle.get('key', 'default', { + * context: { targetingKey: 'user-456' } + * }); + * ``` + */ + public async get( + toggleKey: string, + defaultValue: T, + options?: GetOptions, + ): Promise { + try { + const context: ToggleEvaluation = { + application: this._applicationId ?? "", + /* v8 ignore next -- @preserve */ + environment: this._environment ?? "development", + }; + + if (options?.context) { + context.targetingKey = options?.context.targetingKey; + context.ipAddress = options?.context.ipAddress; + context.user = options?.context.user; + context.customAttributes = options?.context.customAttributes; + } else { + context.targetingKey = this._defaultContext?.targetingKey; + context.ipAddress = this._defaultContext?.ipAddress; + context.user = this._defaultContext?.user; + context.customAttributes = this._defaultContext?.customAttributes; + } + + const fetchOptions = { headers: {} as Record }; + + if (!context.targetingKey) { + context.targetingKey = this.getTargetingKey(context); + } + + // api key + if (this._publicApiKey) { + fetchOptions.headers["x-api-key"] = this._publicApiKey; + } else { + throw new Error("You must set the publicApiKey"); + } + + // application + if (context.application === "") { + throw new Error("You must set the applicationId"); + } + + const result = await this.fetch( + "/toggle/evaluate", + context, + fetchOptions, + ); + + /* v8 ignore next -- @preserve */ + if (result?.toggles) { + return result.toggles[toggleKey].value as T; + } + } catch (error) { + this.emit(ToggleEvents.Error, error); + } + + return defaultValue; + } + + /** + * Retrieves a boolean toggle value. + * + * This is a convenience method that wraps the generic get() method with boolean type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The boolean value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the boolean toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const isFeatureEnabled = await toggle.getBoolean('feature-flag', false); + * console.log(isFeatureEnabled); // true or false + * ``` + */ + public async getBoolean( + toggleKey: string, + defaultValue: boolean, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves a string toggle value. + * + * This is a convenience method that wraps the generic get() method with string type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The string value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the string toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const message = await toggle.getString('welcome-message', 'Hello World'); + * console.log(message); // 'Welcome to our app!' or 'Hello World' + * ``` + */ + public async getString( + toggleKey: string, + defaultValue: string, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves an object toggle value. + * + * This is a convenience method that wraps the generic get() method with object type safety. + * Note that the toggle service may return JSON as a string, which should be parsed if needed. + * + * @template T - The expected object type + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The object value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the object toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const config = await toggle.getObject('app-config', { theme: 'light' }); + * console.log(config); // { theme: 'dark', features: ['a', 'b'] } or { theme: 'light' } + * ``` + */ + public async getObject( + toggleKey: string, + defaultValue: T, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Retrieves a number toggle value. + * + * This is a convenience method that wraps the generic get() method with number type safety. + * + * @param toggleKey - The key of the toggle to retrieve + * @param defaultValue - The number value to return if the toggle is not found or an error occurs + * @param options - Optional configuration including context for toggle evaluation + * @returns Promise resolving to the number toggle value or defaultValue + * + * @example + * ```typescript + * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' }); + * const maxRetries = await toggle.getNumber('max-retries', 3); + * console.log(maxRetries); // 5 or 3 + * ``` + */ + public async getNumber( + toggleKey: string, + defaultValue: number, + options?: GetOptions, + ): Promise { + return this.get(toggleKey, defaultValue, options); + } + + /** + * Makes an HTTP POST request to the specified URL with automatic authentication. + * + * This method uses browser-compatible fetch and automatically includes the + * public API key in the x-api-key header if available. It supports load + * balancing across multiple horizon URLs with fallback behavior. + * + * @template T - The expected response type + * @param path - The API path to request (e.g., '/api/toggles') + * @param payload - The JSON payload to send in the request body + * @param options - Optional fetch configuration. Cache is set at .cache + * @returns Promise resolving to the parsed JSON response + * @throws {Error} If no horizon URLs are configured or all requests fail + * + * @example + * ```typescript + * const toggle = new Toggle({ + * publicApiKey: 'public_your-key-here', + * horizonUrls: ['https://api.hyphen.cloud'] + * }); + * + * interface ToggleResponse { + * enabled: boolean; + * value: string; + * } + * + * const result = await toggle.fetch('/api/toggle/feature-flag', { + * context: { targetingKey: 'user-123' } + * }); + * console.log(result.enabled); // true/false + * ``` + */ + public async fetch( + path: string, + payload?: unknown, + options?: Omit, + ): Promise { + if (this._horizonUrls.length === 0) { + throw new Error( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + } + + const headers: Record = { + "Content-Type": "application/json", + }; + + if (options?.headers) { + if (options.headers instanceof Headers) { + options.headers.forEach((value, key) => { + headers[key] = value; + }); + } else if (Array.isArray(options.headers)) { + options.headers.forEach(([key, value]) => { + headers[key] = value; + }); + } else { + Object.assign(headers, options.headers); + } + } + + if (this._publicApiKey) { + headers["x-api-key"] = this._publicApiKey; + } + + const fetchOptions: FetchOptions = { + method: "POST", + ...options, + headers, + body: payload ? JSON.stringify(payload) : options?.body, + }; + + const errors: Error[] = []; + + for (const baseUrl of this._horizonUrls) { + try { + const url = `${baseUrl.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`; + const response = await this._net.fetch(url, fetchOptions); + + /* v8 ignore next -- @preserve */ + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const data = (await response.json()) as T; + return data; + } catch (error) { + const fetchError = + /* v8 ignore next -- @preserve */ + error instanceof Error ? error : new Error("Unknown fetch error"); + + // Extract status code from CacheableNet error messages + const statusMatch = fetchError.message.match(/status (\d{3})/); + if (statusMatch) { + const status = statusMatch[1]; + errors.push(new Error(`HTTP ${status}: ${fetchError.message}`)); + } else { + errors.push(fetchError); + } + } + } + + throw new Error( + `All horizon URLs failed. Last errors: ${errors.map((e) => e.message).join(", ")}`, + ); + } + + /** + * Validates and sets the public API key. + * + * This method is used internally by the publicApiKey setter to validate + * that the key starts with "public_" prefix. If the key is invalid, + * an error is thrown. + * + * @param key - The public API key string or undefined to clear + * @throws {Error} If the key doesn't start with "public_" + * + * @example + * ```typescript + * const toggle = new Toggle(); + * + * // Valid key + * toggle.setPublicKey('public_abc123'); // OK + * + * // Invalid key + * toggle.setPublicKey('invalid_key'); // Throws error + * + * // Clear key + * toggle.setPublicKey(undefined); // OK + * ``` + */ + public setPublicKey(key: string | undefined): void { + if (key !== undefined && !key.startsWith("public_")) { + throw new Error("Public API key must start with 'public_'"); + } + this._publicApiKey = key; + } + + /** + * Extracts the organization ID from a public API key. + * + * The public key format is: `public_` + * The base64 data contains: `orgId:secretData` + * Only alphanumeric characters, underscores, and hyphens are considered valid in org IDs. + * + * @param publicKey - The public API key to extract the organization ID from + * @returns The organization ID if valid and extractable, undefined otherwise + * + * @example + * ```typescript + * const toggle = new Toggle(); + * const orgId = toggle.getOrgIdFromPublicKey('public_dGVzdC1vcmc6c2VjcmV0'); + * console.log(orgId); // 'test-org' + * ``` + */ + public getOrgIdFromPublicKey(publicKey: string): string | undefined { + try { + const keyWithoutPrefix = publicKey.replace(/^public_/, ""); + const decoded = globalThis.atob + ? globalThis.atob(keyWithoutPrefix) + : Buffer.from(keyWithoutPrefix, "base64").toString(); + const [orgId] = decoded.split(":"); + const isValidOrgId = /^[a-zA-Z0-9_-]+$/.test(orgId); + return isValidOrgId ? orgId : undefined; + } catch { + return undefined; + } + } + + /** + * Builds the default Horizon API URL for the given public key. + * + * If a valid organization ID can be extracted from the public key, returns an + * organization-specific URL. Otherwise, returns the default fallback URL. + * + * @param publicKey - The public API key to build the URL for + * @returns Organization-specific URL or default fallback URL + * + * @example + * ```typescript + * const toggle = new Toggle(); + * + * // With valid org ID + * const orgUrl = toggle.buildDefaultHorizonUrl('public_dGVzdC1vcmc6c2VjcmV0'); + * console.log(orgUrl); // 'https://test-org.toggle.hyphen.cloud' + * + * // With invalid key + * const defaultUrl = toggle.buildDefaultHorizonUrl('invalid-key'); + * console.log(defaultUrl); // 'https://toggle.hyphen.cloud' + * ``` + */ + public getDefaultHorizonUrl(publicKey?: string): string { + if (publicKey) { + const orgId = this.getOrgIdFromPublicKey(publicKey); + return orgId + ? `https://${orgId}.toggle.hyphen.cloud` + : "https://toggle.hyphen.cloud"; + } + + return "https://toggle.hyphen.cloud"; + } + + /** + * Gets the default Horizon URLs for load balancing and failover. + * + * If a public key is provided, returns an array with the organization-specific + * URL as primary and the default Hyphen URL as fallback. Without a public key, + * returns only the default Hyphen URL. + * + * @param publicKey - Optional public API key to derive organization-specific URL + * @returns Array of Horizon URLs for load balancing + * + * @example + * ```typescript + * const toggle = new Toggle(); + * + * // Without public key - returns default only + * const defaultUrls = toggle.getDefaultHorizonUrls(); + * // ['https://toggle.hyphen.cloud'] + * + * // With public key - returns org-specific + fallback + * const urls = toggle.getDefaultHorizonUrls('public_dGVzdC1vcmc6c2VjcmV0'); + * // ['https://test-org.toggle.hyphen.cloud', 'https://toggle.hyphen.cloud'] + * ``` + */ + public getDefaultHorizonUrls(publicKey?: string): string[] { + let result = [this.getDefaultHorizonUrl()]; + if (publicKey) { + const defaultUrl = result[0]; + const orgUrl = this.getDefaultHorizonUrl(publicKey); + result = []; + if (orgUrl !== defaultUrl) { + result.push(orgUrl); + } + // make the default url the secondary + result.push(defaultUrl); + } + return result; + } + + /** + * Generates a unique targeting key based on available context. + * + * @returns A targeting key in the format: `[app]-[env]-[random]` or simplified versions + */ + public generateTargetKey(): string { + const randomSuffix = Math.random().toString(36).substring(7); + const app = this._applicationId || ""; + /* v8 ignore next -- @preserve */ + const env = this._environment || ""; + + // Build key components in order of preference + const components = [app, env, randomSuffix].filter(Boolean); + + return components.join("-"); + } + + /** + * Extracts targeting key from a toggle context with fallback logic. + * + * @param context - The toggle context to extract targeting key from + * @returns The targeting key string + */ + private getTargetingKey(context: ToggleContext): string { + if (context.targetingKey) { + return context.targetingKey; + } + if (context.user) { + return context.user.id; + } + // TODO: what is a better way to do this? Should we also have a service property so we don't add the random value? + return this._defaultTargetingKey; + } +} diff --git a/packages/nodejs-sdk/test/base-service.test.ts b/packages/nodejs-sdk/test/base-service.test.ts new file mode 100644 index 0000000..4e4774c --- /dev/null +++ b/packages/nodejs-sdk/test/base-service.test.ts @@ -0,0 +1,157 @@ +import process from "node:process"; +import { Cacheable } from "cacheable"; +import pino from "pino"; +import { describe, expect, test, vi } from "vitest"; +import { BaseService } from "../src/base-service.js"; + +const mockHttpUrl = process.env.MOCK_HTTP_URL ?? "https://mockhttp.org"; +const testTimeout = 20_000; + +describe("BaseService", () => { + test("should create an instance of BaseService", () => { + const service = new BaseService(); + expect(service).toBeInstanceOf(BaseService); + }); + + test("should have default properties", () => { + const service = new BaseService(); + expect(service.log).toBeDefined(); + expect(service.cache).toBeDefined(); + }); + + test("should allow setting and getting log", () => { + const service = new BaseService(); + const logger: pino.Logger = pino(); + service.log = logger; + expect(service.log).toBe(logger); + }); + + test("should allow setting and getting cache", () => { + const service = new BaseService(); + const cache = new Cacheable(); + service.cache = cache; + expect(service.cache).toBe(cache); + }); + + test("should log error and emit error event", () => { + const service = new BaseService(); + service.on("error", () => {}); + const errorSpy = vi.spyOn(service.log, "error"); + const emitSpy = vi.spyOn(service, "emit"); + service.error("Test error"); + expect(errorSpy).toHaveBeenCalledWith("Test error"); + expect(emitSpy).toHaveBeenCalledWith("error", "Test error"); + }); + + test("should log warning and emit warn event", () => { + const service = new BaseService(); + const warnSpy = vi.spyOn(service.log, "warn"); + const emitSpy = vi.spyOn(service, "emit"); + service.warn("Test warning"); + expect(warnSpy).toHaveBeenCalledWith("Test warning"); + expect(emitSpy).toHaveBeenCalledWith("warn", "Test warning"); + }); + + test("should log info and emit info event", () => { + const service = new BaseService(); + const infoSpy = vi.spyOn(service.log, "info"); + const emitSpy = vi.spyOn(service, "emit"); + service.info("Test info"); + expect(infoSpy).toHaveBeenCalledWith("Test info"); + expect(emitSpy).toHaveBeenCalledWith("info", "Test info"); + }); + + test( + "should do a get request", + async () => { + const service = new BaseService(); + const url = `${mockHttpUrl}/get`; + const response = await service.get(url); + expect(response).toBeDefined(); + }, + testTimeout, + ); + + test("should handle a post request", async () => { + const service = new BaseService(); + const url = `${mockHttpUrl}/post`; + const data = { key: "value" }; + const response = await service.post(url, data); + expect(response).toBeDefined(); + }); + + test("should handle a put request", async () => { + const service = new BaseService(); + const url = `${mockHttpUrl}/put`; + const data = { key: "value" }; + const response = await service.put(url, data); + expect(response).toBeDefined(); + }); + + test("should handle a delete request", async () => { + const service = new BaseService(); + const url = `${mockHttpUrl}/delete`; + const data = { key: "value" }; + const response = await service.delete(url, { data }); + expect(response).toBeDefined(); + }); + + test("should handle a patch request", async () => { + const service = new BaseService(); + const url = `${mockHttpUrl}/patch`; + const data = { key: "value" }; + const response = await service.patch(url, data); + expect(response).toBeDefined(); + }); + + test("should handle a delete request with string data", async () => { + const service = new BaseService(); + const mockFetch = vi.fn().mockResolvedValue({ + status: 200, + statusText: "OK", + headers: {}, + text: vi.fn().mockResolvedValue(JSON.stringify({ ok: true })), + }); + // @ts-expect-error - accessing private property for testing + service._net.fetch = mockFetch; + + const url = "https://example.com/delete"; + const data = { message: "plain text string" }; + const response = await service.delete(url, { data }); + + expect(response).toBeDefined(); + expect(response.status).toBe(200); + expect(mockFetch).toHaveBeenCalledWith( + url, + expect.objectContaining({ + method: "DELETE", + body: JSON.stringify(data), + }), + ); + }); + + test("should handle a delete request with non-JSON text response", async () => { + const service = new BaseService(); + + // Mock the fetch to return non-JSON text + const mockFetch = vi.fn().mockResolvedValue({ + status: 200, + statusText: "OK", + headers: {}, + text: vi.fn().mockResolvedValue("This is plain text, not JSON"), + }); + + // Replace the _net.fetch with our mock + // @ts-expect-error - accessing private property for testing + service._net.fetch = mockFetch; + + const url = "https://example.com/test"; + const response = await service.delete(url); + + expect(response).toBeDefined(); + expect(response.status).toBe(200); + // The plain text should be stored as the data since JSON.parse will fail + expect(response.data).toBe("This is plain text, not JSON"); + expect(typeof response.data).toBe("string"); + }); +}); diff --git a/packages/nodejs-sdk/test/env-service.test.ts b/packages/nodejs-sdk/test/env-service.test.ts new file mode 100644 index 0000000..b401da7 --- /dev/null +++ b/packages/nodejs-sdk/test/env-service.test.ts @@ -0,0 +1,765 @@ +import { Buffer } from "node:buffer"; +import { createCipheriv, createHash } from "node:crypto"; +import process from "node:process"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import type { HttpResponse } from "../src/base-service.js"; +import { + Env, + type EnvKey, + type EnvServiceOptions, +} from "../src/env-service.js"; + +const apiKey = "private-test-api-key"; +const organizationId = "org_test"; +const projectId = "proj_test"; +const applicationId = "app_test"; +const productionEnvironment = "production"; +const defaultEnvHorizonUri = "https://toggle.hyphen.cloud"; +const defaultEnvKeyStoreUri = "https://vinz.hyphen.ai"; +const testVariableNames = [ + "CUSTOM_URI", + "DEFAULT_ONLY", + "DEFAULT_VALUE", + "DEPLOY_FALLBACK", + "DIRECT_KEY", + "EXPLICIT", + "FROM_ENV", + "ID_PRECEDENCE", + "LEGACY_APP_ID", + "NAMED_ONLY", + "NEW_VALUE", + "ONLY_NAMED", + "QUOTED", + "SETTER_KEY", + "SHARED", + "UNCHANGED", +]; + +const decryptionKey: EnvKey = { + secretKeyId: 1_725_000_000, + secretKey: "dGVzdC1zZWNyZXQ=", +}; + +const authHeaders = { + accept: "application/json", + "content-type": "application/json", + "x-api-key": apiKey, +}; + +const keyStoreUrl = `${defaultEnvKeyStoreUri}/${organizationId}/${projectId}/key`; +const horizonUrl = `${defaultEnvHorizonUri}/api/organizations/${organizationId}/apps/${applicationId}/dot-env/`; + +function response( + data: T, + status = 200, + statusText = status === 200 ? "OK" : "Request failed", +): HttpResponse { + return { + data, + status, + statusText, + headers: {}, + config: {}, + }; +} + +function padBase64(value: string): string { + return value.padEnd(value.length + ((4 - (value.length % 4)) % 4), "="); +} + +/** + * Produces the wire format used by hx: SHA-256 hex characters as the AES key, + * followed by AES-256-CFB with the IV prefixed to padded base64url ciphertext. + */ +function encryptBytesLikeHx( + plaintext: Uint8Array, + secretKey = decryptionKey.secretKey, + ivByte = 1, +): string { + const hash = createHash("sha256").update(secretKey).digest("hex"); + const key = Buffer.from(hash.slice(0, 32), "utf8"); + const iv = Buffer.alloc(16, ivByte); + const cipher = createCipheriv("aes-256-cfb", key, iv); + const encrypted = Buffer.concat([ + iv, + cipher.update(plaintext), + cipher.final(), + ]); + + return padBase64(encrypted.toString("base64url")); +} + +function encryptLikeHx( + plaintext: string, + secretKey = decryptionKey.secretKey, + ivByte = 1, +): string { + return encryptBytesLikeHx(Buffer.from(plaintext), secretKey, ivByte); +} + +function createService(overrides: EnvServiceOptions = {}): Env { + return new Env({ + apiKey, + organizationId, + projectId, + applicationId, + ...overrides, + }); +} + +function mockKeyResponse(key = decryptionKey): HttpResponse { + return response({ + key: { + secret_key_id: key.secretKeyId, + secret_key: key.secretKey, + }, + }); +} + +function mockEnvResponse(plaintext: string, ivByte = 1): HttpResponse { + return response({ + data: encryptLikeHx(plaintext, decryptionKey.secretKey, ivByte), + }); +} + +let originalEnvironment: NodeJS.ProcessEnv; + +beforeEach(() => { + originalEnvironment = { ...process.env }; + delete process.env.HYPHEN_API_KEY; + delete process.env.HYPHEN_ORGANIZATION_ID; + delete process.env.HYPHEN_PROJECT_ID; + delete process.env.HYPHEN_PROJECT_NAME; + delete process.env.HYPHEN_APPLICATION_ID; + delete process.env.HYPHEN_APP_ID; + delete process.env.HYPHEN_APP_NAME; + delete process.env.HYPHEN_APP_ENVIRONMENT; + for (const name of testVariableNames) { + delete process.env[name]; + } +}); + +afterEach(() => { + for (const key of Object.keys(process.env)) { + delete process.env[key]; + } + Object.assign(process.env, originalEnvironment); + vi.restoreAllMocks(); +}); + +describe("Env", () => { + test("uses the production ENV service endpoints", () => { + expect(defaultEnvHorizonUri).toBe("https://toggle.hyphen.cloud"); + expect(defaultEnvKeyStoreUri).toBe("https://vinz.hyphen.ai"); + }); + + test("decrypts a fixed ciphertext produced by the Go hx algorithm", async () => { + const service = createService({ + decryptionKey: { + secretKeyId: 1, + secretKey: "c2VjcmV0LWtleQ==", + }, + }); + const getSpy = vi.spyOn(service, "get").mockResolvedValue( + response({ + data: "AAECAwQFBgcICQoLDA0OD3bIZNW5zB1r27HjMfDRJ2Xghuc=", + }), + ); + + const variables = await service.load("default"); + + expect(variables).toEqual({ FOO: "bar", NESTED: "a=b" }); + expect(process.env.FOO).toBe("bar"); + expect(process.env.NESTED).toBe("a=b"); + expect(getSpy).toHaveBeenCalledOnce(); + }); + + test("fetches the key, merges default and named ENV, and applies named values last", async () => { + const service = createService(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce( + mockEnvResponse( + 'DEFAULT_ONLY=base\nSHARED=default\nQUOTED="hello world"\n', + 2, + ), + ) + .mockResolvedValueOnce( + mockEnvResponse("SHARED=named\nNAMED_ONLY=value=with=equals\n", 3), + ); + + const variables = await service.load(productionEnvironment); + + expect(variables).toEqual({ + DEFAULT_ONLY: "base", + NAMED_ONLY: "value=with=equals", + QUOTED: "hello world", + SHARED: "named", + }); + expect(process.env.DEFAULT_ONLY).toBe("base"); + expect(process.env.NAMED_ONLY).toBe("value=with=equals"); + expect(process.env.QUOTED).toBe("hello world"); + expect(process.env.SHARED).toBe("named"); + + expect(getSpy).toHaveBeenNthCalledWith(1, keyStoreUrl, { + caching: false, + headers: authHeaders, + }); + expect(getSpy).toHaveBeenNthCalledWith(2, horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + expect(getSpy).toHaveBeenNthCalledWith(3, horizonUrl, { + caching: false, + headers: authHeaders, + params: { + environmentId: productionEnvironment, + secretKeyId: decryptionKey.secretKeyId, + }, + }); + }); + + test("fetches only the named ENV when includeDefault is false", async () => { + const service = createService(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("ONLY_NAMED=yes\n")); + + await expect( + service.load(productionEnvironment, { includeDefault: false }), + ).resolves.toEqual({ ONLY_NAMED: "yes" }); + + expect(getSpy).toHaveBeenCalledTimes(2); + expect(getSpy).toHaveBeenLastCalledWith(horizonUrl, { + caching: false, + headers: authHeaders, + params: { + environmentId: productionEnvironment, + secretKeyId: decryptionKey.secretKeyId, + }, + }); + }); + + test("loads the default ENV only once", async () => { + const service = createService(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("DEFAULT_VALUE=yes\n")); + + await expect(service.load()).resolves.toEqual({ DEFAULT_VALUE: "yes" }); + + expect(getSpy).toHaveBeenCalledTimes(2); + expect(getSpy).toHaveBeenLastCalledWith(horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + }); + + test("returns remote values but preserves existing process values when override is false", async () => { + process.env.SHARED = "existing"; + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue( + mockEnvResponse("SHARED=remote\nNEW_VALUE=added\n"), + ); + + await expect(service.load("default", { override: false })).resolves.toEqual( + { NEW_VALUE: "added", SHARED: "remote" }, + ); + + expect(process.env.SHARED).toBe("existing"); + expect(process.env.NEW_VALUE).toBe("added"); + }); + + test("overwrites existing process values by default", async () => { + process.env.SHARED = "existing"; + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue( + mockEnvResponse("SHARED=remote\n"), + ); + + await service.load(); + + expect(process.env.SHARED).toBe("remote"); + }); + + test("uses an explicit key without requiring a project or requesting the key store", async () => { + const service = new Env({ + apiKey, + organizationId, + applicationId, + decryptionKey, + }); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValue(mockEnvResponse("DIRECT_KEY=yes\n")); + + await expect( + service.load(productionEnvironment, { includeDefault: false }), + ).resolves.toEqual({ DIRECT_KEY: "yes" }); + + expect(getSpy).toHaveBeenCalledOnce(); + expect(getSpy).toHaveBeenCalledWith(horizonUrl, { + caching: false, + headers: authHeaders, + params: { + environmentId: productionEnvironment, + secretKeyId: decryptionKey.secretKeyId, + }, + }); + }); + + test("falls back to the documented environment variables", async () => { + process.env.HYPHEN_API_KEY = apiKey; + process.env.HYPHEN_ORGANIZATION_ID = organizationId; + process.env.HYPHEN_PROJECT_ID = projectId; + process.env.HYPHEN_APPLICATION_ID = applicationId; + const service = new Env(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("FROM_ENV=yes\n")); + + await expect(service.load()).resolves.toEqual({ FROM_ENV: "yes" }); + + expect(service.apiKey).toBe(apiKey); + expect(getSpy).toHaveBeenNthCalledWith(1, keyStoreUrl, { + caching: false, + headers: authHeaders, + }); + expect(getSpy).toHaveBeenNthCalledWith(2, horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + }); + + test("supports HYPHEN_APP_ID as a legacy application fallback", async () => { + process.env.HYPHEN_API_KEY = apiKey; + process.env.HYPHEN_ORGANIZATION_ID = organizationId; + process.env.HYPHEN_PROJECT_ID = projectId; + process.env.HYPHEN_APP_ID = applicationId; + const service = new Env({ decryptionKey }); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValue(mockEnvResponse("LEGACY_APP_ID=yes\n")); + + await service.load(); + + expect(getSpy).toHaveBeenCalledWith(horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + }); + + test("uses Hyphen Deploy names and environment as final fallbacks", async () => { + const deployProjectName = "project-from-deploy"; + const deployApplicationName = "app-from-deploy"; + const deployEnvironment = "staging"; + process.env.HYPHEN_API_KEY = apiKey; + process.env.HYPHEN_ORGANIZATION_ID = organizationId; + process.env.HYPHEN_PROJECT_NAME = deployProjectName; + process.env.HYPHEN_APP_NAME = deployApplicationName; + process.env.HYPHEN_APP_ENVIRONMENT = deployEnvironment; + const service = new Env(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("DEFAULT_VALUE=yes\n")) + .mockResolvedValueOnce(mockEnvResponse("DEPLOY_FALLBACK=yes\n")); + + await expect(service.load()).resolves.toEqual({ + DEFAULT_VALUE: "yes", + DEPLOY_FALLBACK: "yes", + }); + + expect(getSpy).toHaveBeenNthCalledWith( + 1, + `${defaultEnvKeyStoreUri}/${organizationId}/${deployProjectName}/key`, + { + caching: false, + headers: authHeaders, + }, + ); + expect(getSpy).toHaveBeenNthCalledWith( + 2, + `${defaultEnvHorizonUri}/api/organizations/${organizationId}/apps/${deployApplicationName}/dot-env/`, + { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }, + ); + expect(getSpy).toHaveBeenNthCalledWith( + 3, + `${defaultEnvHorizonUri}/api/organizations/${organizationId}/apps/${deployApplicationName}/dot-env/`, + { + caching: false, + headers: authHeaders, + params: { + environmentId: deployEnvironment, + secretKeyId: decryptionKey.secretKeyId, + }, + }, + ); + }); + + test("prefers ID variables and an explicit environment over deploy fallbacks", async () => { + process.env.HYPHEN_API_KEY = apiKey; + process.env.HYPHEN_ORGANIZATION_ID = organizationId; + process.env.HYPHEN_PROJECT_ID = projectId; + process.env.HYPHEN_PROJECT_NAME = "ignored-project-name"; + process.env.HYPHEN_APPLICATION_ID = applicationId; + process.env.HYPHEN_APP_ID = "ignored-legacy-app-id"; + process.env.HYPHEN_APP_NAME = "ignored-app-name"; + process.env.HYPHEN_APP_ENVIRONMENT = "ignored-environment"; + const service = new Env(); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("ID_PRECEDENCE=yes\n")); + + await expect( + service.load("PRODUCTION", { includeDefault: false }), + ).resolves.toEqual({ ID_PRECEDENCE: "yes" }); + + expect(getSpy).toHaveBeenNthCalledWith(1, keyStoreUrl, { + caching: false, + headers: authHeaders, + }); + expect(getSpy).toHaveBeenNthCalledWith(2, horizonUrl, { + caching: false, + headers: authHeaders, + params: { + environmentId: productionEnvironment, + secretKeyId: decryptionKey.secretKeyId, + }, + }); + }); + + test("prefers explicit options over environment variable fallbacks", async () => { + process.env.HYPHEN_API_KEY = "environment-api-key"; + process.env.HYPHEN_ORGANIZATION_ID = "org_environment"; + process.env.HYPHEN_PROJECT_ID = "proj_environment"; + process.env.HYPHEN_APPLICATION_ID = "app_environment"; + const service = createService({ decryptionKey }); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValue(mockEnvResponse("EXPLICIT=yes\n")); + + await service.load(); + + expect(getSpy).toHaveBeenCalledWith(horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + }); + + test("uses custom service URIs without duplicate trailing slashes", async () => { + const customKeyStoreUri = "https://keys.example.test///"; + const customHorizonUri = "https://env.example.test///"; + const service = createService({ + keyStoreUri: customKeyStoreUri, + horizonUri: customHorizonUri, + }); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockKeyResponse()) + .mockResolvedValueOnce(mockEnvResponse("CUSTOM_URI=yes\n")); + + await service.load(); + + expect(getSpy).toHaveBeenNthCalledWith( + 1, + `https://keys.example.test/${organizationId}/${projectId}/key`, + expect.any(Object), + ); + expect(getSpy).toHaveBeenNthCalledWith( + 2, + `https://env.example.test/api/organizations/${organizationId}/apps/${applicationId}/dot-env/`, + expect.any(Object), + ); + }); + + test("allows the API key to be supplied after construction", async () => { + const service = new Env({ + organizationId, + applicationId, + decryptionKey, + }); + service.apiKey = apiKey; + vi.spyOn(service, "get").mockResolvedValue( + mockEnvResponse("SETTER_KEY=yes\n"), + ); + + expect(service.apiKey).toBe(apiKey); + await expect(service.load()).resolves.toEqual({ SETTER_KEY: "yes" }); + }); + + test("rejects a public API key on load before making a request", async () => { + const constructorService = createService({ apiKey: "public_test-key" }); + const constructorGetSpy = vi.spyOn(constructorService, "get"); + await expect(constructorService.load()).rejects.toThrow( + "A public API key cannot load Hyphen ENV data.", + ); + expect(constructorGetSpy).not.toHaveBeenCalled(); + + const setterService = createService(); + setterService.apiKey = "public_test-key"; + const setterGetSpy = vi.spyOn(setterService, "get"); + await expect(setterService.load()).rejects.toThrow( + "A public API key cannot load Hyphen ENV data.", + ); + expect(setterGetSpy).not.toHaveBeenCalled(); + }); + + test("normalizes uppercase and empty environment names", async () => { + const service = createService({ decryptionKey }); + const getSpy = vi + .spyOn(service, "get") + .mockResolvedValueOnce(mockEnvResponse("ONLY_NAMED=yes\n")) + .mockResolvedValueOnce(mockEnvResponse("DEFAULT_VALUE=yes\n")); + + await service.load("PRODUCTION", { includeDefault: false }); + await service.load(""); + + expect(getSpy).toHaveBeenNthCalledWith(1, horizonUrl, { + caching: false, + headers: authHeaders, + params: { + environmentId: "production", + secretKeyId: decryptionKey.secretKeyId, + }, + }); + expect(getSpy).toHaveBeenNthCalledWith(2, horizonUrl, { + caching: false, + headers: authHeaders, + params: { secretKeyId: decryptionKey.secretKeyId }, + }); + }); + + test("rejects an invalid environment name before making a request", async () => { + const service = createService({ decryptionKey }); + const getSpy = vi.spyOn(service, "get"); + + await expect(service.load("invalid environment!")).rejects.toThrow( + "Environment must contain only lowercase letters, numbers, hyphens, and underscores.", + ); + expect(getSpy).not.toHaveBeenCalled(); + }); + + describe("validation", () => { + test.each([ + { + label: "API key", + options: { organizationId, projectId, applicationId }, + error: "An API key is required to load Hyphen ENV data.", + }, + { + label: "organization ID", + options: { apiKey, projectId, applicationId }, + error: "An organization ID is required to load Hyphen ENV data.", + }, + { + label: "application ID", + options: { apiKey, organizationId, projectId }, + error: "An application ID is required to load Hyphen ENV data.", + }, + { + label: "project ID", + options: { apiKey, organizationId, applicationId }, + error: + "A project ID or decryption key is required to load Hyphen ENV data.", + }, + ])( + "rejects a missing $label before making a request", + async ({ options, error }) => { + const service = new Env(options); + const getSpy = vi.spyOn(service, "get"); + + await expect(service.load()).rejects.toThrow(error); + expect(getSpy).not.toHaveBeenCalled(); + }, + ); + + test.each([ + { secretKeyId: 0, secretKey: decryptionKey.secretKey }, + { secretKeyId: -1, secretKey: decryptionKey.secretKey }, + { secretKeyId: Number.NaN, secretKey: decryptionKey.secretKey }, + { secretKeyId: decryptionKey.secretKeyId, secretKey: "" }, + ])("rejects an invalid explicit decryption key %#", async (invalidKey) => { + const service = createService({ decryptionKey: invalidKey }); + const getSpy = vi.spyOn(service, "get"); + + await expect(service.load()).rejects.toThrow( + "The Hyphen ENV key is invalid.", + ); + expect(getSpy).not.toHaveBeenCalled(); + }); + }); + + describe("failures are atomic", () => { + test("rejects a failed key-store response without mutating process.env", async () => { + process.env.UNCHANGED = "before"; + const service = createService(); + vi.spyOn(service, "get").mockResolvedValue( + response({ message: "unauthorized" }, 401, "Unauthorized"), + ); + + await expect(service.load()).rejects.toThrow( + "Failed to fetch the Hyphen ENV key: HTTP 401", + ); + + expect(process.env.UNCHANGED).toBe("before"); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }); + + test.each([ + null, + {}, + { key: null }, + { key: {} }, + { key: { secret_key_id: "not-a-number", secret_key: "secret" } }, + { key: { secret_key_id: 1, secret_key: "" } }, + { key: { secret_key_id: 1, secret_key: 123 } }, + ])("rejects a malformed key-store payload %#", async (payload) => { + const service = createService(); + vi.spyOn(service, "get").mockResolvedValue(response(payload)); + + await expect(service.load()).rejects.toThrow( + "Failed to fetch the Hyphen ENV key:", + ); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }); + + test("rejects a failed Horizon response without mutating process.env", async () => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue( + response({ message: "unavailable" }, 503, "Service Unavailable"), + ); + + await expect(service.load()).rejects.toThrow( + 'Failed to fetch Hyphen ENV "default": HTTP 503', + ); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }); + + test.each([null, {}, { data: null }, { data: 123 }])( + "rejects a malformed Horizon payload %#", + async (payload) => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue(response(payload)); + + await expect(service.load()).rejects.toThrow( + 'Failed to fetch Hyphen ENV "default":', + ); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }, + ); + + test.each(["not-base64!", "A", "AA=", "AB", "AAECAwQFBgcICQ=="])( + "rejects malformed or truncated ciphertext %s", + async (data) => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue(response({ data })); + + await expect(service.load()).rejects.toThrow( + 'Failed to decrypt or parse Hyphen ENV "default".', + ); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }, + ); + + test("rejects decrypted bytes that are not valid UTF-8", async () => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue( + response({ data: encryptBytesLikeHx(Uint8Array.of(0xff)) }), + ); + + await expect(service.load()).rejects.toThrow( + 'Failed to decrypt or parse Hyphen ENV "default".', + ); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }); + + test.each([ + "SAFE_VALUE=before\nBAD\0NAME=value\n", + "SAFE_VALUE=before\nBAD_VALUE=value\0suffix\n", + ])( + "rejects process-incompatible variables atomically", + async (contents) => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue(mockEnvResponse(contents)); + + await expect(service.load()).rejects.toThrow( + "Hyphen ENV contains a variable that cannot be added to process.env.", + ); + expect(process.env.SAFE_VALUE).toBeUndefined(); + }, + ); + + test("accepts empty and comment-only ENV documents", async () => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockResolvedValue( + mockEnvResponse("# This environment intentionally has no variables.\n"), + ); + + await expect(service.load()).resolves.toEqual({}); + }); + + test("rejects ciphertext when required base64url padding is missing", async () => { + const service = createService({ decryptionKey }); + const data = encryptLikeHx("UNPADDED=yes\n").replace(/=+$/, ""); + vi.spyOn(service, "get").mockResolvedValue(response({ data })); + + await expect(service.load()).rejects.toThrow( + 'Failed to decrypt or parse Hyphen ENV "default".', + ); + }); + + test("does not apply a valid default ENV when the named ENV fails", async () => { + process.env.UNCHANGED = "before"; + const service = createService({ decryptionKey }); + vi.spyOn(service, "get") + .mockResolvedValueOnce(mockEnvResponse("DEFAULT_ONLY=base\n")) + .mockResolvedValueOnce( + response({ message: "not found" }, 404, "Not Found"), + ); + + await expect(service.load(productionEnvironment)).rejects.toThrow( + 'Failed to fetch Hyphen ENV "production": HTTP 404', + ); + + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + expect(process.env.UNCHANGED).toBe("before"); + }); + + test("sanitizes request failures without mutating process.env", async () => { + const service = createService({ decryptionKey }); + const sensitiveDetail = `network down: ${decryptionKey.secretKey}`; + vi.spyOn(service, "get").mockRejectedValue(new Error(sensitiveDetail)); + + const error = await service.load().catch((caught) => caught as Error); + expect(error.message).toBe( + 'Failed to fetch Hyphen ENV "default": Request failed.', + ); + expect(error.message).not.toContain(decryptionKey.secretKey); + expect(process.env.DEFAULT_ONLY).toBeUndefined(); + }); + + test("uses a stable message for a non-Error request rejection", async () => { + const service = createService({ decryptionKey }); + vi.spyOn(service, "get").mockRejectedValue("network down"); + + await expect(service.load()).rejects.toThrow( + 'Failed to fetch Hyphen ENV "default": Request failed.', + ); + }); + }); +}); diff --git a/packages/nodejs-sdk/test/env.test.ts b/packages/nodejs-sdk/test/env.test.ts new file mode 100644 index 0000000..4550cc5 --- /dev/null +++ b/packages/nodejs-sdk/test/env.test.ts @@ -0,0 +1,66 @@ +import process from "node:process"; +import { describe, expect, test } from "vitest"; +import { env, loadEnv } from "../src/env.js"; + +describe("ENV", () => { + test("should be able to load the environment", () => { + loadEnv(); + expect(process.env.HYPHEN_PUBLIC_API_KEY).toBeDefined(); + expect(process.env.HYPHEN_APPLICATION_ID).toBeDefined(); + }); + + test("should be able to load multiple environments", () => { + loadEnv({ path: "./test/fixtures/env-file-load" }); + expect(process.env.KEY_ID).toBe("default_key_id"); + }); + + test("should be able to load multiple environments not local", () => { + delete process.env.KEY_ID; + expect(process.env.KEY_ID).toBeUndefined(); + loadEnv({ + path: "./test/fixtures/env-file-load", + environment: "development", + local: false, + }); + expect(process.env.KEY_ID).toBe("development_key_id"); + }); + + test("should be able to load multiple environments and local", () => { + delete process.env.KEY_ID; + expect(process.env.KEY_ID).toBeUndefined(); + loadEnv({ + path: "./test/fixtures/env-file-load", + environment: "development", + }); + expect(process.env.KEY_ID).toBe("development_key_id_local"); + }); + + test("should be able to load the environment", () => { + env(); + expect(process.env.HYPHEN_PUBLIC_API_KEY).toBeDefined(); + expect(process.env.HYPHEN_APPLICATION_ID).toBeDefined(); + }); + + test("should be able to load multiple environments", () => { + env({ path: "./test/fixtures/env-file-load" }); + expect(process.env.KEY_ID).toBe("default_key_id"); + }); + + test("should be able to load multiple environments not local", () => { + delete process.env.KEY_ID; + expect(process.env.KEY_ID).toBeUndefined(); + env({ + path: "./test/fixtures/env-file-load", + environment: "development", + local: false, + }); + expect(process.env.KEY_ID).toBe("development_key_id"); + }); + + test("should be able to load multiple environments and local", () => { + delete process.env.KEY_ID; + expect(process.env.KEY_ID).toBeUndefined(); + env({ path: "./test/fixtures/env-file-load", environment: "development" }); + expect(process.env.KEY_ID).toBe("development_key_id_local"); + }); +}); diff --git a/packages/nodejs-sdk/test/execution-context-integration.test.ts b/packages/nodejs-sdk/test/execution-context-integration.test.ts new file mode 100644 index 0000000..5de2ee4 --- /dev/null +++ b/packages/nodejs-sdk/test/execution-context-integration.test.ts @@ -0,0 +1,39 @@ +import { Cacheable } from "cacheable"; +import { describe, expect, test } from "vitest"; +import { env } from "../src/env.js"; +import { getExecutionContext } from "../src/execution-context.js"; + +env(); + +const apiKey = process.env.HYPHEN_API_KEY; +const organizationId = process.env.HYPHEN_ORGANIZATION_ID; +const testTimeout = 10_000; + +describe("getExecutionContext integration", () => { + test.skipIf(!apiKey)( + "should fetch execution context from live API", + async () => { + const context = await getExecutionContext(apiKey as string); + expect(context).toBeDefined(); + expect(context.user).toBeDefined(); + expect(context.member).toBeDefined(); + expect(context.member?.organization).toBeDefined(); + }, + testTimeout, + ); + + test.skipIf(apiKey === undefined && organizationId === undefined)( + "should fetch organization level execution context from live API", + async () => { + const context = await getExecutionContext(apiKey as string, { + organizationId, + cache: new Cacheable(), + }); + expect(context).toBeDefined(); + expect(context.user).toBeDefined(); + expect(context.member).toBeDefined(); + expect(context.organization).toBeDefined(); + }, + testTimeout, + ); +}); diff --git a/packages/nodejs-sdk/test/execution-context.test.ts b/packages/nodejs-sdk/test/execution-context.test.ts new file mode 100644 index 0000000..a6de7c6 --- /dev/null +++ b/packages/nodejs-sdk/test/execution-context.test.ts @@ -0,0 +1,111 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { getExecutionContext } from "../src/execution-context.js"; + +// Shared mock state that can be configured per test +const mockState: { + getResponse: { + response: { status: number; statusText?: string }; + data: Record | null; + }; + getCalls: Array<[string, unknown]>; +} = { + getResponse: { + response: { status: 200 }, + data: { organization: { id: "default-org" } }, + }, + getCalls: [], +}; + +// Mock for CacheableNet +vi.mock("@cacheable/net", () => { + return { + CacheableNet: class MockCacheableNet { + async get(url: string, config: unknown) { + mockState.getCalls.push([url, config]); + return mockState.getResponse; + } + }, + }; +}); + +describe("getExecutionContext", () => { + beforeEach(() => { + // Reset mock state before each test + mockState.getResponse = { + response: { status: 200 }, + data: { organization: { id: "default-org" } }, + }; + mockState.getCalls = []; + }); + + test("should throw an error if apiKey is not provided", async () => { + await expect(getExecutionContext("")).rejects.toThrow( + "API key is required", + ); + }); + + test("should fetch execution context successfully with mocked response", async () => { + mockState.getResponse = { + response: { status: 200 }, + data: { + organization: { id: "org-123", name: "Test Org" }, + user: { id: "user-123", name: "Test User" }, + }, + }; + + const context = await getExecutionContext("test-api-key"); + + expect(context).toBeDefined(); + expect(context.organization).toEqual({ id: "org-123", name: "Test Org" }); + expect(context.user).toEqual({ id: "user-123", name: "Test User" }); + expect(mockState.getCalls.length).toBe(1); + expect(mockState.getCalls[0][0]).toBe( + "https://api.hyphen.ai/api/execution-context", + ); + const callConfig = mockState.getCalls[0][1] as { + headers: Record; + }; + expect(callConfig.headers["x-api-key"]).toBe("test-api-key"); + expect(callConfig.headers["content-type"]).toBe("application/json"); + expect(callConfig.headers.accept).toBe("application/json"); + }); + + test("should include organizationId in URL when provided", async () => { + mockState.getResponse = { + response: { status: 200 }, + data: { organization: { id: "org-456" } }, + }; + + await getExecutionContext("test-api-key", { organizationId: "org-456" }); + + expect(mockState.getCalls[0][0]).toBe( + "https://api.hyphen.ai/api/execution-context?organizationId=org-456", + ); + }); + + test("should use custom baseUri when provided", async () => { + mockState.getResponse = { + response: { status: 200 }, + data: { organization: { id: "org-789" } }, + }; + + await getExecutionContext("test-api-key", { + baseUri: "https://custom.api.com", + }); + + expect(mockState.getCalls[0][0]).toBe( + "https://custom.api.com/api/execution-context", + ); + }); + + test("should throw an error when response status is not 200", async () => { + mockState.getResponse = { + response: { status: 401, statusText: "Unauthorized" }, + data: null, + }; + + await expect(getExecutionContext("invalid-api-key")).rejects.toThrow( + "Failed to get execution context: Unauthorized", + ); + }); +}); diff --git a/packages/nodejs-sdk/test/fixtures/env-file-load/.env b/packages/nodejs-sdk/test/fixtures/env-file-load/.env new file mode 100644 index 0000000..c50bbc0 --- /dev/null +++ b/packages/nodejs-sdk/test/fixtures/env-file-load/.env @@ -0,0 +1,2 @@ +KEY_ID=default_key_id +GLOBAL_API_KEY=global_api_key \ No newline at end of file diff --git a/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development new file mode 100644 index 0000000..5ebcb4b --- /dev/null +++ b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development @@ -0,0 +1 @@ +KEY_ID=development_key_id \ No newline at end of file diff --git a/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development.local b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development.local new file mode 100644 index 0000000..d4df7a6 --- /dev/null +++ b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.development.local @@ -0,0 +1 @@ +KEY_ID=development_key_id_local \ No newline at end of file diff --git a/packages/nodejs-sdk/test/fixtures/env-file-load/.env.local b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.local new file mode 100644 index 0000000..c50bbc0 --- /dev/null +++ b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.local @@ -0,0 +1,2 @@ +KEY_ID=default_key_id +GLOBAL_API_KEY=global_api_key \ No newline at end of file diff --git a/packages/nodejs-sdk/test/fixtures/env-file-load/.env.production b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.production new file mode 100644 index 0000000..148f93f --- /dev/null +++ b/packages/nodejs-sdk/test/fixtures/env-file-load/.env.production @@ -0,0 +1 @@ +KEY_ID=production_key_id \ No newline at end of file diff --git a/packages/nodejs-sdk/test/hyphen.test.ts b/packages/nodejs-sdk/test/hyphen.test.ts new file mode 100644 index 0000000..574dd94 --- /dev/null +++ b/packages/nodejs-sdk/test/hyphen.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, test, vi } from "vitest"; +import { Env } from "../src/env-service.js"; +import { Hyphen } from "../src/hyphen.js"; +import { Link } from "../src/link.js"; +import { NetInfo } from "../src/net-info.js"; +import { Toggle } from "../src/toggle.js"; + +describe("Hyphen", () => { + test("should create an instance of Hyphen", () => { + const hyphen = new Hyphen(); + expect(hyphen).toBeInstanceOf(Hyphen); + }); + + test("should accept options in the constructor", () => { + const options = { publicApiKey: "test-key" }; + const hyphen = new Hyphen(options); + expect(hyphen).toBeInstanceOf(Hyphen); + }); + + test("should have a netInfo property", () => { + const hyphen = new Hyphen(); + expect(hyphen.netInfo).toBeDefined(); + expect(hyphen.netInfo).toBeInstanceOf(NetInfo); + }); + + test("should have a toggle property", () => { + const hyphen = new Hyphen(); + expect(hyphen.toggle).toBeDefined(); + expect(hyphen.toggle).toBeInstanceOf(Toggle); + }); + + test("should have a link property", () => { + const hyphen = new Hyphen(); + expect(hyphen.link).toBeDefined(); + expect(hyphen.link).toBeInstanceOf(Link); + }); + + test("should have an env property", () => { + const hyphen = new Hyphen(); + expect(hyphen.env).toBeDefined(); + expect(hyphen.env).toBeInstanceOf(Env); + }); + + test("should accept nested env service options", () => { + const hyphen = new Hyphen({ + env: { + applicationId: "app-id", + organizationId: "org-id", + projectId: "project-id", + }, + }); + + expect(hyphen.env).toBeInstanceOf(Env); + }); + + test("should allow setting and getting publicApiKey", () => { + const publicApiKey = "public_api_key"; + const hyphen = new Hyphen({ publicApiKey }); + expect(hyphen.publicApiKey).toBe(publicApiKey); + + const newPublicApiKey = "public_new_api_key"; + hyphen.publicApiKey = newPublicApiKey; + expect(hyphen.publicApiKey).toBe(newPublicApiKey); + }); + + test("should allow setting and getting apiKey", () => { + const apiKey = "api_key"; + const hyphen = new Hyphen({ apiKey }); + expect(hyphen.apiKey).toBe(apiKey); + expect(hyphen.env.apiKey).toBe(apiKey); + + const newApiKey = "new_api_key"; + hyphen.apiKey = newApiKey; + expect(hyphen.apiKey).toBe(newApiKey); + expect(hyphen.env.apiKey).toBe(newApiKey); + }); +}); + +describe("Hyphen Emitters", () => { + test("should emit env error events", () => { + const hyphen = new Hyphen(); + hyphen.on("error", () => {}); + const errorSpy = vi.spyOn(hyphen, "emit"); + hyphen.env.error("Test error"); + expect(errorSpy).toHaveBeenCalledWith("error", "Test error"); + }); + + test("should emit env warn events", () => { + const hyphen = new Hyphen(); + const warnSpy = vi.spyOn(hyphen, "emit"); + hyphen.env.warn("Test warn"); + expect(warnSpy).toHaveBeenCalledWith("warn", "Test warn"); + }); + + test("should emit env info events", () => { + const hyphen = new Hyphen(); + const infoSpy = vi.spyOn(hyphen, "emit"); + hyphen.env.info("Test info"); + expect(infoSpy).toHaveBeenCalledWith("info", "Test info"); + }); + + test("should emit link error events", () => { + const hyphen = new Hyphen(); + hyphen.on("error", () => {}); + const errorSpy = vi.spyOn(hyphen.link, "emit"); + hyphen.link.error("Test error"); + expect(errorSpy).toHaveBeenCalledWith("error", "Test error"); + }); + + test("should emit link warn events", () => { + const hyphen = new Hyphen(); + const warnSpy = vi.spyOn(hyphen, "emit"); + hyphen.link.warn("Test warn"); + expect(warnSpy).toHaveBeenCalledWith("warn", "Test warn"); + }); + + test("should emit link info events", () => { + const hyphen = new Hyphen(); + const infoSpy = vi.spyOn(hyphen, "emit"); + hyphen.link.info("Test info"); + expect(infoSpy).toHaveBeenCalledWith("info", "Test info"); + }); + + test("should emit netInfo error events", () => { + const hyphen = new Hyphen(); + hyphen.on("error", () => {}); + const errorSpy = vi.spyOn(hyphen, "emit"); + hyphen.netInfo.error("Test error"); + expect(errorSpy).toHaveBeenCalledWith("error", "Test error"); + }); + + test("should emit netInfo warn events", () => { + const hyphen = new Hyphen(); + const warnSpy = vi.spyOn(hyphen, "emit"); + hyphen.netInfo.warn("Test warn"); + expect(warnSpy).toHaveBeenCalledWith("warn", "Test warn"); + }); + + test("should emit netInfo info events", () => { + const hyphen = new Hyphen(); + const infoSpy = vi.spyOn(hyphen, "emit"); + hyphen.netInfo.info("Test info"); + expect(infoSpy).toHaveBeenCalledWith("info", "Test info"); + }); + + test("should emit toggle error events", () => { + const hyphen = new Hyphen(); + hyphen.on("error", () => {}); + const errorSpy = vi.spyOn(hyphen, "emit"); + hyphen.toggle.emit("error", "Test error"); + expect(errorSpy).toHaveBeenCalledWith("error", "Test error"); + }); + + test("should emit toggle warn events", () => { + const hyphen = new Hyphen(); + const warnSpy = vi.spyOn(hyphen, "emit"); + hyphen.toggle.emit("warn", "Test warn"); + expect(warnSpy).toHaveBeenCalledWith("warn", "Test warn"); + }); + + test("should emit toggle info events", () => { + const hyphen = new Hyphen(); + const infoSpy = vi.spyOn(hyphen, "emit"); + hyphen.toggle.emit("info", "Test info"); + expect(infoSpy).toHaveBeenCalledWith("info", "Test info"); + }); + + test("should emit toggle info events", () => { + const hyphen = new Hyphen(); + const infoSpy = vi.spyOn(hyphen, "emit"); + hyphen.toggle.emit("info", "Test info"); + expect(infoSpy).toHaveBeenCalledWith("info", "Test info"); + }); +}); diff --git a/packages/nodejs-sdk/test/index.test.ts b/packages/nodejs-sdk/test/index.test.ts new file mode 100644 index 0000000..a33b329 --- /dev/null +++ b/packages/nodejs-sdk/test/index.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from "vitest"; +import { Env, Toggle } from "../src/index.js"; + +describe("Hyphen sdk", () => { + test("should create an instance of Toggle", () => { + const toggle = new Toggle({ + applicationId: "my-app", + publicApiKey: "public_my-public-key", + environment: "development", + }); + expect(toggle).toBeInstanceOf(Toggle); + }); + + test("should export the ENV service", () => { + const env = new Env({ apiKey: "test-api-key" }); + expect(env).toBeInstanceOf(Env); + }); +}); diff --git a/packages/nodejs-sdk/test/link.test.ts b/packages/nodejs-sdk/test/link.test.ts new file mode 100644 index 0000000..da91146 --- /dev/null +++ b/packages/nodejs-sdk/test/link.test.ts @@ -0,0 +1,760 @@ +import process from "node:process"; +import { faker } from "@faker-js/faker"; +import { describe, expect, test } from "vitest"; +import { type CreateQrCodeOptions, Link, QrSize } from "../src/link.js"; + +const apiKey: string = process.env.HYPHEN_API_KEY ?? "test-api-key"; +const organizationId: string = + process.env.HYPHEN_ORGANIZATION_ID ?? "test-organization-id"; +const linkDomain: string = process.env.HYPHEN_LINK_DOMAIN ?? "test.domain.com"; +const tags: string[] = ["sdk-test", "unit-test"]; +const longUrl = [ + "https://hyphen.ai", + "https://hyphen.ai/env", + "https://hyphen.ai/link", + "https://hyphen.ai/toggle", + "https://hyphen.ai/net-info", +]; +const testTimeout = 30_000; + +// biome-ignore lint/suspicious/noExportsInTest: this is used across tests +export function getRandomLongUrl(): string { + return longUrl[Math.floor(Math.random() * longUrl.length)]; +} + +/** + * Retry a live API call with a backoff. The link API is eventually + * consistent, so operations that run immediately after a write (creating a + * QR code or reading, updating, or deleting a code right after it was + * created) can transiently fail with a 404 until the write is visible to the + * read path. Wrapping those calls keeps transient failures from flaking the + * suite. Callers can also throw from `fn` when a result is incomplete (for + * example a list that does not include a just-created item yet) to poll + * until it is. + */ +async function retry(fn: () => Promise, attempts = 5): Promise { + let lastError: unknown; + for (let attempt = 1; attempt <= attempts; attempt++) { + try { + return await fn(); + } catch (error) { + lastError = error; + if (attempt < attempts) { + await new Promise((resolve) => setTimeout(resolve, 500 * attempt)); + } + } + } + + throw lastError; +} + +/** + * Best-effort removal of a short code created by a test. Cleanup is not the + * behavior under test (the delete tests assert deletion explicitly), so a + * cleanup failure logs a warning instead of failing the test. + */ +async function cleanupShortCode(link: Link, id: string): Promise { + try { + await retry(() => link.deleteShortCode(id)); + } catch { + console.warn(`Cleanup failed for ${id}`); + } +} + +describe("Link", () => { + test("should create a Link instance with default URIs", () => { + const link = new Link({ organizationId, apiKey }); + expect(link.uris).toEqual([ + "https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/", + ]); + expect(link.organizationId).toBe(organizationId); + }); + + test("should create a Link instance with custom URIs", () => { + const customUris = ["https://custom.api/hyphen/link/codes/"]; + const link = new Link({ uris: customUris, organizationId, apiKey }); + expect(link.uris).toEqual(customUris); + }); + + test("should set and get organization ID", () => { + const link = new Link({ organizationId, apiKey }); + expect(link.organizationId).toBe(organizationId); + link.organizationId = "new-org"; + expect(link.organizationId).toBe("new-org"); + }); + + test("should set and get URIs", () => { + const link = new Link({ organizationId, apiKey }); + const newUris = ["https://new.api/hyphen/link/codes/"]; + link.uris = newUris; + expect(link.uris).toEqual(newUris); + }); + + test("should set and get API key", () => { + const link = new Link({ organizationId, apiKey }); + expect(link.apiKey).toBe(apiKey); + const newApiKey = "new-api-key"; + link.apiKey = newApiKey; + expect(link.apiKey).toBe(newApiKey); + }); + + test('should throw an error if API key starts with "public_"', () => { + const link = new Link({ organizationId, apiKey }); + expect(() => { + link.setApiKey("public_test-api-key"); + }).toThrow('API key cannot start with "public_"'); + }); + + test("should get the uri based on organization ID", () => { + const link = new Link({ organizationId, apiKey }); + const uri = link.getUri(organizationId); + expect(uri).toBe( + `https://api.hyphen.ai/api/organizations/${organizationId}/link/codes`, + ); + }); + + test("should handle if uri doesnt have forward slash and code is added", () => { + const link = new Link({ organizationId, apiKey }); + const code = "code_1234567890abcdef"; + + const uri = link.getUri(organizationId, code); + expect(uri).toBe( + `https://api.hyphen.ai/api/organizations/${organizationId}/link/codes/${code}`, + ); + + link.uris = [ + "https://api.hyphen.ai/api/organizations/{organizationId}/link/codes", + ]; + const uriWithoutSlash = link.getUri(organizationId, code); + expect(uriWithoutSlash).toBe( + `https://api.hyphen.ai/api/organizations/${organizationId}/link/codes/${code}`, + ); + }); +}); + +describe("Link Create", () => { + test( + "should create a short code with valid parameters", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const title = faker.string.alpha(10); + const options = { tags, title }; + + const response = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(response).toBeDefined(); + expect(response.id).toBeDefined(); + + if (response.id) { + await cleanupShortCode(link, response.id); + } + }, + testTimeout, + ); + + test("should throw on create a short code with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + + link.organizationId = undefined; // Clear organization ID to force an error + await expect( + link.createShortCode(longUrl, domain, options), + ).rejects.toThrow(); + }); +}); + +describe("Link Get", () => { + test( + "should get a list of short codes including tags and title", + async () => { + // Create a link instance + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const title = faker.string.alpha(10) as string; + const options = { tags, title }; + + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + expect(createResponse.title).toBe(title); + expect(createResponse.tags).toEqual(tags); + + // Poll until the just-created code is visible in the list, since the + // list can lag behind the create. + const response = await retry(async () => { + const result = await link.getShortCodes(title, tags); + if (result.total === 0) { + throw new Error(`Short code "${title}" is not visible in the list`); + } + + return result; + }); + + expect(response).toBeDefined(); + expect(response.total).toBeGreaterThan(0); + expect(response.pageNum).toBe(1); + expect(response.pageSize).toBe(100); + + // Delete the created short code + if (createResponse.id) { + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test( + "should get short codes without a title or tag filter", + async () => { + const link = new Link({ organizationId, apiKey }); + const response = await retry(() => link.getShortCodes("", [], 1, 10)); + expect(response).toBeDefined(); + expect(response.pageNum).toBe(1); + expect(response.pageSize).toBe(10); + }, + testTimeout, + ); + + test("should throw on get short codes with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + await expect(link.getShortCodes("invalid-title")).rejects.toThrow(); + }); + + test( + "should create a short code and get it by code", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.code).toBeDefined(); + expect(createResponse.long_url).toBe(longUrl); + expect(createResponse.domain).toBe(domain); + expect(createResponse.tags).toEqual(options.tags); + + // Retrieve the short code by ID + if (createResponse.id) { + const getResponse = await retry(() => + link.getShortCode(createResponse.id), + ); + expect(getResponse).toEqual(createResponse); + } + + if (createResponse.id) { + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test("should throw on get if no organization ID is set", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + + await expect(link.getShortCode(fakeCodeId)).rejects.toThrow(); + }); +}); + +describe("Link Delete", () => { + test( + "should create and delete a short code", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const deleteResponse = await retry(() => + link.deleteShortCode(createResponse.id), + ); + expect(deleteResponse).toBe(true); + } + }, + testTimeout, + ); + + test("should delete a short code with invalid organization Id", async () => { + const link = new Link({ organizationId, apiKey }); + const fakeCodeId = "code_1234567890abcdef"; + + link.organizationId = undefined; // Clear organization ID to force an error + await expect(link.deleteShortCode(fakeCodeId)).rejects.toThrow(); + }); +}); + +describe("Link Update", () => { + test("should throw on update short code with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + const fakeCodeId = "code_1234567890abcdef"; + const options = { title: "Updated Title", tags: ["updated-tag"] }; + + link.organizationId = undefined; // Clear organization ID to force an error + await expect(link.updateShortCode(fakeCodeId, options)).rejects.toThrow(); + }); + + test( + "create a short code and update it", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const title = faker.string.alpha(10); + const options = { tags, title }; + + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const updateOptions = { + title: "Updated Title", + tags: ["updated-tag"], + long_url: "https://updated.url", + }; + const updateResponse = await retry(() => + link.updateShortCode(createResponse.id, updateOptions), + ); + + expect(updateResponse).toBeDefined(); + expect(updateResponse.title).toBe("Updated Title"); + expect(updateResponse.tags).toEqual(["updated-tag"]); + expect(updateResponse.long_url).toBe("https://updated.url"); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); +}); + +describe("Link Tags", () => { + test( + "should get tags for the organization", + async () => { + const link = new Link({ organizationId, apiKey }); + const tags = await retry(() => link.getTags()); + expect(tags).toBeDefined(); + expect(Array.isArray(tags)).toBe(true); + }, + testTimeout, + ); + + test( + "should throw on get tags with invalid organization ID", + async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + await expect(link.getTags()).rejects.toThrow(); + }, + testTimeout, + ); +}); + +describe("Link Stats", () => { + test( + "should get code stats for a short code", + async () => { + const link = new Link({ organizationId, apiKey }); + + // Use a short code owned by this test. Picking a random code from the + // organization is flaky: concurrent test runs (such as the CI matrix) + // create and delete their own temporary codes in the same + // organization, so a randomly picked code can be deleted by another + // run before the stats call resolves, which returns a 404. + const createResponse = await retry(() => + link.createShortCode(getRandomLongUrl(), linkDomain, { tags }), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + const codeStats = await retry(() => + link.getCodeStats( + createResponse.id, + new Date(Date.now() - 24 * 60 * 60 * 1000), + new Date(), + ), + ); + + expect(codeStats).toBeDefined(); + expect(codeStats.clicks).toBeDefined(); + expect(codeStats.referrals).toBeDefined(); + expect(codeStats.browsers).toBeDefined(); + expect(codeStats.devices).toBeDefined(); + expect(codeStats.locations).toBeDefined(); + + if (createResponse.id) { + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test("should throw on get code stats with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + await expect( + link.getCodeStats(fakeCodeId, new Date(), new Date()), + ).rejects.toThrow(); + }); +}); + +describe("Link QR Code", () => { + test( + "should create a QR code for a short code", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const qrCodeResponse = await retry(() => + link.createQrCode(createResponse.id), + ); + expect(qrCodeResponse).toBeDefined(); + expect(qrCodeResponse.qrCode).toBeDefined(); + expect(qrCodeResponse.qrLink).toBeDefined(); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + // The QR create endpoint consumes multipart/form-data, so the custom options + // (title/backgroundColor/color/size) are sent as form fields. This exercises + // that contract end-to-end against the live API. See issue #133. + test( + "should create a QR code with custom options", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const qrCodeOptions: CreateQrCodeOptions = { + title: "Custom QR Code", + backgroundColor: "#ffffff", + color: "#000000", + size: QrSize.MEDIUM, + }; + const qrCodeResponse = await retry(() => + link.createQrCode(createResponse.id, qrCodeOptions), + ); + expect(qrCodeResponse).toBeDefined(); + expect(qrCodeResponse.qrCode).toBeDefined(); + expect(qrCodeResponse.qrLink).toBeDefined(); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + // Coverage for the custom-options path of createQrCode without hitting the + // live API. The network layer is stubbed so the multipart body is built and + // the options-defined branches of the request are exercised. + test("should build a multipart body when creating a QR code with options", async () => { + const link = new Link({ organizationId, apiKey }); + const qrCodeOptions: CreateQrCodeOptions = { + title: "Custom QR Code", + backgroundColor: "#ffffff", + color: "#000000", + size: QrSize.MEDIUM, + logo: "bG9nbw==", + }; + + let capturedBody: FormData | undefined; + let capturedHeaders: Record | undefined; + // biome-ignore lint/suspicious/noExplicitAny: minimal stub of the post method + (link as any).post = async (_url: string, data: FormData, config: any) => { + capturedBody = data; + capturedHeaders = config?.headers; + return { + data: { + id: "qr_test", + qrCode: Buffer.from("qr").toString("base64"), + qrLink: "https://hyphen.ai/qr", + }, + status: 201, + statusText: "Created", + headers: {}, + config: undefined, + request: undefined, + }; + }; + + const response = await link.createQrCode("code_test", qrCodeOptions); + + expect(capturedBody).toBeInstanceOf(FormData); + expect(capturedBody?.get("title")).toBe("Custom QR Code"); + expect(capturedBody?.get("backgroundColor")).toBe("#ffffff"); + expect(capturedBody?.get("color")).toBe("#000000"); + expect(capturedBody?.get("size")).toBe("medium"); + const logo = capturedBody?.get("logo"); + expect(logo).toBeInstanceOf(Blob); + expect(await (logo as Blob).text()).toBe("logo"); + // The JSON content-type must be removed so the multipart boundary is set + // automatically by the underlying fetch call. + expect(capturedHeaders?.["content-type"]).toBeUndefined(); + expect(response.qrCode).toBeDefined(); + expect(response.qrCodeBytes).toBeInstanceOf(Uint8Array); + expect(Buffer.from(response.qrCodeBytes).toString()).toBe("qr"); + expect(response.qrLink).toBe("https://hyphen.ai/qr"); + }); + + // Coverage for the no-options path: the API rejects an empty multipart body, + // so an empty JSON payload is sent instead (keeping the JSON content-type). + test("should send an empty JSON body when creating a QR code without options", async () => { + const link = new Link({ organizationId, apiKey }); + + let capturedBody: unknown; + let capturedHeaders: Record | undefined; + // biome-ignore lint/suspicious/noExplicitAny: minimal stub of the post method + (link as any).post = async (_url: string, data: unknown, config: any) => { + capturedBody = data; + capturedHeaders = config?.headers; + return { + data: { + id: "qr_test", + qrCode: Buffer.from("qr").toString("base64"), + qrLink: "https://hyphen.ai/qr", + }, + status: 201, + statusText: "Created", + headers: {}, + config: undefined, + request: undefined, + }; + }; + + await link.createQrCode("code_test"); + + expect(capturedBody).toEqual({}); + expect(capturedBody).not.toBeInstanceOf(FormData); + expect(capturedHeaders?.["content-type"]).toBe("application/json"); + }); + + test("should throw on create QR code with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + await expect(link.createQrCode(fakeCodeId)).rejects.toThrow(); + }); + + test( + "should create multiple QR codes for a short code and get them", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const qrCode1 = await retry(() => link.createQrCode(createResponse.id)); + expect(qrCode1).toBeDefined(); + expect(qrCode1.qrCode).toBeDefined(); + expect(qrCode1.qrLink).toBeDefined(); + + const qrCode2 = await retry(() => link.createQrCode(createResponse.id)); + expect(qrCode2).toBeDefined(); + expect(qrCode2.qrCode).toBeDefined(); + expect(qrCode2.qrLink).toBeDefined(); + + // Poll until both QR codes are visible in the list. + const qrCodes = await retry(async () => { + const result = await link.getQrCodes(createResponse.id); + if (result.data.length < 2) { + throw new Error("QR codes are not visible in the list"); + } + + return result; + }); + expect(qrCodes).toBeDefined(); + expect(qrCodes.data.length).toBeGreaterThanOrEqual(2); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test("should throw on get QR codes with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + await expect(link.getQrCodes(fakeCodeId)).rejects.toThrow(); + }); + + test( + "should get QR codes for a short code with pagination", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + await retry(() => link.createQrCode(createResponse.id)); + await retry(() => link.createQrCode(createResponse.id)); + + // Poll until both QR codes are visible in the list. + const qrCodes = await retry(async () => { + const result = await link.getQrCodes(createResponse.id, 1, 10); + if (result.data.length < 2) { + throw new Error("QR codes are not visible in the list"); + } + + return result; + }); + expect(qrCodes).toBeDefined(); + expect(qrCodes.data.length).toBeGreaterThanOrEqual(2); + expect(qrCodes.pageNum).toBe(1); + expect(qrCodes.pageSize).toBe(10); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test( + "should create a QR code and then get it by ID", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const qrCodeResponse = await retry(() => + link.createQrCode(createResponse.id), + ); + expect(qrCodeResponse).toBeDefined(); + expect(qrCodeResponse.qrCode).toBeDefined(); + expect(qrCodeResponse.qrLink).toBeDefined(); + + const qrCodeById = await retry(() => + link.getQrCode(createResponse.id, qrCodeResponse.id), + ); + expect(qrCodeById.id).toEqual(qrCodeResponse.id); + + await cleanupShortCode(link, createResponse.id); + } + }, + testTimeout, + ); + + test("should throw on get QR code by ID with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + const fakeQrCodeId = "qr_code_1234567890abcdef"; + await expect(link.getQrCode(fakeCodeId, fakeQrCodeId)).rejects.toThrow(); + }); + + test( + "should delete a QR code by ID", + async () => { + const link = new Link({ organizationId, apiKey }); + const longUrl = getRandomLongUrl(); + const domain = linkDomain; + const options = { tags }; + const createResponse = await retry(() => + link.createShortCode(longUrl, domain, options), + ); + + expect(createResponse).toBeDefined(); + expect(createResponse.id).toBeDefined(); + + if (createResponse.id) { + const qrCodeResponse = await retry(() => + link.createQrCode(createResponse.id), + ); + expect(qrCodeResponse).toBeDefined(); + expect(qrCodeResponse.qrCode).toBeDefined(); + expect(qrCodeResponse.qrLink).toBeDefined(); + + const deleteQrCodeResponse = await retry(() => + link.deleteQrCode(createResponse.id, qrCodeResponse.id), + ); + expect(deleteQrCodeResponse).toBe(true); + + const deleteShortCodeResponse = await retry(() => + link.deleteShortCode(createResponse.id), + ); + expect(deleteShortCodeResponse).toBe(true); + } + }, + testTimeout, + ); + + test("should throw on delete QR code with invalid parameters", async () => { + const link = new Link({ organizationId, apiKey }); + link.organizationId = undefined; // Clear organization ID to force an error + const fakeCodeId = "code_1234567890abcdef"; + const fakeQrCodeId = "qr_code_1234567890abcdef"; + await expect(link.deleteQrCode(fakeCodeId, fakeQrCodeId)).rejects.toThrow(); + }); +}); diff --git a/packages/nodejs-sdk/test/mock-contexts.ts b/packages/nodejs-sdk/test/mock-contexts.ts new file mode 100644 index 0000000..a89cec2 --- /dev/null +++ b/packages/nodejs-sdk/test/mock-contexts.ts @@ -0,0 +1,225 @@ +import type { ToggleContext } from "../src/toggle.js"; + +/** + * Mock ToggleContext examples for testing purposes. + * These provide a variety of realistic scenarios for comprehensive test coverage. + */ +export const mockToggleContexts: ToggleContext[] = [ + // Basic context with minimal data + { + targetingKey: "user-123", + }, + + // Standard user context with email and basic attributes + { + targetingKey: "user-456", + ipAddress: "203.0.113.42", + user: { + id: "user-456", + email: "john.doe@example.com", + name: "John Doe", + }, + customAttributes: { + region: "us-west", + plan: "basic", + }, + }, + + // Premium user with extensive custom attributes + { + targetingKey: "premium-user-789", + ipAddress: "198.51.100.15", + user: { + id: "premium-user-789", + email: "jane.smith@company.com", + name: "Jane Smith", + customAttributes: { + role: "admin", + department: "engineering", + seniority: "senior", + permissions: ["read", "write", "delete"], + }, + }, + customAttributes: { + subscriptionLevel: "premium", + region: "us-east", + tier: "gold", + betaFeatures: true, + accountType: "business", + }, + }, + + // Mobile user context with device information + { + targetingKey: "mobile-user-321", + ipAddress: "192.168.1.100", + user: { + id: "mobile-user-321", + email: "mobile@user.com", + name: "Mobile User", + customAttributes: { + deviceType: "mobile", + os: "iOS", + appVersion: "2.1.0", + }, + }, + customAttributes: { + platform: "mobile", + region: "eu-west", + language: "en", + }, + }, + + // Enterprise user with complex organizational data + { + targetingKey: "enterprise-user-654", + ipAddress: "10.0.0.5", + user: { + id: "enterprise-user-654", + email: "admin@enterprise.com", + name: "Enterprise Admin", + customAttributes: { + role: "super-admin", + organizationId: "org-12345", + tenantId: "tenant-abc", + permissions: ["all"], + lastLogin: "2023-12-01T10:00:00Z", + }, + }, + customAttributes: { + subscriptionLevel: "enterprise", + region: "us-central", + industryVertical: "finance", + companySize: "large", + contractType: "annual", + }, + }, + + // Anonymous user context + { + targetingKey: "anonymous-987", + ipAddress: "172.16.0.25", + customAttributes: { + region: "ap-southeast", + sessionId: "sess_anonymous_123", + userAgent: "Mozilla/5.0", + referrer: "https://google.com", + }, + }, + + // Developer/QA testing context + { + targetingKey: "dev-user-111", + ipAddress: "127.0.0.1", + user: { + id: "dev-user-111", + email: "developer@test.com", + name: "Test Developer", + customAttributes: { + role: "developer", + team: "platform", + environment: "staging", + }, + }, + customAttributes: { + region: "us-west", + testMode: true, + debugEnabled: true, + featureFlags: ["new-ui", "beta-api"], + }, + }, + + // International user with localization data + { + targetingKey: "intl-user-888", + ipAddress: "185.199.108.153", + user: { + id: "intl-user-888", + email: "usuario@ejemplo.es", + name: "Marรญa Garcรญa", + customAttributes: { + locale: "es-ES", + timezone: "Europe/Madrid", + currency: "EUR", + }, + }, + customAttributes: { + region: "eu-south", + language: "spanish", + country: "Spain", + gdprConsent: true, + }, + }, + + // API/Service account context + { + targetingKey: "service-account-555", + ipAddress: "10.1.1.50", + user: { + id: "service-account-555", + email: "api@service.com", + name: "API Service Account", + customAttributes: { + accountType: "service", + apiVersion: "v2", + clientId: "client_12345", + }, + }, + customAttributes: { + region: "us-east", + serviceType: "api", + rateLimitTier: "premium", + authentication: "oauth2", + }, + }, + + // Edge case: User with numeric and special character data + { + targetingKey: "edge-case-user_999", + ipAddress: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + user: { + id: "edge-case-user_999", + email: "test+special@domain-name.co.uk", + name: "Test User-Name O'Connor", + customAttributes: { + userId: 12345, + score: 98.5, + isActive: true, + tags: ["vip", "beta-tester", "early-adopter"], + metadata: { + source: "referral", + campaign: "spring-2023", + }, + }, + }, + customAttributes: { + region: "ap-north", + numericId: 999, + percentage: 85.75, + enabled: false, + complexData: { + nested: { + value: "deep-nested-value", + array: [1, 2, 3], + }, + }, + }, + }, +]; + +/** + * Gets a random ToggleContext from the mock contexts array. + * Useful for testing with varied context data without hardcoding specific indices. + * + * @returns A randomly selected ToggleContext from the mockToggleContexts array + * + * @example + * ```typescript + * const randomContext = getRandomToggleContext(); + * const toggle = new Toggle({ defaultContext: randomContext }); + * ``` + */ +export function getRandomToggleContext(): ToggleContext { + const randomIndex = Math.floor(Math.random() * mockToggleContexts.length); + return mockToggleContexts[randomIndex]; +} diff --git a/packages/nodejs-sdk/test/net-info.test.ts b/packages/nodejs-sdk/test/net-info.test.ts new file mode 100644 index 0000000..7f3d146 --- /dev/null +++ b/packages/nodejs-sdk/test/net-info.test.ts @@ -0,0 +1,170 @@ +import process from "node:process"; +import { describe, expect, test, vi } from "vitest"; +import { ErrorMessages } from "../src/base-service.js"; +import { NetInfo } from "../src/net-info.js"; + +const validIpAddresses = ["1.1.1.1", "8.8.8.8", "2.2.2.2"]; + +const invalidIpAddresses = ["256.256.256.256", "123.456.789.0"]; + +const mixedIpAddresses = [...validIpAddresses, ...invalidIpAddresses]; + +const testTimeout = 10_000; + +describe("NetInfo", () => { + test("should create an instance of NetInfo", () => { + const netInfo = new NetInfo(); + expect(netInfo).toBeInstanceOf(NetInfo); + }); + + test("should have default properties", () => { + const netInfo = new NetInfo(); + expect(netInfo.log).toBeDefined(); + expect(netInfo.cache).toBeDefined(); + }); + + test("should allow setting and getting apiKey", () => { + const netInfo = new NetInfo({ apiKey: "test_api_key1" }); + expect(netInfo.apiKey).toBe("test_api_key1"); + netInfo.apiKey = "test_api_key2"; + expect(netInfo.apiKey).toBe("test_api_key2"); + }); + + test("should allow setting and getting baseUri", () => { + const netInfo = new NetInfo({ baseUri: "https://example.com" }); + expect(netInfo.baseUri).toBe("https://example.com"); + netInfo.baseUri = "https://another-example.com"; + expect(netInfo.baseUri).toBe("https://another-example.com"); + }); + + test("should throw an error if apiKey is not set", () => { + // Ensure that the environment variable is not set for this test + const originalApiKey = process.env.HYPHEN_API_KEY; + delete process.env.HYPHEN_API_KEY; + let didThrow = false; + try { + new NetInfo({ throwOnEmitError: true }); + } catch (error) { + expect(error).toEqual(new Error(ErrorMessages.API_KEY_REQUIRED)); + didThrow = true; + } + + expect(didThrow).toBe(true); + + // Restore the original environment variable + if (originalApiKey) { + process.env.HYPHEN_API_KEY = originalApiKey; + } + }); + + test("should throw an error if apiKey is set to public api key", () => { + // Ensure that the environment variable is not set for this test + const originalApiKey = process.env.HYPHEN_API_KEY; + delete process.env.HYPHEN_API_KEY; + let didThrow = false; + try { + new NetInfo({ + throwOnEmitError: true, + apiKey: "public_api_key", + }); + } catch (error) { + expect(error).toEqual( + new Error(ErrorMessages.PUBLIC_API_KEY_SHOULD_NOT_BE_USED), + ); + didThrow = true; + } + + expect(didThrow).toBe(true); + + // Restore the original environment variable + if (originalApiKey) { + process.env.HYPHEN_API_KEY = originalApiKey; + } + }); + + test("should fail to fetch IP info without API key", async () => { + // Ensure that the environment variable is not set for this test + const originalApiKey = process.env.HYPHEN_API_KEY; + delete process.env.HYPHEN_API_KEY; + let didThrow = false; + try { + const netInfo = new NetInfo({ throwOnEmitError: true }); + netInfo.apiKey = undefined; // Explicitly set apiKey to undefined + await netInfo.getIpInfo("1.1.1.1"); + } catch (error) { + expect(error).toEqual(new Error(ErrorMessages.API_KEY_REQUIRED)); + didThrow = true; + } + + expect(didThrow).toBe(true); + // Restore the original environment variable + if (originalApiKey) { + process.env.HYPHEN_API_KEY = originalApiKey; + } + }); + + test( + "should fetch IP info failure", + async () => { + // API key should be set in the environment variable HYPHEN_API_KEY + const netInfo = new NetInfo(); + netInfo.on("error", () => {}); + const invalidIpAddress = + invalidIpAddresses[ + Math.floor(Math.random() * invalidIpAddresses.length) + ]; + const ipInfo = await netInfo.getIpInfo(invalidIpAddress); + expect(ipInfo).toBeDefined(); + expect(ipInfo).toHaveProperty("ip", invalidIpAddress); + expect(ipInfo).toHaveProperty("type"); + }, + testTimeout, + ); + + test("should fetch IP info successfully", async () => { + // API key should be set in the environment variable HYPHEN_API_KEY + const netInfo = new NetInfo(); + const validIpAddress = + validIpAddresses[Math.floor(Math.random() * validIpAddresses.length)]; + const ipInfo = await netInfo.getIpInfo(validIpAddress); + expect(ipInfo).toBeDefined(); + expect(ipInfo).toHaveProperty("ip", validIpAddress); + expect(ipInfo).toHaveProperty("location"); + }); + + test("should fetch multiple IP infos successfully", async () => { + // API key should be set in the environment variable HYPHEN_API_KEY + const netInfo = new NetInfo(); + const ipInfos = await netInfo.getIpInfos(mixedIpAddresses); + expect(ipInfos).toBeDefined(); + expect(ipInfos.length).toBe(mixedIpAddresses.length); + for (const [index, ipInfo] of ipInfos.entries()) { + if (validIpAddresses.includes(mixedIpAddresses[index])) { + expect(ipInfo).toHaveProperty("ip", mixedIpAddresses[index]); + expect(ipInfo).toHaveProperty("location"); + } else { + expect(ipInfo).toHaveProperty("type"); + } + } + }); + + test("should handle empty IP array gracefully", async () => { + const netInfo = new NetInfo(); + netInfo.on("error", () => {}); + const ipInfos = await netInfo.getIpInfos([]); + expect(ipInfos).toBeDefined(); + expect(ipInfos.length).toBe(0); + }); + + test("should return an error result when the request throws", async () => { + const netInfo = new NetInfo({ apiKey: "test_api_key" }); + netInfo.on("error", () => {}); + // With @cacheable/net returning non-2xx responses instead of throwing, + // force a thrown error to exercise the catch path. + netInfo.get = vi.fn().mockRejectedValue(new Error("network down")); + const ipInfo = await netInfo.getIpInfo("1.1.1.1"); + expect(ipInfo).toHaveProperty("ip", "1.1.1.1"); + expect(ipInfo).toHaveProperty("type", "error"); + expect(ipInfo).toHaveProperty("errorMessage", "network down"); + }); +}); diff --git a/packages/nodejs-sdk/test/toggle-evals.test.ts b/packages/nodejs-sdk/test/toggle-evals.test.ts new file mode 100644 index 0000000..0ae8c44 --- /dev/null +++ b/packages/nodejs-sdk/test/toggle-evals.test.ts @@ -0,0 +1,297 @@ +import process from "node:process"; +import { describe, expect, test } from "vitest"; +import { Toggle, type ToggleContext } from "../src/toggle.js"; + +/* +hyphen-sdk-boolean +hyphen-sdk-json +hyphen-sdk-number +hyphen-sdk-string +*/ + +try { + process.loadEnvFile(); +} catch { + // .env file doesn't exist, skip silently +} + +const hyphenPublicApiKey = process.env.HYPHEN_PUBLIC_API_KEY; +const hyphenApplicationId = process.env.HYPHEN_APPLICATION_ID; + +const defaultTimeout = 10_000; + +// check that we have values + +if (!hyphenPublicApiKey || !hyphenApplicationId) { + console.warn("You need HYPHEN_PUBLIC_API_KEY and HYPHEN_APPLICATION_ID"); +} + +const context: ToggleContext = { + targetingKey: "user-123", + ipAddress: "203.0.113.42", + customAttributes: { + subscriptionLevel: "premium", + region: "us-east", + }, + user: { + id: "user-123", + email: "john.doe@example.com", + name: "John Doe", + customAttributes: { + role: "admin", + }, + }, +}; + +describe("Toggle Evaluations", () => { + test( + "Getting a string", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.get( + "hyphen-sdk-string", + "fake-default-value-123", + ); + + expect(result).toBe("Hyphen!"); + }, + defaultTimeout, + ); + + test( + "getBoolean helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getBoolean("hyphen-sdk-boolean", false); + + expect(typeof result).toBe("boolean"); + expect(result).toBe(true); + }, + defaultTimeout, + ); + + test( + "getString helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getString( + "hyphen-sdk-string", + "default-string", + ); + + expect(typeof result).toBe("string"); + expect(result).toBe("Hyphen!"); + }, + defaultTimeout, + ); + + test( + "getNumber helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getNumber("hyphen-sdk-number", 0); + + expect(typeof result).toBe("number"); + expect(result).toBe(42); + }, + defaultTimeout, + ); + + test( + "getObject helper method", + async () => { + const toggle = new Toggle(); + toggle.publicApiKey = hyphenPublicApiKey; + toggle.applicationId = hyphenApplicationId; + toggle.defaultContext = context; + + const result = await toggle.getObject("hyphen-sdk-json", {}); + + // The toggle returns a JSON string, so we expect a string type + expect(typeof result).toBe("string"); + expect(result).toBe('{ "id": "Hello World!"}'); + + // Verify it's valid JSON + const parsed = JSON.parse(result as string); + expect(parsed).toEqual({ id: "Hello World!" }); + }, + defaultTimeout, + ); + + describe("get method error handling", () => { + test( + "should return defaultValue when no publicApiKey is set", + async () => { + const toggle = new Toggle({ + applicationId: "test-app", + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "default-value"); + expect(result).toBe("default-value"); + }, + defaultTimeout, + ); + + test( + "should return defaultValue when no defaultContext and no context option", + async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "test-app", + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "fallback"); + expect(result).toBe("fallback"); + }, + defaultTimeout, + ); + + test( + "should return defaultValue when application is empty", + async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "", + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "default"); + expect(result).toBe("default"); + }, + defaultTimeout, + ); + + test("should set targetingKey when context has no targetingKey", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultTargetKey: "fallback-key", + }); + + const result = await toggle.get("hyphen-sdk-string", "default", { + context: { user: { id: "user-123" } }, + }); + + expect(typeof result).toBe("string"); + }); + + test("should handle fetch failures gracefully", async () => { + const toggle = new Toggle({ + publicApiKey: "public_invalid-key", + applicationId: "test-app", + defaultContext: { targetingKey: "test" }, + horizonUrls: ["https://invalid-domain.test"], + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "fallback-value"); + expect(result).toBe("fallback-value"); + }); + + test("should handle missing toggle in response", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("non-existent-toggle", "not-found"); + expect(result).toBe("not-found"); + }); + + test("should use provided context with all properties", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + }); + + // This should trigger lines 244-247 (options?.context branch) + const customContext: ToggleContext = { + targetingKey: "custom-targeting", + ipAddress: "192.168.1.1", + user: { id: "custom-user", email: "test@example.com" }, + customAttributes: { role: "tester" }, + }; + + const result = await toggle.get("hyphen-sdk-string", "default", { + context: customContext, + }); + + expect(typeof result).toBe("string"); + }); + + test("should handle application validation error", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: undefined, // This will cause validation to fail + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + + test("should copy context properties correctly when no options.context", async () => { + const toggle = new Toggle({ + publicApiKey: hyphenPublicApiKey, + applicationId: hyphenApplicationId, + defaultContext: { + targetingKey: "default-targeting", + ipAddress: "127.0.0.1", + user: { id: "default-user" }, + customAttributes: { plan: "basic" }, + }, + }); + + // This should trigger lines 249-252 (else branch, using defaultContext) + const result = await toggle.get("hyphen-sdk-string", "default"); + expect(typeof result).toBe("string"); + }); + + test("should handle application validation error when applicationId is empty", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + applicationId: "", // This will cause validation to fail + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + + test("should handle application validation error when applicationId is undefined", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + // No applicationId provided, will be undefined -> "" + defaultContext: { targetingKey: "test" }, + }); + toggle.on("error", () => {}); + + const result = await toggle.get("test-toggle", "validation-failed"); + expect(result).toBe("validation-failed"); + }); + }); +}); diff --git a/packages/nodejs-sdk/test/toggle-methods.test.ts b/packages/nodejs-sdk/test/toggle-methods.test.ts new file mode 100644 index 0000000..50b4e29 --- /dev/null +++ b/packages/nodejs-sdk/test/toggle-methods.test.ts @@ -0,0 +1,594 @@ +import process from "node:process"; +import { describe, expect, test } from "vitest"; +import { Toggle } from "../src/toggle.js"; + +const baseMockUrl = process.env.BASE_MOCK_URL ?? "https://mockhttp.org"; + +const testTimeout = 10_000; + +describe("getOrgIdFromPublicKey", () => { + test("should extract org ID from valid public key", () => { + const toggle = new Toggle(); + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + }); + + test("should handle public key without prefix", () => { + const toggle = new Toggle(); + const orgId = "org-without-prefix"; + const keyWithoutPrefix = Buffer.from(`${orgId}:secret-data`).toString( + "base64", + ); + expect(toggle.getOrgIdFromPublicKey(keyWithoutPrefix)).toBe(orgId); + }); + + test("should return undefined for malformed base64", () => { + const toggle = new Toggle(); + expect( + toggle.getOrgIdFromPublicKey("public_invalid-base64!"), + ).toBeUndefined(); + }); + + test("should return undefined for empty decoded content", () => { + const toggle = new Toggle(); + const emptyKey = `public_${Buffer.from("").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(emptyKey)).toBeUndefined(); + }); + + test("should return undefined for decoded content without colon", () => { + const toggle = new Toggle(); + const keyWithoutColon = `public_${Buffer.from("orgidwithoutcolon").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithoutColon)).toBe( + "orgidwithoutcolon", + ); + }); + + test("should handle org ID with valid characters", () => { + const toggle = new Toggle(); + const orgId = "valid_org-123"; + const validKey = `public_${Buffer.from(`${orgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + }); + + test("should return undefined for org ID with invalid characters", () => { + const toggle = new Toggle(); + const invalidOrgId = "org@invalid#chars"; + const invalidKey = `public_${Buffer.from(`${invalidOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(invalidKey)).toBeUndefined(); + }); + + test("should handle org ID with spaces (invalid)", () => { + const toggle = new Toggle(); + const orgIdWithSpaces = "org with spaces"; + const keyWithSpaces = `public_${Buffer.from(`${orgIdWithSpaces}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithSpaces)).toBeUndefined(); + }); + + test("should handle multiple colons in decoded content", () => { + const toggle = new Toggle(); + const orgId = "multi-colon-org"; + const keyWithMultipleColons = `public_${Buffer.from(`${orgId}:secret:extra:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(keyWithMultipleColons)).toBe(orgId); + }); + + test("should handle empty org ID", () => { + const toggle = new Toggle(); + const emptyOrgKey = `public_${Buffer.from(":secret-data").toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(emptyOrgKey)).toBeUndefined(); + }); + + test("should handle numeric org ID", () => { + const toggle = new Toggle(); + const numericOrgId = "123456"; + const numericKey = `public_${Buffer.from(`${numericOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(numericKey)).toBe(numericOrgId); + }); + + test("should handle very long org ID", () => { + const toggle = new Toggle(); + const longOrgId = "a".repeat(100); + const longKey = `public_${Buffer.from(`${longOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(longKey)).toBe(longOrgId); + }); + + test("should handle single character org ID", () => { + const toggle = new Toggle(); + const singleCharOrgId = "a"; + const singleCharKey = `public_${Buffer.from(`${singleCharOrgId}:data`).toString("base64")}`; + expect(toggle.getOrgIdFromPublicKey(singleCharKey)).toBe(singleCharOrgId); + }); + + test("should return undefined for null input", () => { + const toggle = new Toggle(); + expect(() => + toggle.getOrgIdFromPublicKey(null as unknown as string), + ).not.toThrow(); + }); + + test("should return undefined for undefined input", () => { + const toggle = new Toggle(); + expect(() => + toggle.getOrgIdFromPublicKey(undefined as unknown as string), + ).not.toThrow(); + }); + + test("should handle edge case with only public_ prefix", () => { + const toggle = new Toggle(); + expect(toggle.getOrgIdFromPublicKey("public_")).toBeUndefined(); + }); + + test("should use Buffer fallback when atob is not available", () => { + const toggle = new Toggle(); + const orgId = "fallback-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + + // Temporarily remove atob to force Buffer fallback + const originalAtob = globalThis.atob; + // @ts-expect-error - Intentionally setting to undefined for testing + globalThis.atob = undefined; + + try { + expect(toggle.getOrgIdFromPublicKey(validKey)).toBe(orgId); + } finally { + // Restore original atob + globalThis.atob = originalAtob; + } + }); +}); + +describe("fetch method", () => { + test("should throw error when horizon URLs array is explicitly empty", async () => { + const toggle = new Toggle({ horizonUrls: [] }); + await expect(toggle.fetch("/api/test")).rejects.toThrow( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + }); + + test("should throw error when horizon URLs array is empty", async () => { + const toggle = new Toggle({ horizonUrls: [] }); + await expect(toggle.fetch("/api/test")).rejects.toThrow( + "No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.", + ); + }); + + test( + "should successfully make POST request to mockhttp.org", + async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + body: Record; + } + + const result = await toggle.fetch("/post", { + test: "data", + }); + expect(result.method).toBe("POST"); + expect(result.headers).toBeDefined(); + expect(result.body).toBeDefined(); + }, + testTimeout, + ); + + test("should handle 404 error response from mockhttp.org", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + await expect( + toggle.fetch("/status/404", { test: "error" }), + ).rejects.toThrow("HTTP 404"); + }); + + test("should handle 500 error response from mockhttp.org", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + await expect( + toggle.fetch("/status/500", { test: "error" }), + ).rejects.toThrow("HTTP 500"); + }); + + test("should return typed JSON response with request body", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpPostResponse { + method: string; + body: { + test: string; + number: number; + }; + } + + const result = await toggle.fetch("/post", { + test: "hello", + number: 42, + }); + expect(result.method).toBe("POST"); + expect(result.body.test).toBe("hello"); + expect(result.body.number).toBe(42); + }); + + test("should include x-api-key header when publicApiKey is set", async () => { + const toggle = new Toggle({ + publicApiKey: "public_test-key", + horizonUrls: [baseMockUrl], + }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch("/post", { + test: "auth", + }); + expect(result.method).toBe("POST"); + expect(result.headers["x-api-key"]).toBe("public_test-key"); + }); + + test("should include custom headers in request", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "custom" }, + { + headers: { "X-Custom-Header": "test-value" }, + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-custom-header"]).toBe("test-value"); + }); + + test("should work with path without leading slash", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const result = await toggle.fetch("post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should work with path with leading slash", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should try multiple horizon URLs on failure", async () => { + const toggle = new Toggle({ + horizonUrls: [ + "https://invalid-url-that-should-fail.example", + baseMockUrl, + ], + }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should fail when all horizon URLs are invalid", async () => { + const toggle = new Toggle({ + horizonUrls: [ + "https://invalid-url-1.example", + "https://invalid-url-2.example", + ], + }); + + await expect(toggle.fetch("/test", { test: "data" })).rejects.toThrow( + "All horizon URLs failed", + ); + }); + + test("should handle URLs with trailing slashes correctly", async () => { + const toggle = new Toggle({ horizonUrls: [`${baseMockUrl}/`] }); + + const result = await toggle.fetch("/post", { test: "data" }); + expect(result).toBeDefined(); + }); + + test("should handle Headers object in request options", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + const headers = new Headers(); + headers.set("X-Test-Header", "headers-object-value"); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "headers" }, + { + headers: headers, + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-test-header"]).toBe("headers-object-value"); + }); + + test("should handle array headers in request options", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + headers: Record; + } + + const result = await toggle.fetch( + "/post", + { test: "array" }, + { + headers: [ + ["X-Array-Header", "array-value"], + ["X-Another-Header", "another-value"], + ], + }, + ); + + expect(result.method).toBe("POST"); + expect(result.headers["x-array-header"]).toBe("array-value"); + expect(result.headers["x-another-header"]).toBe("another-value"); + }); + + test("should handle non-Error exceptions in fetch method", async () => { + const toggle = new Toggle({ + horizonUrls: ["https://invalid-domain-that-does-not-exist.test"], + }); + + // Mock fetch to throw a non-Error value + const originalFetch = global.fetch; + global.fetch = (() => { + throw "string error"; // Non-Error exception + }) as typeof fetch; + + try { + await expect(toggle.fetch("/test", { test: "data" })).rejects.toThrow( + "All horizon URLs failed", + ); + } finally { + // Restore original fetch + global.fetch = originalFetch; + } + }); + + test("should send payload as JSON in request body", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + name: string; + age: number; + active: boolean; + }; + } + + const payload = { name: "test-user", age: 25, active: true }; + const result = await toggle.fetch("/post", payload); + + expect(result.method).toBe("POST"); + expect(result.body.name).toBe("test-user"); + expect(result.body.age).toBe(25); + expect(result.body.active).toBe(true); + }); + + test("should handle undefined payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: unknown; + } + + const result = await toggle.fetch("/post", undefined, { + body: JSON.stringify({ default: "body" }), + }); + expect(result.method).toBe("POST"); + }); + + test("should handle null payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: unknown; + } + + const result = await toggle.fetch("/post", null, { + body: JSON.stringify({ default: "body" }), + }); + expect(result.method).toBe("POST"); + }); + + test("should handle complex nested payload", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + user: { + profile: { + name: string; + preferences: string[]; + }; + }; + metadata: Record; + }; + } + + const complexPayload = { + user: { + profile: { + name: "complex-user", + preferences: ["dark-mode", "notifications"], + }, + }, + metadata: { + version: "1.0", + feature_flags: { newUI: true }, + }, + }; + + const result = await toggle.fetch( + "/post", + complexPayload, + ); + + expect(result.method).toBe("POST"); + expect(result.body.user.profile.name).toBe("complex-user"); + expect(result.body.user.profile.preferences).toEqual([ + "dark-mode", + "notifications", + ]); + expect(result.body.metadata.version).toBe("1.0"); + }); + + test("should prioritize payload over options.body when both provided", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + source: string; + }; + } + + const result = await toggle.fetch( + "/post", + { source: "payload" }, + { + body: JSON.stringify({ source: "options" }), + }, + ); + + expect(result.method).toBe("POST"); + expect(result.body.source).toBe("payload"); + }); + + test("should fall back to options.body when payload is undefined", async () => { + const toggle = new Toggle({ horizonUrls: [baseMockUrl] }); + + interface MockHttpResponse { + method: string; + body: { + source: string; + }; + } + + const result = await toggle.fetch("/post", undefined, { + body: JSON.stringify({ source: "options" }), + }); + + expect(result.method).toBe("POST"); + expect(result.body.source).toBe("options"); + }); +}); + +describe("buildDefaultHorizonUrl", () => { + test("should build URL with org ID from valid public key", () => { + const toggle = new Toggle(); + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(validKey)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL when org ID cannot be extracted", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("invalid-key")).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for malformed base64", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("public_invalid-base64!")).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should build URL with complex org ID", () => { + const toggle = new Toggle(); + const orgId = "my-org-123_test"; + const validKey = `public_${Buffer.from(`${orgId}:secret-data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(validKey)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL for org ID with invalid characters", () => { + const toggle = new Toggle(); + const invalidOrgId = "org@invalid#chars"; + const invalidKey = `public_${Buffer.from(`${invalidOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(invalidKey)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for empty org ID", () => { + const toggle = new Toggle(); + const emptyOrgKey = `public_${Buffer.from(":secret-data").toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(emptyOrgKey)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should build URL with numeric org ID", () => { + const toggle = new Toggle(); + const numericOrgId = "123456"; + const numericKey = `public_${Buffer.from(`${numericOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(numericKey)).toBe( + `https://${numericOrgId}.toggle.hyphen.cloud`, + ); + }); + + test("should build URL with single character org ID", () => { + const toggle = new Toggle(); + const singleCharOrgId = "a"; + const singleCharKey = `public_${Buffer.from(`${singleCharOrgId}:data`).toString("base64")}`; + expect(toggle.getDefaultHorizonUrl(singleCharKey)).toBe( + `https://${singleCharOrgId}.toggle.hyphen.cloud`, + ); + }); + + test("should return default URL for null input", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl(null as unknown as string)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for undefined input", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl(undefined as unknown as string)).toBe( + "https://toggle.hyphen.cloud", + ); + }); + + test("should return default URL for empty string", () => { + const toggle = new Toggle(); + expect(toggle.getDefaultHorizonUrl("")).toBe("https://toggle.hyphen.cloud"); + }); + + test("should handle key without prefix", () => { + const toggle = new Toggle(); + const orgId = "no-prefix-org"; + const keyWithoutPrefix = Buffer.from(`${orgId}:secret-data`).toString( + "base64", + ); + expect(toggle.getDefaultHorizonUrl(keyWithoutPrefix)).toBe( + `https://${orgId}.toggle.hyphen.cloud`, + ); + }); +}); diff --git a/packages/nodejs-sdk/test/toggle.test.ts b/packages/nodejs-sdk/test/toggle.test.ts new file mode 100644 index 0000000..a2f046d --- /dev/null +++ b/packages/nodejs-sdk/test/toggle.test.ts @@ -0,0 +1,683 @@ +import { Cacheable } from "cacheable"; +import { describe, expect, test, vi } from "vitest"; +import { Toggle, type ToggleOptions } from "../src/toggle.js"; +import { getRandomToggleContext, mockToggleContexts } from "./mock-contexts.js"; + +describe("Hyphen sdk", () => { + test("should create an instance of Toggle", () => { + const toggle = new Toggle(); + expect(toggle).toBeInstanceOf(Toggle); + }); + + describe("constructor", () => { + test("should create Toggle with no options", () => { + const toggle = new Toggle(); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with undefined options", () => { + const toggle = new Toggle(undefined); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with empty options object", () => { + const options: ToggleOptions = {}; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBeUndefined(); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with defaultContext option", () => { + const customContext = getRandomToggleContext(); + const options: ToggleOptions = { + defaultContext: customContext, + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.ipAddress).toBe(customContext.ipAddress); + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should create Toggle with publicApiKey option", () => { + const options: ToggleOptions = { + publicApiKey: "public_test-api-key", + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBe("public_test-api-key"); + expect(toggle.defaultContext).toBeUndefined(); + }); + + test("should create Toggle with both defaultContext and publicApiKey options", () => { + const customContext = getRandomToggleContext(); + const options: ToggleOptions = { + defaultContext: customContext, + publicApiKey: "public_comprehensive-key", + }; + const toggle = new Toggle(options); + expect(toggle).toBeInstanceOf(Toggle); + expect(toggle.publicApiKey).toBe("public_comprehensive-key"); + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.user?.email).toBe( + customContext.user?.email, + ); + }); + + test("should not validate publicApiKey in constructor", () => { + const options: ToggleOptions = { + publicApiKey: "invalid-key-without-prefix", + }; + expect(() => { + new Toggle(options); + }).not.toThrow(); + const toggle = new Toggle(options); + expect(toggle.publicApiKey).toBe("invalid-key-without-prefix"); + }); + }); + + describe("publicApiKey property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should allow getting the publicApiKey property", () => { + const toggle = new Toggle(); + const apiKey = toggle.publicApiKey; + expect(apiKey).toBeUndefined(); + }); + + test("should allow setting the publicApiKey property", () => { + const toggle = new Toggle(); + const testApiKey = "public_test-api-key-123"; + toggle.publicApiKey = testApiKey; + expect(toggle.publicApiKey).toBe(testApiKey); + }); + + test("should allow setting publicApiKey to undefined", () => { + const toggle = new Toggle(); + toggle.publicApiKey = "public_test-key"; + toggle.publicApiKey = undefined; + expect(toggle.publicApiKey).toBeUndefined(); + }); + + test("should maintain the same publicApiKey value when accessed multiple times", () => { + const toggle = new Toggle(); + const testApiKey = "public_consistent-api-key"; + toggle.publicApiKey = testApiKey; + const key1 = toggle.publicApiKey; + const key2 = toggle.publicApiKey; + expect(key1).toBe(key2); + expect(key1).toBe(testApiKey); + }); + + test("should update publicApiKey property when set to a new value", () => { + const toggle = new Toggle(); + const originalKey = "public_original-key"; + const newKey = "public_new-key"; + toggle.publicApiKey = originalKey; + expect(toggle.publicApiKey).toBe(originalKey); + toggle.publicApiKey = newKey; + expect(toggle.publicApiKey).toBe(newKey); + expect(toggle.publicApiKey).not.toBe(originalKey); + }); + + test("should throw error when publicApiKey does not start with 'public_'", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = "invalid-key"; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should throw error when publicApiKey starts with different prefix", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = "private_some-key"; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should throw error when publicApiKey is empty string", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = ""; + }).toThrow("Public API key must start with 'public_'"); + }); + + test("should accept publicApiKey that starts with 'public_'", () => { + const toggle = new Toggle(); + const validKey = "public_valid-key-123"; + expect(() => { + toggle.publicApiKey = validKey; + }).not.toThrow(); + expect(toggle.publicApiKey).toBe(validKey); + }); + + test("should accept undefined publicApiKey without throwing", () => { + const toggle = new Toggle(); + expect(() => { + toggle.publicApiKey = undefined; + }).not.toThrow(); + expect(toggle.publicApiKey).toBeUndefined(); + }); + }); + + describe("defaultContext property", () => { + test("should return undefined when no defaultContext is set", () => { + const toggle = new Toggle(); + const context = toggle.defaultContext; + expect(context).toBeUndefined(); + }); + + test("should allow getting the defaultContext property", () => { + const toggle = new Toggle(); + const context = toggle.defaultContext; + expect(context).toBeUndefined(); + }); + + test("should allow setting the defaultContext property", () => { + const toggle = new Toggle(); + const customContext = getRandomToggleContext(); + toggle.defaultContext = customContext; + expect(toggle.defaultContext).toBe(customContext); + expect(toggle.defaultContext?.targetingKey).toBe( + customContext.targetingKey, + ); + expect(toggle.defaultContext?.ipAddress).toBe(customContext.ipAddress); + }); + + test("should maintain the same defaultContext when accessed multiple times", () => { + const toggle = new Toggle(); + const customContext = getRandomToggleContext(); + toggle.defaultContext = customContext; + const context1 = toggle.defaultContext; + const context2 = toggle.defaultContext; + expect(context1).toBe(context2); + }); + + test("should update defaultContext property when set to a new value", () => { + const toggle = new Toggle(); + const originalContext = toggle.defaultContext; // undefined + const newContext = getRandomToggleContext(); + toggle.defaultContext = newContext; + expect(toggle.defaultContext).not.toBe(originalContext); + expect(toggle.defaultContext).toBe(newContext); + expect(toggle.defaultContext?.targetingKey).toBe(newContext.targetingKey); + }); + + test("should handle complex defaultContext with all properties", () => { + const toggle = new Toggle(); + // Using specific index for edge case user to test complex nested data structures + const complexContext = mockToggleContexts[9]; + toggle.defaultContext = complexContext; + expect(toggle.defaultContext).toBe(complexContext); + expect(toggle.defaultContext?.user?.customAttributes?.tags).toEqual([ + "vip", + "beta-tester", + "early-adopter", + ]); + expect(toggle.defaultContext?.customAttributes?.complexData).toEqual({ + nested: { + value: "deep-nested-value", + array: [1, 2, 3], + }, + }); + }); + }); + + describe("horizonUrls property", () => { + test("should return default url", () => { + const toggle = new Toggle(); + expect(toggle.horizonUrls).toEqual(["https://toggle.hyphen.cloud"]); + }); + + test("should be set when constructor receives horizonUrls option", () => { + const testUrls = [ + "https://org1.toggle.hyphen.cloud", + "https://org2.toggle.hyphen.cloud", + ]; + const toggle = new Toggle({ horizonUrls: testUrls }); + expect(toggle.horizonUrls).toEqual(testUrls); + }); + + test("should remain empty when constructor receives no horizonUrls", () => { + const toggle = new Toggle({ publicApiKey: "public_test-key" }); + expect(toggle.horizonUrls).toEqual(["https://toggle.hyphen.cloud"]); + }); + + test("should allow getting the horizonUrls property", () => { + const toggle = new Toggle(); + const urls = toggle.horizonUrls; + expect(urls).toEqual(["https://toggle.hyphen.cloud"]); + expect(Array.isArray(urls)).toBe(true); + }); + + test("should allow setting the horizonUrls property", () => { + const toggle = new Toggle(); + const testUrls = ["https://test.toggle.hyphen.cloud"]; + toggle.horizonUrls = testUrls; + expect(toggle.horizonUrls).toEqual(testUrls); + }); + + test("should allow setting horizonUrls to empty array", () => { + const toggle = new Toggle(); + const testUrls = ["https://test.toggle.hyphen.cloud"]; + toggle.horizonUrls = testUrls; + toggle.horizonUrls = []; + expect(toggle.horizonUrls).toEqual([]); + }); + + test("should maintain the same horizonUrls array when accessed multiple times", () => { + const toggle = new Toggle(); + const testUrls = [ + "https://endpoint1.hyphen.cloud", + "https://endpoint2.hyphen.cloud", + ]; + toggle.horizonUrls = testUrls; + const urls1 = toggle.horizonUrls; + const urls2 = toggle.horizonUrls; + expect(urls1).toBe(urls2); + expect(urls1).toEqual(testUrls); + }); + + test("should update horizonUrls property when set to a new array", () => { + const toggle = new Toggle(); + const originalUrls = ["https://original.hyphen.cloud"]; + const newUrls = [ + "https://new1.hyphen.cloud", + "https://new2.hyphen.cloud", + ]; + toggle.horizonUrls = originalUrls; + expect(toggle.horizonUrls).toEqual(originalUrls); + toggle.horizonUrls = newUrls; + expect(toggle.horizonUrls).toEqual(newUrls); + expect(toggle.horizonUrls).not.toEqual(originalUrls); + }); + + test("should handle single URL in array", () => { + const toggle = new Toggle(); + const singleUrl = ["https://single.toggle.hyphen.cloud"]; + toggle.horizonUrls = singleUrl; + expect(toggle.horizonUrls).toEqual(singleUrl); + expect(toggle.horizonUrls.length).toBe(1); + }); + + test("should handle multiple URLs with different formats", () => { + const toggle = new Toggle(); + const mixedUrls = [ + "https://prod.toggle.hyphen.cloud", + "http://staging.toggle.hyphen.cloud", + "https://org-123.toggle.hyphen.cloud", + "https://api.custom-domain.com/toggle", + ]; + toggle.horizonUrls = mixedUrls; + expect(toggle.horizonUrls).toEqual(mixedUrls); + expect(toggle.horizonUrls.length).toBe(4); + }); + + test("should handle very large URL array", () => { + const toggle = new Toggle(); + const largeUrlArray = Array.from( + { length: 100 }, + (_, i) => `https://endpoint-${i}.toggle.hyphen.cloud`, + ); + toggle.horizonUrls = largeUrlArray; + expect(toggle.horizonUrls).toEqual(largeUrlArray); + expect(toggle.horizonUrls.length).toBe(100); + }); + + test("should not interfere with other properties", () => { + const testOrgId = "test-org"; + const validKey = `public_${Buffer.from(`${testOrgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + const testUrls = ["https://test.hyphen.cloud"]; + const testContext = getRandomToggleContext(); + + toggle.horizonUrls = testUrls; + toggle.defaultContext = testContext; + + expect(toggle.horizonUrls).toEqual(testUrls); + expect(toggle.defaultContext).toBe(testContext); + expect(toggle.organizationId).toBe(testOrgId); + }); + + test("should work with constructor containing all options", () => { + const testUrls = [ + "https://primary.toggle.hyphen.cloud", + "https://secondary.toggle.hyphen.cloud", + ]; + const testContext = getRandomToggleContext(); + const toggle = new Toggle({ + publicApiKey: "public_test-comprehensive-key", + defaultContext: testContext, + horizonUrls: testUrls, + }); + + expect(toggle.horizonUrls).toEqual(testUrls); + expect(toggle.defaultContext).toBe(testContext); + expect(toggle.publicApiKey).toBe("public_test-comprehensive-key"); + }); + + test("should handle URLs with query parameters and paths", () => { + const toggle = new Toggle(); + const complexUrls = [ + "https://api.hyphen.cloud/v1/toggle?version=latest", + "https://cdn.hyphen.cloud/toggle/endpoint", + "https://backup.hyphen.cloud:8443/api/toggle", + ]; + toggle.horizonUrls = complexUrls; + expect(toggle.horizonUrls).toEqual(complexUrls); + }); + }); + + describe("applicationId property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.applicationId).toBeUndefined(); + }); + + test("should be set when constructor receives applicationId option", () => { + const toggle = new Toggle({ applicationId: "test-app" }); + expect(toggle.applicationId).toBe("test-app"); + }); + + test("should allow getting the applicationId property", () => { + const toggle = new Toggle(); + const appId = toggle.applicationId; + expect(appId).toBeUndefined(); + }); + + test("should allow setting the applicationId property", () => { + const toggle = new Toggle(); + const testAppId = "my-application"; + toggle.applicationId = testAppId; + expect(toggle.applicationId).toBe(testAppId); + }); + + test("should allow setting applicationId to undefined", () => { + const toggle = new Toggle(); + toggle.applicationId = "test-app"; + toggle.applicationId = undefined; + expect(toggle.applicationId).toBeUndefined(); + }); + }); + + describe("defaultTargetingKey property", () => { + test("should generate random key by default", () => { + const toggle = new Toggle(); + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + expect(toggle.defaultTargetingKey.length).toBeGreaterThan(0); + }); + + test("should be set when constructor receives defaultTargetKey option", () => { + const toggle = new Toggle({ + defaultTargetKey: "explicit-key", + }); + expect(toggle.defaultTargetingKey).toBe("explicit-key"); + }); + + test("should be set from defaultContext with targetingKey", () => { + const toggle = new Toggle({ + defaultContext: { targetingKey: "context-key" }, + }); + expect(toggle.defaultTargetingKey).toBe("context-key"); + }); + + test("should be set from defaultContext with user.id", () => { + const toggle = new Toggle({ + defaultContext: { + user: { id: "user-123" }, + }, + }); + expect(toggle.defaultTargetingKey).toBe("user-123"); + }); + + test("should generate key with applicationId and environment when no context", () => { + const toggle = new Toggle({ + applicationId: "test-app", + environment: "production", + }); + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-production-[a-z0-9]+$/, + ); + }); + + test("should prefer defaultTargetKey option over defaultContext", () => { + const toggle = new Toggle({ + defaultTargetKey: "explicit-key", + defaultContext: { + targetingKey: "context-key", + }, + }); + expect(toggle.defaultTargetingKey).toBe("explicit-key"); + }); + + test("should prefer targetingKey over user.id in context", () => { + const toggle = new Toggle({ + defaultContext: { + targetingKey: "targeting-key", + user: { id: "user-123" }, + }, + }); + expect(toggle.defaultTargetingKey).toBe("targeting-key"); + }); + + test("should allow setting defaultTargetingKey property", () => { + const toggle = new Toggle(); + const originalKey = toggle.defaultTargetingKey; + toggle.defaultTargetingKey = "custom-key"; + expect(toggle.defaultTargetingKey).toBe("custom-key"); + expect(toggle.defaultTargetingKey).not.toBe(originalKey); + }); + + test("should generate different keys for different instances", () => { + const toggle1 = new Toggle(); + const toggle2 = new Toggle(); + expect(toggle1.defaultTargetingKey).not.toBe(toggle2.defaultTargetingKey); + }); + + test("should generate key with applicationId and default environment", () => { + const toggle = new Toggle({ + applicationId: "test-app", + }); + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-development-[a-z0-9]+$/, + ); + }); + + test("should generate key with environment only", () => { + const toggle = new Toggle({ + environment: "staging", + }); + expect(toggle.defaultTargetingKey).toMatch(/^staging-[a-z0-9]+$/); + }); + + test("should fall back to getTargetingKey when defaultContext returns to default", () => { + const toggle = new Toggle({ + defaultContext: {}, + }); + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + }); + + test("should generate key with environment when no applicationId", () => { + const toggle = new Toggle(); + // This triggers generateTargetKey() since no defaultContext is provided + expect(toggle.defaultTargetingKey).toMatch(/^development-[a-z0-9]+$/); + }); + + test("should handle empty string values in key generation", () => { + const toggle = new Toggle({ + applicationId: "", + environment: "", + }); + // Empty environment defaults to "development", empty app is filtered out + expect(toggle.defaultTargetingKey).toMatch(/^development-[a-z0-9]+$/); + }); + + test("should generate key when environment is explicitly set to empty", () => { + const toggle = new Toggle({ + applicationId: "test-app", + environment: "", + }); + // Empty environment defaults to "development" + expect(toggle.defaultTargetingKey).toMatch( + /^test-app-development-[a-z0-9]+$/, + ); + }); + + test("should handle environment set to undefined after construction", () => { + const toggle = new Toggle({ + applicationId: "test-app", + }); + + // Set environment to undefined to trigger the fallback branch + toggle.environment = undefined; + + // Set a new defaultContext to trigger regeneration via getTargetingKey + toggle.defaultContext = {}; + + // This should eventually trigger generateTargetKey with undefined environment + expect(toggle.defaultTargetingKey).toBeDefined(); + expect(typeof toggle.defaultTargetingKey).toBe("string"); + }); + }); + + describe("environment property", () => { + test("should return 'development' by default", () => { + const toggle = new Toggle(); + expect(toggle.environment).toBe("development"); + }); + + test("should be set when constructor receives environment option", () => { + const toggle = new Toggle({ environment: "production" }); + expect(toggle.environment).toBe("production"); + }); + + test("should allow getting the environment property", () => { + const toggle = new Toggle(); + const env = toggle.environment; + expect(env).toBe("development"); + }); + + test("should allow setting the environment property", () => { + const toggle = new Toggle(); + const testEnv = "staging"; + toggle.environment = testEnv; + expect(toggle.environment).toBe(testEnv); + }); + + test("should allow setting environment to undefined", () => { + const toggle = new Toggle(); + toggle.environment = "production"; + toggle.environment = undefined; + expect(toggle.environment).toBeUndefined(); + }); + }); + + describe("organizationId property", () => { + test("should return undefined by default", () => { + const toggle = new Toggle(); + expect(toggle.organizationId).toBeUndefined(); + }); + + test("should be set when constructor receives valid publicApiKey", () => { + const orgId = "test-org"; + const validKey = `public_${Buffer.from(`${orgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + expect(toggle.organizationId).toBe(orgId); + }); + + test("should remain undefined when constructor receives invalid publicApiKey", () => { + const toggle = new Toggle({ publicApiKey: "invalid-key" }); + expect(toggle.organizationId).toBeUndefined(); + }); + + test("should allow getting the organizationId property", () => { + const toggle = new Toggle(); + const orgId = toggle.organizationId; + expect(orgId).toBeUndefined(); + }); + + test("should maintain the same organizationId value when accessed multiple times", () => { + const testOrgId = "consistent-org-id"; + const validKey = `public_${Buffer.from(`${testOrgId}:some-secret`).toString("base64")}`; + const toggle = new Toggle({ publicApiKey: validKey }); + const orgId1 = toggle.organizationId; + const orgId2 = toggle.organizationId; + expect(orgId1).toBe(orgId2); + expect(orgId1).toBe(testOrgId); + }); + }); + + describe("cache property", () => { + test("should get the cache instance", () => { + const toggle = new Toggle(); + const cache = toggle.cache; + expect(cache).toBeInstanceOf(Cacheable); + }); + + test("should set the cache instance", () => { + const toggle = new Toggle(); + const customCache = new Cacheable({ ttl: 5000 }); + toggle.cache = customCache; + expect(toggle.cache).toBe(customCache); + }); + + test("should accept cache in constructor options", () => { + const customCache = new Cacheable({ ttl: 10000 }); + const toggle = new Toggle({ cache: customCache }); + expect(toggle.cache).toBe(customCache); + }); + + test("should allow updating cache after construction", () => { + const toggle = new Toggle(); + const firstCache = toggle.cache; + const newCache = new Cacheable({ ttl: 3000 }); + toggle.cache = newCache; + expect(toggle.cache).toBe(newCache); + expect(toggle.cache).not.toBe(firstCache); + }); + }); + + describe("get method", () => { + test("should return defaultValue when error occurs", async () => { + const toggle = new Toggle({ + horizonUrls: ["https://api.test.com"], + }); + toggle.on("error", () => {}); + + const result = await toggle.get("feature-flag", false); + expect(result).toBe(false); // Returns defaultValue when error occurs + }); + }); + + describe("fetch", () => { + test("should extract the status code from CacheableNet error messages", async () => { + const toggle = new Toggle({ horizonUrls: ["https://horizon.example"] }); + // @cacheable/net surfaces HTTP failures as errors whose message + // includes "status "; verify that code is parsed out. + toggle._net.fetch = vi + .fn() + .mockRejectedValue(new Error("Request failed with status 404")); + + await expect( + toggle.fetch("/toggle/evaluate", { key: "value" }), + ).rejects.toThrow( + "All horizon URLs failed. Last errors: HTTP 404: Request failed with status 404", + ); + }); + }); +}); diff --git a/packages/nodejs-sdk/tsconfig.json b/packages/nodejs-sdk/tsconfig.json new file mode 100644 index 0000000..d1fd6d0 --- /dev/null +++ b/packages/nodejs-sdk/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "outDir": "./dist", + "rootDir": "./src", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "declaration": true, + "isolatedDeclarations": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] + } \ No newline at end of file diff --git a/packages/nodejs-sdk/vitest.config.ts b/packages/nodejs-sdk/vitest.config.ts new file mode 100644 index 0000000..5dce5e0 --- /dev/null +++ b/packages/nodejs-sdk/vitest.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + sequence: { + concurrent: false, // run tests in each file sequentially + }, + coverage: { + // The lcov paths start at the repository root, so that Codecov finds each file. + reporter: ['text', 'json', ['lcov', { projectRoot: '../..' }]], + exclude: [ + 'dist/**', + 'src/index.ts', + 'vitest.config.ts', + 'src/link-stats-type.ts', + ], + }, + }, +}); diff --git a/packages/react-sdk/AGENTS.md b/packages/react-sdk/AGENTS.md new file mode 100644 index 0000000..3c5dc31 --- /dev/null +++ b/packages/react-sdk/AGENTS.md @@ -0,0 +1,38 @@ +# Hyphen React SDK + +## Package Manager +**Important**: This project uses `pnpm` instead of `npm` for package management. Always use `pnpm` commands when working with this codebase: + +- Install dependencies: `pnpm install` +- Run tests: `pnpm test` +- Run linting: `pnpm lint` +- Build the project: `pnpm build` + +## Development Guidelines + +### Testing +- Uses Vitest for testing framework +- Comprehensive test coverage including edge cases +- Tests cover both positive and negative scenarios +- Mock-friendly architecture for testing + +### Code Quality +- Uses Biome for linting and formatting +- TypeScript for type safety +- Follows consistent code style and patterns +- Error handling with graceful fallbacks + +### Architecture Patterns +- Extends Hookified for event-driven extensibility +- Uses dependency injection for network client +- Immutable configuration patterns +- Defensive programming with validation + +## Common Development Tasks + +### Adding New Features +1. Implement the feature in the main Toggle class +2. Add comprehensive unit tests +3. Update TypeScript types as needed +4. Run `pnpm test` to ensure all tests pass +5. Run `pnpm lint` to check code quality diff --git a/packages/react-sdk/CLAUDE.md b/packages/react-sdk/CLAUDE.md new file mode 100644 index 0000000..eef4bd2 --- /dev/null +++ b/packages/react-sdk/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md \ No newline at end of file diff --git a/packages/react-sdk/LICENSE b/packages/react-sdk/LICENSE new file mode 100644 index 0000000..5533221 --- /dev/null +++ b/packages/react-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Hyphen + +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. diff --git a/packages/react-sdk/README.md b/packages/react-sdk/README.md new file mode 100644 index 0000000..e2cded5 --- /dev/null +++ b/packages/react-sdk/README.md @@ -0,0 +1,264 @@ +![Hyphen AI](https://github.com/Hyphen/javascript-sdks/raw/main/logo.png) + +[![npm](https://img.shields.io/npm/v/@hyphen/react-sdk)](https://www.npmjs.com/package/@hyphen/react-sdk) +[![npm](https://img.shields.io/npm/dm/@hyphen/react-sdk)](https://www.npmjs.com/package/@hyphen/react-sdk) +[![license](https://img.shields.io/github/license/Hyphen/javascript-sdks)](https://github.com/Hyphen/javascript-sdks/blob/main/LICENSE) +[![tests](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml/badge.svg)](https://github.com/Hyphen/javascript-sdks/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/gh/Hyphen/javascript-sdks/graph/badge.svg)](https://codecov.io/gh/Hyphen/javascript-sdks) + +# Hyphen React SDK + +The Hyphen React SDK provides React components, hooks, and higher-order components (HOCs) for integrating Hyphen's feature flag and toggle service into your React applications. + +## Installation + +```bash +npm install @hyphen/react-sdk +``` + +## Quick Start + +The SDK provides three ways to integrate Hyphen into your React application: + +### 1. Higher-Order Component (HOC) Pattern + +Wrap your root component with `withToggleProvider()`: + +```tsx +import { withToggleProvider } from '@hyphen/react-sdk'; +import App from './App'; + +export default withToggleProvider({ + publicApiKey: 'public_...', + applicationId: 'my-app', + environment: 'production', + defaultContext: { + user: { + id: 'user-123', + email: 'user@example.com' + } + } +})(App); +``` + +### 2. Provider Component Pattern + +Use the `ToggleProvider` component directly: + +```tsx +import { ToggleProvider } from '@hyphen/react-sdk'; +import App from './App'; + +function Root() { + return ( + + + + ); +} +``` + +### 3. Using the `useToggle` Hook + +Access feature flags in any component: + +```tsx +import { useToggle } from '@hyphen/react-sdk'; + +function MyComponent() { + const toggle = useToggle(); + + // Get boolean feature flag + const isNewFeatureEnabled = toggle.getBoolean('new-feature', false); + + // Get string feature flag + const theme = toggle.getString('theme', 'light'); + + // Get number feature flag + const maxItems = toggle.getNumber('max-items', 10); + + // Get object feature flag + const config = toggle.getObject('ui-config', { layout: 'grid' }); + + return ( +
+ {isNewFeatureEnabled && } +

Theme: {theme}

+

Max Items: {maxItems}

+
+ ); +} +``` + +## Configuration Options + +All configuration options are passed to the Toggle instance from `@hyphen/browser-sdk`: + +| Option | Type | Required | Description | +|--------|------|----------|-------------| +| `publicApiKey` | string | Yes | Your Hyphen public API key (starts with `public_`) | +| `applicationId` | string | No | Application identifier | +| `environment` | string | No | Environment name (e.g., 'development', 'production') | +| `defaultContext` | object | No | Default evaluation context (user, targeting, etc.) | +| `horizonUrls` | string[] | No | Custom Horizon endpoint URLs for load balancing | +| `defaultTargetKey` | string | No | Default targeting key | + +### Default Context + +The `defaultContext` option allows you to set default user and targeting information: + +```tsx +{ + defaultContext: { + targetingKey: 'user-123', + user: { + id: 'user-123', + email: 'user@example.com', + name: 'John Doe', + customAttributes: { + plan: 'premium', + region: 'us-west' + } + }, + ipAddress: '192.168.1.1', + customAttributes: { + deviceType: 'mobile' + } + } +} +``` + +## API Reference + +### `ToggleProvider` + +React context provider component that creates and provides a Toggle instance. + +**Props:** Extends `ToggleOptions` from `@hyphen/browser-sdk` plus: +- `children`: ReactNode - Components to wrap with the provider + +### `withToggleProvider(options)` + +Higher-order component that wraps a component with `ToggleProvider`. + +**Parameters:** +- `options`: `ToggleOptions` - Configuration for the Toggle instance + +**Returns:** Function that accepts a component and returns a wrapped component + +### `useToggle()` + +React hook to access the Toggle instance from context. + +**Returns:** `Toggle` instance from `@hyphen/browser-sdk` + +**Throws:** Error if used outside of `ToggleProvider` + +### Toggle Methods + +The `Toggle` instance provides these methods: + +- `getBoolean(key, defaultValue, options?)` - Get a boolean feature flag +- `getString(key, defaultValue, options?)` - Get a string feature flag +- `getNumber(key, defaultValue, options?)` - Get a number feature flag +- `getObject(key, defaultValue, options?)` - Get an object feature flag +- `get(key, defaultValue, options?)` - Generic getter for any type + +All methods accept an optional `options` parameter for context overrides: + +```tsx +const isEnabled = toggle.getBoolean('feature-key', false, { + context: { + user: { id: 'different-user' } + } +}); +``` + +## TypeScript Support + +The SDK is written in TypeScript and provides full type definitions out of the box. + +```tsx +import type { ToggleProviderProps } from '@hyphen/react-sdk'; + +const config: ToggleProviderProps = { + publicApiKey: 'public_...', + applicationId: 'my-app', + children: +}; +``` + +## Examples + +### Conditional Rendering + +```tsx +function FeatureFlag({ flagKey, children }) { + const toggle = useToggle(); + const isEnabled = toggle.getBoolean(flagKey, false); + + return isEnabled ? <>{children} : null; +} + +// Usage + + + +``` + +### A/B Testing + +```tsx +function ABTest() { + const toggle = useToggle(); + const variant = toggle.getString('homepage-variant', 'control'); + + switch (variant) { + case 'variant-a': + return ; + case 'variant-b': + return ; + default: + return ; + } +} +``` + +### Dynamic Configuration + +```tsx +function ConfigurableComponent() { + const toggle = useToggle(); + const config = toggle.getObject('component-config', { + maxItems: 10, + showImages: true, + layout: 'grid' + }); + + return ( + + ); +} +``` + +# Contributing + +We welcome contributions to the Hyphen Node.js SDK! If you have an idea for a new feature, bug fix, or improvement, please follow the [Contribution](../../CONTRIBUTING.md) guidelines and our [Code of Conduct](../../CODE_OF_CONDUCT.md). + +# License and Copyright +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. +The copyright for this project is held by Hyphen, Inc. All rights reserved. \ No newline at end of file diff --git a/packages/react-sdk/biome.json b/packages/react-sdk/biome.json new file mode 100644 index 0000000..2b580b1 --- /dev/null +++ b/packages/react-sdk/biome.json @@ -0,0 +1,35 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "vcs": { + "enabled": false, + "clientKind": "git", + "useIgnoreFile": false + }, + "files": { + "ignoreUnknown": false, + "includes": ["src/**/*.ts", "src/**/*.tsx", "test/**/*.ts", "test/**/*.tsx"] + }, + "formatter": { + "enabled": true, + "indentStyle": "tab" + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + }, + "assist": { + "enabled": true, + "actions": { + "source": { + "organizeImports": "on" + } + } + } +} diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.json new file mode 100644 index 0000000..672d0fd --- /dev/null +++ b/packages/react-sdk/package.json @@ -0,0 +1,78 @@ +{ + "name": "@hyphen/react-sdk", + "version": "2.0.3", + "description": "Hyphen SDK for React", + "type": "module", + "main": "dist/index.mjs", + "module": "dist/index.mjs", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "types": "dist/index.d.mts", + "scripts": { + "lint": "biome check --write --error-on-warnings", + "test": "pnpm lint && vitest run --coverage", + "test:ci": "biome check --error-on-warnings && vitest run --coverage", + "build": "tsdown", + "clean": "rimraf ./dist node_modules coverage", + "prepublishOnly": "pnpm build" + }, + "keywords": [ + "hyphen", + "sdk", + "browser", + "react", + "javascript", + "typescript" + ], + "author": "Team Hyphen ", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Hyphen/javascript-sdks.git", + "directory": "packages/react-sdk" + }, + "engines": { + "node": ">=22.12.0" + }, + "devDependencies": { + "@biomejs/biome": "^2.6.4", + "@faker-js/faker": "^10.6.0", + "@testing-library/react": "^16.3.3", + "@types/node": "^22.20.5", + "@types/react": "^19.3.0", + "@vitest/coverage-v8": "^5.0.5", + "dotenv": "^18.0.9", + "happy-dom": "^21.0.4", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "rimraf": "^6.1.3", + "tsd": "^0.33.0", + "tsdown": "^0.23.4", + "typescript": "^7.0.2", + "vitest": "^5.0.5" + }, + "files": [ + "dist", + "LICENSE" + ], + "dependencies": { + "@hyphen/browser-sdk": "workspace:^" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0" + }, + "homepage": "https://github.com/Hyphen/javascript-sdks/tree/main/packages/react-sdk#readme", + "bugs": { + "url": "https://github.com/Hyphen/javascript-sdks/issues" + } +} diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts new file mode 100644 index 0000000..31311b9 --- /dev/null +++ b/packages/react-sdk/src/index.ts @@ -0,0 +1,9 @@ +// Re-export core Toggle and types from browser-sdk +import { Toggle, type ToggleOptions } from "@hyphen/browser-sdk"; + +// Export React-specific components, hooks, and types +export { ToggleContext, ToggleProvider } from "./toggle-provider"; +export type { ToggleProviderProps } from "./types"; +export { useToggle } from "./use-toggle"; +export { withToggleProvider } from "./with-toggle-provider"; +export { Toggle, type ToggleOptions }; diff --git a/packages/react-sdk/src/toggle-provider.tsx b/packages/react-sdk/src/toggle-provider.tsx new file mode 100644 index 0000000..1b7659f --- /dev/null +++ b/packages/react-sdk/src/toggle-provider.tsx @@ -0,0 +1,60 @@ +import { Toggle } from "@hyphen/browser-sdk"; +import { type Context, createContext, useEffect, useMemo } from "react"; +import type { ToggleProviderProps } from "./types"; + +/** + * React Context for the Toggle instance + */ +export const ToggleContext: Context = + createContext(null); + +/** + * Provider component that creates and provides a Toggle instance to the React tree + * + * @example + * ```tsx + * + * + * + * ``` + */ +export function ToggleProvider({ + children, + publicApiKey, + applicationId, + environment, + defaultContext, + horizonUrls, + defaultTargetKey, +}: ToggleProviderProps) { + // Create Toggle instance, memoized by configuration + const toggle = useMemo(() => { + return new Toggle({ + publicApiKey, + applicationId, + environment, + defaultContext, + horizonUrls, + defaultTargetKey, + }); + }, [ + publicApiKey, + applicationId, + environment, + defaultContext, + horizonUrls, + defaultTargetKey, + ]); + + // Cleanup on unmount + useEffect(() => { + return () => { + // Toggle cleanup if needed (currently Toggle doesn't have a destroy method) + // This is here for future-proofing + }; + }, []); + + return ( + {children} + ); +} diff --git a/packages/react-sdk/src/types.ts b/packages/react-sdk/src/types.ts new file mode 100644 index 0000000..f2b0322 --- /dev/null +++ b/packages/react-sdk/src/types.ts @@ -0,0 +1,13 @@ +import type { ToggleOptions } from "@hyphen/browser-sdk"; +import type { ReactNode } from "react"; + +/** + * Props for the ToggleProvider component + * Extends ToggleOptions from @hyphen/browser-sdk + */ +export interface ToggleProviderProps extends ToggleOptions { + /** + * React children to be wrapped by the provider + */ + children: ReactNode; +} diff --git a/packages/react-sdk/src/use-toggle.tsx b/packages/react-sdk/src/use-toggle.tsx new file mode 100644 index 0000000..707e7a4 --- /dev/null +++ b/packages/react-sdk/src/use-toggle.tsx @@ -0,0 +1,32 @@ +import type { Toggle } from "@hyphen/browser-sdk"; +import { useContext } from "react"; +import { ToggleContext } from "./toggle-provider"; + +/** + * Hook to access the Toggle instance from the ToggleProvider + * + * @throws {Error} If used outside of a ToggleProvider + * @returns {Toggle} The Toggle instance from the provider + * + * @example + * ```tsx + * function MyComponent() { + * const toggle = useToggle(); + * const isEnabled = toggle.getBoolean('my-feature', false); + * + * return
{isEnabled ? 'Feature enabled' : 'Feature disabled'}
; + * } + * ``` + */ +export function useToggle(): Toggle { + const toggle = useContext(ToggleContext); + + if (!toggle) { + throw new Error( + "useToggle must be used within a ToggleProvider. " + + "Wrap your component tree with or use withToggleProvider().", + ); + } + + return toggle; +} diff --git a/packages/react-sdk/src/with-toggle-provider.tsx b/packages/react-sdk/src/with-toggle-provider.tsx new file mode 100644 index 0000000..a5552ce --- /dev/null +++ b/packages/react-sdk/src/with-toggle-provider.tsx @@ -0,0 +1,41 @@ +import type { ToggleOptions } from "@hyphen/browser-sdk"; +import type { ComponentType } from "react"; +import { ToggleProvider } from "./toggle-provider"; + +/** + * Higher-order component that wraps a component with ToggleProvider + * + * @param options - Configuration options for the Toggle instance + * @returns A function that wraps a component with ToggleProvider + * + * @example + * ```tsx + * export default withToggleProvider({ + * publicApiKey: "public_...", + * applicationId: "my-app", + * environment: "production", + * defaultContext: { + * user: { id: "user-123" } + * } + * })(App); + * ``` + */ +export function withToggleProvider(options: ToggleOptions) { + return

(Component: ComponentType

): ComponentType

=> { + const WrappedComponent = (props: P) => { + return ( + + + + ); + }; + + // Preserve the original component name for debugging + /* v8 ignore next -- @preserve */ + const componentName = + Component.displayName || Component.name || "Component"; + WrappedComponent.displayName = `withToggleProvider(${componentName})`; + + return WrappedComponent; + }; +} diff --git a/packages/react-sdk/test/index.test.ts b/packages/react-sdk/test/index.test.ts new file mode 100644 index 0000000..fdf6799 --- /dev/null +++ b/packages/react-sdk/test/index.test.ts @@ -0,0 +1,8 @@ +import { describe, expect, test } from "vitest"; +import { Toggle } from "../src/index.js"; + +describe("index", () => { + test("should export Toggle", () => { + expect(Toggle).toBeDefined(); + }); +}); diff --git a/packages/react-sdk/test/setup.ts b/packages/react-sdk/test/setup.ts new file mode 100644 index 0000000..1f082b8 --- /dev/null +++ b/packages/react-sdk/test/setup.ts @@ -0,0 +1,48 @@ +import { afterAll, beforeAll } from "vitest"; + +// Suppress React error boundary and jsdom error output during tests +// This prevents expected error stack traces from cluttering test output +let originalConsoleError: typeof console.error; +let originalStderrWrite: typeof process.stderr.write; + +beforeAll(() => { + // Suppress console.error for React errors + originalConsoleError = console.error; + console.error = (...args: unknown[]) => { + const message = String(args[0] || ""); + // Suppress known React/testing error messages + if ( + message.includes("Error: Uncaught") || + message.includes("The above error occurred") || + message.includes("React will try to recreate") || + message.includes("Consider adding an error boundary") || + message.includes("useToggle must be used within") + ) { + return; + } + originalConsoleError(...args); + }; + + // Suppress stderr writes for jsdom errors + originalStderrWrite = process.stderr.write; + process.stderr.write = (( + chunk: string | Uint8Array, + ...args: unknown[] + ): boolean => { + const message = String(chunk); + // Suppress jsdom error stack traces + if ( + message.includes("Error: Uncaught") || + message.includes("at reportException") || + message.includes("useToggle must be used within") + ) { + return true; + } + return originalStderrWrite.call(process.stderr, chunk, ...args); + }) as typeof process.stderr.write; +}); + +afterAll(() => { + console.error = originalConsoleError; + process.stderr.write = originalStderrWrite; +}); diff --git a/packages/react-sdk/test/toggle-provider.test.tsx b/packages/react-sdk/test/toggle-provider.test.tsx new file mode 100644 index 0000000..79245f7 --- /dev/null +++ b/packages/react-sdk/test/toggle-provider.test.tsx @@ -0,0 +1,62 @@ +import { render } from "@testing-library/react"; +import { useContext } from "react"; +import { describe, expect, test } from "vitest"; +import { ToggleContext, ToggleProvider } from "../src/toggle-provider"; + +let toggleInstance: unknown; + +function ReadToggle() { + toggleInstance = useContext(ToggleContext); + return

Test
; +} + +describe("ToggleProvider", () => { + test("should render children", () => { + const { getByText } = render( + +
Test Child
+
, + ); + + expect(getByText("Test Child")).toBeDefined(); + }); + + test("should provide Toggle instance through context", () => { + toggleInstance = null; + + render( + + + , + ); + + expect(toggleInstance).toBeDefined(); + expect(toggleInstance).not.toBeNull(); + }); + + test("should create Toggle with correct configuration", () => { + toggleInstance = null; + + render( + + + , + ); + + expect(toggleInstance).toBeDefined(); + // The Toggle instance should be created with the provided configuration + // We can't easily test the internal configuration, but we can verify it exists + }); + + test("should provide null context when no provider is used", () => { + toggleInstance = undefined; + + render(); + + expect(toggleInstance).toBeNull(); + }); +}); diff --git a/packages/react-sdk/test/use-toggle.test.tsx b/packages/react-sdk/test/use-toggle.test.tsx new file mode 100644 index 0000000..00dee2c --- /dev/null +++ b/packages/react-sdk/test/use-toggle.test.tsx @@ -0,0 +1,95 @@ +import { render } from "@testing-library/react"; +import { describe, expect, test } from "vitest"; +import { ToggleProvider } from "../src/toggle-provider"; +import { useToggle } from "../src/use-toggle"; + +let toggleInstance: unknown = null; + +function CaptureToggle() { + toggleInstance = useToggle(); + return
Test
; +} + +function ThrowToggle() { + useToggle(); + return
Test
; +} + +let hasGetBooleanMethod = false; +let hasGetStringMethod = false; +let hasGetNumberMethod = false; + +function InspectToggle() { + const toggle = useToggle(); + hasGetBooleanMethod = typeof toggle.getBoolean === "function"; + hasGetStringMethod = typeof toggle.getString === "function"; + hasGetNumberMethod = typeof toggle.getNumber === "function"; + return
Test
; +} + +const instances: unknown[] = []; + +function RecordToggle({ renderCount }: { renderCount: number }) { + const toggle = useToggle(); + instances[renderCount] = toggle; + return
Test
; +} + +describe("useToggle", () => { + test("should return Toggle instance when used within ToggleProvider", () => { + toggleInstance = null; + + render( + + + , + ); + + expect(toggleInstance).toBeDefined(); + expect(toggleInstance).not.toBeNull(); + }); + + test("should throw error when used outside ToggleProvider", () => { + expect(() => { + render(); + }).toThrow( + "useToggle must be used within a ToggleProvider. " + + "Wrap your component tree with or use withToggleProvider().", + ); + }); + + test("should provide access to Toggle methods", () => { + hasGetBooleanMethod = false; + hasGetStringMethod = false; + hasGetNumberMethod = false; + + render( + + + , + ); + + expect(hasGetBooleanMethod).toBe(true); + expect(hasGetStringMethod).toBe(true); + expect(hasGetNumberMethod).toBe(true); + }); + + test("should return same instance across multiple renders", () => { + instances.length = 0; + + const { rerender } = render( + + + , + ); + + rerender( + + + , + ); + + // Both renders should get the same Toggle instance + expect(instances[0]).toBe(instances[1]); + }); +}); diff --git a/packages/react-sdk/test/with-toggle-provider.test.tsx b/packages/react-sdk/test/with-toggle-provider.test.tsx new file mode 100644 index 0000000..abb47c0 --- /dev/null +++ b/packages/react-sdk/test/with-toggle-provider.test.tsx @@ -0,0 +1,105 @@ +import { render } from "@testing-library/react"; +import { describe, expect, test } from "vitest"; +import { useToggle } from "../src/use-toggle"; +import { withToggleProvider } from "../src/with-toggle-provider"; + +function StaticTestComponent() { + return
Test Component
; +} + +let toggleInstance: unknown = null; + +function CaptureToggle() { + toggleInstance = useToggle(); + return
Test
; +} + +function NamedTestComponent() { + return
Test
; +} + +function TestComponent() { + return
Test
; +} + +interface TestProps { + testProp: string; +} + +function PropTestComponent({ testProp }: TestProps) { + return
{testProp}
; +} + +describe("withToggleProvider", () => { + test("should wrap component with ToggleProvider", () => { + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + })(StaticTestComponent); + + const { getByText } = render(); + + expect(getByText("Test Component")).toBeDefined(); + }); + + test("should provide Toggle instance to wrapped component", () => { + toggleInstance = null; + + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + applicationId: "test-app", + })(CaptureToggle); + + render(); + + expect(toggleInstance).toBeDefined(); + expect(toggleInstance).not.toBeNull(); + }); + + test("should preserve component display name", () => { + NamedTestComponent.displayName = "MyTestComponent"; + + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + })(NamedTestComponent); + + expect(WrappedComponent.displayName).toBe( + "withToggleProvider(MyTestComponent)", + ); + }); + + test("should use component name when displayName is not set", () => { + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + })(TestComponent); + + expect(WrappedComponent.displayName).toBe( + "withToggleProvider(TestComponent)", + ); + }); + + test("should pass props to wrapped component", () => { + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + })(PropTestComponent); + + const { getByText } = render(); + + expect(getByText("Hello World")).toBeDefined(); + }); + + test("should pass Toggle configuration to provider", () => { + toggleInstance = null; + + const WrappedComponent = withToggleProvider({ + publicApiKey: "public_test", + applicationId: "my-app", + environment: "production", + })(CaptureToggle); + + render(); + + // Verify that Toggle instance was created (configuration is internal) + expect(toggleInstance).toBeDefined(); + expect(toggleInstance).not.toBeNull(); + }); +}); diff --git a/packages/react-sdk/tsconfig.json b/packages/react-sdk/tsconfig.json new file mode 100644 index 0000000..5c9c895 --- /dev/null +++ b/packages/react-sdk/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ESNext", + "lib": ["DOM", "ES2022", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "strict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "noEmit": true, + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "moduleDetection": "force" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] + } \ No newline at end of file diff --git a/packages/react-sdk/tsdown.config.ts b/packages/react-sdk/tsdown.config.ts new file mode 100644 index 0000000..df51d0d --- /dev/null +++ b/packages/react-sdk/tsdown.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm', 'cjs'], + dts: true, + clean: true, + target: 'es2020', + deps: { + neverBundle: ['react'], + alwaysBundle: ['@hyphen/browser-sdk'], + onlyBundle: false, + }, +}); diff --git a/packages/react-sdk/vitest.config.ts b/packages/react-sdk/vitest.config.ts new file mode 100644 index 0000000..2d3a26c --- /dev/null +++ b/packages/react-sdk/vitest.config.ts @@ -0,0 +1,19 @@ +import {defineConfig} from 'vitest/config'; + +export default defineConfig({ + test: { + environment: 'happy-dom', + setupFiles: ['./test/setup.ts'], + coverage: { + // The lcov paths start at the repository root, so that Codecov finds each file. + reporter: ['text', 'json', ['lcov', { projectRoot: '../..' }]], + exclude: [ + 'dist/**', + 'vitest.config.ts', + 'tsup.config.ts', + 'src/types.ts', + 'src/index.ts', + ], + }, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..5368822 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,4716 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.17.0 + version: 12.17.0 + +packages: + + '@pnpm/exe.android-arm64@12.17.0': + resolution: {integrity: sha512-gwu/F5YyoJp1bIbrIBl7B8JO3rkjkGlKikwQg9s0aVa5xWaBYIqPX+ZJqQ7I4D1YfbdI/Omfze0+6vnYiWHG6A==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.17.0': + resolution: {integrity: sha512-qUNhCvWyeBrUByNWkqqQ3Koy1gIAQ8UV5HDHXxoo5NUWVTde0Ld2BxweNwWJw8CNKpqEGceCUdjZ506JYpTjJg==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.17.0': + resolution: {integrity: sha512-0nkEqRLIbrm7dWl+p2EPpmyNKyM0bbdPEovdtMhHYbhkO+Vls38S+6emkx8kSTAr75BNXYXkCl4RtGinGG4Erg==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.17.0': + resolution: {integrity: sha512-w89cboNi4KCzmt/dSKrE4ijVNKICKiZsE9TcIWf77Tz+VpoDfuhPSmWPZK+iCHBvlI/9dIN+M3HiPPVsFnAx4Q==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.17.0': + resolution: {integrity: sha512-DJ0FOaUDXc71icSgiuBFEvqReqoSiS/rmnC6kltoiC3MzPyw3awcGbT/7FnnYzi/ziuoTC7v6vfBh0Vzv7VKOQ==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.17.0': + resolution: {integrity: sha512-w5ZwZ4j8S804DGhMYlLLpc+G3Kkc+5GlDO++LLvO/nDIXBTHRhdxPfQBQU08q31k0JYfp3wXCQk0Y7DnsuVF6w==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.17.0': + resolution: {integrity: sha512-Cj2nIzWTVm6ZuhQHqL9SiJ11scBnEGxJyNg7tYQPzh9fVF5UVRkv+LbyfwdftnAtJerK/7HDpK/55WeQqp8OkA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.17.0': + resolution: {integrity: sha512-Gb//Wm15fXl+qWcxjNQmwlYDjGiJOnLU/A9uRZYmtkyZie2Yx8AHI6XkUIJioQz99TwVDKQ87ywD5Jtk8zcgyg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.17.0': + resolution: {integrity: sha512-+kItEcFjdVZEDzODsc7icb8cB+3AouCrEzOCezzxLITRhw86m9t3J/qyPdcFELBjeMnS+IXV8sJaSCQcpSqfgA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.17.0': + resolution: {integrity: sha512-jf5ghD2uDeknWQgK/EsCFNwlyL7BYLWfXe687g5UMVFclPLt524CREZ8Yl5hf4u7p3evCIPBN/m5I1QXUmJpHw==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.17.0': + resolution: {integrity: sha512-JGxrGSxkDkqRAUD49T9dOnKyJkQ3bWBeHnYH4o4mvj09R9eUzhWFi8oa6WPNyCO0/7/Max2gsSfgXOHj3QW7ug==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.17.0': + resolution: {integrity: sha512-vQAusDzMofc/Ee4KOUYjE6FWeHOlMGQyvhR7W39QSamVeJWS16co/n+bhjdjwjI3UFh8IWOpamvTS+b4lvQUog==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.win32-arm64@12.17.0': + resolution: {integrity: sha512-qDQh8rmyK5sxlaCSCADcmPrvytJabMCbxtJ0nCitzRo2j3/8BhzLjlOcWF3C6iPGhR5CbIb+btNy+VCVhd06mQ==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.17.0': + resolution: {integrity: sha512-qCo1OQlE3WrFZIAUK0O5EoupLaQ1fST7zNX8Qd+Tc4ojWgCvYA/ze0uP9hox8mSFC/JPAGRSG5o8gUBSq2rRxw==} + cpu: [x64] + os: [win32] + + pnpm@12.17.0: + resolution: {integrity: sha512-uNIj6+wEtYContIG2qcdG8y2oe4dUu+pXMOw23UnFWHfjw2OLEOt05xewIAYr3qKlRCOcJD5Win4hye3pA/VPQ==} + engines: {node: '>=18'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.17.0': + optional: true + + '@pnpm/exe.android-x64@12.17.0': + optional: true + + '@pnpm/exe.darwin-arm64@12.17.0': + optional: true + + '@pnpm/exe.darwin-x64@12.17.0': + optional: true + + '@pnpm/exe.freebsd-x64@12.17.0': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.17.0': + optional: true + + '@pnpm/exe.linux-arm64@12.17.0': + optional: true + + '@pnpm/exe.linux-ppc64@12.17.0': + optional: true + + '@pnpm/exe.linux-riscv64@12.17.0': + optional: true + + '@pnpm/exe.linux-s390x@12.17.0': + optional: true + + '@pnpm/exe.linux-x64-musl@12.17.0': + optional: true + + '@pnpm/exe.linux-x64@12.17.0': + optional: true + + '@pnpm/exe.win32-arm64@12.17.0': + optional: true + + '@pnpm/exe.win32-x64@12.17.0': + optional: true + + pnpm@12.17.0: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.17.0 + '@pnpm/exe.android-x64': 12.17.0 + '@pnpm/exe.darwin-arm64': 12.17.0 + '@pnpm/exe.darwin-x64': 12.17.0 + '@pnpm/exe.freebsd-x64': 12.17.0 + '@pnpm/exe.linux-arm64': 12.17.0 + '@pnpm/exe.linux-arm64-musl': 12.17.0 + '@pnpm/exe.linux-ppc64': 12.17.0 + '@pnpm/exe.linux-riscv64': 12.17.0 + '@pnpm/exe.linux-s390x': 12.17.0 + '@pnpm/exe.linux-x64': 12.17.0 + '@pnpm/exe.linux-x64-musl': 12.17.0 + '@pnpm/exe.win32-arm64': 12.17.0 + '@pnpm/exe.win32-x64': 12.17.0 + +--- +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +overrides: + normalize-package-data@2>semver: 7.8.5 + undici-types@6.21.0: 8.12.3 + +importers: + + .: {} + + packages/browser-sdk: + dependencies: + hookified: + specifier: ^3.0.3 + version: 3.0.3 + devDependencies: + '@biomejs/biome': + specifier: ^2.5.13 + version: 2.5.13 + '@faker-js/faker': + specifier: ^10.6.0 + version: 10.6.0 + '@hyphen/sdk': + specifier: workspace:^ + version: link:../nodejs-sdk + '@types/node': + specifier: ^24.13.3 + version: 24.13.4 + '@vitest/coverage-v8': + specifier: ^5.0.0 + version: 5.0.0(vitest@5.0.0) + rimraf: + specifier: ^6.1.3 + version: 6.1.3 + tsdown: + specifier: ^0.23.0 + version: 0.23.0(typescript@7.0.2)(unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)) + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.0 + version: 5.0.0(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + + packages/nodejs-sdk: + dependencies: + '@cacheable/net': + specifier: ^2.1.0 + version: 2.1.0 + cacheable: + specifier: ^2.5.0 + version: 2.5.0 + hookified: + specifier: ^3.0.4 + version: 3.0.4 + pino: + specifier: ^10.3.1 + version: 10.3.1 + devDependencies: + '@biomejs/biome': + specifier: ^2.5.15 + version: 2.5.15 + '@faker-js/faker': + specifier: ^10.6.0 + version: 10.6.0 + '@types/node': + specifier: ^24.19.0 + version: 24.19.0 + '@vitest/coverage-v8': + specifier: ^5.0.3 + version: 5.0.3(vitest@5.0.3) + rimraf: + specifier: ^6.1.3 + version: 6.1.3 + tsd: + specifier: ^0.33.0 + version: 0.33.0 + tsdown: + specifier: ^0.23.0 + version: 0.23.0(typescript@7.0.2)(unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)) + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.3 + version: 5.0.3(@types/node@24.19.0)(@vitest/coverage-v8@5.0.3)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + + packages/react-sdk: + dependencies: + '@hyphen/browser-sdk': + specifier: workspace:^ + version: link:../browser-sdk + devDependencies: + '@biomejs/biome': + specifier: ^2.6.4 + version: 2.6.4 + '@faker-js/faker': + specifier: ^10.6.0 + version: 10.6.0 + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.1)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@types/node': + specifier: ^22.20.5 + version: 22.20.5 + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@vitest/coverage-v8': + specifier: ^5.0.5 + version: 5.0.5(vitest@5.0.5) + dotenv: + specifier: ^18.0.9 + version: 18.0.9 + happy-dom: + specifier: ^21.0.4 + version: 21.0.4 + react: + specifier: ^19.3.1 + version: 19.3.1 + react-dom: + specifier: ^19.3.1 + version: 19.3.1(react@19.3.1) + rimraf: + specifier: ^6.1.3 + version: 6.1.3 + tsd: + specifier: ^0.33.0 + version: 0.33.0 + tsdown: + specifier: ^0.23.4 + version: 0.23.4(typescript@7.0.2)(unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)) + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(happy-dom@21.0.4)(vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + +packages: + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.9': + resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/runtime@7.29.7': + resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} + + '@bcoe/v8-coverage@1.0.2': + resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} + engines: {node: '>=18'} + + '@biomejs/biome@2.5.13': + resolution: {integrity: sha512-+SEC/mFk1a+5mvUANZgbZTaiZXs1nj4iMhL/PHiqDT5TPUEPFIlliEtkKKZB4N862yylHC3UI+/Sj2I0HJEqhA==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/biome@2.5.15': + resolution: {integrity: sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/biome@2.6.4': + resolution: {integrity: sha512-8sKKwaNW4ot22awZ3lBjwWLHnUFXgXnrBPYS2gNlBAXRbDC++7kqjK2H7dR/FgCDtPvO1xfKpgEhJkGxAKYkxA==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-android-arm64@2.6.4': + resolution: {integrity: sha512-jwrwigP4tBcHxzuV8izioX/BOUhJL/4e2rNSOE5nCjBkVC018LQAQUGiH+CNkFYvLtQ1dcZo5/xXERmaAGc7JQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [android] + + '@biomejs/cli-android-x64@2.6.4': + resolution: {integrity: sha512-HdGInPJ4nZFwHxzvEtcp2nmSBtUyJrurmtIK43upFckuS3+ZqVM05HtsxQWnqGsuy/pxckIAjyKWlEKRlBXUyA==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [android] + + '@biomejs/cli-darwin-arm64@2.5.13': + resolution: {integrity: sha512-nYSuDJ6zgVqZUkAkJkvhXxsF2PYIrUk/g638K4voCXz7foI9f7b6C2/7+oAihsHQlivZNMUrm/y8ywlcHQtZOw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-arm64@2.5.15': + resolution: {integrity: sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-arm64@2.6.4': + resolution: {integrity: sha512-0VvcUz46wbg59Q4TZ59KkIjDJrxEyu4Eoe79+F4SChxoWe+W7AEyIp6F5r72C9+p6MsB6dIovnZt1D30lGM3XA==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.5.13': + resolution: {integrity: sha512-KVy1ceEDuJ3AzFxjT9kkxbVy+UANw1pjEMUS6lvKfxjJ+fmkRvc7sQn1Xo6ETgseEI7wUQoV03KSga3XfE8YRQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.5.15': + resolution: {integrity: sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.6.4': + resolution: {integrity: sha512-fxmvkF81srlS3DiMyfm+aG3J0eG+6/BjaxRyjy57KbLSafnq0PO+hHfVWmtH2ty0S7nm6yDXBRwySfFeaRJKRQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@2.5.13': + resolution: {integrity: sha512-CH32xpep3dNS5EVJpAHlYchkBYznxyVZQrx0b6YYYlPL9u9ZeD2NtqiK/6s64+HFS2a7hGnryLlqqZAOh8ax5g==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64-musl@2.5.15': + resolution: {integrity: sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64-musl@2.6.4': + resolution: {integrity: sha512-31ZaH/MHqPX+O+evRwRrCHQ8W5/9adY+/eMytGGWZnRx1T41QsWIF09+/WujynLBhWZUxNGS5CtsWLwgOFTAyg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64@2.5.13': + resolution: {integrity: sha512-VlNMtoxOqs0dUR6drxxHr18SNUvI7xxAuHZlH4s/dstYSf3g6RaqVgo8JRnhcOhKz9afWrvtJTboNG1JuYlIDQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-arm64@2.5.15': + resolution: {integrity: sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-arm64@2.6.4': + resolution: {integrity: sha512-6+bK1Y/evmIUiJr7auertuMbiaYVicJhqA1bZyL47lCMWugv8l0gFQCqvR/gN1vZMHYm+HwoTKgeMxdNFCoQTg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64-musl@2.5.13': + resolution: {integrity: sha512-F3pmwl+VHoUuVJN/tbNLKeLt0SVK3EIyN1jXlMcNyQGYRQQTVqXF+GgkP0/CjGXFN87e/mv0sBfUnWqWza5PKQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64-musl@2.5.15': + resolution: {integrity: sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64-musl@2.6.4': + resolution: {integrity: sha512-bomSa2XdQAGGj6Cwdm4M13qE+lN9+AOlW8KtI4hdyVyRRF/Z71qPAi95T4wtdZK0QpBbkTW8hgbZZCwPi4xzIw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64@2.5.13': + resolution: {integrity: sha512-Fi6gIxbUaJ3ZCIXeG3ggIBPF76O2DjDN67WrPX/ODRv54GeXPm2gbEPC96Yb0yrJoiH0Eax1JLx1Pi0XbsNFZQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64@2.5.15': + resolution: {integrity: sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64@2.6.4': + resolution: {integrity: sha512-tbFZMdL6dP/ws4edXxYG9WhvaVa1ZDzL4G5DzahnWW7Psib9H+VTdyU4XXVxpJk5j/nYZroSbvSNyYlpW3yCIw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-win32-arm64@2.5.13': + resolution: {integrity: sha512-+WD13qshXrr0Icv4BfsAdzm8Fs3TL+nZ59zEQxsYNd8lcgZJ0A5+OrlwsL1PipVCmWeRpxgIPD6DAcEd7smkCQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-arm64@2.5.15': + resolution: {integrity: sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-arm64@2.6.4': + resolution: {integrity: sha512-eCsqt8Ma3eVap+oyJCDnJZH60SIU464B66n3y38EUTJdM1T/HfZol1FJC9vb+sHToX0ix8XzqPcwJnOzyAJz0g==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@2.5.13': + resolution: {integrity: sha512-VOofU/nW761XWzUeUNE8zzYNyPrxuMuNFMizL0qz7J75yeV8N7WFheUlk1/K6dOkaFpH9wJ+lDKlwjAbw0346w==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + + '@biomejs/cli-win32-x64@2.5.15': + resolution: {integrity: sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + + '@biomejs/cli-win32-x64@2.6.4': + resolution: {integrity: sha512-pYsMy5AThiHFOZAsngg8qN4PurM6nInKBhVX7sbj3eNpRQqo1Hb0MgCwPL7VqVMrmcEEMj9Ks3qbkallR65e8g==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + + '@cacheable/memory@2.2.0': + resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==} + + '@cacheable/net@2.1.0': + resolution: {integrity: sha512-DlLnk6EWquHuFKd7sMQop4/mKwYRxU36ZAn1JrvvJzTed8JmOGlJ6InzOXUqyXs8duP3LhmN1fNmBUwx4ChD3g==} + + '@cacheable/utils@2.5.0': + resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + + '@emnapi/core@1.11.1': + resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} + + '@emnapi/runtime@1.11.1': + resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} + + '@emnapi/wasi-threads@1.2.2': + resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + + '@esbuild/aix-ppc64@0.27.7': + resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.27.7': + resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.27.7': + resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.27.7': + resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.27.7': + resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.7': + resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.27.7': + resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.7': + resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.27.7': + resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.27.7': + resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.27.7': + resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.27.7': + resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.27.7': + resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.27.7': + resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.7': + resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.27.7': + resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.27.7': + resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.7': + resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.7': + resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.7': + resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.7': + resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.7': + resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.27.7': + resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.27.7': + resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.27.7': + resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.27.7': + resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@faker-js/faker@10.6.0': + resolution: {integrity: sha512-3RQHgEtvL1Frl/d1cSreo7qhJ3Gk1OdNUai/CtZ8G+wYeRQnJih3s9xJ9/kgYekPQRdwgh0HXRPqMlzWGwivIQ==} + engines: {node: ^20.19.0 || ^22.13.0 || ^23.5.0 || >=24.0.0, npm: '>=10'} + + '@jest/schemas@29.6.3': + resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/source-map@0.3.11': + resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@keyv/bigmap@1.3.1': + resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==} + engines: {node: '>= 18'} + peerDependencies: + keyv: ^5.6.0 + + '@keyv/serialize@1.1.1': + resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + + '@napi-rs/wasm-runtime@1.1.6': + resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} + peerDependencies: + '@emnapi/core': ^1.7.1 + '@emnapi/runtime': ^1.7.1 + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@oxc-project/types@0.122.0': + resolution: {integrity: sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==} + + '@oxc-project/types@0.149.0': + resolution: {integrity: sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@pinojs/redact@0.4.0': + resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + + '@quansync/fs@1.0.0': + resolution: {integrity: sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm-eabi@1.2.8': + resolution: {integrity: sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.0.0-rc.12': + resolution: {integrity: sha512-pv1y2Fv0JybcykuiiD3qBOBdz6RteYojRFY1d+b95WVuzx211CRh+ytI/+9iVyWQ6koTh5dawe4S/yRfOFjgaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-android-arm64@1.2.8': + resolution: {integrity: sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.0.0-rc.12': + resolution: {integrity: sha512-cFYr6zTG/3PXXF3pUO+umXxt1wkRK/0AYT8lDwuqvRC+LuKYWSAQAQZjCWDQpAH172ZV6ieYrNnFzVVcnSflAg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-arm64@1.2.8': + resolution: {integrity: sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.0.0-rc.12': + resolution: {integrity: sha512-ZCsYknnHzeXYps0lGBz8JrF37GpE9bFVefrlmDrAQhOEi4IOIlcoU1+FwHEtyXGx2VkYAvhu7dyBf75EJQffBw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.8': + resolution: {integrity: sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.0.0-rc.12': + resolution: {integrity: sha512-dMLeprcVsyJsKolRXyoTH3NL6qtsT0Y2xeuEA8WQJquWFXkEC4bcu1rLZZSnZRMtAqwtrF/Ib9Ddtpa/Gkge9Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-freebsd-x64@1.2.8': + resolution: {integrity: sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.12': + resolution: {integrity: sha512-YqWjAgGC/9M1lz3GR1r1rP79nMgo3mQiiA+Hfo+pvKFK1fAJ1bCi0ZQVh8noOqNacuY1qIcfyVfP6HoyBRZ85Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.8': + resolution: {integrity: sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.0.0-rc.12': + resolution: {integrity: sha512-/I5AS4cIroLpslsmzXfwbe5OmWvSsrFuEw3mwvbQ1kDxJ822hFHIx+vsN/TAzNVyepI/j/GSzrtCIwQPeKCLIg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-gnu@1.2.8': + resolution: {integrity: sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.0.0-rc.12': + resolution: {integrity: sha512-V6/wZztnBqlx5hJQqNWwFdxIKN0m38p8Jas+VoSfgH54HSj9tKTt1dZvG6JRHcjh6D7TvrJPWFGaY9UBVOaWPw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-arm64-musl@1.2.8': + resolution: {integrity: sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.12': + resolution: {integrity: sha512-AP3E9BpcUYliZCxa3w5Kwj9OtEVDYK6sVoUzy4vTOJsjPOgdaJZKFmN4oOlX0Wp0RPV2ETfmIra9x1xuayFB7g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-ppc64-gnu@1.2.8': + resolution: {integrity: sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.0.0-rc.12': + resolution: {integrity: sha512-nWwpvUSPkoFmZo0kQazZYOrT7J5DGOJ/+QHHzjvNlooDZED8oH82Yg67HvehPPLAg5fUff7TfWFHQS8IV1n3og==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.8': + resolution: {integrity: sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.0.0-rc.12': + resolution: {integrity: sha512-RNrafz5bcwRy+O9e6P8Z/OCAJW/A+qtBczIqVYwTs14pf4iV1/+eKEjdOUta93q2TsT/FI0XYDP3TCky38LMAg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.8': + resolution: {integrity: sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.0.0-rc.12': + resolution: {integrity: sha512-Jpw/0iwoKWx3LJ2rc1yjFrj+T7iHZn2JDg1Yny1ma0luviFS4mhAIcd1LFNxK3EYu3DHWCps0ydXQ5i/rrJ2ig==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-x64-musl@1.2.8': + resolution: {integrity: sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.0.0-rc.12': + resolution: {integrity: sha512-vRugONE4yMfVn0+7lUKdKvN4D5YusEiPilaoO2sgUWpCvrncvWgPMzK00ZFFJuiPgLwgFNP5eSiUlv2tfc+lpA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-openharmony-arm64@1.2.8': + resolution: {integrity: sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.0.0-rc.12': + resolution: {integrity: sha512-ykGiLr/6kkiHc0XnBfmFJuCjr5ZYKKofkx+chJWDjitX+KsJuAmrzWhwyOMSHzPhzOHOy7u9HlFoa5MoAOJ/Zg==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.0.0-rc.12': + resolution: {integrity: sha512-5eOND4duWkwx1AzCxadcOrNeighiLwMInEADT0YM7xeEOOFcovWZCq8dadXgcRHSf3Ulh1kFo/qvzoFiCLOL1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-arm64-msvc@1.2.8': + resolution: {integrity: sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.0.0-rc.12': + resolution: {integrity: sha512-PyqoipaswDLAZtot351MLhrlrh6lcZPo2LSYE+VDxbVk24LVKAGOuE4hb8xZQmrPAuEtTZW8E6D2zc5EUZX4Lw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.8': + resolution: {integrity: sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.0-rc.12': + resolution: {integrity: sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==} + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@sinclair/typebox@0.27.12': + resolution: {integrity: sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==} + + '@testing-library/dom@10.4.1': + resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} + engines: {node: '>=18'} + + '@testing-library/react@16.3.3': + resolution: {integrity: sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@tsd/typescript@5.9.3': + resolution: {integrity: sha512-JSSdNiS0wgd8GHhBwnMAI18Y8XPhLVN+dNelPfZCXFhy9Lb3NbnFyp9JKxxr54jSUkEJPk3cidvCoHducSaRMQ==} + engines: {node: '>=14.17'} + + '@tybys/wasm-util@0.10.3': + resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} + + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/eslint@7.29.0': + resolution: {integrity: sha512-VNcvioYDH8/FxaeTKkM4/TiTwt6pBV9E3OfGmvaw8tPl0rrHCJ4Ll15HRT+pMiFAf/MLQvAzC+6RzUMEL9Ceng==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/minimist@1.2.5': + resolution: {integrity: sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==} + + '@types/node@22.20.5': + resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==} + + '@types/node@24.13.4': + resolution: {integrity: sha512-YJ7EqCstVTzIr0fMr7qul/977en+pQHrfmuKIo6Zr9i75Be21dr3MovcfvGtyvi2HAUrRerWps5sMO9I7WaxDw==} + + '@types/node@24.19.0': + resolution: {integrity: sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==} + + '@types/normalize-package-data@2.4.4': + resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==} + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + + '@types/whatwg-mimetype@3.0.2': + resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} + + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/coverage-v8@5.0.0': + resolution: {integrity: sha512-toMg6PZGCIa/lQNCDoASrfb1ly4hsUKXFtFYC9kD4t78o5Y6LyNJU7AENt8eHPr3quYdxaxK7hj2mnbFfUk9NA==} + peerDependencies: + '@vitest/browser': 5.0.0 + vitest: 5.0.0 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/coverage-v8@5.0.3': + resolution: {integrity: sha512-+klsyz7BvT1vCU28Zkfzms1Ia78XD0V41U3FUtRaa3S+vOr/EXvK1O6BvVD7l1RzEjm6SONR2aybOvDDf9u0mQ==} + peerDependencies: + '@vitest/browser': 5.0.3 + vitest: 5.0.3 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/coverage-v8@5.0.5': + resolution: {integrity: sha512-4KpkGdIrSqBihx/JyP/e+S+IKB98etg1XDQiLAxksLfcShnwi1VReGeOT9NI43hLHbknosKp/1CCLn9Zgcs8mg==} + peerDependencies: + '@vitest/browser': 5.0.5 + vitest: 5.0.5 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/istanbul-lib-coverage@1.0.1': + resolution: {integrity: sha512-k3DJZ8LhMBK9NS4SclF1ASD3OgXEWDorbIcPTRDK0/Zae6fRvu+fJRxtFdLfHsa9Y24beCdPnoNZ4LviTNstfA==} + engines: {node: '>=22'} + + '@vitest/istanbul-lib-coverage@1.0.2': + resolution: {integrity: sha512-9J/JMwOf9AoJhAywhrn7ScKTL38hsWQP/qPG60OtaAFcQ5OXPwKsxZFlbnuCKmZ61m8/lGgHYnFpdyQZUvG/iA==} + engines: {node: '>=22'} + + '@vitest/istanbul-lib-report@1.0.1': + resolution: {integrity: sha512-1EOLRfsTMnyAr3+kEAsP4o9dhaDlGPpD7H5iLBBeq//YpNB1VIahkPhB+eRp9N2Dkfw8oySROjE3yf9XDeaIkQ==} + engines: {node: '>=22'} + + '@vitest/istanbul-lib-report@1.0.2': + resolution: {integrity: sha512-gUsfXZJbzPamoIY5TvHFiMMoXESBrUMo+xqaj+rYrWI69+EnvRlYBlP96ZnHPY4vX8kyUpgAnFUCg5wZG/HkDQ==} + engines: {node: '>=22'} + + '@vitest/mocker@5.0.0': + resolution: {integrity: sha512-66PGTMIiVJP3t4a5yxU9qPtf7MdTBs8jmToMvy+HVflB3Yy13WJZTtPePdvU+wjRV02SKK5doLbSA6o9pwOmiA==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/mocker@5.0.3': + resolution: {integrity: sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.0': + resolution: {integrity: sha512-uy+luWBAPw9XfthoHi5AkfHUnuPYEESjl0p/r+meoBnU8bxg5GDQ3Ey8MjcJ6sqahkL4PFyrvfMJJBw7LbU06g==} + + '@vitest/spy@5.0.3': + resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + '@yuku-codegen/binding-android-arm64@0.9.5': + resolution: {integrity: sha512-jrOY5WM+AaAqkv51fHP1x28ifto4WgcZVzodLUyMU1jMWn5Sq+VciRdk/n8E0Ey5w4p4cWWE+m5GfXWOYh7Kzw==} + cpu: [arm64] + os: [android] + + '@yuku-codegen/binding-darwin-arm64@0.9.5': + resolution: {integrity: sha512-4O4lkCQIzPZGjiNB1GORSI6hBECbiiSBS/APZXPvNKYH+nhY4uuqv03LNXA+SET3hoBjvr95P5rIhY8KQaQUBA==} + cpu: [arm64] + os: [darwin] + + '@yuku-codegen/binding-darwin-x64@0.9.5': + resolution: {integrity: sha512-9EvoUO0SEhD6/d8VHdWuPerepPMSR1y84+UEgz8Un1Ope14Oe7xMvePpEQLTLovoIFZ8Zg3iZ8z8E11pZMqC3g==} + cpu: [x64] + os: [darwin] + + '@yuku-codegen/binding-freebsd-x64@0.9.5': + resolution: {integrity: sha512-HqT78WwgHTmp8lwujoUa9CrIortX4DdpuiVC18ZPSGvuuJf4ylpIEI6QrQEM78Zwz3muhAWAOXZ5irdiYY+AyA==} + cpu: [x64] + os: [freebsd] + + '@yuku-codegen/binding-linux-arm-gnu@0.9.5': + resolution: {integrity: sha512-QJXwIW6Ms3QIawbcBIedmrmXnfdpuAOjZJ/eAABq5XTzWvSxZ7lutu9W5yIHahlaTaFnBo7ikrVMD1szLTpPUw==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@yuku-codegen/binding-linux-arm-musl@0.9.5': + resolution: {integrity: sha512-eHbFy3IHGb+IYarrYwAo0yWSEQV3eAmEn6VrsKA6I1Wy1YPJxWqSJlV69JhqsHtJuJlljUIF3ex0y46yaKIu9w==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@yuku-codegen/binding-linux-arm64-gnu@0.9.5': + resolution: {integrity: sha512-ByoJMbySTaDhjAXSu8q6Lh7HKg3YoesXpcT72aYk0Aiw4PCznmY4ybpLTq0RCvp0RIPhFm/6yECFiGBwyCC1nw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@yuku-codegen/binding-linux-arm64-musl@0.9.5': + resolution: {integrity: sha512-gD9vfXIoBw1toSxhO9rgmSu/FEfy3PMznJAxVjIuH8DrWEiDKXmJO0pJKfj1Ltbe/TmtWVZR+TjISqeSIGQzMg==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@yuku-codegen/binding-linux-x64-gnu@0.9.5': + resolution: {integrity: sha512-BARvdnvqMGjOr5Iel2JH+9H5vAIE0R6H0Z2fsT02xrvmI/1ZXNB8lkuX+ZGevPhZb3zJ9WeC/R8JZstrsUOK5g==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@yuku-codegen/binding-linux-x64-musl@0.9.5': + resolution: {integrity: sha512-x8flcevS1fbb7ESrmpOY/pON4eInSaE/7Ktjqx2udOE2W33BNSZmJuwpyUgo54AoHNqrcaM7szqydyJn5fNvew==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@yuku-codegen/binding-win32-arm64@0.9.5': + resolution: {integrity: sha512-KOL/rBatWqH4ZpCNoF8ZtSNdOJbAxBJLmk/VeRciepGROPTbPum1A9t67GpFgOU7qrkUWlPJdJ+KHKbvbmOt+w==} + cpu: [arm64] + os: [win32] + + '@yuku-codegen/binding-win32-x64@0.9.5': + resolution: {integrity: sha512-FxENahEjWSan59Syh/us/Kf4wNq8qrJLFJ3R2N4Oiwtb6yNdz/rWLNTIoNSssnsp7IoWJdUP6o/Z8ppg7lXMcg==} + cpu: [x64] + os: [win32] + + '@yuku-core/binding-android-arm64@0.19.0': + resolution: {integrity: sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw==} + cpu: [arm64] + os: [android] + + '@yuku-core/binding-darwin-arm64@0.19.0': + resolution: {integrity: sha512-7sNJa6XJhyetnTy64jw3NEi4YgUcezHk1G5GH9FSvXAuC8wIlbaOwT9lgq5qo5sspjrZJQlBR1TWflP49uRpMw==} + cpu: [arm64] + os: [darwin] + + '@yuku-core/binding-darwin-x64@0.19.0': + resolution: {integrity: sha512-pTC7dYEc59isdyizc3nsuyFNBu2LU5wMYZ1be6UMr59PY/AJNtO1aBLWV0MgL/z7C1nv/2sX4TNjGgKLoeevJw==} + cpu: [x64] + os: [darwin] + + '@yuku-core/binding-freebsd-x64@0.19.0': + resolution: {integrity: sha512-xrZjF6XOEwyLOiDIfrwDdRCS6ghxcJeirNC1KivQhVcUwlRonaU79S3/Uiyx3lBylPnT8qKJ3/aMT+H52nGTJQ==} + cpu: [x64] + os: [freebsd] + + '@yuku-core/binding-linux-arm-gnu@0.19.0': + resolution: {integrity: sha512-0OyIH53C0I1CbADHn9FSdCfX5qbpeLwJhmOVhonFJNYheybOnkSJ50qGMfTJIb8y5zrwqvLs7FVBvz6Fk8maZg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@yuku-core/binding-linux-arm-musl@0.19.0': + resolution: {integrity: sha512-z/iPfkCOCSXE34VXNt0uP1ORSW+4mEa9b5CiJcWZeqZH08g49bFU/jRM2T04f+Wpw5mJ6HIzNBiojxeAbrHjeg==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@yuku-core/binding-linux-arm64-gnu@0.19.0': + resolution: {integrity: sha512-jLNTi+gzaRwBJ+gwhCJ+rDb5dmx/8hEBx93UWd7hjMSqPTL1D1wvVSvXVAldV5kALvju7b0/m51EHEhs4+I1fA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@yuku-core/binding-linux-arm64-musl@0.19.0': + resolution: {integrity: sha512-YwyPIdW/rN2Fmv0MTFWi47FaB3F9g+2b+sJISyAw83Yd60RWH4T3Nx6XkAHHVN+uKJNBAd6So7/BVihSiFYvuQ==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@yuku-core/binding-linux-x64-gnu@0.19.0': + resolution: {integrity: sha512-/vskaAXVX3ESR43FiTdfiYS7z1b9uoQJwVQ/0RgUHgN2sWoAyCZs+aX4CgU7eKGIHTVfp9VFwv+c+2XchYiEtQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@yuku-core/binding-linux-x64-musl@0.19.0': + resolution: {integrity: sha512-FuXL5igeSKib9Rye02TdH+D6SQezTyGxIATMu1Qsn/QywrzwpGl35OLpS2C1x5vpGLeVE2XgiLd5mVPFHmIglQ==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@yuku-core/binding-win32-arm64@0.19.0': + resolution: {integrity: sha512-YuJAe7zEKT1Xa7LuHlhGJpPnYQeVtvo0rZvNjJRqkH0hQGOw4C8QeP30Tg5VKGzZfo2x8CjhjEhKt4TmLwfmdg==} + cpu: [arm64] + os: [win32] + + '@yuku-core/binding-win32-x64@0.19.0': + resolution: {integrity: sha512-o8iY/mXwlRkedp0LNTr4+TEfXTPQwoNZmv6k+1WIAd1ZXEn8xJJTBCtB0osaVvdZo/x/cNmV16UrWrrGpM5Mvw==} + cpu: [x64] + os: [win32] + + '@yuku-parser/binding-android-arm64@0.9.5': + resolution: {integrity: sha512-A2JCFCSHfnficqYEw4Iujpx7XrkMM3UfFcgJFmYpZSo9zM4nyhmdIIE0FogSduuU60lhM0/UcfuUBXIVNBMlGQ==} + cpu: [arm64] + os: [android] + + '@yuku-parser/binding-darwin-arm64@0.9.5': + resolution: {integrity: sha512-3PiyU+Eare4YuKaQ22N98/yAiROPY5o/NQJHraICzDvk4pgS+m+bgLKOvkGBRn33OnV95Vdv1Mn38b+MQHpULQ==} + cpu: [arm64] + os: [darwin] + + '@yuku-parser/binding-darwin-x64@0.9.5': + resolution: {integrity: sha512-blFMAFI7AInI83XaiOF8cIeiRM46Nz9EfpZtZPRLbKxSA9aAr5v8aHYpmfN6NoyXxAv/10pwS4gsAuc1W6fy5Q==} + cpu: [x64] + os: [darwin] + + '@yuku-parser/binding-freebsd-x64@0.9.5': + resolution: {integrity: sha512-TsNuL4qsZdO0tHp5GW43Y5fHeLPpPHA675wdcPNTcdq2ZO5AvsQWFFoiDg8CH4oBktfsQ9tdvKhjLnLYwKvp4g==} + cpu: [x64] + os: [freebsd] + + '@yuku-parser/binding-linux-arm-gnu@0.9.5': + resolution: {integrity: sha512-b0afYK5gHeV8RdmOcqAlgM8ONsye4cax4DMnIBaoJyPMd1UTGvTbpkqQcPVdhmHlcfcGVGMV1laeVovlr/dscw==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@yuku-parser/binding-linux-arm-musl@0.9.5': + resolution: {integrity: sha512-fD3lKzl+r6j6n8DwiMY53qnh5DLqD8KJjCp+NbVud54Nnh3Q9Wprqss3YzyMHP3NSJk663Wlg1E1X5qOuFVFig==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@yuku-parser/binding-linux-arm64-gnu@0.9.5': + resolution: {integrity: sha512-aRU/aCphV1MWCl/lvI6NX8LgucHQ68Fx+vz7NBb/5MEr2EuzCxiPOQqeFcMdWh+2AED/p0AvAREch0c+cSnlhA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@yuku-parser/binding-linux-arm64-musl@0.9.5': + resolution: {integrity: sha512-5+Guro0l8H473YXlEjVNBRLN/IbPbJdnQh1zo0OLt49xxnON+XMJRRaEyTOTfkn9QSRg0+BhEKGR4W9Gu2uZJQ==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@yuku-parser/binding-linux-x64-gnu@0.9.5': + resolution: {integrity: sha512-pwwSyV9q+GlvzSXlsMZBMlgk22L5bud714/vqZCdeUTivzeUVltQzUaf3IQXOGXdpc59JYTeuMCtbGquaAUoCA==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@yuku-parser/binding-linux-x64-musl@0.9.5': + resolution: {integrity: sha512-z18j6JN3lBHH8vzN7gG1M8fI0nlgItSfnC9PfbmUbt97iHViKfw2iA2G9fGwRMe5LyPRZBrejIlapbygPbpdaw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@yuku-parser/binding-win32-arm64@0.9.5': + resolution: {integrity: sha512-s6Gwttb1dQvtPX6Bgkw+UPC9IO3UBDXc6Zezog8MMgvu3UfJBBB9TQqKBX/2quu0Eyh+lLSAyNlIyyecaagUPg==} + cpu: [arm64] + os: [win32] + + '@yuku-parser/binding-win32-x64@0.9.5': + resolution: {integrity: sha512-FrERt9YWatY3bJfSUdi4YWY+6iQcyo3MzCC821BxlWM5TFZEHijnpz/bknR79VHlXY/9CvXz8ZlaAGPsTtN3nw==} + cpu: [x64] + os: [win32] + + '@yuku-toolchain/types@0.19.0': + resolution: {integrity: sha512-tFkNbsP4WXX9UMUC5syJGdK9dPMLK0PPaIuXCcCYH75sZ8MrebfBZ2XvCILRTw8AgLivSSCfDa4R67iYBDa4Kg==} + + '@yuku-toolchain/types@0.9.5': + resolution: {integrity: sha512-KiuLNNgX9uNealaWAR+G3/cMXnRk9x4TY2EkYe/KIag+UPdwiA0RRf1hr1WAxzTP8KGzCTkqUdLPvqh32sEO3w==} + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + ansi-escapes@4.3.2: + resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==} + engines: {node: '>=8'} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + + array-union@2.1.0: + resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} + engines: {node: '>=8'} + + arrify@1.0.1: + resolution: {integrity: sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==} + engines: {node: '>=0.10.0'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + ast-v8-to-istanbul@1.0.6: + resolution: {integrity: sha512-fvpl29helSO2w/z7utIbrkNXILdrLwDwAMH2I/zPKlGf5244+gf+B4cyS1sANcrPY2h+hWCGSgC8N61s/+AF9A==} + + ast-v8-to-istanbul@1.0.7: + resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} + + atomic-sleep@1.0.0: + resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} + engines: {node: '>=8.0.0'} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + brace-expansion@5.0.9: + resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + engines: {node: 20 || >=22} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buffer-image-size@0.6.4: + resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==} + engines: {node: '>=4.0'} + + cac@7.0.0: + resolution: {integrity: sha512-tixWYgm5ZoOD+3g6UTea91eow5z6AAHaho3g0V9CNSNb45gM8SmflpAc+GRd1InC4AqN/07Unrgp56Y94N9hJQ==} + engines: {node: '>=20.19.0'} + + cac@7.1.0: + resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} + engines: {node: '>=20.19.0'} + + cacheable@2.5.0: + resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} + + camelcase-keys@6.2.2: + resolution: {integrity: sha512-YrwaA0vEKazPBkn0ipTiMpSajYDSe+KjQfrjhcBMxJt/znbvlHd8Pw/Vamaz5EB4Wfhs3SUR3Z9mwRu/P3s3Yg==} + engines: {node: '>=8'} + + camelcase@5.3.1: + resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==} + engines: {node: '>=6'} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + commander@2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + decamelize-keys@1.1.1: + resolution: {integrity: sha512-WiPxgEirIV0/eIOMcnFBA3/IJZAZqKnwAwWyvvdi4lsr1WCN22nhdf/3db3DoZcUjTV2SqfzIwNyp6y2xs3nmg==} + engines: {node: '>=0.10.0'} + + decamelize@1.2.0: + resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} + engines: {node: '>=0.10.0'} + + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + diff-sequences@29.6.3: + resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + dir-glob@3.0.1: + resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} + engines: {node: '>=8'} + + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + + dotenv@18.0.9: + resolution: {integrity: sha512-3fVOW4cB02R066PUSwn8O4TJyz9NckQl7F81blIbaq9jKBm2tSmOKky7ZHIXzGvkVPXCSn6jkpziBPZdGFs8Tw==} + engines: {node: '>=12'} + hasBin: true + + dts-resolver@3.0.0: + resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==} + engines: {node: ^22.18.0 || >=24.0.0} + peerDependencies: + oxc-resolver: '>=11.0.0' + peerDependenciesMeta: + oxc-resolver: + optional: true + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + empathic@2.0.1: + resolution: {integrity: sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==} + engines: {node: '>=14'} + + empathic@2.1.0: + resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} + engines: {node: '>=14'} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + error-ex@1.3.4: + resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + esbuild@0.27.7: + resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} + engines: {node: '>=18'} + hasBin: true + + eslint-formatter-pretty@4.1.0: + resolution: {integrity: sha512-IsUTtGxF1hrH6lMWiSl1WbGaiP01eT6kzywdY1U+zLc0MP+nwEnUiS9UI8IaOTUhTeQJLlCEWIbXINBH4YJbBQ==} + engines: {node: '>=10'} + + eslint-rule-docs@1.1.235: + resolution: {integrity: sha512-+TQ+x4JdTnDoFEXXb3fDvfGOwnyNV7duH8fXWTPD1ieaBmB8omj7Gw/pMBBu4uI2uJCCU8APDaQJzWuXnTsH4A==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + + fastq@1.20.3: + resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + find-up@4.1.0: + resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} + engines: {node: '>=8'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + get-tsconfig@5.0.0-beta.6: + resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==} + engines: {node: '>=20.20.0'} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob@13.0.6: + resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + engines: {node: 18 || 20 || >=22} + + globby@11.1.0: + resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} + engines: {node: '>=10'} + + happy-dom@21.0.4: + resolution: {integrity: sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==} + engines: {node: '>=20.0.0'} + + hard-rejection@2.1.0: + resolution: {integrity: sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==} + engines: {node: '>=6'} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + hashery@1.5.1: + resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} + engines: {node: '>=20'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + hookable@6.1.1: + resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==} + + hookable@6.1.2: + resolution: {integrity: sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==} + + hookified@1.15.1: + resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} + + hookified@2.2.0: + resolution: {integrity: sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==} + + hookified@3.0.3: + resolution: {integrity: sha512-ZcbRytYgERoKtosiaXolUIPIWMgUCrSiWQEzFZ0kc8etD/LPgpy4/KOrtssFdK7ZXlTTyb4cob2veqj7osv8yA==} + engines: {node: '>=22.18.0'} + + hookified@3.0.4: + resolution: {integrity: sha512-Uos6DSO6BKv4DeR1C22UosRpeUaaoQgEQ+eDCyoJRll2OGzGpZc708vL7orIvqrYLo6zhVV+pkwO9zKVCsq3PQ==} + engines: {node: '>=22.18.0'} + + hosted-git-info@2.8.9: + resolution: {integrity: sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==} + + hosted-git-info@4.1.0: + resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} + engines: {node: '>=10'} + + http-cache-semantics@4.2.0: + resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + import-without-cache@0.4.0: + resolution: {integrity: sha512-NkJQA7oZ4YHQhd2+H3BoRFKF3d/XNsiKpHZCQEMH9pDX27hQQLsTyOocyRgaIVtf8gHX3Nt3LPkR4e5EdtPAGQ==} + engines: {node: ^22.18.0 || >=24.0.0} + + import-without-cache@0.4.1: + resolution: {integrity: sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A==} + engines: {node: ^22.18.0 || >=24.0.0} + + indent-string@4.0.0: + resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} + engines: {node: '>=8'} + + irregular-plurals@3.5.0: + resolution: {integrity: sha512-1ANGLZ+Nkv1ptFb2pa8oG8Lem4krflKuX/gINiHJHjJUKaJHk/SXk5x6K3J+39/p0h1RQ2saROclJJ+QLvETCQ==} + engines: {node: '>=8'} + + is-arrayish@0.2.1: + resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} + + is-core-module@2.16.2: + resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-plain-obj@1.1.0: + resolution: {integrity: sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==} + engines: {node: '>=0.10.0'} + + is-unicode-supported@0.1.0: + resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} + engines: {node: '>=10'} + + jest-diff@29.7.0: + resolution: {integrity: sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-get-type@29.6.3: + resolution: {integrity: sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jiti@2.6.1: + resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} + hasBin: true + + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + json-parse-even-better-errors@2.3.1: + resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} + + keyv@5.6.0: + resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} + + kind-of@6.0.3: + resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} + engines: {node: '>=0.10.0'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + locate-path@5.0.0: + resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} + engines: {node: '>=8'} + + log-symbols@4.1.0: + resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} + engines: {node: '>=10'} + + lru-cache@11.5.2: + resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} + engines: {node: 20 || >=22} + + lru-cache@6.0.0: + resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} + engines: {node: '>=10'} + + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + + magic-string@1.3.1: + resolution: {integrity: sha512-rm91zr2Ou+XueDTohjQQjdQEcYM6zVi8KVUCG8Ec3vHwUEKrhSdCNyfuIywkA6hcCAteIn0ZOtAHA6eGpiX+Pg==} + + magic-string@1.4.2: + resolution: {integrity: sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==} + + magic-string@1.4.3: + resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==} + + magicast@0.5.5: + resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} + + map-obj@1.0.1: + resolution: {integrity: sha512-7N/q3lyZ+LVCp7PzuxrJr4KMbBE2hW7BT7YNia330OFxIf4d3r5zVpicP2650l7CPN6RM9zOJRl3NGpqSiw3Eg==} + engines: {node: '>=0.10.0'} + + map-obj@4.3.0: + resolution: {integrity: sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==} + engines: {node: '>=8'} + + meow@9.0.0: + resolution: {integrity: sha512-+obSblOQmRhcyBt62furQqRAQpNyWXo8BuQ5bN7dG8wmwQ+vwHKp/rCFD4CrTP8CsDQD1sjoZ94K417XEUk8IQ==} + engines: {node: '>=10'} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + min-indent@1.0.1: + resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} + engines: {node: '>=4'} + + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + minimist-options@4.1.0: + resolution: {integrity: sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==} + engines: {node: '>= 6'} + + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + nanoid@3.3.19: + resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + normalize-package-data@2.5.0: + resolution: {integrity: sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==} + + normalize-package-data@3.0.3: + resolution: {integrity: sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA==} + engines: {node: '>=10'} + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + on-exit-leak-free@2.1.2: + resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} + engines: {node: '>=14.0.0'} + + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + + p-locate@4.1.0: + resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} + engines: {node: '>=8'} + + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + + parse-json@5.2.0: + resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} + engines: {node: '>=8'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + path-scurry@2.0.2: + resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + engines: {node: 18 || 20 || >=22} + + path-type@4.0.0: + resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} + engines: {node: '>=8'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + pino-abstract-transport@3.0.0: + resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + + pino-std-serializers@7.1.0: + resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} + + pino@10.3.1: + resolution: {integrity: sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==} + hasBin: true + + plur@4.0.0: + resolution: {integrity: sha512-4UGewrYgqDFw9vV6zNV+ADmPAUAfJPKtGvb/VdpQAx25X5f3xXdGdyOEVFwkl8Hl/tl7+xbeHqSEM+D5/TirUg==} + engines: {node: '>=10'} + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + + pretty-format@29.7.0: + resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + process-warning@5.1.0: + resolution: {integrity: sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==} + + qified@0.10.1: + resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} + engines: {node: '>=20'} + + quansync@1.0.0: + resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + quick-format-unescaped@4.0.4: + resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} + + quick-lru@4.0.1: + resolution: {integrity: sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g==} + engines: {node: '>=8'} + + react-dom@19.3.1: + resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==} + peerDependencies: + react: ^19.3.1 + + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + + react-is@18.3.1: + resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==} + + react@19.3.1: + resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} + engines: {node: '>=0.10.0'} + + read-pkg-up@7.0.1: + resolution: {integrity: sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==} + engines: {node: '>=8'} + + read-pkg@5.2.0: + resolution: {integrity: sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==} + engines: {node: '>=8'} + + real-require@0.2.0: + resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==} + engines: {node: '>= 12.13.0'} + + real-require@1.0.0: + resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} + + redent@3.0.0: + resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} + engines: {node: '>=8'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rimraf@6.1.3: + resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==} + engines: {node: 20 || >=22} + hasBin: true + + rolldown-plugin-dts@0.28.5: + resolution: {integrity: sha512-yYd3C9CeJwqjOc9X23m0Tyxcqic491uLZlfg51szT287S8zCCqLR2uoySoElgqy2CLn7PdXcEo1dlkBs4n1WHg==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + peerDependencies: + '@typescript/native-preview': '*' + '@volar/typescript': ~2.4.0 + rolldown: ^1.2.0 + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + '@typescript/native-preview': + optional: true + '@volar/typescript': + optional: true + typescript: + optional: true + vue-tsc: + optional: true + + rolldown-plugin-dts@0.28.8: + resolution: {integrity: sha512-FVhfqxorCWcc20BVT5eVRfRjzLLl6mgzjcMR4gSBf0K4oQMXT0qoHhhzfXy0L7y83fQy7Ug5ZDNk90xM3/LiCQ==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + peerDependencies: + '@typescript/native-preview': '*' + '@volar/typescript': ~2.4.0 + '@vue/language-core': ~3.2.0 || ~3.3.0 + rolldown: ^1.2.0 + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + '@typescript/native-preview': + optional: true + '@volar/typescript': + optional: true + '@vue/language-core': + optional: true + typescript: + optional: true + vue-tsc: + optional: true + + rolldown@1.0.0-rc.12: + resolution: {integrity: sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rolldown@1.2.8: + resolution: {integrity: sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + + sonic-boom@4.2.1: + resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + spdx-correct@3.2.0: + resolution: {integrity: sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==} + + spdx-exceptions@2.5.0: + resolution: {integrity: sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==} + + spdx-expression-parse@3.0.1: + resolution: {integrity: sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==} + + spdx-license-ids@3.0.23: + resolution: {integrity: sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.2.0: + resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-indent@3.0.0: + resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} + engines: {node: '>=8'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-hyperlinks@2.3.0: + resolution: {integrity: sha512-RpsAZlpWcDwOPQA22aCH4J0t7L8JmAvsCxfOSEwm7cQs3LshN36QaTkwd70DnBOXDWGssw2eUoc8CaRWT0XunA==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + terser@5.39.0: + resolution: {integrity: sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==} + engines: {node: '>=10'} + hasBin: true + + thread-stream@4.2.0: + resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==} + engines: {node: '>=20'} + + tinybench@6.1.4: + resolution: {integrity: sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==} + engines: {node: '>=20.0.0'} + + tinybench@6.2.0: + resolution: {integrity: sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==} + engines: {node: '>=20.0.0'} + + tinybench@6.2.2: + resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.0: + resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==} + engines: {node: '>=18'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyps@0.5.1: + resolution: {integrity: sha512-B6Ykif5HflC3AdDkS4Zst/2muYVfeXoVMy+KorqH80s/1x4vunIORpNySH681X7fjj+dFM9MDKD6/Hsccjb87Q==} + + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} + engines: {node: '>=14.0.0'} + + tinyrainbow@3.2.0: + resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} + engines: {node: '>=14.0.0'} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + + trim-newlines@3.0.1: + resolution: {integrity: sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw==} + engines: {node: '>=8'} + + tsd@0.33.0: + resolution: {integrity: sha512-/PQtykJFVw90QICG7zyPDMIyueOXKL7jOJVoX5pILnb3Ux+7QqynOxfVvarE+K+yi7BZyOSY4r+OZNWSWRiEwQ==} + engines: {node: '>=14.16'} + hasBin: true + + tsdown@0.23.0: + resolution: {integrity: sha512-BaT+ep1xnj5hdyICLd5r5SYYE+TXnI1ATePLykv9vcKpHpFTWUWRH+x1AF/E2qcu3YB6+vI8IdyxIIIffEqw5Q==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@arethetypeswrong/core': ^0.18.1 + '@tsdown/css': 0.23.0 + '@tsdown/exe': 0.23.0 + '@vitejs/devtools': '*' + publint: ^0.3.8 + tsx: '*' + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: '>=0.5.0' + unrun: '*' + peerDependenciesMeta: + '@arethetypeswrong/core': + optional: true + '@tsdown/css': + optional: true + '@tsdown/exe': + optional: true + '@vitejs/devtools': + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + + tsdown@0.23.4: + resolution: {integrity: sha512-AQQ/2Y7KBnf15GL4Ynjdltc94PkbKRI+arStyrp7inSQkRmTWNiXgfv50ESsjhBEsoVtiSloCAO2VyrqojWIOQ==} + engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@arethetypeswrong/core': ^0.18.1 + '@tsdown/css': 0.23.4 + '@tsdown/exe': 0.23.4 + '@vitejs/devtools': '*' + publint: ^0.3.8 + tsx: '*' + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: '>=0.5.0' + unrun: '*' + peerDependenciesMeta: + '@arethetypeswrong/core': + optional: true + '@tsdown/css': + optional: true + '@tsdown/exe': + optional: true + '@vitejs/devtools': + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + type-fest@0.18.1: + resolution: {integrity: sha512-OIAYXk8+ISY+qTOwkHtKqzAuxchoMiD9Udx+FSGQDuiRR+PJKJHc2NJAXlbhkGwTt/4/nKZxELY1w3ReWOL8mw==} + engines: {node: '>=10'} + + type-fest@0.21.3: + resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} + engines: {node: '>=10'} + + type-fest@0.6.0: + resolution: {integrity: sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==} + engines: {node: '>=8'} + + type-fest@0.8.1: + resolution: {integrity: sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==} + engines: {node: '>=8'} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + unconfig-core@7.5.0: + resolution: {integrity: sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w==} + + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + undici-types@8.12.3: + resolution: {integrity: sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA==} + + undici@7.29.1: + resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==} + engines: {node: '>=20.18.1'} + + unrun@0.2.34: + resolution: {integrity: sha512-LyaghRBR++r7svhDK6tnDz2XaYHWdneBOA0jbS8wnRsHerI9MFljX4fIiTgbbNbEVzZ0C9P1OjWLLe1OqoaaEw==} + engines: {node: '>=20.19.0'} + hasBin: true + peerDependencies: + synckit: ^0.11.11 + peerDependenciesMeta: + synckit: + optional: true + + validate-npm-package-license@3.0.4: + resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} + + verkit@0.4.0: + resolution: {integrity: sha512-sXMwN6DMHeouPfCxkxWkKAmxphWKEenHYY5H1nIBzU3PmDsmJp6kBXJdshjVdpMZuWCmL9SH7KFRx29AylpP6g==} + engines: {node: '>=18.12.0'} + + verkit@0.5.0: + resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} + engines: {node: '>=18.12.0'} + + vite@8.3.0: + resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.0: + resolution: {integrity: sha512-gpsMNoRhMjMktVxPtstOH4/PJuPyovVaMDr4oDilXaGH1EcqM2OE96SoHT2VIQ6fTGtTjqmHDrEu2X9RQiXf8Q==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.0 + '@vitest/browser-preview': 5.0.0 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.0 + '@vitest/coverage-v8': 5.0.0 + '@vitest/ui': 5.0.0 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vitest@5.0.3: + resolution: {integrity: sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.3 + '@vitest/browser-preview': 5.0.3 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.3 + '@vitest/coverage-v8': 5.0.3 + '@vitest/ui': 5.0.3 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + whatwg-mimetype@3.0.0: + resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} + engines: {node: '>=12'} + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + + ws@8.21.3: + resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + yallist@4.0.0: + resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + + yargs-parser@20.2.9: + resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} + engines: {node: '>=10'} + + yuku-ast@0.19.0: + resolution: {integrity: sha512-PyCsiScaelhxBGzL8dyeJkLqvRZycoh78R31Vrt/WqYrm0hMFoKwIw/X7Dx5mBKLWAMlV9I9HEyBOHnj2gZVyw==} + engines: {node: '>=14.18.0'} + + yuku-ast@0.9.5: + resolution: {integrity: sha512-Q8qW8WwQnN5Cm0ZZivdRIfv0sRLTjUq0YumXJkw8CYN1aCdICH9rk4C47/4n6kA5EqDtlj+F608twoTSV2MwdQ==} + + yuku-codegen@0.19.0: + resolution: {integrity: sha512-uymAKHjDuaP4BEpkXC/BSLz4DUEF5oArZ5AuD3888nb2miChjWSgpPdojEJxm3pjpXkgUaCRJQyNAbnMN33wHg==} + engines: {node: '>=14.18.0'} + + yuku-codegen@0.9.5: + resolution: {integrity: sha512-zGUVyDpSK4b6c9B0yyxi2P0wujn1XZTbG9dCb7d6gyAoP63EMgyLzUwPUvwxPG5jgYqhlI7w+S3oCyapqGr4PA==} + + yuku-core@0.19.0: + resolution: {integrity: sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg==} + engines: {node: '>=14.18.0'} + + yuku-parser@0.19.0: + resolution: {integrity: sha512-XrBh9ZiQK5mJVRxZBAvD6LwRyAYrK3MFtH3+onyuxFL5hFD44EC3QOmIC1FjTj6H2MMwq46/NAI+NZxLZPZgxg==} + engines: {node: '>=14.18.0'} + + yuku-parser@0.9.5: + resolution: {integrity: sha512-IBnAdNVMswWbJcM7woPluOudectJzFjJ1N8jVRxP9Uq4CIv5hZdBIcdmtRbFDYF/Ph2j2gVup4YJ4N9mh0jYFA==} + +snapshots: + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/parser@7.29.9': + dependencies: + '@babel/types': 7.29.8 + + '@babel/runtime@7.29.7': {} + + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@bcoe/v8-coverage@1.0.2': {} + + '@biomejs/biome@2.5.13': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 2.5.13 + '@biomejs/cli-darwin-x64': 2.5.13 + '@biomejs/cli-linux-arm64': 2.5.13 + '@biomejs/cli-linux-arm64-musl': 2.5.13 + '@biomejs/cli-linux-x64': 2.5.13 + '@biomejs/cli-linux-x64-musl': 2.5.13 + '@biomejs/cli-win32-arm64': 2.5.13 + '@biomejs/cli-win32-x64': 2.5.13 + + '@biomejs/biome@2.5.15': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 2.5.15 + '@biomejs/cli-darwin-x64': 2.5.15 + '@biomejs/cli-linux-arm64': 2.5.15 + '@biomejs/cli-linux-arm64-musl': 2.5.15 + '@biomejs/cli-linux-x64': 2.5.15 + '@biomejs/cli-linux-x64-musl': 2.5.15 + '@biomejs/cli-win32-arm64': 2.5.15 + '@biomejs/cli-win32-x64': 2.5.15 + + '@biomejs/biome@2.6.4': + optionalDependencies: + '@biomejs/cli-android-arm64': 2.6.4 + '@biomejs/cli-android-x64': 2.6.4 + '@biomejs/cli-darwin-arm64': 2.6.4 + '@biomejs/cli-darwin-x64': 2.6.4 + '@biomejs/cli-linux-arm64': 2.6.4 + '@biomejs/cli-linux-arm64-musl': 2.6.4 + '@biomejs/cli-linux-x64': 2.6.4 + '@biomejs/cli-linux-x64-musl': 2.6.4 + '@biomejs/cli-win32-arm64': 2.6.4 + '@biomejs/cli-win32-x64': 2.6.4 + + '@biomejs/cli-android-arm64@2.6.4': + optional: true + + '@biomejs/cli-android-x64@2.6.4': + optional: true + + '@biomejs/cli-darwin-arm64@2.5.13': + optional: true + + '@biomejs/cli-darwin-arm64@2.5.15': + optional: true + + '@biomejs/cli-darwin-arm64@2.6.4': + optional: true + + '@biomejs/cli-darwin-x64@2.5.13': + optional: true + + '@biomejs/cli-darwin-x64@2.5.15': + optional: true + + '@biomejs/cli-darwin-x64@2.6.4': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.5.13': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.5.15': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.6.4': + optional: true + + '@biomejs/cli-linux-arm64@2.5.13': + optional: true + + '@biomejs/cli-linux-arm64@2.5.15': + optional: true + + '@biomejs/cli-linux-arm64@2.6.4': + optional: true + + '@biomejs/cli-linux-x64-musl@2.5.13': + optional: true + + '@biomejs/cli-linux-x64-musl@2.5.15': + optional: true + + '@biomejs/cli-linux-x64-musl@2.6.4': + optional: true + + '@biomejs/cli-linux-x64@2.5.13': + optional: true + + '@biomejs/cli-linux-x64@2.5.15': + optional: true + + '@biomejs/cli-linux-x64@2.6.4': + optional: true + + '@biomejs/cli-win32-arm64@2.5.13': + optional: true + + '@biomejs/cli-win32-arm64@2.5.15': + optional: true + + '@biomejs/cli-win32-arm64@2.6.4': + optional: true + + '@biomejs/cli-win32-x64@2.5.13': + optional: true + + '@biomejs/cli-win32-x64@2.5.15': + optional: true + + '@biomejs/cli-win32-x64@2.6.4': + optional: true + + '@cacheable/memory@2.2.0': + dependencies: + '@cacheable/utils': 2.5.0 + '@keyv/bigmap': 1.3.1(keyv@5.6.0) + hookified: 1.15.1 + keyv: 5.6.0 + + '@cacheable/net@2.1.0': + dependencies: + '@cacheable/utils': 2.5.0 + cacheable: 2.5.0 + hookified: 1.15.1 + http-cache-semantics: 4.2.0 + undici: 7.29.1 + + '@cacheable/utils@2.5.0': + dependencies: + hashery: 1.5.1 + keyv: 5.6.0 + + '@emnapi/core@1.11.1': + dependencies: + '@emnapi/wasi-threads': 1.2.2 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.11.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@esbuild/aix-ppc64@0.27.7': + optional: true + + '@esbuild/android-arm64@0.27.7': + optional: true + + '@esbuild/android-arm@0.27.7': + optional: true + + '@esbuild/android-x64@0.27.7': + optional: true + + '@esbuild/darwin-arm64@0.27.7': + optional: true + + '@esbuild/darwin-x64@0.27.7': + optional: true + + '@esbuild/freebsd-arm64@0.27.7': + optional: true + + '@esbuild/freebsd-x64@0.27.7': + optional: true + + '@esbuild/linux-arm64@0.27.7': + optional: true + + '@esbuild/linux-arm@0.27.7': + optional: true + + '@esbuild/linux-ia32@0.27.7': + optional: true + + '@esbuild/linux-loong64@0.27.7': + optional: true + + '@esbuild/linux-mips64el@0.27.7': + optional: true + + '@esbuild/linux-ppc64@0.27.7': + optional: true + + '@esbuild/linux-riscv64@0.27.7': + optional: true + + '@esbuild/linux-s390x@0.27.7': + optional: true + + '@esbuild/linux-x64@0.27.7': + optional: true + + '@esbuild/netbsd-arm64@0.27.7': + optional: true + + '@esbuild/netbsd-x64@0.27.7': + optional: true + + '@esbuild/openbsd-arm64@0.27.7': + optional: true + + '@esbuild/openbsd-x64@0.27.7': + optional: true + + '@esbuild/openharmony-arm64@0.27.7': + optional: true + + '@esbuild/sunos-x64@0.27.7': + optional: true + + '@esbuild/win32-arm64@0.27.7': + optional: true + + '@esbuild/win32-ia32@0.27.7': + optional: true + + '@esbuild/win32-x64@0.27.7': + optional: true + + '@faker-js/faker@10.6.0': {} + + '@jest/schemas@29.6.3': + dependencies: + '@sinclair/typebox': 0.27.12 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + optional: true + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/source-map@0.3.11': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + optional: true + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@keyv/bigmap@1.3.1(keyv@5.6.0)': + dependencies: + hashery: 1.5.1 + hookified: 1.15.1 + keyv: 5.6.0 + + '@keyv/serialize@1.1.1': {} + + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': + dependencies: + '@emnapi/core': 1.11.1 + '@emnapi/runtime': 1.11.1 + '@tybys/wasm-util': 0.10.3 + optional: true + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.3 + + '@oxc-project/types@0.122.0': + optional: true + + '@oxc-project/types@0.149.0': {} + + '@oxc-project/types@0.156.0': {} + + '@pinojs/redact@0.4.0': {} + + '@quansync/fs@1.0.0': + dependencies: + quansync: 1.0.0 + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm-eabi@1.2.8': + optional: true + + '@rolldown/binding-android-arm64@1.0.0-rc.12': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.8': + optional: true + + '@rolldown/binding-darwin-arm64@1.0.0-rc.12': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.8': + optional: true + + '@rolldown/binding-darwin-x64@1.0.0-rc.12': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.8': + optional: true + + '@rolldown/binding-freebsd-x64@1.0.0-rc.12': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.8': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.8': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.8': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.8': + optional: true + + '@rolldown/binding-linux-x64-musl@1.0.0-rc.12': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.8': + optional: true + + '@rolldown/binding-openharmony-arm64@1.0.0-rc.12': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.8': + optional: true + + '@rolldown/binding-wasm32-wasi@1.0.0-rc.12(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': + dependencies: + '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.0.0-rc.12': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.8': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.0.0-rc.12': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.8': + optional: true + + '@rolldown/pluginutils@1.0.0-rc.12': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@sinclair/typebox@0.27.12': {} + + '@testing-library/dom@10.4.1': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/runtime': 7.29.7 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.5.1 + + '@testing-library/react@16.3.3(@testing-library/dom@10.4.1)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.7 + '@testing-library/dom': 10.4.1 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + + '@tsd/typescript@5.9.3': {} + + '@tybys/wasm-util@0.10.3': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/aria-query@5.0.4': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/eslint@7.29.0': + dependencies: + '@types/estree': 1.0.9 + '@types/json-schema': 7.0.15 + + '@types/estree@1.0.9': {} + + '@types/json-schema@7.0.15': {} + + '@types/minimist@1.2.5': {} + + '@types/node@22.20.5': + dependencies: + undici-types: 8.12.3 + + '@types/node@24.13.4': + dependencies: + undici-types: 7.18.2 + + '@types/node@24.19.0': + dependencies: + undici-types: 7.24.6 + + '@types/normalize-package-data@2.4.4': {} + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + + '@types/whatwg-mimetype@3.0.2': {} + + '@types/ws@8.18.1': + dependencies: + '@types/node': 22.20.5 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/coverage-v8@5.0.0(vitest@5.0.0)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/istanbul-lib-coverage': 1.0.1 + '@vitest/istanbul-lib-report': 1.0.1 + ast-v8-to-istanbul: 1.0.6 + magicast: 0.5.5 + obug: 2.2.1 + std-env: 4.2.0 + tinyrainbow: 3.1.1 + vitest: 5.0.0(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + + '@vitest/coverage-v8@5.0.3(vitest@5.0.3)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/istanbul-lib-coverage': 1.0.2 + '@vitest/istanbul-lib-report': 1.0.2 + ast-v8-to-istanbul: 1.0.7 + magicast: 0.5.5 + obug: 2.2.1 + std-env: 4.3.0 + tinyrainbow: 3.2.0 + vitest: 5.0.3(@types/node@24.19.0)(@vitest/coverage-v8@5.0.3)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + + '@vitest/coverage-v8@5.0.5(vitest@5.0.5)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/istanbul-lib-coverage': 1.0.2 + '@vitest/istanbul-lib-report': 1.0.2 + ast-v8-to-istanbul: 1.0.7 + magicast: 0.5.5 + obug: 3.0.0 + std-env: 4.3.0 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(happy-dom@21.0.4)(vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + + '@vitest/istanbul-lib-coverage@1.0.1': {} + + '@vitest/istanbul-lib-coverage@1.0.2': {} + + '@vitest/istanbul-lib-report@1.0.1': + dependencies: + '@vitest/istanbul-lib-coverage': 1.0.1 + + '@vitest/istanbul-lib-report@1.0.2': + dependencies: + '@vitest/istanbul-lib-coverage': 1.0.2 + + '@vitest/mocker@5.0.0(vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.0 + estree-walker: 3.0.3 + magic-string: 1.3.1 + optionalDependencies: + vite: 8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + + '@vitest/mocker@5.0.3(vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.3 + estree-walker: 3.0.3 + magic-string: 1.4.2 + optionalDependencies: + vite: 8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + + '@vitest/mocker@5.0.5(vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.3 + optionalDependencies: + vite: 8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + + '@vitest/spy@5.0.0': {} + + '@vitest/spy@5.0.3': {} + + '@vitest/spy@5.0.5': {} + + '@yuku-codegen/binding-android-arm64@0.9.5': + optional: true + + '@yuku-codegen/binding-darwin-arm64@0.9.5': + optional: true + + '@yuku-codegen/binding-darwin-x64@0.9.5': + optional: true + + '@yuku-codegen/binding-freebsd-x64@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-arm-gnu@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-arm-musl@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-arm64-gnu@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-arm64-musl@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-x64-gnu@0.9.5': + optional: true + + '@yuku-codegen/binding-linux-x64-musl@0.9.5': + optional: true + + '@yuku-codegen/binding-win32-arm64@0.9.5': + optional: true + + '@yuku-codegen/binding-win32-x64@0.9.5': + optional: true + + '@yuku-core/binding-android-arm64@0.19.0': + optional: true + + '@yuku-core/binding-darwin-arm64@0.19.0': + optional: true + + '@yuku-core/binding-darwin-x64@0.19.0': + optional: true + + '@yuku-core/binding-freebsd-x64@0.19.0': + optional: true + + '@yuku-core/binding-linux-arm-gnu@0.19.0': + optional: true + + '@yuku-core/binding-linux-arm-musl@0.19.0': + optional: true + + '@yuku-core/binding-linux-arm64-gnu@0.19.0': + optional: true + + '@yuku-core/binding-linux-arm64-musl@0.19.0': + optional: true + + '@yuku-core/binding-linux-x64-gnu@0.19.0': + optional: true + + '@yuku-core/binding-linux-x64-musl@0.19.0': + optional: true + + '@yuku-core/binding-win32-arm64@0.19.0': + optional: true + + '@yuku-core/binding-win32-x64@0.19.0': + optional: true + + '@yuku-parser/binding-android-arm64@0.9.5': + optional: true + + '@yuku-parser/binding-darwin-arm64@0.9.5': + optional: true + + '@yuku-parser/binding-darwin-x64@0.9.5': + optional: true + + '@yuku-parser/binding-freebsd-x64@0.9.5': + optional: true + + '@yuku-parser/binding-linux-arm-gnu@0.9.5': + optional: true + + '@yuku-parser/binding-linux-arm-musl@0.9.5': + optional: true + + '@yuku-parser/binding-linux-arm64-gnu@0.9.5': + optional: true + + '@yuku-parser/binding-linux-arm64-musl@0.9.5': + optional: true + + '@yuku-parser/binding-linux-x64-gnu@0.9.5': + optional: true + + '@yuku-parser/binding-linux-x64-musl@0.9.5': + optional: true + + '@yuku-parser/binding-win32-arm64@0.9.5': + optional: true + + '@yuku-parser/binding-win32-x64@0.9.5': + optional: true + + '@yuku-toolchain/types@0.19.0': {} + + '@yuku-toolchain/types@0.9.5': {} + + acorn@8.16.0: + optional: true + + ansi-escapes@4.3.2: + dependencies: + type-fest: 0.21.3 + + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.2.0: {} + + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + + array-union@2.1.0: {} + + arrify@1.0.1: {} + + assertion-error@2.0.1: {} + + ast-v8-to-istanbul@1.0.6: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + + ast-v8-to-istanbul@1.0.7: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + + atomic-sleep@1.0.0: {} + + balanced-match@4.0.4: {} + + brace-expansion@5.0.9: + dependencies: + balanced-match: 4.0.4 + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + buffer-from@1.1.2: + optional: true + + buffer-image-size@0.6.4: + dependencies: + '@types/node': 22.20.5 + + cac@7.0.0: {} + + cac@7.1.0: {} + + cacheable@2.5.0: + dependencies: + '@cacheable/memory': 2.2.0 + '@cacheable/utils': 2.5.0 + hookified: 1.15.1 + keyv: 5.6.0 + qified: 0.10.1 + + camelcase-keys@6.2.2: + dependencies: + camelcase: 5.3.1 + map-obj: 4.3.0 + quick-lru: 4.0.1 + + camelcase@5.3.1: {} + + chai@6.2.2: {} + + chai@6.3.0: {} + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + commander@2.20.3: + optional: true + + csstype@3.2.3: {} + + decamelize-keys@1.1.1: + dependencies: + decamelize: 1.2.0 + map-obj: 1.0.1 + + decamelize@1.2.0: {} + + defu@6.1.7: {} + + dequal@2.0.3: {} + + detect-libc@2.1.2: {} + + diff-sequences@29.6.3: {} + + dir-glob@3.0.1: + dependencies: + path-type: 4.0.0 + + dom-accessibility-api@0.5.16: {} + + dotenv@18.0.9: {} + + dts-resolver@3.0.0: {} + + emoji-regex@8.0.0: {} + + empathic@2.0.1: {} + + empathic@2.1.0: {} + + entities@7.0.1: {} + + error-ex@1.3.4: + dependencies: + is-arrayish: 0.2.1 + + es-errors@1.3.0: {} + + es-module-lexer@2.3.2: {} + + esbuild@0.27.7: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.7 + '@esbuild/android-arm': 0.27.7 + '@esbuild/android-arm64': 0.27.7 + '@esbuild/android-x64': 0.27.7 + '@esbuild/darwin-arm64': 0.27.7 + '@esbuild/darwin-x64': 0.27.7 + '@esbuild/freebsd-arm64': 0.27.7 + '@esbuild/freebsd-x64': 0.27.7 + '@esbuild/linux-arm': 0.27.7 + '@esbuild/linux-arm64': 0.27.7 + '@esbuild/linux-ia32': 0.27.7 + '@esbuild/linux-loong64': 0.27.7 + '@esbuild/linux-mips64el': 0.27.7 + '@esbuild/linux-ppc64': 0.27.7 + '@esbuild/linux-riscv64': 0.27.7 + '@esbuild/linux-s390x': 0.27.7 + '@esbuild/linux-x64': 0.27.7 + '@esbuild/netbsd-arm64': 0.27.7 + '@esbuild/netbsd-x64': 0.27.7 + '@esbuild/openbsd-arm64': 0.27.7 + '@esbuild/openbsd-x64': 0.27.7 + '@esbuild/openharmony-arm64': 0.27.7 + '@esbuild/sunos-x64': 0.27.7 + '@esbuild/win32-arm64': 0.27.7 + '@esbuild/win32-ia32': 0.27.7 + '@esbuild/win32-x64': 0.27.7 + optional: true + + eslint-formatter-pretty@4.1.0: + dependencies: + '@types/eslint': 7.29.0 + ansi-escapes: 4.3.2 + chalk: 4.1.2 + eslint-rule-docs: 1.1.235 + log-symbols: 4.1.0 + plur: 4.0.0 + string-width: 4.2.3 + supports-hyperlinks: 2.3.0 + + eslint-rule-docs@1.1.235: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fastq@1.20.3: + dependencies: + reusify: 1.1.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@4.1.0: + dependencies: + locate-path: 5.0.0 + path-exists: 4.0.0 + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + get-tsconfig@5.0.0-beta.6: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob@13.0.6: + dependencies: + minimatch: 10.2.6 + minipass: 7.1.3 + path-scurry: 2.0.2 + + globby@11.1.0: + dependencies: + array-union: 2.1.0 + dir-glob: 3.0.1 + fast-glob: 3.3.3 + ignore: 5.3.2 + merge2: 1.4.1 + slash: 3.0.0 + + happy-dom@21.0.4: + dependencies: + '@types/node': 22.20.5 + '@types/whatwg-mimetype': 3.0.2 + '@types/ws': 8.18.1 + buffer-image-size: 0.6.4 + entities: 7.0.1 + whatwg-mimetype: 3.0.0 + ws: 8.21.3 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + hard-rejection@2.1.0: {} + + has-flag@4.0.0: {} + + hashery@1.5.1: + dependencies: + hookified: 1.15.1 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + hookable@6.1.1: {} + + hookable@6.1.2: {} + + hookified@1.15.1: {} + + hookified@2.2.0: {} + + hookified@3.0.3: {} + + hookified@3.0.4: {} + + hosted-git-info@2.8.9: {} + + hosted-git-info@4.1.0: + dependencies: + lru-cache: 6.0.0 + + http-cache-semantics@4.2.0: {} + + ignore@5.3.2: {} + + import-without-cache@0.4.0: {} + + import-without-cache@0.4.1: {} + + indent-string@4.0.0: {} + + irregular-plurals@3.5.0: {} + + is-arrayish@0.2.1: {} + + is-core-module@2.16.2: + dependencies: + hasown: 2.0.4 + + is-extglob@2.1.1: {} + + is-fullwidth-code-point@3.0.0: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-number@7.0.0: {} + + is-plain-obj@1.1.0: {} + + is-unicode-supported@0.1.0: {} + + jest-diff@29.7.0: + dependencies: + chalk: 4.1.2 + diff-sequences: 29.6.3 + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-get-type@29.6.3: {} + + jiti@2.6.1: + optional: true + + js-tokens@10.0.0: {} + + js-tokens@4.0.0: {} + + json-parse-even-better-errors@2.3.1: {} + + keyv@5.6.0: + dependencies: + '@keyv/serialize': 1.1.1 + + kind-of@6.0.3: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lines-and-columns@1.2.4: {} + + locate-path@5.0.0: + dependencies: + p-locate: 4.1.0 + + log-symbols@4.1.0: + dependencies: + chalk: 4.1.2 + is-unicode-supported: 0.1.0 + + lru-cache@11.5.2: {} + + lru-cache@6.0.0: + dependencies: + yallist: 4.0.0 + + lz-string@1.5.0: {} + + magic-string@1.3.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.4.2: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.4.3: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magicast@0.5.5: + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + source-map-js: 1.2.1 + + map-obj@1.0.1: {} + + map-obj@4.3.0: {} + + meow@9.0.0: + dependencies: + '@types/minimist': 1.2.5 + camelcase-keys: 6.2.2 + decamelize: 1.2.0 + decamelize-keys: 1.1.1 + hard-rejection: 2.1.0 + minimist-options: 4.1.0 + normalize-package-data: 3.0.3 + read-pkg-up: 7.0.1 + redent: 3.0.0 + trim-newlines: 3.0.1 + type-fest: 0.18.1 + yargs-parser: 20.2.9 + + merge2@1.4.1: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + min-indent@1.0.1: {} + + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.9 + + minimist-options@4.1.0: + dependencies: + arrify: 1.0.1 + is-plain-obj: 1.1.0 + kind-of: 6.0.3 + + minipass@7.1.3: {} + + nanoid@3.3.19: {} + + normalize-package-data@2.5.0: + dependencies: + hosted-git-info: 2.8.9 + resolve: 1.22.12 + semver: 7.8.5 + validate-npm-package-license: 3.0.4 + + normalize-package-data@3.0.3: + dependencies: + hosted-git-info: 4.1.0 + is-core-module: 2.16.2 + semver: 7.8.5 + validate-npm-package-license: 3.0.4 + + obug@2.2.1: {} + + obug@3.0.0: {} + + on-exit-leak-free@2.1.2: {} + + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + + p-locate@4.1.0: + dependencies: + p-limit: 2.3.0 + + p-try@2.2.0: {} + + package-json-from-dist@1.0.1: {} + + parse-json@5.2.0: + dependencies: + '@babel/code-frame': 7.29.7 + error-ex: 1.3.4 + json-parse-even-better-errors: 2.3.1 + lines-and-columns: 1.2.4 + + path-exists@4.0.0: {} + + path-parse@1.0.7: {} + + path-scurry@2.0.2: + dependencies: + lru-cache: 11.5.2 + minipass: 7.1.3 + + path-type@4.0.0: {} + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.7: {} + + pino-abstract-transport@3.0.0: + dependencies: + split2: 4.2.0 + + pino-std-serializers@7.1.0: {} + + pino@10.3.1: + dependencies: + '@pinojs/redact': 0.4.0 + atomic-sleep: 1.0.0 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pino-std-serializers: 7.1.0 + process-warning: 5.1.0 + quick-format-unescaped: 4.0.4 + real-require: 0.2.0 + safe-stable-stringify: 2.5.0 + sonic-boom: 4.2.1 + thread-stream: 4.2.0 + + plur@4.0.0: + dependencies: + irregular-plurals: 3.5.0 + + postcss@8.5.28: + dependencies: + nanoid: 3.3.19 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + + pretty-format@29.7.0: + dependencies: + '@jest/schemas': 29.6.3 + ansi-styles: 5.2.0 + react-is: 18.3.1 + + process-warning@5.1.0: {} + + qified@0.10.1: + dependencies: + hookified: 2.2.0 + + quansync@1.0.0: {} + + queue-microtask@1.2.3: {} + + quick-format-unescaped@4.0.4: {} + + quick-lru@4.0.1: {} + + react-dom@19.3.1(react@19.3.1): + dependencies: + react: 19.3.1 + scheduler: 0.28.0 + + react-is@17.0.2: {} + + react-is@18.3.1: {} + + react@19.3.1: {} + + read-pkg-up@7.0.1: + dependencies: + find-up: 4.1.0 + read-pkg: 5.2.0 + type-fest: 0.8.1 + + read-pkg@5.2.0: + dependencies: + '@types/normalize-package-data': 2.4.4 + normalize-package-data: 2.5.0 + parse-json: 5.2.0 + type-fest: 0.6.0 + + real-require@0.2.0: {} + + real-require@1.0.0: {} + + redent@3.0.0: + dependencies: + indent-string: 4.0.0 + strip-indent: 3.0.0 + + resolve-pkg-maps@1.0.0: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.16.2 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + reusify@1.1.0: {} + + rimraf@6.1.3: + dependencies: + glob: 13.0.6 + package-json-from-dist: 1.0.1 + + rolldown-plugin-dts@0.28.5(rolldown@1.2.8)(typescript@7.0.2): + dependencies: + dts-resolver: 3.0.0 + get-tsconfig: 5.0.0-beta.6 + obug: 2.2.1 + rolldown: 1.2.8 + yuku-ast: 0.9.5 + yuku-codegen: 0.9.5 + yuku-parser: 0.9.5 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - oxc-resolver + + rolldown-plugin-dts@0.28.8(rolldown@1.2.16)(typescript@7.0.2): + dependencies: + dts-resolver: 3.0.0 + get-tsconfig: 5.0.0-beta.6 + obug: 3.0.0 + rolldown: 1.2.16 + yuku-ast: 0.19.0 + yuku-codegen: 0.19.0 + yuku-parser: 0.19.0 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - oxc-resolver + + rolldown@1.0.0-rc.12(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1): + dependencies: + '@oxc-project/types': 0.122.0 + '@rolldown/pluginutils': 1.0.0-rc.12 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.0.0-rc.12 + '@rolldown/binding-darwin-arm64': 1.0.0-rc.12 + '@rolldown/binding-darwin-x64': 1.0.0-rc.12 + '@rolldown/binding-freebsd-x64': 1.0.0-rc.12 + '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-rc.12 + '@rolldown/binding-linux-arm64-gnu': 1.0.0-rc.12 + '@rolldown/binding-linux-arm64-musl': 1.0.0-rc.12 + '@rolldown/binding-linux-ppc64-gnu': 1.0.0-rc.12 + '@rolldown/binding-linux-s390x-gnu': 1.0.0-rc.12 + '@rolldown/binding-linux-x64-gnu': 1.0.0-rc.12 + '@rolldown/binding-linux-x64-musl': 1.0.0-rc.12 + '@rolldown/binding-openharmony-arm64': 1.0.0-rc.12 + '@rolldown/binding-wasm32-wasi': 1.0.0-rc.12(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.12 + '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.12 + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + optional: true + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + rolldown@1.2.8: + dependencies: + '@oxc-project/types': 0.149.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.8 + '@rolldown/binding-android-arm64': 1.2.8 + '@rolldown/binding-darwin-arm64': 1.2.8 + '@rolldown/binding-darwin-x64': 1.2.8 + '@rolldown/binding-freebsd-x64': 1.2.8 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.8 + '@rolldown/binding-linux-arm64-gnu': 1.2.8 + '@rolldown/binding-linux-arm64-musl': 1.2.8 + '@rolldown/binding-linux-ppc64-gnu': 1.2.8 + '@rolldown/binding-linux-s390x-gnu': 1.2.8 + '@rolldown/binding-linux-x64-gnu': 1.2.8 + '@rolldown/binding-linux-x64-musl': 1.2.8 + '@rolldown/binding-openharmony-arm64': 1.2.8 + '@rolldown/binding-win32-arm64-msvc': 1.2.8 + '@rolldown/binding-win32-x64-msvc': 1.2.8 + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + safe-stable-stringify@2.5.0: {} + + scheduler@0.28.0: {} + + semver@7.8.5: {} + + siginfo@2.0.0: {} + + slash@3.0.0: {} + + sonic-boom@4.2.1: + dependencies: + atomic-sleep: 1.0.0 + + source-map-js@1.2.1: {} + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + optional: true + + source-map@0.6.1: + optional: true + + spdx-correct@3.2.0: + dependencies: + spdx-expression-parse: 3.0.1 + spdx-license-ids: 3.0.23 + + spdx-exceptions@2.5.0: {} + + spdx-expression-parse@3.0.1: + dependencies: + spdx-exceptions: 2.5.0 + spdx-license-ids: 3.0.23 + + spdx-license-ids@3.0.23: {} + + split2@4.2.0: {} + + stackback@0.0.2: {} + + std-env@4.2.0: {} + + std-env@4.3.0: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-indent@3.0.0: + dependencies: + min-indent: 1.0.1 + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-hyperlinks@2.3.0: + dependencies: + has-flag: 4.0.0 + supports-color: 7.2.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + terser@5.39.0: + dependencies: + '@jridgewell/source-map': 0.3.11 + acorn: 8.16.0 + commander: 2.20.3 + source-map-support: 0.5.21 + optional: true + + thread-stream@4.2.0: + dependencies: + real-require: 1.0.0 + + tinybench@6.1.4: {} + + tinybench@6.2.0: {} + + tinybench@6.2.2: {} + + tinyexec@1.3.0: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyps@0.5.1: {} + + tinyrainbow@3.1.1: {} + + tinyrainbow@3.2.0: {} + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tree-kill@1.2.2: {} + + trim-newlines@3.0.1: {} + + tsd@0.33.0: + dependencies: + '@tsd/typescript': 5.9.3 + eslint-formatter-pretty: 4.1.0 + globby: 11.1.0 + jest-diff: 29.7.0 + meow: 9.0.0 + path-exists: 4.0.0 + read-pkg-up: 7.0.1 + + tsdown@0.23.0(typescript@7.0.2)(unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)): + dependencies: + cac: 7.0.0 + defu: 6.1.7 + empathic: 2.0.1 + hookable: 6.1.1 + import-without-cache: 0.4.0 + obug: 2.2.1 + picomatch: 4.0.7 + rolldown: 1.2.8 + rolldown-plugin-dts: 0.28.5(rolldown@1.2.8)(typescript@7.0.2) + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tree-kill: 1.2.2 + unconfig-core: 7.5.0 + verkit: 0.4.0 + optionalDependencies: + typescript: 7.0.2 + unrun: 0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + transitivePeerDependencies: + - '@typescript/native-preview' + - '@volar/typescript' + - oxc-resolver + - vue-tsc + + tsdown@0.23.4(typescript@7.0.2)(unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)): + dependencies: + cac: 7.1.0 + defu: 6.1.7 + empathic: 2.1.0 + hookable: 6.1.2 + import-without-cache: 0.4.1 + obug: 3.0.0 + picomatch: 4.0.7 + rolldown: 1.2.16 + rolldown-plugin-dts: 0.28.8(rolldown@1.2.16)(typescript@7.0.2) + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tinyps: 0.5.1 + unconfig-core: 7.5.0 + verkit: 0.5.0 + optionalDependencies: + typescript: 7.0.2 + unrun: 0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + transitivePeerDependencies: + - '@typescript/native-preview' + - '@volar/typescript' + - '@vue/language-core' + - oxc-resolver + - vue-tsc + + tslib@2.8.1: + optional: true + + type-fest@0.18.1: {} + + type-fest@0.21.3: {} + + type-fest@0.6.0: {} + + type-fest@0.8.1: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + unconfig-core@7.5.0: + dependencies: + '@quansync/fs': 1.0.0 + quansync: 1.0.0 + + undici-types@7.18.2: {} + + undici-types@7.24.6: {} + + undici-types@8.12.3: {} + + undici@7.29.1: {} + + unrun@0.2.34(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1): + dependencies: + rolldown: 1.0.0-rc.12(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + optional: true + + validate-npm-package-license@3.0.4: + dependencies: + spdx-correct: 3.2.0 + spdx-expression-parse: 3.0.1 + + verkit@0.4.0: {} + + verkit@0.5.0: {} + + vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 22.20.5 + esbuild: 0.27.7 + fsevents: 2.3.3 + jiti: 2.6.1 + terser: 5.39.0 + + vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.13.4 + esbuild: 0.27.7 + fsevents: 2.3.3 + jiti: 2.6.1 + terser: 5.39.0 + + vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.19.0 + esbuild: 0.27.7 + fsevents: 2.3.3 + jiti: 2.6.1 + terser: 5.39.0 + + vitest@5.0.0(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.0(vite@8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + chai: 6.2.2 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.3.1 + obug: 2.2.1 + picomatch: 4.0.7 + std-env: 4.2.0 + tinybench: 6.1.4 + tinyexec: 1.3.0 + tinyglobby: 0.2.17 + vite: 8.3.0(@types/node@24.13.4)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.13.4 + '@vitest/coverage-v8': 5.0.0(vitest@5.0.0) + happy-dom: 21.0.4 + transitivePeerDependencies: + - msw + + vitest@5.0.3(@types/node@24.19.0)(@vitest/coverage-v8@5.0.3)(happy-dom@21.0.4)(vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.3(vite@8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + chai: 6.2.2 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.2 + obug: 2.2.1 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.0 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.0(@types/node@24.19.0)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 24.19.0 + '@vitest/coverage-v8': 5.0.3(vitest@5.0.3) + happy-dom: 21.0.4 + transitivePeerDependencies: + - msw + + vitest@5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(happy-dom@21.0.4)(vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.3 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.0(@types/node@22.20.5)(esbuild@0.27.7)(jiti@2.6.1)(terser@5.39.0) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 22.20.5 + '@vitest/coverage-v8': 5.0.5(vitest@5.0.5) + happy-dom: 21.0.4 + transitivePeerDependencies: + - msw + + whatwg-mimetype@3.0.0: {} + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + why-is-node-running@3.2.1: {} + + ws@8.21.3: {} + + yallist@4.0.0: {} + + yargs-parser@20.2.9: {} + + yuku-ast@0.19.0: + dependencies: + '@yuku-toolchain/types': 0.19.0 + + yuku-ast@0.9.5: + dependencies: + '@yuku-toolchain/types': 0.9.5 + + yuku-codegen@0.19.0: + dependencies: + '@yuku-toolchain/types': 0.19.0 + + yuku-codegen@0.9.5: + dependencies: + '@yuku-toolchain/types': 0.9.5 + optionalDependencies: + '@yuku-codegen/binding-android-arm64': 0.9.5 + '@yuku-codegen/binding-darwin-arm64': 0.9.5 + '@yuku-codegen/binding-darwin-x64': 0.9.5 + '@yuku-codegen/binding-freebsd-x64': 0.9.5 + '@yuku-codegen/binding-linux-arm-gnu': 0.9.5 + '@yuku-codegen/binding-linux-arm-musl': 0.9.5 + '@yuku-codegen/binding-linux-arm64-gnu': 0.9.5 + '@yuku-codegen/binding-linux-arm64-musl': 0.9.5 + '@yuku-codegen/binding-linux-x64-gnu': 0.9.5 + '@yuku-codegen/binding-linux-x64-musl': 0.9.5 + '@yuku-codegen/binding-win32-arm64': 0.9.5 + '@yuku-codegen/binding-win32-x64': 0.9.5 + + yuku-core@0.19.0: + dependencies: + '@yuku-toolchain/types': 0.19.0 + optionalDependencies: + '@yuku-core/binding-android-arm64': 0.19.0 + '@yuku-core/binding-darwin-arm64': 0.19.0 + '@yuku-core/binding-darwin-x64': 0.19.0 + '@yuku-core/binding-freebsd-x64': 0.19.0 + '@yuku-core/binding-linux-arm-gnu': 0.19.0 + '@yuku-core/binding-linux-arm-musl': 0.19.0 + '@yuku-core/binding-linux-arm64-gnu': 0.19.0 + '@yuku-core/binding-linux-arm64-musl': 0.19.0 + '@yuku-core/binding-linux-x64-gnu': 0.19.0 + '@yuku-core/binding-linux-x64-musl': 0.19.0 + '@yuku-core/binding-win32-arm64': 0.19.0 + '@yuku-core/binding-win32-x64': 0.19.0 + + yuku-parser@0.19.0: + dependencies: + '@yuku-toolchain/types': 0.19.0 + yuku-core: 0.19.0 + + yuku-parser@0.9.5: + dependencies: + '@yuku-toolchain/types': 0.9.5 + yuku-ast: 0.9.5 + optionalDependencies: + '@yuku-parser/binding-android-arm64': 0.9.5 + '@yuku-parser/binding-darwin-arm64': 0.9.5 + '@yuku-parser/binding-darwin-x64': 0.9.5 + '@yuku-parser/binding-freebsd-x64': 0.9.5 + '@yuku-parser/binding-linux-arm-gnu': 0.9.5 + '@yuku-parser/binding-linux-arm-musl': 0.9.5 + '@yuku-parser/binding-linux-arm64-gnu': 0.9.5 + '@yuku-parser/binding-linux-arm64-musl': 0.9.5 + '@yuku-parser/binding-linux-x64-gnu': 0.9.5 + '@yuku-parser/binding-linux-x64-musl': 0.9.5 + '@yuku-parser/binding-win32-arm64': 0.9.5 + '@yuku-parser/binding-win32-x64': 0.9.5 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..fade7b7 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,19 @@ +packages: + - "packages/*" + +minimumReleaseAge: 10080 # 7 days, in minutes +minimumReleaseAgeStrict: true # fail instead of falling back to a too-new version +minimumReleaseAgeIgnoreMissingTime: false # missing publish-time metadata fails closed +trustPolicy: no-downgrade # fail if a later version has weaker trust evidence +blockExoticSubdeps: true # fail when a subdependency uses a non-registry source +strictDepBuilds: true # fail when a dependency build is not approved +dangerouslyAllowAllBuilds: false # do not run every dependency build script +overrides: + # semver 5.7.2 fixes CVE-2022-25883, but it has no trust evidence. + # semver 7.8.5 has the fix and trustedPublisher evidence. + "normalize-package-data@2>semver": 7.8.5 + # undici-types 6.21.0 has no trust evidence, but earlier versions have it. + # undici-types 8.12.3 has the trust evidence. + undici-types@6.21.0: 8.12.3 +allowBuilds: + esbuild: false # the optional package supplies the binary diff --git a/scripts/setup-cloud-environment.sh b/scripts/setup-cloud-environment.sh new file mode 100755 index 0000000..cdb159d --- /dev/null +++ b/scripts/setup-cloud-environment.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# setup-cloud-environment.sh โ€” Aikido Safe Chain bootstrap for Codespaces, Cursor Cloud Agents, +# Claude Code on the web, and Codex cloud. +# +# Fail closed: never install dependencies unless Safe Chain shims are on PATH. +# Copied into the target repo as scripts/setup-cloud-environment.sh. + +set -euo pipefail + +export SAFE_CHAIN_VERSION="1.5.15" +SAFE_CHAIN_INSTALLER_SHA256="de0565e3d6346407a604e84e639e95fea8758748063da2216bbfdca5feda5dd2" +SAFE_CHAIN_INSTALLER_URL="https://github.com/AikidoSec/safe-chain/releases/download/${SAFE_CHAIN_VERSION}/install-safe-chain.sh" +SAFE_CHAIN_SHIMS="${HOME}/.safe-chain/shims" +SAFE_CHAIN_BIN="${HOME}/.safe-chain/bin" + +persist_shim_path() { + local rc="$1" + local line="export PATH=\"${SAFE_CHAIN_SHIMS}:${SAFE_CHAIN_BIN}:\$PATH\"" + if [[ -f "$rc" ]] && grep -Fqx -- "$line" "$rc"; then + return 0 + fi + mkdir -p "$(dirname "$rc")" + printf '\n# Aikido Safe Chain shims\n%s\n' "$line" >> "$rc" +} + +# Claude Code starts each Bash command from a shell snapshot taken at launch, not the rc files, +# and runs CLAUDE_ENV_FILE before every command instead. A failed SessionStart hook does not stop +# the session, so the shims go on its PATH before anything here can fail, holding stubs that +# refuse to run until Safe Chain's setup-ci replaces them. +if [[ -n "${CLAUDE_ENV_FILE:-}" ]]; then + mkdir -p "$SAFE_CHAIN_SHIMS" + for cmd in npm npx pnpm pnpx; do + if [[ ! -e "${SAFE_CHAIN_SHIMS}/${cmd}" ]]; then + printf '#!/bin/sh\necho "error: Safe Chain is not set up, so %s is blocked; run bash ./scripts/setup-cloud-environment.sh" >&2\nexit 1\n' \ + "$cmd" > "${SAFE_CHAIN_SHIMS}/${cmd}" + chmod +x "${SAFE_CHAIN_SHIMS}/${cmd}" + fi + done + persist_shim_path "$CLAUDE_ENV_FILE" +fi + +if git_root=$(git rev-parse --show-toplevel 2>/dev/null); then + cd "$git_root" +fi + +if [[ ! -f pnpm-lock.yaml ]]; then + echo "error: pnpm-lock.yaml is required; refusing to install without a frozen lockfile" >&2 + exit 1 +fi + +if ! command -v pnpm >/dev/null \ + && [[ -f package.json ]] \ + && grep -q '"packageManager"' package.json \ + && command -v corepack >/dev/null; then + mkdir -p "$SAFE_CHAIN_BIN" + corepack enable --install-directory "$SAFE_CHAIN_BIN" pnpm + export PATH="${SAFE_CHAIN_BIN}:${PATH}" +fi + +if ! command -v pnpm >/dev/null; then + echo "error: pnpm is required on PATH before Safe Chain can wrap it" >&2 + exit 1 +fi + +installer=$(mktemp) +trap 'rm -f "$installer"' EXIT + +curl -fsSL "$SAFE_CHAIN_INSTALLER_URL" -o "$installer" +echo "${SAFE_CHAIN_INSTALLER_SHA256} ${installer}" | sha256sum -c - + +# NVM auto-selects from the current directory when sourced. Run outside the +# repository so .nvmrc cannot break the installer's optional legacy scan. +( + cd / + sh "$installer" --ci +) + +export PATH="${SAFE_CHAIN_SHIMS}:${SAFE_CHAIN_BIN}:${PATH}" + +persist_shim_path "${HOME}/.profile" +persist_shim_path "${HOME}/.bashrc" +persist_shim_path "${HOME}/.zshrc" + +if [[ -n "${GITHUB_PATH:-}" ]]; then + printf '%s\n' "$SAFE_CHAIN_SHIMS" >> "$GITHUB_PATH" + printf '%s\n' "$SAFE_CHAIN_BIN" >> "$GITHUB_PATH" +fi + +pnpm safe-chain-verify +pnpm install --frozen-lockfile